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 b... | #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", myWind... |
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 b... | #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:
PostQ... |
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, ... |
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 thi... | #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... |
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 thi... | #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)
siev... |
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_Rec... |
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 ... | #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 (
... |
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, sho... | #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 unde... |
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 ... | #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 ... |
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 ... | #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 $handl... |
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 w... | #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 = to... |
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 a... |
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 ... | #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 d... |
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" /... | #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\" <Stude... |
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" /... | #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/St... |
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,... | #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 internat... | #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... |
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.41421356... | #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$ = SaveFileRequest... |
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... | #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] := Clos... |
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<... |
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, 74283... |
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 b... | #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"
CompareW... |
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 XClo... |
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 = Defau... |
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 thi... | #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((>)11... |
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 i... |
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 ... | #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''
)
... |
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, sho... | #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 po... |
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 ... | #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)
s... |
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 w... | #JavaScript | JavaScript | (() => {
"use strict";
// ------------------- WORD WHEEL --------------------
// gridWords :: [String] -> [String] -> [String]
const gridWords = grid =>
lexemes => {
const
wheel = sort(toLower(grid.join(""))),
wSet = new Set(wheel),
... |
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 ... |
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, co... |
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 ... | #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... |
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" /... | #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" DateOf... |
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,... | #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 internat... | #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... |
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 internat... | #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... |
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.41421356... | #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.41421356... | #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... |
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... | #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] := Clos... |
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 ... |
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 __... |
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 b... | #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.Se... |
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 simultaneous... | #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... |
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 th... | #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
... |
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 ... |
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 thi... | #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 ; inl... |
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 thi... | #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^... |
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 thi... | #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))
... |
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 ... | #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}, ... |
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, sho... | #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 da... |
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, sho... | #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 "
"tha... |
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 ... | #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 )
... |
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 w... | #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 com... |
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 w... | #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... |
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, a... |
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 ... | #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 -> C... |
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" /... | #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" />
</Stude... |
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,... | #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.41421356... | #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)
... |
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.41421356... | #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... | #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... |
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 su... | #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 = ... |
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("|\\________... |
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 (c... |
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 b... | #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
... |
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 simultaneous... | #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) re... |
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 th... | #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 th... | #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 th... | #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_prim... |
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)... |
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 thi... | #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 = ... |
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 ... | #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{... |
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 ... | #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 minWor... |
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, sho... | #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, ... |
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 ... | #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 (subs... |
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 ... | #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 $us... |
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 w... | #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/p... |
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 w... | #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 = lett... |
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 us... |
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... |
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 ... | #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 (un... |
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" /... | #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\"/>"++
" <Stude... |
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,... | #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.41421356... | #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
... |
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.41421356... | #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... |
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... | #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... |
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 su... | #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;
... |
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 ." \/\\\ /\\\/ \///\\\ \/\\\ \/\\\ \/\\\ \/\\\ ... |
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 b... | #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 ... |
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.
Undersc... | #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]) |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.