task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#XProc
XProc
<p:pipeline xmlns:p="http://www.w3.org/ns/xproc" version="1.0"> <p:identity> <p:input port="source"> <p:inline> <root> <element> Some text here </element> </root> </p:inline> </p:input> </p:identity> </p:pipeline>
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#XQuery
XQuery
<root> <element> Some text here </element> </root>
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Dart
Dart
  void main(){ print("""   XXX XX XXX XXXX X X X X X X X X X XXXX XXX X XXX X X X X X """.replaceAll('X','_/')); }  
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#BBC_BASIC
BBC BASIC
SWP_NOMOVE = 2 SWP_NOZORDER = 4 SW_MAXIMIZE = 3 SW_MINIMIZE = 6 SW_RESTORE = 9 SW_HIDE = 0 SW_SHOW = 5   REM Store window handle in a variable: myWindowHandle% = @hwnd%   PRINT "Hiding the window in two seconds..." WAIT 200 SYS "ShowWindow", myWindowHandle%, SW_HIDE WAIT 200 SYS "ShowWindow", myWindowHandle%, SW_SHOW PRINT "Windows shown again."   PRINT "Minimizing the window in two seconds..." WAIT 200 SYS "ShowWindow", myWindowHandle%, SW_MINIMIZE WAIT 200 SYS "ShowWindow", myWindowHandle%, SW_RESTORE PRINT "Maximizing the window in two seconds..." WAIT 200 SYS "ShowWindow", myWindowHandle%, SW_MAXIMIZE WAIT 200 SYS "ShowWindow", myWindowHandle%, SW_RESTORE PRINT "Now restored to its normal size."   PRINT "Resizing the window in two seconds..." WAIT 200 SYS "SetWindowPos", myWindowHandle%, 0, 0, 0, 400, 200, \ \ SWP_NOMOVE OR SWP_NOZORDER   PRINT "Closing the window in two seconds..." WAIT 200 QUIT
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#C
C
  #include<windows.h> #include<unistd.h> #include<stdio.h>   const char g_szClassName[] = "weirdWindow";   LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; }   int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd[3]; MSG Msg; int i,x=0,y=0; char str[3][100]; int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);   char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.", "If you can see two blank windows just behind this message box, you are in luck.", "Let's get started....", "Yes, you will be seeing a lot of me :)", "Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)", "Let's compare the windows for equality.", "Now let's hide Window 1.", "Now let's see Window 1 again.", "Let's close Window 2, bye, bye, Number 2 !", "Let's minimize Window 1.", "Now let's maximize Window 1.", "And finally we come to the fun part, watch Window 1 move !", "Let's double Window 1 in size for all the good work.", "That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"};   wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);   if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; }   for(i=0;i<2;i++){   sprintf(str[i],"Window Number %d",i+1);   hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);   if(hwnd[i] == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; }   ShowWindow(hwnd[i], nCmdShow); UpdateWindow(hwnd[i]); }   for(i=0;i<6;i++){ MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); }   if(hwnd[0]==hwnd[1]) MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); else MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   ShowWindow(hwnd[0], SW_HIDE);   MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   ShowWindow(hwnd[0], SW_SHOW);   MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   ShowWindow(hwnd[1], SW_HIDE);   MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   ShowWindow(hwnd[0], SW_MINIMIZE);   MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   ShowWindow(hwnd[0], SW_MAXIMIZE);   MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   ShowWindow(hwnd[0], SW_RESTORE);   while(x!=maxX/2||y!=maxY/2){ if(x<maxX/2) x++; if(y<maxY/2) y++;   MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0); sleep(10); }   MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   MoveWindow(hwnd[0],0,0,maxX, maxY,0);   MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);   while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }  
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#ALGOL_68
ALGOL 68
FILE window; draw device (window, "X", "600x400"); open (window, "Hello, World!", stand draw channel); draw erase (window); draw move (window, 0.25, 0.5); draw colour (window, 1, 0, 0); draw text (window, "c", "c", "hello world"); draw show (window); VOID (read char); close (window)
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program windows1.s */   /* compile with as */ /* link with gcc and options -lX11 -L/usr/lpp/X11/lib */   /********************************************/ /*Constantes */ /********************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* constantes X11 */ .equ KeyPressed, 2 .equ ButtonPress, 4 .equ MotionNotify, 6 .equ EnterNotify, 7 .equ LeaveNotify, 8 .equ Expose, 12 .equ ClientMessage, 33 .equ KeyPressMask, 1 .equ ButtonPressMask, 4 .equ ButtonReleaseMask, 8 .equ ExposureMask, 1<<15 .equ StructureNotifyMask, 1<<17 .equ EnterWindowMask, 1<<4 .equ LeaveWindowMask, 1<<5 .equ ConfigureNotify, 22   /*******************************************/ /* DONNEES INITIALISEES */ /*******************************************/ .data szWindowName: .asciz "Windows Raspberry" szRetourligne: .asciz "\n" szMessDebutPgm: .asciz "Program start. \n" szMessErreur: .asciz "Server X not found.\n" szMessErrfen: .asciz "Can not create window.\n" szMessErreurX11: .asciz "Error call function X11. \n" szMessErrGc: .asciz "Can not create graphics context.\n" szTitreFenRed: .asciz "Pi" szTexte1: .asciz "Hello world." .equ LGTEXTE1, . - szTexte1 szTexte2: .asciz "Press q for close window or clic X in system menu." .equ LGTEXTE2, . - szTexte2 szLibDW: .asciz "WM_DELETE_WINDOW" @ special label for correct close error   /*************************************************/ szMessErr: .ascii "Error code hexa : " sHexa: .space 9,' ' .ascii " decimal : " sDeci: .space 15,' ' .asciz "\n"   /*******************************************/ /* DONNEES NON INITIALISEES */ /*******************************************/ .bss .align 4 ptDisplay: .skip 4 @ pointer display ptEcranDef: .skip 4 @ pointer screen default ptFenetre: .skip 4 @ pointer window ptGC: .skip 4 @ pointer graphic context key: .skip 4 @ key code wmDeleteMessage: .skip 8 @ ident close message event: .skip 400 @ TODO event size ?? PrpNomFenetre: .skip 100 @ window name proprety buffer: .skip 500 iWhite: .skip 4 @ rgb code for white pixel iBlack: .skip 4 @ rgb code for black pixel /**********************************************/ /* -- Code section */ /**********************************************/ .text .global main   main: @ entry of program ldr r0,iAdrszMessDebutPgm @ bl affichageMess @ display start message on console linux /* attention r6 pointer display*/ /* attention r8 pointer graphic context */ /* attention r9 ident window */ /*****************************/ /* OPEN SERVER X11 */ /*****************************/ mov r0,#0 bl XOpenDisplay @ open X server cmp r0,#0 @ error ? beq erreurServeur ldr r1,iAdrptDisplay str r0,[r1] @ store display address mov r6,r0 @ and in register r6 ldr r2,[r0,#+132] @ load default_screen ldr r1,iAdrptEcranDef str r2,[r1] @ store default_screen mov r2,r0 ldr r0,[r2,#+140] @ load pointer screen list ldr r5,[r0,#+52] @ load value white pixel ldr r4,iAdrWhite @ and store in memory str r5,[r4] ldr r3,[r0,#+56] @ load value black pixel ldr r4,iAdrBlack @ and store in memory str r3,[r4] ldr r4,[r0,#+28] @ load bits par pixel ldr r1,[r0,#+8] @ load root windows /**************************/ /* CREATE WINDOW */ /**************************/ mov r0,r6 @ address display mov r2,#0 @ window position X mov r3,#0 @ window position Y mov r8,#0 @ for stack alignement push {r8} push {r3} @ background = black pixel push {r5} @ border = white pixel mov r8,#2 @ border size push {r8} mov r8,#400 @ hauteur push {r8} mov r8,#600 @ largeur push {r8} bl XCreateSimpleWindow add sp,#24 @ stack alignement 6 push (4 bytes * 6) cmp r0,#0 @ error ? beq erreurF   ldr r1,iAdrptFenetre str r0,[r1] @ store window address in memory mov r9,r0 @ and in register r9 /*****************************/ /* add window property */ /*****************************/ mov r0,r6 @ display address mov r1,r9 @ window address ldr r2,iAdrszWindowName @ window name ldr r3,iAdrszTitreFenRed @ window name reduced mov r4,#0 push {r4} @ parameters not use push {r4} push {r4} push {r4} bl XSetStandardProperties add sp,sp,#16 @ stack alignement for 4 push /**************************************/ /* for correction window close error */ /**************************************/ mov r0,r6 @ display address ldr r1,iAdrszLibDW @ atom address mov r2,#1 @ False créate atom if not exists bl XInternAtom cmp r0,#0 @ error X11 ? ble erreurX11 ldr r1,iAdrwmDeleteMessage @ recept address str r0,[r1] mov r2,r1 @ return address mov r0,r6 @ display address mov r1,r9 @ window address mov r3,#1 @ number of protocols bl XSetWMProtocols cmp r0,#0 @ error X11 ? ble erreurX11 /**********************************/ /* create graphic context */ /**********************************/ mov r0,r6 @ display address mov r1,r9 @ window address mov r2,#0 @ not use for simply context mov r3,#0 bl XCreateGC cmp r0,#0 @ error ? beq erreurGC ldr r1,iAdrptGC str r0,[r1] @ store address graphic context mov r8,r0 @ and in r8 /****************************/ /* modif window background */ /****************************/ mov r0,r6 @ display address mov r1,r9 @ window address ldr r2,iGris1 @ background color bl XSetWindowBackground cmp r0,#0 @ error ? ble erreurX11 /***************************/ /* OUF!! window display */ /***************************/ mov r0,r6 @ display address mov r1,r9 @ window address bl XMapWindow /****************************/ /* Write text in the window */ /****************************/ mov r0,r6 @ display address mov r1,r9 @ window address mov r2,r8 @ address graphic context mov r3,#50 @ position x sub sp,#4 @ stack alignement mov r4,#LGTEXTE1 - 1 @ size string push {r4} @ on the stack ldr r4,iAdrszTexte1 @ string address push {r4} mov r4,#100 @ position y push {r4} bl XDrawString add sp,sp,#16 @ stack alignement 3 push and 1 stack alignement cmp r0,#0 @ error ? blt erreurX11 /* write text 2 */ mov r0,r6 @ display address mov r1,r9 @ window address mov r2,r8 @ address graphic context mov r3,#10 @ position x sub sp,#4 @ stack alignement mov r4,#LGTEXTE2 - 1 @ size string push {r4} @ on the stack ldr r4,iAdrszTexte2 @ string address push {r4} mov r4,#350 @ position y push {r4} bl XDrawString add sp,sp,#16 @ stack alignement 3 push and 1 stack alignement cmp r0,#0 @ error ? blt erreurX11 /****************************/ /* Autorisations */ /****************************/ mov r0,r6 @ display address mov r1,r9 @ window address ldr r2,iFenetreMask @ autorisation mask bl XSelectInput cmp r0,#0 @ error ? ble erreurX11 /****************************/ /* Events loop */ /****************************/ 1: mov r0,r6 @ display address ldr r1,iAdrevent @ events address bl XNextEvent @ event ? ldr r0,iAdrevent ldr r0,[r0] @ code event cmp r0,#KeyPressed @ key ? bne 2f ldr r0,iAdrevent @ yes read key in buffer ldr r1,iAdrbuffer mov r2,#255 ldr r3,iAdrkey mov r4,#0 push {r4} @ stack alignement push {r4} bl XLookupString add sp,#8 @ stack alignement 2 push cmp r0,#1 @ is character key ? bne 2f ldr r0,iAdrbuffer @ yes -> load first buffer character ldrb r0,[r0] cmp r0,#0x71 @ character q for quit beq 5f @ yes -> end b 4f 2: /* */ /* for example clic mouse button */ /************************************/ cmp r0,#ButtonPress @ clic mouse buton bne 3f ldr r0,iAdrevent ldr r1,[r0,#+32] @ position X mouse clic ldr r2,[r0,#+36] @ position Y @ etc for eventuel use b 4f 3: cmp r0,#ClientMessage @ code for close window within error bne 4f ldr r0,iAdrevent ldr r1,[r0,#+28] @ code message address ldr r2,iAdrwmDeleteMessage @ equal code window créate ??? ldr r2,[r2] cmp r1,r2 beq 5f @ yes -> end window   4: @ loop for other event b 1b /***********************************/ /* Close window -> free ressources */ /***********************************/ 5: mov r0,r6 @ display address ldr r1,iAdrptGC ldr r1,[r1] @ load context graphic address bl XFreeGC cmp r0,#0 blt erreurX11 mov r0,r6 @ display address mov r1,r9 @ window address bl XDestroyWindow cmp r0,#0 blt erreurX11 mov r0,r6 @ display address bl XCloseDisplay cmp r0,#0 blt erreurX11 mov r0,#0 @ return code OK b 100f erreurF: @ create error window but possible not necessary. Display error by server ldr r1,iAdrszMessErrfen bl displayError mov r0,#1 @ return error code b 100f erreurGC: @ error create graphic context ldr r1,iAdrszMessErrGc bl displayError mov r0,#1 b 100f erreurX11: @ erreur X11 ldr r1,iAdrszMessErreurX11 bl displayError mov r0,#1 b 100f erreurServeur: @ error no found X11 server see doc putty and Xming ldr r1,iAdrszMessErreur bl displayError mov r0,#1 b 100f   100: @ standard end of the program mov r7, #EXIT svc 0 iFenetreMask: .int KeyPressMask|ButtonPressMask|StructureNotifyMask iGris1: .int 0xFFA0A0A0 iAdrWhite: .int iWhite iAdrBlack: .int iBlack iAdrptDisplay: .int ptDisplay iAdrptEcranDef: .int ptEcranDef iAdrptFenetre: .int ptFenetre iAdrptGC: .int ptGC iAdrevent: .int event iAdrbuffer: .int buffer iAdrkey: .int key iAdrszLibDW: .int szLibDW iAdrszMessDebutPgm: .int szMessDebutPgm iAdrszMessErreurX11: .int szMessErreurX11 iAdrszMessErrGc: .int szMessErrGc iAdrszMessErreur: .int szMessErreur iAdrszMessErrfen: .int szMessErrfen iAdrszWindowName: .int szWindowName iAdrszTitreFenRed: .int szTitreFenRed iAdrszTexte1: .int szTexte1 iAdrszTexte2: .int szTexte2 iAdrPrpNomFenetre: .int PrpNomFenetre iAdrwmDeleteMessage: .int wmDeleteMessage /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur registers */ bx lr @ return /***************************************************/ /* affichage message d erreur */ /***************************************************/ /* r0 contains error code r1 : message address */ displayError: push {r0-r2,lr} @ save registers mov r2,r0 @ save error code mov r0,r1 bl affichageMess mov r0,r2 @ error code ldr r1,iAdrsHexa bl conversion16 @ conversion hexa mov r0,r2 @ error code ldr r1,iAdrsDeci @ result address bl conversion10 @ conversion decimale ldr r0,iAdrszMessErr @ display error message bl affichageMess 100: pop {r0-r2,lr} @ restaur registers bx lr @ return iAdrszMessErr: .int szMessErr iAdrsHexa: .int sHexa iAdrsDeci: .int sDeci /******************************************************************/ /* Converting a register to hexadecimal */ /******************************************************************/ /* r0 contains value and r1 address area */ conversion16: push {r1-r4,lr} @ save registers mov r2,#28 @ start bit position mov r4,#0xF0000000 @ mask mov r3,r0 @ save entry value 1: @ start loop and r0,r3,r4 @value register and mask lsr r0,r2 @ move right cmp r0,#10 @ compare value addlt r0,#48 @ <10 ->digit addge r0,#55 @ >10 ->letter A-F strb r0,[r1],#1 @ store digit on area and + 1 in area address lsr r4,#4 @ shift mask 4 positions subs r2,#4 @ counter bits - 4 <= zero  ? bge 1b @ no -> loop   100: pop {r1-r4,lr} @ restaur registers bx lr @return /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* r0 contains value and r1 address area */ /* r0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL 1: @ start loop bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ else previous position bne 1b @ and loop @ and move digit from left of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] add r2,#1 add r4,#1 cmp r2,#LGZONECAL ble 2b @ and move spaces in end on area mov r0,r4 @ result length mov r1,#' ' @ space 3: strb r1,[r3,r4] @ store space in area add r4,#1 @ next position cmp r4,#LGZONECAL ble 3b @ loop if r4 <= area size   100: pop {r1-r4,lr} @ restaur registres bx lr @return   /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2 umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function iMagicNumber: .int 0xCCCCCCCD  
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#BASIC
BASIC
function isPrime(v) if v <= 1 then return False for i = 2 To int(sqr(v)) if v % i = 0 then return False next i return True end function   function isWilson(n, p) if p < n then return false prod = 1 p2 = p*p #p^2 for i = 1 to n-1 prod = (prod*i) mod p2 next i for i = 1 to p-n prod = (prod*i) mod p2 next i prod = (p2 + prod - (-1)**n) mod p2 if prod = 0 then return true else return false end function   print " n: Wilson primes" print "----------------------" for n = 1 to 11 print n;" : "; for p = 3 to 10499 step 2 if isPrime(p) and isWilson(n, p) then print p; " "; next p print next n end
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h>   std::vector<int> generate_primes(int limit) { std::vector<bool> sieve(limit >> 1, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; } s += (p + 1) << 2; } std::vector<int> primes; if (limit > 2) primes.push_back(2); for (int i = 1; i < sieve.size(); ++i) { if (sieve[i]) primes.push_back((i << 1) + 1); } return primes; }   int main() { using big_int = mpz_class; const int limit = 11000; std::vector<big_int> f{1}; f.reserve(limit); big_int factorial = 1; for (int i = 1; i < limit; ++i) { factorial *= i; f.push_back(factorial); } std::vector<int> primes = generate_primes(limit); std::cout << " n | Wilson primes\n--------------------\n"; for (int n = 1, s = -1; n <= 11; ++n, s = -s) { std::cout << std::setw(2) << n << " |"; for (int p : primes) { if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0) std::cout << ' ' << p; } std::cout << '\n'; } }
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Ada
Ada
with Gtk.Window; use Gtk.Window; with Gtk.Widget; use Gtk.Widget;   with Gtk.Handlers; with Gtk.Main;   procedure Windowed_Application is Window : Gtk_Window;   package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record); package Return_Handlers is new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);   function Delete_Event (Widget : access Gtk_Widget_Record'Class) return Boolean is begin return False; end Delete_Event;   procedure Destroy (Widget : access Gtk_Widget_Record'Class) is begin Gtk.Main.Main_Quit; end Destroy;   begin Gtk.Main.Init; Gtk.Window.Gtk_New (Window); Return_Handlers.Connect ( Window, "delete_event", Return_Handlers.To_Marshaller (Delete_Event'Access) ); Handlers.Connect ( Window, "destroy", Handlers.To_Marshaller (Destroy'Access) ); Show (Window);   Gtk.Main.Main; end Windowed_Application;
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Go
Go
package main   import ( "bufio" "fmt" "log" "math/rand" "os" "regexp" "strings" "time" )   var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}   const ( nRows = 10 nCols = nRows gridSize = nRows * nCols minWords = 25 )   var ( re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows)) re2 = regexp.MustCompile("[^A-Z]") )   type grid struct { numAttempts int cells [nRows][nCols]byte solutions []string }   func check(err error) { if err != nil { log.Fatal(err) } }   func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner := bufio.NewScanner(file) for scanner.Scan() { word := strings.ToLower(strings.TrimSpace(scanner.Text())) if re1.MatchString(word) { words = append(words, word) } } check(scanner.Err()) return words }   func createWordSearch(words []string) *grid { var gr *grid outer: for i := 1; i < 100; i++ { gr = new(grid) messageLen := gr.placeMessage("Rosetta Code") target := gridSize - messageLen cellsFilled := 0 rand.Shuffle(len(words), func(i, j int) { words[i], words[j] = words[j], words[i] }) for _, word := range words { cellsFilled += gr.tryPlaceWord(word) if cellsFilled == target { if len(gr.solutions) >= minWords { gr.numAttempts = i break outer } else { // grid is full but we didn't pack enough words, start over break } } } } return gr }   func (gr *grid) placeMessage(msg string) int { msg = strings.ToUpper(msg) msg = re2.ReplaceAllLiteralString(msg, "") messageLen := len(msg) if messageLen > 0 && messageLen < gridSize { gapSize := gridSize / messageLen for i := 0; i < messageLen; i++ { pos := i*gapSize + rand.Intn(gapSize) gr.cells[pos/nCols][pos%nCols] = msg[i] } return messageLen } return 0 }   func (gr *grid) tryPlaceWord(word string) int { randDir := rand.Intn(len(dirs)) randPos := rand.Intn(gridSize) for dir := 0; dir < len(dirs); dir++ { dir = (dir + randDir) % len(dirs) for pos := 0; pos < gridSize; pos++ { pos = (pos + randPos) % gridSize lettersPlaced := gr.tryLocation(word, dir, pos) if lettersPlaced > 0 { return lettersPlaced } } } return 0 }   func (gr *grid) tryLocation(word string, dir, pos int) int { r := pos / nCols c := pos % nCols le := len(word)   // check bounds if (dirs[dir][0] == 1 && (le+c) > nCols) || (dirs[dir][0] == -1 && (le-1) > c) || (dirs[dir][1] == 1 && (le+r) > nRows) || (dirs[dir][1] == -1 && (le-1) > r) { return 0 } overlaps := 0   // check cells rr := r cc := c for i := 0; i < le; i++ { if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] { return 0 } cc += dirs[dir][0] rr += dirs[dir][1] }   // place rr = r cc = c for i := 0; i < le; i++ { if gr.cells[rr][cc] == word[i] { overlaps++ } else { gr.cells[rr][cc] = word[i] } if i < le-1 { cc += dirs[dir][0] rr += dirs[dir][1] } }   lettersPlaced := le - overlaps if lettersPlaced > 0 { sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr) gr.solutions = append(gr.solutions, sol) } return lettersPlaced }   func printResult(gr *grid) { if gr.numAttempts == 0 { fmt.Println("No grid to display") return } size := len(gr.solutions) fmt.Println("Attempts:", gr.numAttempts) fmt.Println("Number of words:", size) fmt.Println("\n 0 1 2 3 4 5 6 7 8 9") for r := 0; r < nRows; r++ { fmt.Printf("\n%d ", r) for c := 0; c < nCols; c++ { fmt.Printf(" %c ", gr.cells[r][c]) } } fmt.Println("\n") for i := 0; i < size-1; i += 2 { fmt.Printf("%s  %s\n", gr.solutions[i], gr.solutions[i+1]) } if size%2 == 1 { fmt.Println(gr.solutions[size-1]) } }   func main() { rand.Seed(time.Now().UnixNano()) unixDictPath := "/usr/share/dict/words" printResult(createWordSearch(readWords(unixDictPath))) }
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BaCon
BaCon
paragraph$ = "In olden times when wishing still helped one," \ " there lived a king whose daughters were all beautiful, but" \ " the youngest was so beautiful that the sun itself, which has" \ " seen so much, was astonished whenever it shone in her face." \ " Close by the king's castle lay a great dark forest, and under" \ " an old lime tree in the forest was a well, and when the day" \ " was very warm, the king's child went out into the forest and" \ " sat down by the side of the cool fountain, and when she was" \ " bored she took a golden ball, and threw it up on high and" \ " caught it, and this ball was her favorite plaything."   PRINT ALIGN$(paragraph$, 72, 0) PRINT ALIGN$(paragraph$, 90, 0)
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Nim
Nim
import sets, strformat, strutils     func isOneAway(word1, word2: string): bool = ## Return true if "word1" and "word2" has only one letter of difference. for i in 0..word1.high: if word1[i] != word2[i]: if result: return false # More than one letter of difference. else: result = true # One letter of difference, for now.   var words: array[1..22, HashSet[string]] # Set of words sorted by length.   for word in "unixdict.txt".lines: words[word.len].incl word     proc path(start, target: string): seq[string] = ## Return a path from "start" to "target" or an empty list ## if there is no possible path. let lg = start.len doAssert target.len == lg, "Source and destination must have same length." doAssert start in words[lg], "Source must exist in the dictionary." doAssert target in words[lg], "Destination must exist in the dictionary."   var currPaths = @[@[start]] # Current list of paths found. var pool = words[lg] # List of possible words to use.   while true: var newPaths: seq[seq[string]] # Next list of paths. var added: HashSet[string] # Set of words added during the round. for candidate in pool: for path in currPaths: if candidate.isOneAway(path[^1]): let newPath = path & candidate if candidate == target: # Found a path. return newPath else: # Not the target. Add a new path. newPaths.add newPath added.incl candidate break if newPaths.len == 0: break # No path. currPaths = move(newPaths) # Update list of paths. pool.excl added # Remove added words from pool.     when isMainModule: for (start, target) in [("boy", "man"), ("girl", "lady"), ("john", "jane"), ("child", "adult"), ("cat", "dog"), ("lead", "gold"), ("white", "black"), ("bubble", "tickle")]: let path = path(start, target) if path.len == 0: echo &"No path from “{start}” to “{target}”." else: echo path.join(" → ")
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Perl
Perl
use strict; use warnings;   my %dict;   open my $handle, '<', 'unixdict.txt'; while (my $word = <$handle>) { chomp($word); my $len = length $word; if (exists $dict{$len}) { push @{ $dict{ $len } }, $word; } else { my @words = ( $word ); $dict{$len} = \@words; } } close $handle;   sub distance { my $w1 = shift; my $w2 = shift;   my $dist = 0; for my $i (0 .. length($w1) - 1) { my $c1 = substr($w1, $i, 1); my $c2 = substr($w2, $i, 1); if (not ($c1 eq $c2)) { $dist++; } } return $dist; }   sub contains { my $aref = shift; my $needle = shift;   for my $v (@$aref) { if ($v eq $needle) { return 1; } }   return 0; }   sub word_ladder { my $fw = shift; my $tw = shift;   if (exists $dict{length $fw}) { my @poss = @{ $dict{length $fw} }; my @queue = ([$fw]); while (scalar @queue > 0) { my $curr_ref = shift @queue; my $last = $curr_ref->[-1];   my @next; for my $word (@poss) { if (distance($last, $word) == 1) { push @next, $word; } }   if (contains(\@next, $tw)) { push @$curr_ref, $tw; print join (' -> ', @$curr_ref), "\n"; return; }   for my $word (@next) { for my $i (0 .. scalar @poss - 1) { if ($word eq $poss[$i]) { splice @poss, $i, 1; last; } } }   for my $word (@next) { my @temp = @$curr_ref; push @temp, $word;   push @queue, \@temp; } } }   print STDERR "Cannot change $fw into $tw\n"; }   word_ladder('boy', 'man'); word_ladder('girl', 'lady'); word_ladder('john', 'jane'); word_ladder('child', 'adult'); word_ladder('cat', 'dog'); word_ladder('lead', 'gold'); word_ladder('white', 'black'); word_ladder('bubble', 'tickle');
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Haskell
Haskell
import Data.Char (toLower) import Data.List (sort) import System.IO (readFile)   ------------------------ WORD WHEEL ----------------------   gridWords :: [String] -> [String] -> [String] gridWords grid = filter ( ((&&) . (2 <) . length) <*> (((&&) . elem mid) <*> wheelFit wheel) ) where cs = toLower <$> concat grid wheel = sort cs mid = cs !! 4   wheelFit :: String -> String -> Bool wheelFit wheel = go wheel . sort where go _ [] = True go [] _ = False go (w : ws) ccs@(c : cs) | w == c = go ws cs | otherwise = go ws ccs   --------------------------- TEST ------------------------- main :: IO () main = readFile "unixdict.txt" >>= ( mapM_ putStrLn . gridWords ["NDE", "OKG", "ELW"] . lines )
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Phix
Phix
-- -- demo\rosetta\XiaolinWuLine.exw -- ============================== -- -- Resize the window to show lines at any angle -- -- For education/comparision purposes only: see demo\pGUI\aaline.exw -- for a much shorter version, but "wrong algorithm" for the RC task. -- Also note this blends with BACK rather than the actual pixel, -- whereas aaline.exw does it properly. -- with javascript_semantics -- not really fair: pwa/p2js uses OpenGL -- and does not draw bresenham lines anyway/ever, plus the next line -- makes no difference whatsoever when running this in a browser. constant USE_OPENGL = 0 constant TITLE = "Xiaolin Wu's line algorithm" include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas bool wuline = true -- space toggles, for comparison -- when false, and with USE_OPENGL, lines are still smooth, -- but a bit thicker - and therefore less "ropey". -- when false, but without USE_OPENGL, it draws bresenham -- lines (ie jagged, without anti-aliasing [desktop only]). integer BACK = CD_PARCHMENT, LINE = CD_BLUE, {rB, gB, bB} = to_rgb(BACK), {rL, gL, bL} = to_rgb(LINE) procedure plot(atom x, y, c, bool steep=false) -- plot the pixel at (x, y) with brightness c (where 0 <= c <= 1) if steep then {x,y} = {y,x} end if atom C = 1-c c = rgb(rL*c+rB*C,gL*c+gB*C,bL*c+bB*C) cdCanvasPixel(cddbuffer, x, y, c) end procedure procedure plot2(atom x, y, f, xgap, bool steep) plot(x,y,(1-f)*xgap,steep) plot(x,y+1,(f)*xgap,steep) end procedure function fpart(atom x) return x-floor(x) -- fractional part of x end function procedure wu_line(atom x0,y0,x1,y1) bool steep := abs(y1 - y0) > abs(x1 - x0) if steep then {x0, y0, x1, y1} = {y0, x0, y1, x1} end if if x0>x1 then {x0, x1, y0, y1} = {x1, x0, y1, y0} end if atom dx := x1 - x0, dy := y1 - y0, gradient := iff(dx=0? 1 : dy / dx) -- handle first endpoint atom xend := round(x0), yend := y0 + gradient * (xend - x0), xgap := 1 - fpart(x0 + 0.5), xpxl1 := xend, -- this will be used in the main loop ypxl1 := floor(yend) plot2(xpxl1, ypxl1, fpart(yend), xgap, steep) atom intery := yend + gradient -- first y-intersection for the main loop -- handle second endpoint xend := round(x1) yend := y1 + gradient * (xend - x1) xgap := fpart(x1 + 0.5) atom xpxl2 := xend, -- this will be used in the main loop ypxl2 := floor(yend) plot2(xpxl2, ypxl2, fpart(yend), xgap, steep) -- main loop for x = xpxl1+1 to xpxl2-1 do plot2(x, floor(intery), fpart(intery), 1, steep) intery += gradient end for end procedure procedure plot_4_points(integer cx, cy, x, y, atom f, angle1=0, angle2=360, angle=0) integer x1 = cx+x, x2 = cx-x, y1 = cy+y, y2 = cy-y if angle<0 or angle>90.01 then ?9/0 end if if angle >=angle1 and angle <=angle2 then plot(x1, y1, f) end if -- top right if (180-angle)>=angle1 and (180-angle)<=angle2 then plot(x2, y1, f) end if -- top left if (180+angle)>=angle1 and (180+angle)<=angle2 then plot(x2, y2, f) end if -- btm left if (360-angle)>=angle1 and (360-angle)<=angle2 then plot(x1, y2, f) end if -- btm right end procedure procedure wu_ellipse(atom cx, cy, w, h, angle1=0, angle2=360) -- -- (draws a circle when w=h) credit: -- https://yellowsplash.wordpress.com/2009/10/23/fast-antialiased-circles-and-ellipses-from-xiaolin-wus-concepts/ -- if w<=0 or h<=0 then return end if cx = round(cx) cy = round(cy) w = round(w) h = round(h) angle1 = mod(angle1,360) angle2 = mod(angle2,360) -- Match cdCanvasArc/Sector angles: angle1 = atan2((h/2)*sin(angle1*CD_DEG2RAD), (w/2)*cos(angle1*CD_DEG2RAD))*CD_RAD2DEG angle2 = atan2((h/2)*sin(angle2*CD_DEG2RAD), (w/2)*cos(angle2*CD_DEG2RAD))*CD_RAD2DEG if angle2<=angle1 then angle2 += 360 end if atom a := w/2, asq := a*a, b := h/2, bsq := b*b, sqab = sqrt(asq+bsq), ffd = round(asq/sqab), -- forty-five-degree coord xj, yj, frc, flr, angle -- draw top right, and the 3 mirrors of it in horizontal fashion -- (ie 90 to 45 degrees for a circle) for xi=0 to ffd do yj := b*sqrt(1-xi*xi/asq) -- real y value frc := fpart(yj) flr := floor(yj) angle := iff(xi=0?90:arctan(yj/xi)*CD_RAD2DEG) plot_4_points(cx, cy, xi, flr, 1-frc, angle1, angle2, angle) plot_4_points(cx, cy, xi, flr+1, frc, angle1, angle2, angle) end for -- switch from horizontal to vertial mode for the rest, ditto 3 -- (ie 45..0 degrees for a circle) ffd = round(bsq/sqab) for yi=0 to ffd do xj := a*sqrt(1-yi*yi/bsq) -- real x value frc := fpart(xj) flr := floor(xj) angle = iff(xj=0?0:arctan(yi/xj)*CD_RAD2DEG) plot_4_points (cx, cy, flr, yi, 1-frc, angle1, angle2, angle) plot_4_points (cx, cy, flr+1, yi, frc, angle1, angle2, angle) end for end procedure function redraw_cb(Ihandle /*ih*/) integer {w, h} = sq_sub(IupGetIntInt(canvas, "DRAWSIZE"),10) cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) if platform()=JS then cdCanvasSetLineWidth(cddbuffer,iff(wuline?1:4)) end if if wuline then wu_line(0,0,200,200) wu_line(w,0,200,200) wu_line(0,h,200,200) wu_line(w,h,200,200) else cdCanvasLine(cddbuffer,0,0,200,200) cdCanvasLine(cddbuffer,w,0,200,200) cdCanvasLine(cddbuffer,0,h,200,200) cdCanvasLine(cddbuffer,w,h,200,200) end if if wuline then wu_ellipse(200,200,200,200) -- cdCanvasSector(cddbuffer, 200, 200, 200, 200, 0, 360) wu_ellipse(200,200,300,100) -- wu_ellipse(200,200,300,100,15,85) -- cdCanvasArc(cddbuffer, 205, 205, 300, 100, 15, 85) else cdCanvasArc(cddbuffer, 200, 200, 200, 200, 0, 360) -- cdCanvasSector(cddbuffer, 200, 200, 200, 200, 0, 360) cdCanvasArc(cddbuffer, 200, 200, 300, 100, 0, 360) end if --test - it works (much better) if you draw the polygon /after/ the lines!! -- cdCanvasBegin(cddbuffer,CD_FILL) -- cdCanvasVertex(cddbuffer,w,h) -- cdCanvasVertex(cddbuffer,0,h) -- cdCanvasVertex(cddbuffer,200,200) -- cdCanvasEnd(cddbuffer) --/test cdCanvasFlush(cddbuffer) if USE_OPENGL then if platform()!=JS then IupGLSwapBuffers(canvas) end if end if return IUP_DEFAULT end function function map_cb(Ihandle ih) if USE_OPENGL then IupGLMakeCurrent(canvas) if platform()=JS then cdcanvas = cdCreateCanvas(CD_IUP, canvas) else atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cdcanvas = cdCreateCanvas(CD_GL, "10x10 %g", {res}) end if cddbuffer = cdcanvas else cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) end if cdCanvasSetBackground(cddbuffer, BACK) cdCanvasSetForeground(cddbuffer, LINE) return IUP_DEFAULT end function function canvas_resize_cb(Ihandle /*canvas*/) if USE_OPENGL then integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cdCanvasSetAttribute(cdcanvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) end if return IUP_DEFAULT end function procedure set_title() string title = TITLE if USE_OPENGL then title &= iff(wuline?" (wu_line)":" (opengl)") else title &= iff(wuline?" (anti-aliased)":" (bresenham)") end if IupSetStrAttribute(dlg,"TITLE",title) end procedure function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if if c=' ' then wuline = not wuline set_title() IupRedraw(canvas) end if return IUP_CONTINUE end function procedure main() IupOpen() if USE_OPENGL then canvas = IupGLCanvas() IupSetAttribute(canvas, "BUFFER", "DOUBLE") else canvas = IupCanvas() end if IupSetAttribute(canvas, "RASTERSIZE", "640x480") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb"), "RESIZE_CB", Icallback("canvas_resize_cb")}) dlg = IupDialog(canvas) set_title() IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#FreeBASIC
FreeBASIC
Data "April", "Bubbly: I'm > Tam and <= Emily", _ "Tam O'Shanter", "Burns: ""When chapman billies leave the street ...""", _ "Emily", "Short & shrift"   Declare Function xmlquote(ByRef s As String) As String Dim n As Integer, dev As String, remark As String   Print "<CharacterRemarks>" For n = 0 to 2 Read dev, remark Print " <Character name="""; xmlquote(dev); """>"; _ xmlquote(remark); "</Character>" Next Print "</CharacterRemarks>"   End   Function xmlquote(ByRef s As String) As String Dim n As Integer Dim r As String For n = 0 To Len(s) Dim c As String c = Mid(s,n,1) Select Case As Const Asc(c) Case Asc("<") r = r + "&lt;" Case Asc(">") r = r + "&gt;" Case Asc("&") r = r + "&amp;" Case Asc("""") r = r + "&quot;" Case Asc("'") r = r + "&apos;" Case Else r = r + c End Select Next Function = r End Function
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Forth
Forth
include ffl/est.fs include ffl/str.fs include ffl/xis.fs   \ Build input string str-create xmlstr : x+ xmlstr str-append-string ;   s\" <Students>\n" x+ s\" <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" x+ s\" <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n" x+ s\" <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n" x+ s\" <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n" x+ s\" <Pet Type=\"dog\" Name=\"Rover\" />\n" x+ s\" </Student>\n" x+ s\" <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n" x+ s\" </Students>\n" x+   \ Setup xml parser xis-create xmlparser xmlstr str-get xmlparser xis-set-string   \ Parse the xml : xmlparse BEGIN xmlparser xis-read dup xis.error <> over xis.done <> AND WHILE dup xis.start-tag = over xis.empty-element = OR IF drop s" Student" compare 0= IF 0 ?DO 2swap s" Name" compare 0= IF type cr ELSE 2drop THEN LOOP ELSE xis+remove-attribute-parameters THEN ELSE xis+remove-read-parameters THEN REPEAT drop ;   xmlparse
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Fortran
Fortran
  program tixi_rosetta use tixi implicit none integer :: i character (len=100) :: xml_file_name integer :: handle integer :: error character(len=100) :: name, xml_attr xml_file_name = 'rosetta.xml'   call tixi_open_document( xml_file_name, handle, error ) i = 1 do xml_attr = '/Students/Student['//int2char(i)//']' call tixi_get_text_attribute( handle, xml_attr,'Name', name, error ) if(error /= 0) exit write(*,*) name i = i + 1 enddo   call tixi_close_document( handle, error )   contains   function int2char(i) result(res) character(:),allocatable :: res integer,intent(in) :: i character(range(i)+2) :: tmp write(tmp,'(i0)') i res = trim(tmp) end function int2char   end program tixi_rosetta  
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Tern
Tern
let list = [1, 22, 3, 24, 35, 6];   for(i in list) { println(i); }  
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Wren
Wren
import "/fmt" for Conv, Fmt import "/sort" for Sort   var games = ["12", "13", "14", "23", "24", "34"] var results = "000000"   var nextResult = Fn.new { if (results == "222222") return false var res = Conv.atoi(results, 3) + 1 results = Fmt.swrite("$06t", res) return true }   var points = List.filled(4, null) for (i in 0..3) points[i] = List.filled(10, 0) while (true) { var records = List.filled(4, 0) for (i in 0..5) { var g0 = Num.fromString(games[i][0]) - 1 var g1 = Num.fromString(games[i][1]) - 1 if (results[i] == "2") { records[g0] = records[g0] + 3 } else if (results[i] == "1") { records[g0] = records[g0] + 1 records[g1] = records[g1] + 1 } else if (results[i] == "0") { records[g1] = records[g1] + 3 } } Sort.insertion(records) for (i in 0..3) points[i][records[i]] = points[i][records[i]] +1 if (!nextResult.call()) break } System.print("POINTS 0 1 2 3 4 5 6 7 8 9") System.print("---------------------------------------------------------------") for (i in 0..3) { Fmt.write("$r place ", i+1) points[3-i].each { |p| Fmt.write("$5d", p) } System.print() }
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#PureBasic
PureBasic
#Size = 4   DataSection Data.f 1, 2, 3, 1e11 ;x values, how many values needed is determined by #Size EndDataSection   Dim x.f(#Size - 1) Dim y.f(#Size - 1)   Define i For i = 0 To #Size - 1 Read.f x(i) y(i) = Sqr(x(i)) Next   Define file$, fileID, xprecision = 3, yprecision = 5, output$   file$ = SaveFileRequester("Text file for float data", "xydata.txt","Text file | *.txt", 0) If file$ fileID = OpenFile(#PB_Any, file$) If fileID For i = 0 To #Size - 1 output$ = StrF(x(i), xprecision) + Chr(9) + StrF(y(i), yprecision) WriteStringN(fileID, output$) Next CloseFile(fileID) EndIf EndIf
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#MMIX
MMIX
MODULE Doors; IMPORT InOut;   TYPE State = (Closed, Open); TYPE List = ARRAY [1 .. 100] OF State;   VAR Doors: List; I, J: CARDINAL;   BEGIN FOR I := 1 TO 100 DO FOR J := 1 TO 100 DO IF J MOD I = 0 THEN IF Doors[J] = Closed THEN Doors[J] := Open ELSE Doors[J] := Closed END END END END;   FOR I := 1 TO 100 DO InOut.WriteCard(I, 3); InOut.WriteString(' is ');   IF Doors[I] = Closed THEN InOut.WriteString('Closed.') ELSE InOut.WriteString('Open.') END;   InOut.WriteLn END END Doors.
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#XSLT
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" /> <xsl:template match="/"> <!-- replace the root of the incoming document with our own model --> <xsl:element name="root"> <xsl:element name="element"> <xsl:text>Some text here</xsl:text> </xsl:element> </xsl:element> </xsl:template> </xsl:stylesheet>
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Delphi
Delphi
  program Write_language_name_in_3D_ASCII;   {$APPTYPE CONSOLE}   uses System.SysUtils;   const z: TArray<char> = [' ', ' ', '_', '/']; f: TArray<TArray<Cardinal>> = [[87381, 87381, 87381, 87381, 87381, 87381, 87381], [349525, 375733, 742837, 742837, 375733, 349525, 349525], [742741, 768853, 742837, 742837, 768853, 349525, 349525], [349525, 375733, 742741, 742741, 375733, 349525, 349525], [349621, 375733, 742837, 742837, 375733, 349525, 349525], [349525, 375637, 768949, 742741, 375733, 349525, 349525], [351157, 374101, 768949, 374101, 374101, 349525, 349525], [349525, 375733, 742837, 742837, 375733, 349621, 351157], [742741, 768853, 742837, 742837, 742837, 349525, 349525], [181, 85, 181, 181, 181, 85, 85], [1461, 1365, 1461, 1461, 1461, 1461, 2901], [742741, 744277, 767317, 744277, 742837, 349525, 349525], [181, 181, 181, 181, 181, 85, 85], [1431655765, 3149249365, 3042661813, 3042661813, 3042661813, 1431655765, 1431655765], [349525, 768853, 742837, 742837, 742837, 349525, 349525], [349525, 375637, 742837, 742837, 375637, 349525, 349525], [349525, 768853, 742837, 742837, 768853, 742741, 742741], [349525, 375733, 742837, 742837, 375733, 349621, 349621], [349525, 744373, 767317, 742741, 742741, 349525, 349525], [349525, 375733, 767317, 351157, 768853, 349525, 349525], [374101, 768949, 374101, 374101, 351157, 349525, 349525], [349525, 742837, 742837, 742837, 375733, 349525, 349525], [5592405, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405], [366503875925, 778827027893, 778827027893, 392374737749, 368114513237, 366503875925, 366503875925], [349525, 742837, 375637, 742837, 742837, 349525, 349525], [349525, 742837, 742837, 742837, 375733, 349621, 375637], [349525, 768949, 351061, 374101, 768949, 349525, 349525], [375637, 742837, 768949, 742837, 742837, 349525, 349525], [768853, 742837, 768853, 742837, 768853, 349525, 349525], [375733, 742741, 742741, 742741, 375733, 349525, 349525], [192213, 185709, 185709, 185709, 192213, 87381, 87381], [1817525, 1791317, 1817429, 1791317, 1817525, 1398101, 1398101], [768949, 742741, 768853, 742741, 742741, 349525, 349525], [375733, 742741, 744373, 742837, 375733, 349525, 349525], [742837, 742837, 768949, 742837, 742837, 349525, 349525], [48053, 23381, 23381, 23381, 48053, 21845, 21845], [349621, 349621, 349621, 742837, 375637, 349525, 349525], [742837, 744277, 767317, 744277, 742837, 349525, 349525], [742741, 742741, 742741, 742741, 768949, 349525, 349525], [11883957, 12278709, 11908533, 11883957, 11883957, 5592405, 5592405], [11883957, 12277173, 11908533, 11885493, 11883957, 5592405, 5592405], [375637, 742837, 742837, 742837, 375637, 349525, 349525], [768853, 742837, 768853, 742741, 742741, 349525, 349525], [6010197, 11885397, 11909973, 11885397, 6010293, 5592405, 5592405], [768853, 742837, 768853, 742837, 742837, 349525, 349525], [375733, 742741, 375637, 349621, 768853, 349525, 349525], [12303285, 5616981, 5616981, 5616981, 5616981, 5592405, 5592405], [742837, 742837, 742837, 742837, 375637, 349525, 349525], [11883957, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405], [3042268597, 3042268597, 3042661813, 1532713813, 1437971797, 1431655765, 1431655765], [11883957, 5987157, 5616981, 5987157, 11883957, 5592405, 5592405], [11883957, 5987157, 5616981, 5616981, 5616981, 5592405, 5592405], [12303285, 5593941, 5616981, 5985621, 12303285, 5592405, 5592405]];   function ReverseString(s: string): string; var i, len: integer; begin len := s.Length; SetLength(Result, len); for i := 1 to len do Result[len - i + 1] := s[i]; end;   procedure F5(s: ansistring); begin var o: TArray<TStringBuilder>; SetLength(o, 7); for var i := 0 to High(o) do o[i] := TStringBuilder.Create;   var l := length(s); for var i := 1 to l do begin var c: Integer := ord(s[i]); if c in [65..90] then c := c - 39 else if c in [97..122] then c := c - 97 else c := -1;   inc(c); var d: TArray<Cardinal> := f[c]; for var j := 0 to 6 do begin var b := TStringBuilder.Create; var v := d[j];   while v > 0 do begin b.Append(z[Trunc(v and 3)]); v := v shr 2; end; o[j].Append(ReverseString(b.ToString)); b.Free; end; end; for var i := 0 to 6 do begin for var j := 0 to 6 - i do write(' '); writeln(o[i].ToString); end;   for var i := 0 to High(o) do o[i].Free; end;   begin F5('Delphi'); F5('Thanks Java'); F5('guy'); readln; end.
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#Gambas
Gambas
sWindow As New String[4] '________________________ Public Sub Form_Open()   Manipulate   End '________________________ Public Sub Manipulate() Dim siDelay As Short = 2   Me.Show Print "Show" Wait siDelay   sWindow[0] = Me.Width sWindow[1] = Me.Height sWindow[2] = Me.X sWindow[3] = Me.y   Me.Hide Print "Hidden" CompareWindow Wait siDelay   Me.Show Print "Show" CompareWindow Wait siDelay   Me.Minimized = True Print "Minimized" CompareWindow Wait siDelay   Me.Show Print "Show" CompareWindow Wait siDelay   Me.Maximized = True Print "Maximized" CompareWindow Wait siDelay   Me.Maximized = False Print "Not Maximized" CompareWindow Wait siDelay   Me.Height = 200 Me.Width = 300 Print "Resized" CompareWindow Wait siDelay   Me.x = 10 Me.Y = 10 Print "Moved" CompareWindow Wait siDelay   Me.Close   End '________________________ Public Sub CompareWindow() Dim sNewWindow As New String[4] Dim siCount As Short Dim bMatch As Boolean = True   sNewWindow[0] = Me.Width sNewWindow[1] = Me.Height sNewWindow[2] = Me.X sNewWindow[3] = Me.y   For siCount = 0 To 3 If sWindow[siCount] <> sNewWindow[siCount] Then bMatch = False Next   If bMatch Then Print "Windows identities match the original window size" Else Print "Windows identities DONOT match the original window size" End If   End
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#BaCon
BaCon
  '--- added a flush to exit cleanly PRAGMA LDFLAGS `pkg-config --cflags --libs x11` PRAGMA INCLUDE <X11/Xlib.h> PRAGMA INCLUDE <X11/Xutil.h>   OPTION PARSE FALSE   '---XLIB is so ugly ALIAS XNextEvent TO EVENT ALIAS XOpenDisplay TO DISPLAY ALIAS DefaultScreen TO SCREEN ALIAS XCreateSimpleWindow TO CREATE ALIAS XCloseDisplay TO CLOSE_DISPLAY ALIAS XSelectInput TO EVENT_TYPE ALIAS XMapWindow TO MAP_EVENT ALIAS XFillRectangle TO FILL_RECTANGLE ALIAS XDrawString TO DRAW_STRING ALIAS XFlush TO FLUSH     '---pointer to X Display structure DECLARE d TYPE Display*   '---pointer to the newly created window 'DECLARE w TYPE WINDOW   '---pointer to the XEvent DECLARE e TYPE XEvent   DECLARE msg TYPE char*   '--- number of screen to place the window on DECLARE s TYPE int       msg = "Hello, World!"     d = DISPLAY(NULL) IF d == NULL THEN EPRINT "Cannot open display" FORMAT "%s%s\n" END END IF   s = SCREEN(d) w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))   EVENT_TYPE(d, w, ExposureMask | KeyPressMask) MAP_EVENT(d, w)   WHILE (1) EVENT(d, &e) IF e.type == Expose THEN FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10) DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg)) END IF IF e.type == KeyPress THEN BREAK END IF WEND FLUSH(d) CLOSE_DISPLAY(d)
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#C
C
#include <X11/Xlib.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   int main(void) { Display *d; Window w; XEvent e; const char *msg = "Hello, World!"; int s;   d = XOpenDisplay(NULL); if (d == NULL) { fprintf(stderr, "Cannot open display\n"); exit(1); }   s = DefaultScreen(d); w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 100, 1, BlackPixel(d, s), WhitePixel(d, s)); XSelectInput(d, w, ExposureMask | KeyPressMask); XMapWindow(d, w);   while (1) { XNextEvent(d, &e); if (e.type == Expose) { XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10); XDrawString(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg)); } if (e.type == KeyPress) break; }   XCloseDisplay(d); return 0; }
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#F.23
F#
  // Wilson primes. Nigel Galloway: July 31st., 2021 let rec fN g=function n when n<2I->g |n->fN(n*g)(n-1I) let fG (n:int)(p:int)=let g,p=bigint n,bigint p in (((fN 1I (g-1I))*(fN 1I (p-g))-(-1I)**n)%(p*p))=0I [1..11]|>List.iter(fun n->printf "%2d -> " n; let fG=fG n in pCache|>Seq.skipWhile((>)n)|>Seq.takeWhile((>)11000)|>Seq.filter fG|>Seq.iter(printf "%d "); printfn "")  
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#ALGOL_68
ALGOL 68
PROGRAM firstgtk CONTEXT VOID USE standard BEGIN MODE GDATA = REF BITS; MODE GUINT = BITS; MODE GSIZE = BITS; MODE GTYPE = GSIZE; MODE GTYPECLASS = STRUCT(GTYPE g type); MODE GTYPEINSTANCE = STRUCT(REF GTYPECLASS g class); MODE GTKWIDGETPRIVATE = REF BITS;   MODE GOBJECT = STRUCT( GTYPEINSTANCE g type instance, GUINT ref count, REF GDATA qdata);   MODE GTKWIDGET = STRUCT( GOBJECT parent instance, REF GTKWIDGETPRIVATE priv);   PROC(REF INT,REF CCHARPTRPTR)VOID gtk init = ALIEN "GTK_INIT" "#define GTK_INIT(argc,argv) gtk_init(argc,argv)"; PROC(INT)REF GTKWIDGET gtk window new = ALIEN "GTK_WINDOW_NEW" "#define GTK_WINDOW_NEW(type) (void *)gtk_window_new(type)"; PROC(REF GTKWIDGET)VOID gtk widget show = ALIEN "GTK_WIDGET_SHOW" "#define GTK_WIDGET_SHOW(widget) gtk_widget_show((void *)widget)"; PROC gtk main = VOID: CODE "gtk_main();";   INT gtk window toplevel = 0; FILE argf; REF GTKWIDGET window;   open(argf,"",arg channel); gtk init(argc,argv); window:=gtk window new(gtk window toplevel); gtk widget show(window); gtk main END FINISH
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#J
J
require'web/gethttp'   unixdict=:verb define if. _1 -: fread 'unixdict.txt' do. (gethttp 'http://www.puzzlers.org/pub/wordlists/unixdict.txt') fwrite 'unixdict.txt' end. fread 'unixdict.txt' )   words=:verb define (#~ 1 - 0&e.@e.&'abcdefghijklmnopqrstuvwxyz'@>) (#~ [: (2&< * 10&>:) #@>) <;._2 unixdict'' )   dirs=: 10#.0 0-.~>,{,~<i:1 lims=: _10+,"2 +/&>/"1 (0~:i:4)#>,{,~<<"1]1 10 1 +i."0]10*i:_1 dnms=: ;:'nw north ne west east sw south se'   genpuz=:verb define words=. words'' fill=. 'ROSETTACODE' grid=. ,10 10$' ' inds=. ,i.10 10 patience=. -:#words key=. i.0 0 inuse=. i.0 2 while. (26>#key)+.0<cap=. (+/' '=grid)-#fill do. word=. >({~ ?@#) words dir=. ?@#dirs offs=. (inds#~(#word)<:inds{dir{lims)+/(i.#word)*/dir{dirs cool=. ' '=offs{grid sel=. */"1 cool+.(offs{grid)="1 word offs=. (sel*cap>:+/"1 cool)#offs if. (#offs) do. off=. ({~ ?@#) offs loc=. ({.off),dir if. -. loc e. inuse do. inuse=. inuse,loc grid=. word off} grid patience=. patience+1 key=. /:~ key,' ',(10{.word),(3":1+10 10#:{.off),' ',dir{::dnms end. else. NB. grr... if. 0 > patience=. patience-1 do. inuse=.i.0 2 key=.i.0 0 grid=. ,10 10$' ' patience=. -:#words end. end. end. puz=. (_23{.":i.10),' ',1j1#"1(":i.10 1),.' ',.10 10$fill (I.grid=' ')} grid puz,' ',1 1}._1 _1}.":((</.~ <.) i.@# * 3%#)key )
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Batch_File
Batch File
@echo off   set "input=Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur!" rem call the function (the second parameter is the line width) call :wrap "%input%" 40 echo( call :wrap "%input%" 70 pause>nul exit /b 0 :: The procedure :wrap set "line=" set "tmp_str=%~1" set /a "width=%2", "width-=1"   :proc_loop rem check if we are done already if "%tmp_str%"=="" ( setlocal enabledelayedexpansion if defined line echo(!line! endlocal & goto :EOF ) rem not yet done, so take a word and process it for /f "tokens=1,* delims= " %%A in ("%tmp_str%") do ( set "word=%%A" set "tmp_str=%%B"   setlocal enabledelayedexpansion if "!line!"=="" (set "testline=!word!") else (set "testline=!line! !word!") if "!testline:~%width%,1!" == "" ( set "line=!testline!" ) else ( echo(!line! set "line=!word!" ) ) endlocal & set "line=%line%" goto proc_loop
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Phix
Phix
with javascript_semantics sequence words = unix_dict() function right_length(string word, integer l) return length(word)=l end function function one_away(string a, b) return sum(sq_ne(a,b))=1 end function function dca(sequence s, n) return append(deep_copy(s),n) end function procedure word_ladder(string a, b) sequence poss = filter(words,right_length,length(a)), todo = {{a}}, curr -- aka todo[1], word chain starting from a while length(todo) do {curr,todo} = {todo[1],todo[2..$]} sequence next = filter(poss,one_away,curr[$]) if find(b,next) then printf(1,"%s\n",{join(append(deep_copy(curr),b),"->")}) return end if poss = filter(poss,"out",next) todo &= apply(true,dca,{{curr},next}) end while printf(1,"%s into %s cannot be done\n",{a,b}) end procedure word_ladder("boy","man") word_ladder("girl","lady") word_ladder("john","jane") word_ladder("child","adult")
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#JavaScript
JavaScript
(() => { "use strict";   // ------------------- WORD WHEEL --------------------   // gridWords :: [String] -> [String] -> [String] const gridWords = grid => lexemes => { const wheel = sort(toLower(grid.join(""))), wSet = new Set(wheel), mid = wheel[4];   return lexemes.filter(w => { const cs = [...w];   return 2 < cs.length && cs.every( c => wSet.has(c) ) && cs.some(x => mid === x) && ( wheelFit(wheel, cs) ); }); };     // wheelFit :: [Char] -> [Char] -> Bool const wheelFit = (wheel, word) => { const go = (ws, cs) => 0 === cs.length ? ( true ) : 0 === ws.length ? ( false ) : ws[0] === cs[0] ? ( go(ws.slice(1), cs.slice(1)) ) : go(ws.slice(1), cs);   return go(wheel, sort(word)); };     // ---------------------- TEST ----------------------- // main :: IO () const main = () => gridWords(["NDE", "OKG", "ELW"])( lines(readFile("unixdict.txt")) ) .join("\n");     // ---------------- GENERIC FUNCTIONS ----------------   // lines :: String -> [String] const lines = s => // A list of strings derived from a single string // which is delimited by \n or by \r\n or \r. Boolean(s.length) ? ( s.split(/\r\n|\n|\r/u) ) : [];     // readFile :: FilePath -> IO String const readFile = fp => { // The contents of a text file at the // given file path. const e = $(), ns = $.NSString .stringWithContentsOfFileEncodingError( $(fp).stringByStandardizingPath, $.NSUTF8StringEncoding, e );   return ObjC.unwrap( ns.isNil() ? ( e.localizedDescription ) : ns ); };     // sort :: Ord a => [a] -> [a] const sort = xs => Array.from(xs).sort();     // toLower :: String -> String const toLower = s => // Lower-case version of string. s.toLocaleLowerCase();     // MAIN --- return main(); })();
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#PicoLisp
PicoLisp
(scl 2)   (de plot (Img X Y C) (set (nth Img (*/ Y 1.0) (*/ X 1.0)) (- 100 C)) )   (de ipart (X) (* 1.0 (/ X 1.0)) )   (de iround (X) (ipart (+ X 0.5)) )   (de fpart (X) (% X 1.0) )   (de rfpart (X) (- 1.0 (fpart X)) )   (de xiaolin (Img X1 Y1 X2 Y2) (let (DX (- X2 X1) DY (- Y2 Y1)) (use (Grad Xend Yend Xgap Xpxl1 Ypxl1 Xpxl2 Ypxl2 Intery) (when (> (abs DY) (abs DX)) (xchg 'X1 'Y1 'X2 'Y2) ) (when (> X1 X2) (xchg 'X1 'X2 'Y1 'Y2) ) (setq Grad (*/ DY 1.0 DX) Xend (iround X1) Yend (+ Y1 (*/ Grad (- Xend X1) 1.0)) Xgap (rfpart (+ X1 0.5)) Xpxl1 Xend Ypxl1 (ipart Yend) ) (plot Img Xpxl1 Ypxl1 (*/ (rfpart Yend) Xgap 1.0)) (plot Img Xpxl1 (+ 1.0 Ypxl1) (*/ (fpart Yend) Xgap 1.0)) (setq Intery (+ Yend Grad) Xend (iround X2) Yend (+ Y2 (*/ Grad (- Xend X2) 1.0)) Xgap (fpart (+ X2 0.5)) Xpxl2 Xend Ypxl2 (ipart Yend) ) (plot Img Xpxl2 Ypxl2 (*/ (rfpart Yend) Xgap 1.0)) (plot Img Xpxl2 (+ 1.0 Ypxl2) (*/ (fpart Yend) Xgap 1.0)) (for (X (+ Xpxl1 1.0) (>= (- Xpxl2 1.0) X) (+ X 1.0)) (plot Img X (ipart Intery) (rfpart Intery)) (plot Img X (+ 1.0 (ipart Intery)) (fpart Intery)) (inc 'Intery Grad) ) ) ) )   (let Img (make (do 90 (link (need 120 99)))) # Create image 120 x 90 (xiaolin Img 10.0 10.0 110.0 80.0) # Draw lines (xiaolin Img 10.0 10.0 110.0 45.0) (xiaolin Img 10.0 80.0 110.0 45.0) (xiaolin Img 10.0 80.0 110.0 10.0) (out "img.pgm" # Write to bitmap file (prinl "P2") (prinl 120 " " 90) (prinl 100) (for Y Img (apply printsp Y)) ) )
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#PureBasic
PureBasic
Macro PlotB(x, y, Color, b) Plot(x, y, RGB(Red(Color) * (b), Green(Color) * (b), Blue(Color) * (b))) EndMacro   Procedure.f fracPart(x.f) ProcedureReturn x - Int(x) EndProcedure   Procedure.f invFracPart(x.f) ProcedureReturn 1.0 - fracPart(x) EndProcedure   Procedure drawAntiAliasedLine(x1.f, y1.f, x2.f, y2.f, color) Protected.f dx, dy, xend, yend, grad, yf, xgap, ix1, iy1, ix2, iy2 Protected x   dx = x2 - x1 dy = y2 - y1 If Abs(dx) < Abs(dy) Swap x1, y1 Swap x2, y2 Swap dx, dy EndIf   If x2 < x1 Swap x1, x2 Swap y1, y2 EndIf   grad = dy / dx   ;handle first endpoint xend = Round(x1, #pb_round_nearest) yend = y1 + grad * (xend - x1) xgap = invFracPart(x1 + 0.5) ix1 = xend ;this will be used in the MAIN loop iy1 = Int(yend) PlotB(ix1, iy1, color, invFracPart(yend) * xgap) PlotB(ix1, iy1 + 1, color, fracPart(yend) * xgap) yf = yend + grad ;first y-intersection for the MAIN loop   ;handle second endpoint xend = Round(x2, #pb_round_nearest) yend = y2 + grad * (xend - x2) xgap = fracPart(x2 + 0.5) ix2 = xend ;this will be used in the MAIN loop iy2 = Int(yend) PlotB(ix2, iy2, color, invFracPart(yend) * xgap) PlotB(ix2, iy2 + 1, color, fracPart(yend) * xgap) ;MAIN loop For x = ix1 + 1 To ix2 - 1 PlotB(x, Int(yf), color, invFracPart(yf)) PlotB(x, Int(yf) + 1, color, fracPart(yf)) yf + grad Next EndProcedure   Define w = 200, h = 200, img = 1 CreateImage(img, w, h) ;img is internal id of the image   OpenWindow(0, 0, 0, w, h,"Xiaolin Wu's line algorithm", #PB_Window_SystemMenu)   StartDrawing(ImageOutput(img)) drawAntiAliasedLine(80,20, 130,80, RGB(255, 0, 0)) StopDrawing()   ImageGadget(0, 0, 0, w, h, ImageID(img))   Define event Repeat event = WaitWindowEvent() Until event = #PB_Event_CloseWindow
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Go
Go
package main   import ( "encoding/xml" "fmt" )   // Function required by task description. func xRemarks(r CharacterRemarks) (string, error) { b, err := xml.MarshalIndent(r, "", " ") return string(b), err }   // Task description allows the function to take "a single mapping..." // This data structure represents a mapping. type CharacterRemarks struct { Character []crm }   type crm struct { Name string `xml:"name,attr"` Remark string `xml:",chardata"` }   func main() { x, err := xRemarks(CharacterRemarks{[]crm{ {`April`, `Bubbly: I'm > Tam and <= Emily`}, {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`}, {`Emily`, `Short & shrift`}, }}) if err != nil { x = err.Error() } fmt.Println(x) }
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Go
Go
package main   import ( "encoding/xml" "fmt" )   const XML_Data = ` <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> `   type Students struct { Student []Student }   type Student struct { Name string `xml:",attr"` // Gender string `xml:",attr"` // DateOfBirth string `xml:",attr"` // Pets []Pet `xml:"Pet"` }   type Pet struct { Type string `xml:",attr"` Name string `xml:",attr"` }   // xml.Unmarshal quietly skips well formed input with no corresponding // member in the output data structure. With Gender, DateOfBirth, and // Pets commented out of the Student struct, as above, Student contains // only Name, and this is the only value extracted from the input XML_Data. func main() { var data Students err := xml.Unmarshal([]byte(XML_Data), &data) if err != nil { fmt.Println(err) return } for _, s := range data.Student { fmt.Println(s.Name) } }
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#TI-83_BASIC
TI-83 BASIC
{1,2,3,4,5}→L1
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Yabasic
Yabasic
data "12", "13", "14", "23", "24", "34"   dim game$(6)   for i = 1 to 6 : read game$(i) : next   result$ = "000000"     sub ParseInt(number$, base) local x, i, pot, digits   digits = len(number$)   for i = digits to 1 step -1 x = x + base^pot * dec(mid$(number$, i, 1)) pot = pot + 1 next   return x end sub     sub Format$(decimal, base) local cociente, i, j, conv$   repeat cociente = int(decimal / base) conv$ = str$(mod(decimal, base)) + conv$ decimal = cociente i = i + 1 until(cociente = 0)   return conv$ end sub     sub nextResult() if result$ = "222222" return false res = ParseInt(result$, 3) result$ = Format$(res+1, 3) while(len(result$) < 6) result$ = "0" + result$ wend return true end sub     sub Sort(array()) local n, i, t, sw   n = arraysize(array(), 1)   repeat sw = false for i = 0 to n - 1 if array(i) > array(i + 1) then sw = true t = array(i) array(i) = array(i + 1) array(i + 1) = t end if next until(not sw) end sub     dim points(4, 10)   sub compute() local records(4), i, t   for i = 1 to arraysize(game$(), 1) switch mid$(result$, i, 1) case "2": t = val(mid$(game$(i), 1, 1)) records(t) = records(t) + 3 break case "1": t = val(mid$(game$(i), 1, 1)) records(t) = records(t) + 1 t = val(mid$(game$(i), 2, 1)) records(t) = records(t) + 1 break case "0": t = val(mid$(game$(i), 2, 1)) records(t) = records(t) + 3 break end switch next Sort(records()) for i = 1 to 4 points(i, records(i)) = points(i, records(i)) + 1 next if not nextResult() return false return true end sub   repeat until(not compute())   print "POINTS 0 1 2 3 4 5 6 7 8 9" print "-------------------------------------------------------------"   dim place$(4)   data "1st", "2nd", "3rd", "4th" for i = 1 to 4 : read place$(i) : next   for i = 1 to 4 print place$(i), " place "; for j = 0 to 9 print points(5 - i, j) using "%-4.0f"; next print next
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#zkl
zkl
combos :=Utils.Helpers.pickNFrom(2,T(0,1,2,3)); // ( (0,1),(0,2) ... ) scoring:=T(0,1,3); histo  :=(0).pump(4,List().write,(0).pump(10,List().write,0).copy); //[4][10] of zeros   foreach r0,r1,r2,r3,r4,r5 in ([0..2],[0..2],[0..2],[0..2],[0..2],[0..2]){ s:=L(0,0,0,0); foreach i,r in (T(r0,r1,r2,r3,r4,r5).enumerate()){ g:=combos[i]; s[g[0]]+=scoring[r]; s[g[1]]+=scoring[2 - r]; } foreach h,v in (histo.zip(s.sort())){ h[v]+=1; } } foreach h in (histo.reverse()){ println(h.apply("%3d ".fmt).concat()) }
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Python
Python
import itertools def writedat(filename, x, y, xprecision=3, yprecision=5): with open(filename,'w') as f: for a, b in itertools.izip(x, y): print >> f, "%.*g\t%.*g" % (xprecision, a, yprecision, b)
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#R
R
writexy <- function(file, x, y, xprecision=3, yprecision=3) { fx <- formatC(x, digits=xprecision, format="g", flag="-") fy <- formatC(y, digits=yprecision, format="g", flag="-") dfr <- data.frame(fx, fy) write.table(dfr, file=file, sep="\t", row.names=F, col.names=F, quote=F) }   x <- c(1, 2, 3, 1e11) y <- sqrt(x) writexy("test.txt", x, y, yp=5)
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Modula-2
Modula-2
MODULE Doors; IMPORT InOut;   TYPE State = (Closed, Open); TYPE List = ARRAY [1 .. 100] OF State;   VAR Doors: List; I, J: CARDINAL;   BEGIN FOR I := 1 TO 100 DO FOR J := 1 TO 100 DO IF J MOD I = 0 THEN IF Doors[J] = Closed THEN Doors[J] := Open ELSE Doors[J] := Closed END END END END;   FOR I := 1 TO 100 DO InOut.WriteCard(I, 3); InOut.WriteString(' is ');   IF Doors[I] = Closed THEN InOut.WriteString('Closed.') ELSE InOut.WriteString('Open.') END;   InOut.WriteLn END END Doors.
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Elixir
Elixir
defmodule ASCII3D do def decode(str) do Regex.scan(~r/(\d+)(\D+)/, str) |> Enum.map_join(fn[_,n,s] -> String.duplicate(s, String.to_integer(n)) end) |> String.replace("B", "\\") # Backslash end end   data = "1 12_4 2_1\n1/B2 9_1B2 1/2B 3 2_18 2_1\nB2 B8_1/ 3 B2 1/B_B4 2_6 2_2 1/B_B6 4_1 3 B7_3 4 B2/_2 1/2B_1_2 1/B_B B2/_4 1/ 3_1B\n 2 B2 6_1B3 3 B2 1/B2 B1/_/B_B3/ 2 1/2B 1 /B B2_1/ 2 3 B5_1/4 6 B3 1B/_/2 /1_2 6 B1\n3 3 B10_6 B3 3 /2B_1_6 B1 4 2 B11_2B 1B_B2 B1_B 3 /1B/_/B_B2 B B_B1\n6 1B/11_1/3 B/_/2 3 B/_/" IO.puts ASCII3D.decode(data)
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Erlang
Erlang
%% Implemented by Arjun Sunel -module(three_d). -export([main/0]).   main() -> io:format(" _____ _ \n| ___| | | \n| |__ _ __| | __ _ _ __ __ _ \n| __| '__| |/ _` | '_ \\ / _` |\n| |__| | | | (_| | | | | (_| |\n|____/_| |_|\\__,_|_| |_|\\__, |\n __/ |\n |___/\n").  
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#Go
Go
package main   import ( "github.com/gotk3/gotk3/gtk" "log" "time" )   func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } }   func main() { gtk.Init(nil)   window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetResizable(true) window.SetTitle("Window management") window.SetBorderWidth(5) window.Connect("destroy", func() { gtk.MainQuit() })   stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10) check(err, "Unable to create stack box:")   bmax, err := gtk.ButtonNewWithLabel("Maximize") check(err, "Unable to create maximize button:") bmax.Connect("clicked", func() { window.Maximize() })   bunmax, err := gtk.ButtonNewWithLabel("Unmaximize") check(err, "Unable to create unmaximize button:") bunmax.Connect("clicked", func() { window.Unmaximize() })   bicon, err := gtk.ButtonNewWithLabel("Iconize") check(err, "Unable to create iconize button:") bicon.Connect("clicked", func() { window.Iconify() })   bdeicon, err := gtk.ButtonNewWithLabel("Deiconize") check(err, "Unable to create deiconize button:") bdeicon.Connect("clicked", func() { window.Deiconify() })   bhide, err := gtk.ButtonNewWithLabel("Hide") check(err, "Unable to create hide button:") bhide.Connect("clicked", func() { // not working on Ubuntu 16.04 but window 'dims' after a few seconds window.Hide() time.Sleep(10 * time.Second) window.Show() })   bshow, err := gtk.ButtonNewWithLabel("Show") check(err, "Unable to create show button:") bshow.Connect("clicked", func() { window.Show() })   bmove, err := gtk.ButtonNewWithLabel("Move") check(err, "Unable to create move button:") isShifted := false bmove.Connect("clicked", func() { w, h := window.GetSize() if isShifted { window.Move(w-10, h-10) } else { window.Move(w+10, h+10) } isShifted = !isShifted })   bquit, err := gtk.ButtonNewWithLabel("Quit") check(err, "Unable to create quit button:") bquit.Connect("clicked", func() { window.Destroy() })   stackbox.PackStart(bmax, true, true, 0) stackbox.PackStart(bunmax, true, true, 0) stackbox.PackStart(bicon, true, true, 0) stackbox.PackStart(bdeicon, true, true, 0) stackbox.PackStart(bhide, true, true, 0) stackbox.PackStart(bshow, true, true, 0) stackbox.PackStart(bmove, true, true, 0) stackbox.PackStart(bquit, true, true, 0)   window.Add(stackbox) window.ShowAll() gtk.Main() }
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#11l
11l
V allstates = ‘Ht. ’ V head = allstates[0] V tail = allstates[1] V conductor = allstates[2] V empty = allstates[3]   V w = |‘tH......... . . ... . . Ht.. ......’   T WW [[Char]] world Int w Int h F (world, w, h) .world = world .w = w .h = h   F readfile(f) V world = f.map(row -> row.rtrim(Array[Char]("\r\n"))) V height = world.len V width = max(world.map(row -> row.len)) V nonrow = [‘ ’(‘ ’ * width)‘ ’] V world2 = nonrow [+] world.map(row -> ‘ ’String(row).ljust(@width)‘ ’) [+] nonrow V world3 = world2.map(row -> Array(row)) R WW(world3, width, height)   F newcell(currentworld, x, y) V istate = currentworld[y][x] assert(istate C :allstates, ‘Wireworld cell set to unknown value "#."’.format(istate)) V ostate = :empty I istate == :head ostate = :tail E I istate == :tail ostate = :conductor E I istate == :empty ostate = :empty E V n = sum([(-1, -1), (-1, +0), (-1, +1), (+0, -1), (+0, +1), (+1, -1), (+1, +0), (+1, +1)].map((dx, dy) -> Int(@currentworld[@y + dy][@x + dx] == :head))) ostate = I n C 1..2 {:head} E :conductor R ostate   F nextgen(ww) V (world, width, height) = ww V newworld = copy(world) L(x) 1 .. width L(y) 1 .. height newworld[y][x] = newcell(world, x, y) R WW(newworld, width, height)   F world2string(ww) R ww.world[1 .< (len)-1].map(row -> (row[1 .< (len)-1]).join(‘’).rtrim((‘ ’, "\t", "\r", "\n"))).join("\n")   V ww = readfile(w.split("\n"))   L(gen) 10 print(("\n#3 ".format(gen))‘’(‘=’ * (ww.w - 4))"\n") print(world2string(ww)) ww = nextgen(ww)
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Ada
Ada
with Ada.Text_IO;   procedure Wieferich_Primes is   function Is_Prime (V : Positive) return Boolean is D : Positive := 5; begin if V < 2 then return False; end if; if V mod 2 = 0 then return V = 2; end if; if V mod 3 = 0 then return V = 3; end if; while D * D <= V loop if V mod D = 0 then return False; end if; D := D + 2; end loop; return True; end Is_Prime;   function Is_Wieferich (N : Positive) return Boolean is Q : Natural := 1; begin if not Is_Prime (N) then return False; end if; for P in 2 .. N loop Q := (2 * Q) mod N**2; end loop; return Q = 1; end Is_Wieferich;   begin   Ada.Text_IO.Put_Line ("Wieferich primes below 5000:"); for N in 1 .. 4999 loop if Is_Wieferich (N) then Ada.Text_IO.Put_Line (N'Image); end if; end loop;   end Wieferich_Primes;
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#COBOL
COBOL
identification division. program-id. x11-hello. installation. cobc -x x11-hello.cob -lX11 remarks. Use of private data is likely not cross platform.   data division. working-storage section. 01 msg. 05 filler value z"S'up, Earth?". 01 msg-len usage binary-long value 12.   01 x-display usage pointer. 01 x-window usage binary-c-long.   *> GnuCOBOL does not evaluate C macros, need to peek at opaque *> data from Xlib.h *> some padding is added, due to this comment in the header *> "there is more to this structure, but it is private to Xlib" 01 x-display-private based. 05 x-ext-data usage pointer sync. 05 private1 usage pointer. 05 x-fd usage binary-long. 05 private2 usage binary-long. 05 proto-major-version usage binary-long. 05 proto-minor-version usage binary-long. 05 vendor usage pointer sync. 05 private3 usage pointer. 05 private4 usage pointer. 05 private5 usage pointer. 05 private6 usage binary-long. 05 allocator usage program-pointer sync. 05 byte-order usage binary-long. 05 bitmap-unit usage binary-long. 05 bitmap-pad usage binary-long. 05 bitmap-bit-order usage binary-long. 05 nformats usage binary-long. 05 screen-format usage pointer sync. 05 private8 usage binary-long. 05 x-release usage binary-long. 05 private9 usage pointer sync. 05 private10 usage pointer sync. 05 qlen usage binary-long. 05 last-request-read usage binary-c-long unsigned sync. 05 request usage binary-c-long unsigned sync. 05 private11 usage pointer sync. 05 private12 usage pointer. 05 private13 usage pointer. 05 private14 usage pointer. 05 max-request-size usage binary-long unsigned. 05 x-db usage pointer sync. 05 private15 usage program-pointer sync. 05 display-name usage pointer. 05 default-screen usage binary-long. 05 nscreens usage binary-long. 05 screens usage pointer sync. 05 motion-buffer usage binary-c-long unsigned. 05 private16 usage binary-c-long unsigned. 05 min-keycode usage binary-long. 05 max-keycode usage binary-long. 05 private17 usage pointer sync. 05 private18 usage pointer. 05 private19 usage binary-long. 05 x-defaults usage pointer sync. 05 filler pic x(256).   01 x-screen-private based. 05 scr-ext-data usage pointer sync. 05 display-back usage pointer. 05 root usage binary-c-long. 05 x-width usage binary-long. 05 x-height usage binary-long. 05 m-width usage binary-long. 05 m-height usage binary-long. 05 x-ndepths usage binary-long. 05 depths usage pointer sync. 05 root-depth usage binary-long. 05 root-visual usage pointer sync. 05 default-gc usage pointer. 05 cmap usage pointer. 05 white-pixel usage binary-c-long unsigned sync. 05 black-pixel usage binary-c-long unsigned. 05 max-maps usage binary-long. 05 min-maps usage binary-long. 05 backing-store usage binary-long. 05 save_unders usage binary-char. 05 root-input-mask usage binary-c-long sync. 05 filler pic x(256).   01 event. 05 e-type usage binary-long. 05 filler pic x(188). 05 filler pic x(256). 01 Expose constant as 12. 01 KeyPress constant as 2.   *> ExposureMask or-ed with KeyPressMask, from X.h 01 event-mask usage binary-c-long value 32769.   *> make the box around the message wide enough for the font 01 x-char-struct. 05 lbearing usage binary-short. 05 rbearing usage binary-short. 05 string-width usage binary-short. 05 ascent usage binary-short. 05 descent usage binary-short. 05 attributes usage binary-short unsigned. 01 font-direction usage binary-long. 01 font-ascent usage binary-long. 01 font-descent usage binary-long.   01 XGContext usage binary-c-long. 01 box-width usage binary-long. 01 box-height usage binary-long.   *> *************************************************************** procedure division.   call "XOpenDisplay" using by reference null returning x-display on exception display function module-id " Error: " "no XOpenDisplay linkage, requires libX11" upon syserr stop run returning 1 end-call if x-display equal null then display function module-id " Error: " "XOpenDisplay returned null" upon syserr stop run returning 1 end-if set address of x-display-private to x-display   if screens equal null then display function module-id " Error: " "XOpenDisplay associated screen null" upon syserr stop run returning 1 end-if set address of x-screen-private to screens   call "XCreateSimpleWindow" using by value x-display root 10 10 200 50 1 black-pixel white-pixel returning x-window call "XStoreName" using by value x-display x-window by reference msg   call "XSelectInput" using by value x-display x-window event-mask   call "XMapWindow" using by value x-display x-window   call "XGContextFromGC" using by value default-gc returning XGContext call "XQueryTextExtents" using by value x-display XGContext by reference msg by value msg-len by reference font-direction font-ascent font-descent x-char-struct compute box-width = string-width + 8 compute box-height = font-ascent + font-descent + 8   perform forever call "XNextEvent" using by value x-display by reference event if e-type equal Expose then call "XDrawRectangle" using by value x-display x-window default-gc 5 5 box-width box-height call "XDrawString" using by value x-display x-window default-gc 10 20 by reference msg by value msg-len end-if if e-type equal KeyPress then exit perform end-if end-perform   call "XCloseDisplay" using by value x-display   goback. end program x11-hello.
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#Factor
Factor
USING: formatting infix io kernel literals math math.functions math.primes math.ranges prettyprint sequences sequences.extras ;   << CONSTANT: limit 11,000 >>   CONSTANT: primes $[ limit primes-upto ]   CONSTANT: factorials $[ limit [1,b] 1 [ * ] accumulate* 1 prefix ]   : factorial ( n -- n! ) factorials nth ; inline   INFIX:: fn ( p n -- m ) factorial(n-1) * factorial(p-n) - -1**n ;   : wilson? ( p n -- ? ) [ fn ] keepd sq divisor? ; inline   : order ( n -- seq ) primes swap [ [ < ] curry drop-while ] keep [ wilson? ] curry filter ;   : order. ( n -- ) dup "%2d: " printf order [ pprint bl ] each nl ;   " n: Wilson primes\n--------------------" print 11 [1,b] [ order. ] each
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#FreeBASIC
FreeBASIC
#include "isprime.bas"   function is_wilson( n as uinteger, p as uinteger ) as boolean 'tests if p^2 divides (n-1)!(p-n)! - (-1)^n 'does NOT test the primality of p; do that first before you call this! 'using mods no big nums are required if p<n then return false dim as uinteger prod = 1, i, p2 = p^2 for i = 1 to n-1 prod = (prod*i) mod p2 next i for i = 1 to p-n prod = (prod*i) mod p2 next i prod = (p2 + prod - (-1)^n) mod p2 if prod = 0 then return true else return false end function   print "n: Wilson primes" print "--------------------" for n as uinteger = 1 to 11 print using "## ";n; for p as uinteger = 3 to 10099 step 2 if isprime(p) andalso is_wilson(n, p) then print p;" "; next p print next n  
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#Go
Go
package main   import ( "fmt" "math/big" "rcu" )   func main() { const LIMIT = 11000 primes := rcu.Primes(LIMIT) facts := make([]*big.Int, LIMIT) facts[0] = big.NewInt(1) for i := int64(1); i < LIMIT; i++ { facts[i] = new(big.Int) facts[i].Mul(facts[i-1], big.NewInt(i)) } sign := int64(1) f := new(big.Int) zero := new(big.Int) fmt.Println(" n: Wilson primes") fmt.Println("--------------------") for n := 1; n < 12; n++ { fmt.Printf("%2d: ", n) sign = -sign for _, p := range primes { if p < n { continue } f.Mul(facts[n-1], facts[p-n]) f.Sub(f, big.NewInt(sign)) p2 := int64(p * p) bp2 := big.NewInt(p2) if f.Rem(f, bp2).Cmp(zero) == 0 { fmt.Printf("%d ", p) } } fmt.Println() } }
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#AmigaBASIC
AmigaBASIC
WINDOW 2,"New Window"
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#AurelBasic
AurelBasic
WIN 0 0 400 300 "New Window"
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#AutoHotkey
AutoHotkey
Gui, Add, Text,, Hello Gui, Show
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Java
Java
import java.io.*; import static java.lang.String.format; import java.util.*;   public class WordSearch { static class Grid { int numAttempts; char[][] cells = new char[nRows][nCols]; List<String> solutions = new ArrayList<>(); }   final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}};   final static int nRows = 10; final static int nCols = 10; final static int gridSize = nRows * nCols; final static int minWords = 25;   final static Random rand = new Random();   public static void main(String[] args) { printResult(createWordSearch(readWords("unixdict.txt"))); }   static List<String> readWords(String filename) { int maxLen = Math.max(nRows, nCols);   List<String> words = new ArrayList<>(); try (Scanner sc = new Scanner(new FileReader(filename))) { while (sc.hasNext()) { String s = sc.next().trim().toLowerCase(); if (s.matches("^[a-z]{3," + maxLen + "}$")) words.add(s); } } catch (FileNotFoundException e) { System.out.println(e); } return words; }   static Grid createWordSearch(List<String> words) { Grid grid = null; int numAttempts = 0;   outer: while (++numAttempts < 100) { Collections.shuffle(words);   grid = new Grid(); int messageLen = placeMessage(grid, "Rosetta Code"); int target = gridSize - messageLen;   int cellsFilled = 0; for (String word : words) { cellsFilled += tryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.solutions.size() >= minWords) { grid.numAttempts = numAttempts; break outer; } else break; // grid is full but we didn't pack enough words, start over } } }   return grid; }   static int placeMessage(Grid grid, String msg) { msg = msg.toUpperCase().replaceAll("[^A-Z]", "");   int messageLen = msg.length(); if (messageLen > 0 && messageLen < gridSize) { int gapSize = gridSize / messageLen;   for (int i = 0; i < messageLen; i++) { int pos = i * gapSize + rand.nextInt(gapSize); grid.cells[pos / nCols][pos % nCols] = msg.charAt(i); } return messageLen; } return 0; }   static int tryPlaceWord(Grid grid, String word) { int randDir = rand.nextInt(dirs.length); int randPos = rand.nextInt(gridSize);   for (int dir = 0; dir < dirs.length; dir++) { dir = (dir + randDir) % dirs.length;   for (int pos = 0; pos < gridSize; pos++) { pos = (pos + randPos) % gridSize;   int lettersPlaced = tryLocation(grid, word, dir, pos); if (lettersPlaced > 0) return lettersPlaced; } } return 0; }   static int tryLocation(Grid grid, String word, int dir, int pos) {   int r = pos / nCols; int c = pos % nCols; int len = word.length();   // check bounds if ((dirs[dir][0] == 1 && (len + c) > nCols) || (dirs[dir][0] == -1 && (len - 1) > c) || (dirs[dir][1] == 1 && (len + r) > nRows) || (dirs[dir][1] == -1 && (len - 1) > r)) return 0;   int rr, cc, i, overlaps = 0;   // check cells for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i)) return 0; cc += dirs[dir][0]; rr += dirs[dir][1]; }   // place for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.cells[rr][cc] == word.charAt(i)) overlaps++; else grid.cells[rr][cc] = word.charAt(i);   if (i < len - 1) { cc += dirs[dir][0]; rr += dirs[dir][1]; } }   int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.solutions.add(format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)); }   return lettersPlaced; }   static void printResult(Grid grid) { if (grid == null || grid.numAttempts == 0) { System.out.println("No grid to display"); return; } int size = grid.solutions.size();   System.out.println("Attempts: " + grid.numAttempts); System.out.println("Number of words: " + size);   System.out.println("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { System.out.printf("%n%d ", r); for (int c = 0; c < nCols; c++) System.out.printf(" %c ", grid.cells[r][c]); }   System.out.println("\n");   for (int i = 0; i < size - 1; i += 2) { System.out.printf("%s  %s%n", grid.solutions.get(i), grid.solutions.get(i + 1)); } if (size % 2 == 1) System.out.println(grid.solutions.get(size - 1)); } }
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Bracmat
Bracmat
( str $ ( "In olden times when wishing still helped one, there lived a king " "whose daughters were all beautiful, but the youngest was so beautiful " "that the sun itself, which has seen so much, was astonished whenever " "it shone in her face. Close by the king's castle lay a great dark " "forest, and under an old lime tree in the forest was a well, and when " "the day was very warm, the king's child went out into the forest and " "sat down by the side of the cool fountain, and when she was bored she " "took a golden ball, and threw it up on high and caught it, and this " "ball was her favorite plaything." )  : ?Text & ( wrap = txt length line output q rem .  !arg:(?txt.?length) & :?output & whl ' ( @( str$!txt  :  ?line (" " %?lastword [?q " " ?rem&!q:~<!length) ) & !lastword " " !rem:?txt & !output !line \n:?output ) & str$(!output !txt) ) & out$(str$("72 columns:\n" wrap$(!Text.72))) & out$(str$("\n80 columns:\n" wrap$(!Text.80))) );
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>   /* nonsensical hyphens to make greedy wrapping method look bad */ const char *string = "In olden times when wishing still helped one, there lived a king " "whose daughters were all beautiful, but the youngest was so beautiful " "that the sun itself, which has seen so much, was astonished whenever " "it shone-in-her-face. Close-by-the-king's castle lay a great dark " "forest, and under an old lime-tree in the forest was a well, and when " "the day was very warm, the king's child went out into the forest and " "sat down by the side of the cool-fountain, and when she was bored she " "took a golden ball, and threw it up on high and caught it, and this " "ball was her favorite plaything.";   /* Each but the last of wrapped lines comes with some penalty as the square of the diff between line length and desired line length. If the line is longer than desired length, the penalty is multiplied by 100. This pretty much prohibits the wrapping routine from going over right margin. If is ok to exceed the margin just a little, something like 20 or 40 will do.   Knuth uses a per-paragraph penalty for line-breaking in TeX, which is-- unlike what I have here--probably bug-free. */   #define PENALTY_LONG 100 #define PENALTY_SHORT 1   typedef struct word_t { const char *s; int len; } *word;   word make_word_list(const char *s, int *n) { int max_n = 0; word words = 0;   *n = 0; while (1) { while (*s && isspace(*s)) s++; if (!*s) break;   if (*n >= max_n) { if (!(max_n *= 2)) max_n = 2; words = realloc(words, max_n * sizeof(*words)); } words[*n].s = s; while (*s && !isspace(*s)) s++; words[*n].len = s - words[*n].s; (*n) ++; }   return words; }   int greedy_wrap(word words, int count, int cols, int *breaks) { int score = 0, line, i, j, d;   i = j = line = 0; while (1) { if (i == count) { breaks[j++] = i; break; }   if (!line) { line = words[i++].len; continue; }   if (line + words[i].len < cols) { line += words[i++].len + 1; continue; }   breaks[j++] = i; if (i < count) { d = cols - line; if (d > 0) score += PENALTY_SHORT * d * d; else if (d < 0) score += PENALTY_LONG * d * d; }   line = 0; } breaks[j++] = 0;   return score; }   /* tries to make right margin more even; pretty sure there's an off-by-one bug here somewhere */ int balanced_wrap(word words, int count, int cols, int *breaks) { int *best = malloc(sizeof(int) * (count + 1));   /* do a greedy wrap to have some baseline score to work with, else we'll end up with O(2^N) behavior */ int best_score = greedy_wrap(words, count, cols, breaks);   void test_wrap(int line_no, int start, int score) { int line = 0, current_score = -1, d;   while (start <= count) { if (line) line ++; line += words[start++].len; d = cols - line; if (start < count || d < 0) { if (d > 0) current_score = score + PENALTY_SHORT * d * d; else current_score = score + PENALTY_LONG * d * d; } else { current_score = score; }   if (current_score >= best_score) { if (d <= 0) return; continue; }   best[line_no] = start; test_wrap(line_no + 1, start, current_score); } if (current_score >= 0 && current_score < best_score) { best_score = current_score; memcpy(breaks, best, sizeof(int) * (line_no)); } } test_wrap(0, 0, 0); free(best);   return best_score; }   void show_wrap(word list, int count, int *breaks) { int i, j; for (i = j = 0; i < count && breaks[i]; i++) { while (j < breaks[i]) { printf("%.*s", list[j].len, list[j].s); if (j < breaks[i] - 1) putchar(' '); j++; } if (breaks[i]) putchar('\n'); } }   int main(void) { int len, score, cols; word list = make_word_list(string, &len); int *breaks = malloc(sizeof(int) * (len + 1));   cols = 80; score = greedy_wrap(list, len, cols, breaks); printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score); show_wrap(list, len, breaks);   score = balanced_wrap(list, len, cols, breaks); printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score); show_wrap(list, len, breaks);     cols = 32; score = greedy_wrap(list, len, cols, breaks); printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score); show_wrap(list, len, breaks);   score = balanced_wrap(list, len, cols, breaks); printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score); show_wrap(list, len, breaks);   return 0; }
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
import os,sys,zlib,urllib.request   def h ( str,x=9 ): for c in str : x = ( x*33 + ord( c )) & 0xffffffffff return x   def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try  : return eval( zlib.decompress( open( n,'rb' ).read())) except : pass s = func( *param ) open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' ))) return s   dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt' read_url = lambda url  : urllib.request.urlopen( url ).read() load_dico = lambda url  : tuple( cache( read_url,url ).split( b'\n')) isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1   def build_map ( words ): map = [(w.decode('ascii'),[]) for w in words] for i1,(w1,n1) in enumerate( map ): for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ): if isnext( w1,w2 ): n1.append( i2 ) n2.append( i1 ) return map   def find_path ( words,w1,w2 ): i = [w[0] for w in words].index( w1 ) front,done,res = [i],{i:-1},[] while front : i = front.pop(0) word,next = words[i] for n in next : if n in done : continue done[n] = i if words[n][0] == w2 : while n >= 0 : res = [words[n][0]] + res n = done[n] return ' '.join( res ) front.append( n ) return '%s can not be turned into %s'%( w1,w2 )   for w in ('boy man','girl lady','john jane','alien drool','child adult'): print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Julia
Julia
using Combinatorics   const tfile = download("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") const wordlist = Dict(w => 1 for w in split(read(tfile, String), r"\s+"))   function wordwheel(wheel, central) returnlist = String[] for combo in combinations([string(i) for i in wheel]) if central in combo && length(combo) > 2 for perm in permutations(combo) word = join(perm) if haskey(wordlist, word) && !(word in returnlist) push!(returnlist, word) end end end end return returnlist end   println(wordwheel("ndeokgelw", "k"))  
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Lua
Lua
LetterCounter = { new = function(self, word) local t = { word=word, letters={} } for ch in word:gmatch(".") do t.letters[ch] = (t.letters[ch] or 0) + 1 end return setmetatable(t, self) end, contains = function(self, other) for k,v in pairs(other.letters) do if (self.letters[k] or 0) < v then return false end end return true end } LetterCounter.__index = LetterCounter   grid = "ndeokgelw" midl = grid:sub(5,5) ltrs = LetterCounter:new(grid) file = io.open("unixdict.txt", "r") for word in file:lines() do if #word >= 3 and word:find(midl) and ltrs:contains(LetterCounter:new(word)) then print(word) end end
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Python
Python
"""Script demonstrating drawing of anti-aliased lines using Xiaolin Wu's line algorithm   usage: python xiaolinwu.py [output-file]   """ from __future__ import division import sys   from PIL import Image     def _fpart(x): return x - int(x)   def _rfpart(x): return 1 - _fpart(x)   def putpixel(img, xy, color, alpha=1): """ Paints color over the background at the point xy in img. Use alpha for blending. alpha=1 means a completely opaque foreground. """ compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg)) c = compose_color(img.getpixel(xy), color) img.putpixel(xy, c)   def draw_line(img, p1, p2, color): """Draws an anti-aliased line in img from p1 to p2 with the given color.""" x1, y1 = p1 x2, y2 = p2 dx, dy = x2-x1, y2-y1 steep = abs(dx) < abs(dy) p = lambda px, py: ((px,py), (py,px))[steep]   if steep: x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx if x2 < x1: x1, x2, y1, y2 = x2, x1, y2, y1   grad = dy/dx intery = y1 + _rfpart(x1) * grad def draw_endpoint(pt): x, y = pt xend = round(x) yend = y + grad * (xend - x) xgap = _rfpart(x + 0.5) px, py = int(xend), int(yend) putpixel(img, p(px, py), color, _rfpart(yend) * xgap) putpixel(img, p(px, py+1), color, _fpart(yend) * xgap) return px   xstart = draw_endpoint(p(*p1)) + 1 xend = draw_endpoint(p(*p2))   for x in range(xstart, xend): y = int(intery) putpixel(img, p(x, y), color, _rfpart(intery)) putpixel(img, p(x, y+1), color, _fpart(intery)) intery += grad     if __name__ == '__main__': if len(sys.argv) != 2: print 'usage: python xiaolinwu.py [output-file]' sys.exit(-1)   blue = (0, 0, 255) yellow = (255, 255, 0) img = Image.new("RGB", (500,500), blue) for a in range(10, 431, 60): draw_line(img, (10, 10), (490, a), yellow) draw_line(img, (10, 10), (a, 490), yellow) draw_line(img, (10, 10), (490, 490), yellow) filename = sys.argv[1] img.save(filename) print 'image saved to', filename
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Groovy
Groovy
def writer = new StringWriter() def builder = new groovy.xml.MarkupBuilder(writer) def names = ["April", "Tam O'Shanter", "Emily"] def remarks = ["Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', "Short & shrift"]   builder.CharacterRemarks() { names.eachWithIndex() { n, i -> Character(name:n, remarks[i]) }; }   println writer.toString()
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Groovy
Groovy
def input = """<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students>"""   def students = new XmlParser().parseText(input) students.each { println it.'@Name' }
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#TorqueScript
TorqueScript
  $array[0] = "hi"; $array[1] = "hello";   for(%i=0;%i<2;%i++) echo($array[%i]);
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Racket
Racket
  #lang racket   (define xs '(1.0 2.0 3.0 1.0e11)) (define ys '(1.0 1.4142135623730951 1.7320508075688772 316227.76601683791))   (define xprecision 3) (define yprecision 5)   (with-output-to-file "some-file" #:exists 'truncate (λ() (for ([x xs] [y ys]) (displayln (~a (~r x #:precision xprecision) " " (~r y #:precision yprecision))))))   #| The output is not using exponenets as above, but that's not needed since Racket can read these numbers fine:   1 1 2 1.41421 3 1.73205 100000000000 316227.76602 |#  
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Raku
Raku
sub writefloat ( $filename, @x, @y, $x_precision = 3, $y_precision = 5 ) { my $fh = open $filename, :w; for flat @x Z @y -> $x, $y { $fh.printf: "%.*g\t%.*g\n", $x_precision, $x, $y_precision, $y; } $fh.close; }   my @x = 1, 2, 3, 1e11; my @y = @x.map({.sqrt});   writefloat( 'sqrt.dat', @x, @y );
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Modula-3
Modula-3
MODULE Doors EXPORTS Main;   IMPORT IO, Fmt;   TYPE State = {Closed, Open}; TYPE List = ARRAY [1..100] OF State;   VAR doors := List{State.Closed, ..};   BEGIN FOR i := 1 TO 100 DO FOR j := FIRST(doors) TO LAST(doors) DO IF j MOD i = 0 THEN IF doors[j] = State.Closed THEN doors[j] := State.Open; ELSE doors[j] := State.Closed; END; END; END; END;   FOR i := FIRST(doors) TO LAST(doors) DO IO.Put(Fmt.Int(i) & " is "); IF doors[i] = State.Closed THEN IO.Put("Closed.\n"); ELSE IO.Put("Open.\n"); END; END; END Doors.
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#11l
11l
F divisors(n) V divs = [1] [Int] divs2 V i = 2 L i * i <= n I n % i == 0 V j = n I/ i divs [+]= i I i != j divs2 [+]= j i++ R divs2 [+] reversed(divs)   F abundant(n, divs) R sum(divs) > n   F semiperfect(n, divs) -> Bool I !divs.empty V h = divs[0] V t = divs[1..] I n < h R semiperfect(n, t) E R n == h | semiperfect(n - h, t) | semiperfect(n, t) E R 0B   F sieve(limit) V w = [0B] * limit L(i) (2 .< limit).step(2) I w[i] L.continue V divs = divisors(i) I !abundant(i, divs) w[i] = 1B E I semiperfect(i, divs) L(j) (i .< limit).step(i) w[j] = 1B R w   V w = sieve(17'000) V count = 0 print(‘The first 25 weird numbers:’) L(n) (2..).step(2) I !w[n] print(n, end' ‘ ’) count++ I count == 25 L.break
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#ERRE
ERRE
PROGRAM 3D_NAME   DIM TBL$[17,1]   BEGIN   FOR I=0 TO 17 DO READ(TBL$[I,0],TBL$[I,1]) END FOR   PRINT(CHR$(12);) ! CLS   FOR I=0 TO 17 DO PRINT(TBL$[I,1];TBL$[I,0];TBL$[I,0];TBL$[I,1]) END FOR   DATA("_________________ ","_____________ ") DATA("|\ \ ","|\ \ ") DATA("|\\_______________\ ","|\\___________\ ") DATA("|\\| \ ","|\\| | ") DATA("|\\| ________ | ","|\\| ________| ") DATA("|\\| | |\| | ","|\\| | ") DATA("|\\| |______|\| | ","|\\| |____ ") DATA("|\\| | \| | ","|\\| | \ ") DATA("|\\| |________| | ","|\\| |_____\ ") DATA("|\\| | ","|\\| | ") DATA("|\\| ___ ____/ ","|\\| _____| ") DATA("|\\| | \\\ \ ","|\\| | ") DATA("|\\| | \\\ \ ","|\\| | ") DATA("|\\| | \\\ \ ","|\\| |______ ") DATA("|\\| | \\\ \ ","|\\| | \ ") DATA("|\\| | \\\ \ ","|\\| |_______\ ") DATA(" \\| | \\\ \ "," \\| | ") DATA(" \|___| \\\___\"," \|___________| ")   END PROGRAM  
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#F.23
F#
let make2Darray (picture : string list) = let maxY = picture.Length let maxX = picture |> List.maxBy String.length |> String.length let arr = (fun y x -> if picture.[y].Length <= x then ' ' else picture.[y].[x]) |> Array2D.init maxY maxX (arr, maxY, maxX)   let (cube, cy, cx) = [ @"///\"; @"\\\/"; ] |> make2Darray     let (p2, my, mx) = [ "*****"; "* * * "; "* * * "; "* **********"; "**** * * "; "* * * "; "* **********"; "* * * "; "* * * "; ] |> make2Darray   let a2 = Array2D.create (cy/2 * (my+1)) (cx/2 * mx + my) ' '   let imax = my * (cy/2) for y in 0 .. Array2D.length1 p2 - 1 do for x in 0 .. Array2D.length2 p2 - 1 do let indent = Math.Max(imax - y, 0) if p2.[y, x] = '*' then Array2D.blit cube 0 0 a2 y (indent+x) cy cx   Array2D.iteri (fun y x c -> if x = 0 then printfn "" printf "%c" c) a2  
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#HicEst
HicEst
CHARACTER title="Rosetta Window_management" REAL :: w=-333, h=25, x=1, y=0.5 ! pixels < 0, relative window size 0...1, script character size > 1   WINDOW(WINdowhandle=wh, Width=w, Height=h, X=x, Y=y, TItle=title) ! create, on return size/pos VARIABLES are set to script char WINDOW(WIN=wh, MINimize) ! minimize WINDOW(WIN=wh, SHowNormal) ! restore WINDOW(WIN=wh, X=31, Y=7+4) !<-- move upper left here (col 31, row 7 + ~4 rows for title, menus, toolbar. Script window in upper left screen) WINDOW(WIN=wh, MAXimize) ! maximize (hides the script window) WINDOW(Kill=wh) ! close END
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Wireworld is type Cell is (' ', 'H', 't', '.'); type Board is array (Positive range <>, Positive range <>) of Cell; -- Perform one transition of the cellular automation procedure Wireworld (State : in out Board) is function "abs" (Left : Cell) return Natural is begin if Left = 'H' then return 1; else return 0; end if; end "abs"; Above  : array (State'Range (2)) of Cell := (others => ' '); Left  : Cell := ' '; Current : Cell; begin for I in State'First (1) + 1..State'Last (1) - 1 loop for J in State'First (2) + 1..State'Last (2) - 1 loop Current := State (I, J); case Current is when ' ' => null; when 'H' => State (I, J) := 't'; when 't' => State (I, J) := '.'; when '.' => if abs Above ( J - 1) + abs Above ( J) + abs Above ( J + 1) + abs Left + abs State (I, J + 1) + abs State (I + 1, J - 1) + abs State (I + 1, J) + abs State (I + 1, J + 1) in 1..2 then State (I, J) := 'H'; else State (I, J) := '.'; end if; end case; Above (J - 1) := Left; Left := Current; end loop; end loop; end Wireworld; -- Print state of the automation procedure Put (State : Board) is begin for I in State'First (1) + 1..State'Last (1) - 1 loop for J in State'First (2) + 1..State'Last (2) - 1 loop case State (I, J) is when ' ' => Put (' '); when 'H' => Put ('H'); when 't' => Put ('t'); when '.' => Put ('.'); end case; end loop; New_Line; end loop; end Put; Oscillator : Board := (" ", " tH ", " . .... ", " .. ", " "); begin for Step in 0..9 loop Put_Line ("Step" & Integer'Image (Step) & " ---------"); Put (Oscillator); Wireworld (Oscillator); end loop; end Test_Wireworld;
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#APL
APL
⎕CY 'dfns' ⍝ import dfns namespace ⍝ pco ← prime finder ⍝ nats ← natural number arithmetic (uses strings) ⍝ Get all Wieferich primes below n: wief←{{⍵/⍨{(,'0')≡(×⍨⍵)|nats 1 -nats⍨ 2 *nats ⍵-1}¨⍵}⍸1 pco⍳⍵} wief 5000 1093 3511  
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Arturo
Arturo
wieferich?: function [n][ and? -> prime? n -> zero? (dec 2 ^ n-1) % n ^ 2 ]   print ["Wieferich primes less than 5000:" select 1..5000 => wieferich?]
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#AWK
AWK
  # syntax: GAWK -f WIEFERICH_PRIMES.AWK # converted from FreeBASIC BEGIN { start = 1 stop = 4999 for (i=start; i<=stop; i++) { if (is_wieferich_prime(i)) { printf("%d\n",i) count++ } } printf("Wieferich primes %d-%d: %d\n",start,stop,count) exit(0) } function is_prime(n, d) { d = 5 if (n < 2) { return(0) } if (n % 2 == 0) { return(n == 2) } if (n % 3 == 0) { return(n == 3) } while (d*d <= n) { if (n % d == 0) { return(0) } d += 2 if (n % d == 0) { return(0) } d += 4 } return(1) } function is_wieferich_prime(p, p2,q) { if (!is_prime(p)) { return(0) } q = 1 p2 = p^2 while (p > 1) { q = (2*q) % p2 p-- } return(q == 1) }  
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#Common_Lisp
Common Lisp
;;; Single-file/interactive setup; large applications should define an ASDF system instead   (let* ((display (open-default-display)) (screen (display-default-screen display)) (root-window (screen-root screen)) (black-pixel (screen-black-pixel screen)) (white-pixel (screen-white-pixel screen)) (window (create-window :parent root-window :x 10 :y 10 :width 100 :height 100 :background white-pixel :event-mask '(:exposure :key-press))) (gc (create-gcontext :drawable window :foreground black-pixel :background white-pixel))) (map-window window) (unwind-protect (event-case (display :discard-p t) (exposure () (draw-rectangle window gc 20 20 10 10 t) (draw-glyphs window gc 10 50 "Hello, World!") nil #| continue receiving events |#) (key-press () t #| non-nil result signals event-case to exit |#)) (when window (destroy-window window)) (when gc (free-gcontext gc)) (close-display display)))    
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on this page the Wilson primes, if any, for orders n = 1 to 11 inclusive and for primes p < 18   or, if your language supports big integers, for p < 11,000. Related task Primality by Wilson's theorem
#GW-BASIC
GW-BASIC
10 PRINT "n: Wilson primes" 20 PRINT "--------------------" 30 FOR N = 1 TO 11 40 PRINT USING "##";N; 50 FOR P=2 TO 18 60 GOSUB 140 70 IF PT=0 THEN GOTO 100 80 GOSUB 230 90 IF WNPT=1 THEN PRINT P; 100 NEXT P 110 PRINT 120 NEXT N 130 END 140 REM tests if the number P is prime 150 REM result is stored in PT 160 PT = 1 170 IF P=2 THEN RETURN 175 IF P MOD 2 = 0 THEN PT=0:RETURN 180 J=3 190 IF J*J>P THEN RETURN 200 IF P MOD J = 0 THEN PT = 0: RETURN 210 J = J + 2 220 GOTO 190 230 REM tests if the prime P is a Wilson prime of order N 240 REM make sure it actually is prime first 250 REM RESULT is stored in WNPT 260 WNPT=0 270 IF P=2 AND N=2 THEN WNPT = 1: RETURN 280 IF N>P THEN WNPT=0: RETURN 290 PROD# = 1 : P2 = P*P 300 FOR I = 1 TO N-1 310 PROD# = (PROD#*I) : GOSUB 3000 320 NEXT I 330 FOR I = 1 TO P-N 340 PROD# = (PROD#*I) : GOSUB 3000 350 NEXT I 360 PROD# = (P2+PROD#-(-1)^N) : GOSUB 3000 370 IF PROD# = 0 THEN WNPT = 1: RETURN 380 WNPT = 0: RETURN 3000 REM PROD# MOD P2 fails if PROD#>32767 so brew our own modulus function 3010 PROD# = PROD# - INT(PROD#/P2)*P2 3020 RETURN
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#AutoIt
AutoIt
GUICreate("Test") GUISetState(@SW_SHOW)   Do Switch GUIGetMsg() Case -3 ; $GUI_EVENT_CLOSE Exit EndSwitch Until False
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#BaCon
BaCon
REM empty window INCLUDE "hug.bac"   mainwin = WINDOW("Rosetta Code empty", 400, 300)   REM start gtk event loop... DISPLAY
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Julia
Julia
using Random   const stepdirections = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] const nrows = 10 const ncols = nrows const gridsize = nrows * ncols const minwords = 25 const minwordsize = 3   mutable struct LetterGrid nattempts::Int nrows::Int ncols::Int cells::Matrix{Char} solutions::Vector{String} LetterGrid() = new(0, nrows, ncols, fill(' ', nrows, ncols), Vector{String}()) end   function wordmatrix(filename, usepropernames = true) words = [lowercase(line) for line in readlines(filename) if match(r"^[a-zA-Z]+$", line) != nothing && (usepropernames || match(r"^[a-z]", line) != nothing) && length(line) >= minwordsize && length(line) <= ncols] n = 1000 for i in 1:n grid = LetterGrid() messagelen = placemessage(grid, "Rosetta Code") target = grid.nrows * grid.ncols - messagelen cellsfilled = 0 shuffle!(words) for word in words cellsfilled += tryplaceword(grid, word) if cellsfilled == target if length(grid.solutions) >= minwords grid.nattempts = i return grid else break end end end end throw("Failed to place words after $n attempts") end   function placemessage(grid, msg) msg = uppercase(msg) msg = replace(msg, r"[^A-Z]" => "") messagelen = length(msg) if messagelen > 0 && messagelen < gridsize p = Int.(floor.(LinRange(messagelen, gridsize, messagelen) .+ (rand(messagelen) .- 0.5) * messagelen / 3)) .- div(messagelen, 3) foreach(i -> grid.cells[div(p[i], nrows) + 1, p[i] % nrows + 1] = msg[i], 1:length(p)) return messagelen end return 0 end   function tryplaceword(grid, word) for dir in shuffle(stepdirections) for pos in shuffle(1:length(grid.cells)) lettersplaced = trylocation(grid, word, dir, pos) if lettersplaced > 0 return lettersplaced end end end return 0 end   function trylocation(grid, word, dir, pos) r, c = divrem(pos, nrows) .+ [1, 1] positions = [[r, c] .+ (dir .* i) for i in 1:length(word)] if !all(x -> 0 < x[1] <= nrows && 0 < x[2] <= ncols, positions) return 0 end for (i, p) in enumerate(positions) letter = grid.cells[p[1],p[2]] if letter != ' ' && letter != word[i] return 0 end end lettersplaced = 0 for (i, p) in enumerate(positions) if grid.cells[p[1], p[2]] == ' ' lettersplaced += 1 grid.cells[p[1],p[2]] = word[i] end end if lettersplaced > 0 push!(grid.solutions, lpad(word, 10) * " $(positions[1]) to $(positions[end])") end return lettersplaced end   function printresult(grid) if grid.nattempts == 0 println("No grid to display: no solution found.") return end size = length(grid.solutions) println("Attempts: ", grid.nattempts) println("Number of words: ", size) println("\n 0 1 2 3 4 5 6 7 8 9") for r in 1:nrows print("\n", rpad(r, 4)) for c in 1:ncols print(" $(grid.cells[r, c]) ") end end println() for i in 1:2:size println("$(grid.solutions[i]) $(i < size ? grid.solutions[i+1] : "")") end end   printresult(wordmatrix("words.txt", false))  
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: Rosetta Code, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8) Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Kotlin
Kotlin
// version 1.2.0   import java.util.Random import java.io.File   val dirs = listOf( intArrayOf( 1, 0), intArrayOf(0, 1), intArrayOf( 1, 1), intArrayOf( 1, -1), intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(-1, -1), intArrayOf(-1, 1) )   val nRows = 10 val nCols = 10 val gridSize = nRows * nCols val minWords = 25 val rand = Random()   class Grid { var numAttempts = 0 val cells = List(nRows) { CharArray(nCols) } val solutions = mutableListOf<String>() }   fun readWords(fileName: String): List<String> { val maxLen = maxOf(nRows, nCols) val rx = Regex("^[a-z]{3,$maxLen}$") val f = File(fileName) return f.readLines().map { it.trim().toLowerCase() } .filter { it.matches(rx) } }   fun createWordSearch(words: List<String>): Grid { var numAttempts = 0 lateinit var grid: Grid outer@ while (++numAttempts < 100) { grid = Grid() val messageLen = placeMessage(grid, "Rosetta Code") val target = gridSize - messageLen var cellsFilled = 0 for (word in words.shuffled()) { cellsFilled += tryPlaceWord(grid, word) if (cellsFilled == target) { if (grid.solutions.size >= minWords) { grid.numAttempts = numAttempts break@outer } else { // grid is full but we didn't pack enough words, start over break } } } } return grid }   fun placeMessage(grid: Grid, msg: String): Int { val rx = Regex("[^A-Z]") val msg2 = msg.toUpperCase().replace(rx, "") val messageLen = msg2.length if (messageLen in (1 until gridSize)) { val gapSize = gridSize / messageLen for (i in 0 until messageLen) { val pos = i * gapSize + rand.nextInt(gapSize) grid.cells[pos / nCols][pos % nCols] = msg2[i] } return messageLen } return 0 }   fun tryPlaceWord(grid: Grid, word: String): Int { val randDir = rand.nextInt(dirs.size) val randPos = rand.nextInt(gridSize) for (d in 0 until dirs.size) { val dir = (d + randDir) % dirs.size for (p in 0 until gridSize) { val pos = (p + randPos) % gridSize val lettersPlaced = tryLocation(grid, word, dir, pos) if (lettersPlaced > 0) return lettersPlaced } } return 0 }   fun tryLocation(grid: Grid, word: String, dir: Int, pos: Int): Int { val r = pos / nCols val c = pos % nCols val len = word.length   // check bounds if ((dirs[dir][0] == 1 && (len + c) > nCols) || (dirs[dir][0] == -1 && (len - 1) > c) || (dirs[dir][1] == 1 && (len + r) > nRows) || (dirs[dir][1] == -1 && (len - 1) > r)) return 0 var overlaps = 0   // check cells var rr = r var cc = c for (i in 0 until len) { if (grid.cells[rr][cc] != '\u0000' && grid.cells[rr][cc] != word[i]) return 0 cc += dirs[dir][0] rr += dirs[dir][1] }   // place rr = r cc = c for (i in 0 until len) { if (grid.cells[rr][cc] == word[i]) overlaps++ else grid.cells[rr][cc] = word[i]   if (i < len - 1) { cc += dirs[dir][0] rr += dirs[dir][1] } }   val lettersPlaced = len - overlaps if (lettersPlaced > 0) { grid.solutions.add(String.format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)) } return lettersPlaced }   fun printResult(grid: Grid) { if (grid.numAttempts == 0) { println("No grid to display") return } val size = grid.solutions.size println("Attempts: ${grid.numAttempts}") println("Number of words: $size") println("\n 0 1 2 3 4 5 6 7 8 9") for (r in 0 until nRows) { print("\n$r ") for (c in 0 until nCols) print(" ${grid.cells[r][c]} ") }   println("\n")   for (i in 0 until size - 1 step 2) { println("${grid.solutions[i]} ${grid.solutions[i + 1]}") } if (size % 2 == 1) println(grid.solutions[size - 1]) }   fun main(args: Array<String>) { printResult(createWordSearch(readWords("unixdict.txt"))) }
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.23
C#
namespace RosettaCode.WordWrap { using System; using System.Collections.Generic;   internal static class Program { private const string LoremIpsum = @" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est, condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu nibh.";   private static void Main() { foreach (var lineWidth in new[] { 72, 80 }) { Console.WriteLine(new string('-', lineWidth)); Console.WriteLine(Wrap(LoremIpsum, lineWidth)); } }   private static string Wrap(string text, int lineWidth) { return string.Join(string.Empty, Wrap( text.Split(new char[0], StringSplitOptions .RemoveEmptyEntries), lineWidth)); }   private static IEnumerable<string> Wrap(IEnumerable<string> words, int lineWidth) { var currentWidth = 0; foreach (var word in words) { if (currentWidth != 0) { if (currentWidth + word.Length < lineWidth) { currentWidth++; yield return " "; } else { currentWidth = 0; yield return Environment.NewLine; } } currentWidth += word.Length; yield return word; } } } }
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Racket
Racket
#lang racket   (define *unixdict* (delay (with-input-from-file "../../data/unixdict.txt" (compose list->set port->lines))))   (define letters-as-strings (map string (string->list "abcdefghijklmnopqrstuvwxyz")))   (define ((replace-for-c-at-i w i) c) (string-append (substring w 0 i) c (substring w (add1 i))))   (define (candidates w) (for*/list (((i w_i) (in-parallel (string-length w) w)) (r (in-value (replace-for-c-at-i w i))) (c letters-as-strings) #:unless (char=? w_i (string-ref c 0))) (r c)))   (define (generate-candidates word.path-hash) (for*/hash (((w p) word.path-hash) (w′ (candidates w))) (values w′ (cons w p))))   (define (hash-filter-keys keep-key? h) (for/hash (((k v) h) #:when (keep-key? k)) (values k v)))   (define (Word-ladder src dest (words (force *unixdict*))) (let loop ((edge (hash src null)) (unused (set-remove words src))) (let ((cands (generate-candidates edge))) (if (hash-has-key? cands dest) (reverse (cons dest (hash-ref cands dest))) (let ((new-edge (hash-filter-keys (curry set-member? unused) cands))) (if (hash-empty? new-edge) `(no-path-between ,src ,dest) (loop new-edge (set-subtract unused (list->set (hash-keys new-edge))))))))))   (module+ main (Word-ladder "boy" "man") (Word-ladder "girl" "lady") (Word-ladder "john" "jane") (Word-ladder "alien" "drool") (Word-ladder "child" "adult"))
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
constant %dict = 'unixdict.txt'.IO.lines .classify(*.chars) .map({ .key => .value.Set });   sub word_ladder ( Str $from, Str $to ) { die if $from.chars != $to.chars;   my $sized_dict = %dict{$from.chars};   my @workqueue = (($from,),); my $used = ($from => True).SetHash; while @workqueue { my @new_q; for @workqueue -> @words { my $last_word = @words.tail; my @new_tails = gather for 'a' .. 'z' -> $replacement_letter { for ^$last_word.chars -> $i { my $new_word = $last_word; $new_word.substr-rw($i, 1) = $replacement_letter;   next unless $new_word ∈ $sized_dict and not $new_word ∈ $used; take $new_word; $used{$new_word} = True;   return |@words, $new_word if $new_word eq $to; } } push @new_q, ( |@words, $_ ) for @new_tails; } @workqueue = @new_q; } } for <boy man>, <girl lady>, <john jane>, <child adult> -> ($from, $to) { say word_ladder($from, $to) // "$from into $to cannot be done"; }
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[possible] possible[letters_List][word_String] := Module[{c1, c2, m}, c1 = Counts[Characters@word]; c2 = Counts[letters]; m = Merge[{c1, c2}, Identity]; Length[Select[Select[m, Length /* GreaterThan[1]], Apply[Greater]]] == 0 ] chars = Characters@"ndeokgelw"; words = Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "String"]; words = StringSplit[ToLowerCase[words], "\n"]; words //= Select[StringLength /* GreaterEqualThan[3]]; words //= Select[StringContainsQ["k"]]; words //= Select[StringMatchQ[Repeated[Alternatives @@ chars]]]; words //= Select[possible[chars]]; words
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid. An example N D E O K G E L W Task Write a program to solve the above "word wheel" puzzle. Specifically: Find all words of 3 or more letters using only the letters in the string   ndeokgelw. All words must contain the central letter   K. Each letter may be used only as many times as it appears in the string. For this task we'll use lowercase English letters exclusively. A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Optional extra Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Nim
Nim
import strutils, sugar, tables   const Grid = """N D E O K G E L W"""   let letters = Grid.toLowerAscii.splitWhitespace.join()   let words = collect(newSeq): for word in "unixdict.txt".lines: if word.len in 3..9: word   let midLetter = letters[4]   let gridCount = letters.toCountTable for word in words: block checkWord: if midLetter in word: for ch, count in word.toCountTable.pairs: if count > gridCount[ch]: break checkWord echo word
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Racket
Racket
#lang racket (require 2htdp/image)   (define (plot img x y c) (define c*255 (exact-round (* (- 1 c) 255))) (place-image (rectangle 1 1 'solid (make-color c*255 c*255 c*255 255)) x y img))   (define ipart exact-floor) ; assume that a "round-down" is what we want when -ve ;;; `round` is built in -- but we'll use exact round (and I'm not keen on over-binding round)   (define (fpart n) (- n (exact-floor n))) (define (rfpart n) (- 1 (fpart n)))   (define (draw-line img x0 y0 x1 y1) (define (draw-line-steeped img x0 y0 x1 y1 steep?) (define (draw-line-steeped-l-to-r img x0 y0 x1 y1 steep?) (define dx (- x1 x0)) (define dy (- y1 y0)) (define gradient (/ dy dx))   (define (handle-end-point img x y) (define xend (exact-round x)) (define yend (+ y (* gradient (- xend x)))) (define xgap (rfpart (+ x 0.5))) (define ypxl (ipart yend)) (define intery (+ yend gradient))   (case steep? [(#t) (define img* (plot img ypxl xend (* xgap (rfpart yend)))) (values (plot img* (+ ypxl 1) xend (* xgap (fpart yend))) xend intery)] [(#f) (define img* (plot img xend ypxl (* xgap (rfpart yend)))) (values (plot img* xend (+ ypxl 1) (* xgap (fpart yend))) xend intery)]))   (define-values (img-with-l-endpoint xpl1 intery) (handle-end-point img x0 y0)) (define-values (img-with-r-endpoint xpl2 _) (handle-end-point img-with-l-endpoint x1 y1))   (for/fold ((img img-with-l-endpoint) (y intery)) ((x (in-range (+ xpl1 1) xpl2))) (define y-i (ipart y)) (values (case steep? [(#t) (define img* (plot img y-i x (rfpart y))) (plot img* (+ 1 y-i) x (fpart y))] [(#f) (define img* (plot img x y-i (rfpart y))) (plot img* x (+ 1 y-i) (fpart y))]) (+ y gradient))))   (if (> x0 x1) (draw-line-steeped-l-to-r img x1 y1 x0 y0 steep?) (draw-line-steeped-l-to-r img x0 y0 x1 y1 steep?)))   (define steep? (> (abs (- y1 y0)) (abs (- x1 x0)))) (define-values (img* _) (if steep? (draw-line-steeped img y0 x0 y1 x1 steep?) (draw-line-steeped img x0 y0 x1 y1 steep?))) img*)   (define img-1 (beside (scale 3 (draw-line (empty-scene 150 100) 12 12 138 88)) (above (scale 1 (draw-line (empty-scene 150 100) 12 50 138 50)) (scale 1 (draw-line (empty-scene 150 100) 75 12 75 88)) (scale 1 (draw-line (empty-scene 150 100) 12 88 138 12)))))   (define img-2 (beside (scale 3 (draw-line (empty-scene 100 150) 12 12 88 138)) (above (scale 1 (draw-line (empty-scene 100 150) 50 12 50 138)) (scale 1 (draw-line (empty-scene 100 150) 12 75 88 75)) (scale 1 (draw-line (empty-scene 100 150) 88 12 12 138)))))   img-1 img-2 (save-image img-1 "images/xiaolin-wu-racket-1.png") (save-image img-2 "images/xiaolin-wu-racket-2.png")
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Raku
Raku
sub plot(\x, \y, \c) { say "plot {x} {y} {c}" }   sub fpart(\x) { x - floor(x) }   sub draw-line(@a is copy, @b is copy) { my Bool \steep = abs(@b[1] - @a[1]) > abs(@b[0] - @a[0]); my $plot = &OUTER::plot;   if steep { $plot = -> $y, $x, $c { plot($x, $y, $c) } @a.=reverse; @b.=reverse; } if @a[0] > @b[0] { my @t = @a; @a = @b; @b = @t }   my (\x0,\y0) = @a; my (\x1,\y1) = @b;   my \dx = x1 - x0; my \dy = y1 - y0; my \gradient = dy / dx;   # handle first endpoint my \x-end1 = round(x0); my \y-end1 = y0 + gradient * (x-end1 - x0); my \x-gap1 = 1 - round(x0 + 0.5);   my \x-pxl1 = x-end1; # this will be used in the main loop my \y-pxl1 = floor(y-end1); my \c1 = fpart(y-end1) * x-gap1;   $plot(x-pxl1, y-pxl1 , 1 - c1) unless c1 == 1; $plot(x-pxl1, y-pxl1 + 1, c1 ) unless c1 == 0;   # handle second endpoint my \x-end2 = round(x1); my \y-end2 = y1 + gradient * (x-end2 - x1); my \x-gap2 = fpart(x1 + 0.5);   my \x-pxl2 = x-end2; # this will be used in the main loop my \y-pxl2 = floor(y-end2); my \c2 = fpart(y-end2) * x-gap2;   my \intery = y-end1 + gradient;   # main loop for (x-pxl1 + 1 .. x-pxl2 - 1) Z (intery, intery + gradient ... *) -> (\x,\y) { my \c = fpart(y); $plot(x, floor(y) , 1 - c) unless c == 1; $plot(x, floor(y) + 1, c ) unless c == 0; }   $plot(x-pxl2, y-pxl2 , 1 - c2) unless c2 == 1; $plot(x-pxl2, y-pxl2 + 1, c2 ) unless c2 == 0; }   draw-line [0,1], [10,2];
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Haskell
Haskell
import Text.XML.Light   characterRemarks :: [String] -> [String] -> String characterRemarks names remarks = showElement $ Element (unqual "CharacterRemarks") [] (zipWith character names remarks) Nothing where character name remark = Elem $ Element (unqual "Character") [Attr (unqual "name") name] [Text $ CData CDataText remark Nothing] Nothing
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Haskell
Haskell
import Data.Maybe import Text.XML.Light   students="<Students>"++ " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"++ " <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />"++ " <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\"/>"++ " <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">"++ " <Pet Type=\"dog\" Name=\"Rover\" /> </Student>"++ " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />"++ "</Students>"   xmlRead elm name = mapM_ putStrLn . concatMap (map (fromJust.findAttr (unqual name)).filterElementsName (== unqual elm)) . onlyElems. parseXML
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it). Please discuss at Village Pump:   Arrays. Please merge code in from these obsolete tasks:   Creating an Array   Assigning Values to an Array   Retrieving an Element of an Array Related tasks   Collections   Creating an Associative Array   Two-dimensional array (runtime)
#Transd
Transd
module1 : { v1: Vector<Int>(), v2: Vector<String>(), v3: Vector<Int>([1,2,3,4]), v4: Vector<String>(["one","two","three"]), // the type of vector values can automaticaly deduced v5: [1.0, 2.5, 8.6], // Vector<Double> v6: ["one","two","three"] // Vector<String> }
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Raven
Raven
3 as $xprecision 5 as $yprecision   [ ] as $results   [ 1 2 3 1e11 ] as $a   group $a each sqrt list as $b   # generate format specifier "%-8.3g %.5g\n" "%%-8.%($xprecision)dg %%.%($yprecision)dg\n" as $f   define print2 use $v1, $v2, $f $v2 1.0 prefer $v1 1.0 prefer $f format $results push   4 each as $i $f $b $i get $a $i get print2 $results "" join "results.dat" write
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#REXX
REXX
/*REXX program writes two arrays to a file with a specified (limited) precision. */ numeric digits 1000 /*allow use of a huge number of digits.*/ oFID= 'filename' /*name of the output File IDentifier.*/ x.=; y.=; x.1= 1  ; y.1= 1 x.2= 2  ; y.2= 1.4142135623730951 x.3= 3  ; y.3= 1.7320508075688772 x.4= 1e11 ; y.4= 316227.76601683791 xPrecision= 3 /*the precision for the X numbers. */ yPrecision= 5 /* " " " " Y " */ do j=1 while x.j\=='' /*process and reformat all the numbers.*/ newX=rule(x.j, xPrecision) /*format X numbers with new precision*/ newY=rule(y.j, yPrecision) /* " Y " " " " */ aLine=translate(newX || left('',4) || newY, "e", 'E') say aLine /*display re─formatted numbers ──► term*/ call lineout oFID, aLine /*write " " " disk*/ end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ rule: procedure; parse arg z 1 oz,p; numeric digits p; z=format(z,,p) parse var z mantissa 'E' exponent /*get the dec dig exponent*/ parse var mantissa int '.' fraction /* " integer and fraction*/ fraction=strip(fraction, 'T', 0) /*strip trailing zeroes.*/ if fraction\=='' then fraction="."fraction /*any fractional digits ? */ if exponent\=='' then exponent="E"exponent /*in exponential format ? */ z=int || fraction || exponent /*format # (as per rules)*/ if datatype(z,'W') then return format(oz/1,,0) /*is it a whole number ? */ return format(oz/1,,,3,0) /*3 dec. digs in exponent.*/
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#MontiLang
MontiLang
101 var l .   for l 0 endfor arr   0 var i . for l i 1 + var i var j . j l < var pass . while pass get j not insert j . j i + var j l < var pass . endwhile endfor print /# show all doors #/   /# show only open doors #/ || print . 0 var i . for l get i if : i out | | out . . endif . i 1 + var i . endfor   input . /# pause until ENTER key pressed #/
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#ALGOL_68
ALGOL 68
BEGIN # find wierd numbers - abundant but not semiperfect numbers - translation of Go # # returns the divisors of n in descending order # PROC divisors = ( INT n )[]INT: BEGIN INT max divs = 2 * ENTIER sqrt( n ); [ 1 : max divs ]INT divs; [ 1 : max divs ]INT divs2; INT d pos := 0, d2 pos := 0; divs[ d pos +:= 1 ] := 1; FOR i FROM 2 WHILE i * i <= n DO IF n MOD i = 0 THEN INT j = n OVER i; divs[ d pos +:= 1 ] := i; IF i /= j THEN divs2[ d2 pos +:= 1 ] := j FI FI OD; FOR i FROM d pos BY -1 WHILE i > 0 DO divs2[ d2 pos +:= 1 ] := divs[ i ] OD; divs2[ 1 : d2 pos ] END # divisors # ; # returns TRUE if n with divisors divs, is abundant, FALSE otherwise # PROC abundant = ( INT n, []INT divs )BOOL: BEGIN INT sum := 0; FOR i FROM LWB divs TO UPB divs DO sum +:= divs[ i ] OD; sum > n END # abundant # ; # returns TRUE if n with divisors divs, is semiperfect, FALSE otherwise # PROC semiperfect = ( INT n, []INT divs, INT lb, ub )BOOL: IF ub < lb THEN FALSE ELIF INT h = divs[ lb ]; n < h THEN semiperfect( n, divs, lb + 1, ub ) ELIF n = h THEN TRUE ELIF semiperfect( n - h, divs, lb + 1, ub ) THEN TRUE ELSE semiperfect( n, divs, lb + 1, ub ) FI # semiperfect # ; # returns a sieve where FALSE = abundant and not semiperfect # PROC sieve = ( INT limit )[]BOOL: BEGIN # Only interested in even numbers >= 2 # [ 1 : limit ]BOOL w; FOR i FROM 1 TO limit DO w[ i ] := FALSE OD; FOR i FROM 2 BY 2 TO limit DO IF NOT w[ i ] THEN []INT divs = divisors( i ); IF NOT abundant( i, divs ) THEN w[ i ] := TRUE ELIF semiperfect( i, divs, LWB divs, UPB divs ) THEN FOR j FROM i BY i TO limit DO w[ j ] := TRUE OD FI FI OD; w END # sieve # ; BEGIN # task # []BOOL w = sieve( 17 000 ); INT count := 0; INT max = 25; print( ( "The first 25 weird numbers are:", newline ) ); FOR n FROM 2 BY 2 WHILE count < max DO IF NOT w[ n ] THEN print( ( whole( n, 0 ), " " ) ); count +:= 1 FI OD; print( ( newline ) ) END END
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Forth
Forth
\ Rossetta Code Write language name in 3D ASCII \ Simple Method   : l1 ." /\\\\\\\\\\\\\ /\\\\ /\\\\\\\ /\\\\\\\\\\\\\ /\\\ /\\\" CR ; : l2 ." \/\\\///////// /\\\//\\\ /\\\/////\\\ \//////\\\//// \/\\\ \/\\\" CR ; : l3 ." \/\\\ /\\\/ \///\\\ \/\\\ \/\\\ \/\\\ \/\\\ \/\\\" CR ; : l4 ." \/\\\\\\\\\ /\\\ \//\\\ \/\\\\\\\\\/ \/\\\ \/\\\\\\\\\\\\\" CR ; : l5 ." \/\\\///// \/\\\ \/\\\ \/\\\////\\\ \/\\\ \/\\\///////\\\" CR ; : l6 ." \/\\\ \//\\\ /\\\ \/\\\ \//\\\ \/\\\ \/\\\ \/\\\" CR ; : l7 ." \/\\\ \///\\\ /\\\ \/\\\ \//\\\ \/\\\ \/\\\ \/\\\" CR ; : l8 ." \/\\\ \///\\\\/ \/\\\ \//\\\ \/\\\ \/\\\ \/\\\" CR ; : l9 ." \/// \//// \/// \/// \/// \/// \///" CR ;   : "FORTH" cr L1 L2 L3 L4 L5 L6 L7 L8 l9 ;   ( test at the console ) page "forth"  
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have been created by your program.
#Icon_and_Unicon
Icon and Unicon
link graphics   procedure main()   Delay := 3000   W1 := open("Window 1","g","resize=on","size=400,400","pos=100,100","bg=black","fg=red") | stop("Unable to open window 1") W2 := open("Window 2","g","resize=on","size=400,400","pos=450,450","bg=blue","fg=yellow") | stop("Unable to open window 2") W3 := open("Window 3","g","resize=on","size=400,400","pos=600,150","bg=orange","fg=black") | stop("Unable to open window 3") WWrite(W3,"Opened three windows")   WWrite(W3,"Window 1&2 with rectangles") every Wx := W1 | W2 | W3 do if Wx ~=== W3 then FillRectangle(Wx,50,50,100,100)   delay(Delay) WWrite(W3,"Window 1 rasied") Raise(W1)   delay(Delay) WWrite(W3,"Window 2 hidden") WAttrib(W2,"canvas=hidden")   delay(Delay) WWrite(W3,"Window 2 maximized") WAttrib(W2,"canvas=maximal") Raise(W3)   delay(Delay) WWrite(W3,"Window 2 restored & resized") WAttrib(W2,"canvas=normal") WAttrib(W2,"size=600,600")   delay(Delay) WWrite(W3,"Window 2 moved") WAttrib(W2,"posx=700","posy=300")   delay(Delay) WWrite(W3,"Window 2 minimized") WAttrib(W2,"canvas=iconic")   delay(Delay) WWrite(W3,"Window 2 restored") WAttrib(W2,"canvas=normal") # restore as maximal, possible bug   delay(Delay) WWrite(W3,"Enter Q or q here to quit") WDone(W3) end
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.   You may treat a compound word like   well-dressed   as either one word or two.   The word   it's   could also be one or two words as you see fit.   You may also choose not to support non US-ASCII characters.   Assume words will not span multiple lines.   Don't worry about normalization of word spelling differences.   Treat   color   and   colour   as two distinct words.   Uppercase letters are considered equivalent to their lowercase counterparts.   Words of equal frequency can be listed in any order.   Feel free to explicitly state the thoughts behind the program decisions. Show example output using Les Misérables from Project Gutenberg as the text file input and display the top   10   most used words. History This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6 where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script (provided as an example below). References McIlroy's program Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#11l
11l
DefaultDict[String, Int] cnt L(word) re:‘\w+’.find_strings(File(‘135-0.txt’).read().lowercase()) cnt[word]++ print(sorted(cnt.items(), key' wordc -> wordc[1], reverse' 1B)[0.<10])