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/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... | #Phix | Phix | with javascript_semantics
include mpfr.e
function weiferich(integer p)
mpz p2pm1m1 = mpz_init()
mpz_ui_pow_ui(p2pm1m1,2,p-1)
mpz_sub_ui(p2pm1m1,p2pm1m1,1)
return mpz_fdiv_q_ui(p2pm1m1,p2pm1m1,p*p)=0
end function
printf(1,"Weiferich primes less than 5000: %V\n",{filter(get_primes_le(5000),weiferich)})
|
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... | #PicoLisp | PicoLisp | (de **Mod (X Y N)
(let M 1
(loop
(when (bit? 1 Y)
(setq M (% (* M X) N)) )
(T (=0 (setq Y (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) )
(let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)))
(until (> D 5000)
(and
(=1 (**Mod 2 (dec D) (* D 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.
| #Perl | Perl | #!/usr/bin/perl -w
use strict;
use X11::Protocol;
my $X = X11::Protocol->new;
my $window = $X->new_rsrc;
$X->CreateWindow ($window,
$X->root, # parent window
'InputOutput', # class
0, # depth, copy from parent
0, ... |
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.
| #F.23 | F# | open System.Windows.Forms
[<System.STAThread>]
do
Form(Text = "F# Window")
|> Application.Run |
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.
| #Factor | Factor | USING: ui ui.gadgets.labels ;
"This is a window..." <label> "Really?" open-window |
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 ... | #Wren | Wren | import "random" for Random
import "/ioutil" for FileUtil
import "/pattern" for Pattern
import "/str" for Str
import "/fmt" for Fmt
var dirs = [ [1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1] ]
var Rows = 10
var Cols = 10
var gridSize = Rows * Cols
var minWords = 25
var rand = Random.new()
cla... |
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... | #F.23 | F# | open System
let 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 cu... |
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... | #Ruby | Ruby | wheel = "ndeokgelw"
middle, wheel_size = wheel[4], wheel.size
res = File.open("unixdict.txt").each_line.select do |word|
w = word.chomp
next unless w.size.between?(3, wheel_size)
next unless w.match?(middle)
wheel.each_char{|c| w.sub!(c, "") } #sub! substitutes only the first occurrence (gsub would substit... |
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... | #Transd | Transd | #lang transd
MainModule: {
maxwLen: 9,
minwLen: 3,
dict: Vector<String>(),
subWords: Vector<String>(),
procGrid: (λ grid String() cent String() subs Bool()
(with cnt 0 (sort grid)
(for w in dict where (and (neq (find w cent) -1)
(match w "^[[:alpha:]]+$")) do
(i... |
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.
| #Yabasic | Yabasic | bresline = false // space toggles, for comparison
rB = 255 : gB = 255 : bB = 224
rL = 0 : gL = 0 : bL = 255
sub round(x)
return int(x + .5)
end sub
sub plot(x, y, c, steep)
// plot the pixel at (x, y) with brightness c (where 0 <= c <= 1)
local t, C
if steep then t = x : x = y : y = t end if
... |
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 ... | #Nim | Nim | import xmltree, strtabs, sequtils
proc charsToXML(names, remarks: seq[string]): XmlNode =
result = <>CharacterRemarks()
for name, remark in items zip(names, remarks):
result.add <>Character(name=name, remark.newText)
echo charsToXML(@["April", "Tam O'Shanter", "Emily"],
@["Bubbly: I'm > Tam and <= Emily",... |
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 ... | #Objeck | Objeck | use Data.XML;
use Collection.Generic;
class Test {
function : Main(args : String[]) ~ Nil {
# list of name
names := Vector->New()<String>;
names->AddBack("April");
names->AddBack("Tam O'Shanter");
names->AddBack("Emily");
# list of comments
comments := Vector->New()<String>;
comments... |
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" /... | #Lua | Lua |
require 'lxp'
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" />... |
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,... | #VBScript | VBScript | 'Arrays - VBScript - 08/02/2021
'create a static array
Dim a(3) ' 4 items : a(0), a(1), a(2), a(3)
'assign a value to elements
For i = 1 To 3
a(i) = i * i
Next
'and retrieve elements
buf=""
For i = 1 To 3
buf = buf & a(i) & " "
Next
WScript.Echo buf
'create ... |
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... | #Vlang | Vlang | import os
const (
x = [1.0, 2, 3, 1e11]
y = [1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]
xprecision = 3
yprecision = 5
)
fn main() {
if x.len != y.len {
println("x, y different length")
return
}
mut f := os.create("filename")?
defer {
f.cl... |
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... | #Wren | Wren | import "io" for File
import "/fmt" for Fmt
var x = [1, 2, 3, 1e11]
var y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]
var xprec = 3 - 1
var yprec = 5 - 1
File.create("filename.txt") { |file|
for (i in 0...x.count) {
var f = (i < x.count-1) ? "h" : "e"
var s = Fmt.swrite("$0.... |
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... | #newLISP | newLISP | (define (status door-num)
(let ((x (int (sqrt door-num))))
(if
(= (* x x) door-num) (string "Door " door-num " Open")
(string "Door " door-num " Closed"))))
(dolist (n (map status (sequence 1 100)))
(println n))
|
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... | #Factor | Factor | USING: combinators.short-circuit io kernel lists lists.lazy
locals math math.primes.factors prettyprint sequences ;
IN: rosetta-code.weird-numbers
:: has-sum? ( n seq -- ? )
seq [ f ] [
unclip-slice :> ( xs x )
n x < [ n xs has-sum? ] [
{
[ n x = ]
[ n x... |
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... | #FreeBASIC | FreeBASIC |
Function GetFactors(n As Long,r() As Long) As Long
Redim r(0)
r(0)=1
Dim As Long count,acc
For z As Long=2 To n\2
If n Mod z=0 Then
count+=1:redim preserve r(0 to count)
r(count)=z
acc+=z
End If
Next z
... |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | locs = Position[
ImageData[Binarize[Rasterize["Mathematica", ImageSize -> 150]]], 0];
Print[StringRiffle[
StringJoin /@
ReplacePart[
ReplacePart[
ConstantArray[
" ", {Max[locs[[All, 1]]] + 1, Max[locs[[All, 2]]] + 1}],
locs -> "\\"], Map[# + 1 &, locs, {2}] -> "#"], "\n"]]; |
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
| #MiniScript | MiniScript | data = [
" ______ _____ _________",
"|\ \/ \ ___ ________ ___|\ _____\ ________ ________ ___ ________ _________ ",
"\ \ _ \ _ \|\ \|\ ___ \|\ \ \ \____||\ ____\|\ ____\|\ \|\ __ \|\___ ___\ ",
" \ \ \\\__\ \ \ \ \ \ \\ \ \ \ \ \_____ \ \ \___|\ \ ... |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible,... | #BBC_BASIC | BBC BASIC | SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF%
SYS "LoadLibrary", "WININET.DLL" TO wininet%
SYS "GetProcAddress", wininet%, "DeleteUrlCacheEntryA" TO DUCE%
url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
file$ = @tmp$+"n... |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible,... | #C | C | #include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#include <sys/types.h>
#include <regex.h>
#define BUFSIZE 16384
size_t lr = 0;
size_t filterit(void *ptr, size_t size, size_t nmemb, void *stream)
{
if ( (lr + size*nmemb) > BUFSIZE ) return BUFSIZE;
memcpy(stream+lr, ptr, size*nmemb);
lr += size... |
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... | #Racket | Racket |
#lang racket/gui
(define (say . xs) (printf ">>> ~a\n" (apply ~a xs)) (flush-output))
(define frame (new frame% [label "Demo"] [width 400] [height 400]))
(say "frame = " frame) ; plain value
(say 'Show) (send frame show #t) (sleep 1)
(say 'Hide) (send frame show #f) (sleep 1)
(say 'Show) (... |
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... | #Raku | Raku | use X11::libxdo;
my $xdo = Xdo.new;
say 'Visible windows:';
printf "Class: %-21s ID#: %10d pid: %5d Name: %s\n", $_<class ID pid name>
for $xdo.get-windows.sort(+*.key)».value;
sleep 2;
my $id = $xdo.get-active-window;
my ($w, $h ) = $xdo.get-window-size( $id );
my ($wx, $wy) = $xdo.get-window-location( ... |
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... | #Batch_File | Batch File |
@echo off
call:wordCount 1 2 3 4 5 6 7 8 9 10 42 101
pause>nul
exit
:wordCount
setlocal enabledelayedexpansion
set word=100000
set line=0
for /f "delims=" %%i in (input.txt) do (
set /a line+=1
for %%j in (%%i) do (
if not !skip%%j!==true (
echo line !line! ^| word !word:~-5! - "%%~j"
type input.t... |
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... | #Delphi | Delphi |
program Wireworld;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IOUtils;
var
rows, cols: Integer;
rx, cx: Integer;
mn: TArray<Integer>;
procedure Print(grid: TArray<byte>);
begin
writeln(string.Create('_', cols * 2), #10);
for var r := 1 to rows do
begin
for var c := 1 to cols do
... |
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... | #Python | Python | #!/usr/bin/python
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isWeiferich(p):
if not isPrime(p):
return False
q = 1
p2 = p ** 2
while p > 1:
q = (2 * q) % p2
p -= 1
if q == 1:
... |
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... | #Quackery | Quackery | 5000 eratosthenes
[ dup isprime iff
[ dup 1 - bit 1 -
swap dup * mod
0 = ]
else [ drop false ] ] is wieferich ( n --> b )
5000 times [ i^ wieferich if [ i^ echo cr ] ] |
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... | #Racket | Racket | #lang typed/racket
(require math/number-theory)
(: wieferich-prime? (-> Positive-Integer Boolean))
(define (wieferich-prime? p)
(and (prime? p)
(divides? (* p p) (sub1 (expt 2 (sub1 p))))))
(module+ main
(define wieferich-primes<5000
(for/list : (Listof Integer) ((p (sequence-filter wieferich-prime... |
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... | #Raku | Raku | put "Wieferich primes less than 5000: ", join ', ', ^5000 .grep: { .is-prime and not ( exp($_-1, 2) - 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.
| #Phix | Phix | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@lib/misc.l" "@lib/gcc.l")
(gcc "x11" '("-lX11") 'simpleWin)
#include <X11/Xlib.h>
any simpleWin(any ex) {
any x = cdr(ex);
int dx, dy;
Display *disp;
int scrn;
Window win;
XEvent ev;
x = cdr(ex), dx = (int)evCnt(ex,x);
x = cdr(x), 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.
| #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@lib/misc.l" "@lib/gcc.l")
(gcc "x11" '("-lX11") 'simpleWin)
#include <X11/Xlib.h>
any simpleWin(any ex) {
any x = cdr(ex);
int dx, dy;
Display *disp;
int scrn;
Window win;
XEvent ev;
x = cdr(ex), dx = (int)evCnt(ex,x);
x = cdr(x), 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.
| #Python | Python | from Xlib import X, display
class Window:
def __init__(self, display, msg):
self.display = display
self.msg = msg
self.screen = self.display.screen()
self.window = self.screen.root.create_window(
10, 10, 100, 100, 1,
self.screen.root_depth,
bac... |
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.
| #Fantom | Fantom |
using fwt
class Main
{
public static Void main ()
{
Window().open
}
}
|
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.
| #Forth | Forth | include ffl/gsv.fs
\ Open the connection to the gtk-server and load the Gtk2 definitions
s" gtk-server.cfg" s" ffl-fifo" gsv+open 0= [IF]
\ Convert the string event to a widget id
: event>widget
0. 2swap >number 2drop d>s
;
0 value window
: window-creation
gtk_init
\ Create the window
GTK_WINDOW_TOPLE... |
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 ... | #zkl | zkl | fcn buildVectors(R,C){ //-->up to 8 vectors of wild card strings
var [const] dirs=T(T(1,0), T(0,1), T(1,1), T(1,-1), T(-1,0),T(0,-1), T(-1,-1), T(-1,1));
vs,v:=List(),List();
foreach dr,dc in (dirs){ v.clear(); r,c:=R,C;
while( (0<=r<10) and (0<=c<10) ){ v.append(grid[r][c]); r+=dr; c+=dc; }
vs.ap... |
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... | #Factor | Factor | USE: wrap.strings
IN: scratchpad "Most languages in widespread use today are applicative languages
: the central construct in the language is some form of function call, where a f
unction is applied to a set of parameters, where each parameter is itself the re
sult of a function call, the name of a variable, or a const... |
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... | #Forth | Forth | \ wrap text
\ usage: gforth wrap.f in.txt 72
0. argc @ 1- arg >number 2drop drop constant maxLine
: .wrapped ( buf len -- )
begin
dup maxLine >
while
over maxLine
begin 1- 2dup + c@ bl = until
dup 1+ >r
begin 1- 2dup + c@ bl <> until
1+ type cr
r> /string
repeat type cr ;
: stri... |
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... | #Wren | Wren | import "io" for File
import "/sort" for Sort, Find
import "/seq" for Lst
var letters = ["d", "e", "e", "g", "k", "l", "n", "o","w"]
var words = File.read("unixdict.txt").split("\n")
// get rid of words under 3 letters or over 9 letters
words = words.where { |w| w.count > 2 && w.count < 10 }.toList
var found = []
fo... |
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 ... | #OCaml | OCaml | # #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;;
# #load "xml-light.cma" ;;
# let data = [
("April", "Bubbly: I'm > Tam and <= Emily");
("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"");
("Emily", "Short & shrift");
] in
let tags =
List.map (fun (name, co... |
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" /... | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Const Enumerator=-4&
xml$={<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... |
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" /... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Column[Cases[Import["test.xml","XML"],Rule["Name", n_ ] -> n,Infinity]] |
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,... | #VHDL | VHDL |
entity Array_Test is
end entity Array_Test;
architecture Example of Array_test is
-- Array type have to be defined first
type Integer_Array is array (Integer range <>) of Integer;
-- Array index range can be ascending...
signal A : Integer_Array (1 to 20);
-- or descending
signal B : Integer... |
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... | #Yabasic | Yabasic | x$ = "1 2 3 1e11"
pr1 = 3 : pr2 = 5
dim x$(1)
n = token(x$, x$())
f = open("filename.txt", "w")
for i = 1 to n
print #f str$(val(x$(i)), "%1." + str$(pr1) + "g") + "\t" + str$(sqrt(val(x$(i))), "%1." + str$(pr2) + "g")
next i
close #f |
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... | #zkl | zkl | fcn writeFloatArraysToFile(filename, xs,xprecision, ys,yprecision){
f :=File(filename,"w");
fmt:="%%.%dg\t%%.%dg".fmt(xprecision,yprecision).fmt; // "%.3g\t%.5g".fmt
foreach x,y in (xs.zip(ys)){ f.writeln(fmt(x,y)); }
f.close();
}
xs,ys := T(1.0, 2.0, 3.0, 1e11), xs.apply("sqrt");
xprecision,yprecision ... |
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... | #Nial | Nial | n:=100;reduce xor (count n eachright mod count n eachall<1)
looloooolooooooloooooooolooooooooooloooooooooooolooooooooooooooloooooooooooooooo
looooooooooooooooool |
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... | #Go | Go | package main
import "fmt"
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i :=... |
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
| #Modula-2 | Modula-2 | MODULE Art;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
BEGIN
(* 3D, but does not fit in the terminal window *)
(*
WriteString("_____ ______ ________ ________ ___ ___ ___ ________ _______");
WriteLn;
WriteString("|\ _ \ _ \|\ __ \|\ ___ \|\ \|\ \|\ ... |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible,... | #C.23 | C# | class Program
{
static void Main(string[] args)
{
WebClient wc = new WebClient();
Stream myStream = wc.OpenRead("http://tycho.usno.navy.mil/cgi-bin/timer.pl");
string html = "";
using (StreamReader sr = new StreamReader(myStream))
{
... |
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... | #Ring | Ring |
Load "guilib.ring"
/*
+--------------------------------------------------------------------------
+ Program Name : ScreenDrawOnReSize.ring
+ Date : 2016.06.16
+ Author : Bert Mariani
+ Purpose : Re-Draw Chart after ReSize or move
+------------------------------... |
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... | #Tcl | Tcl | package require Tk
# How to open a window
proc openWin {} {
global win
if {[info exists win] && [winfo exists $win]} {
# Already existing; just reset
wm deiconify $win
wm state $win normal
return
}
catch {destroy $win} ;# Squelch the old one
set win [toplevel .t]
... |
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... | #Bracmat | Bracmat | ( 10-most-frequent-words
= MergeSort { Local variable declarations. }
types
sorted-words
frequency
type
most-frequent-words
. ( MergeSort { Definition of function MergeSort. }
= A N Z pivot
. !arg:? [... |
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... | #C | C | #include <stdbool.h>
#include <stdio.h>
#include <glib.h>
typedef struct word_count_tag {
const char* word;
size_t count;
} word_count;
int compare_word_count(const void* p1, const void* p2) {
const word_count* w1 = p1;
const word_count* w2 = p2;
if (w1->count > w2->count)
return -1;
... |
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... | #Elena | Elena | import system'routines;
import extensions;
import cellular;
const string sample =
" tH......
. ......
...Ht... .
....
. .....
....
......tH .
. ......
...Ht...";
const string conductorLabel = ".";
const string headLabel = "H";
const string tailL... |
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... | #Elixir | Elixir | defmodule Wireworld do
@empty " "
@head "H"
@tail "t"
@conductor "."
@neighbours (for x<- -1..1, y <- -1..1, do: {x,y}) -- [{0,0}]
def set_up(string) do
lines = String.split(string, "\n", trim: true)
grid = Enum.with_index(lines)
|> Enum.flat_map(fn {line,i} ->
... |
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... | #REXX | REXX | /*REXX program finds and displays Wieferich primes which are under a specified limit N*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 5000 /*Not specified? Then use the default.*/
numeric digits 3000 ... |
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.
| #Racket | Racket | #lang racket/gui
(define frame (new frame%
[label "Example"]
[width 300]
[height 300]))
(new canvas% [parent frame]
[paint-callback
(lambda (canvas dc)
(send dc set-scale 3 3)
(send dc set-text-foregrou... |
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.
| #Raku | Raku | use NativeCall;
class Display is repr('CStruct') {
has int32 $!screen;
has int32 $!window;
}
class GC is repr('CStruct') {
has int32 $!context;
}
class XEvent is repr('CStruct') {
has int32 $.type;
method init { $!type = 0 }
}
sub XOpenDisplay(Str $name = ':0') returns Display is native('... |
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.
| #FreeBASIC | FreeBASIC |
#Include "windows.bi"
Dim As HWND Window_Main
Dim As MSG msg
'Create the window:
Window_Main = CreateWindow("#32770", "I am a window - close me!", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 350, 200, 0, 0, 0, 0)
'Windows message loop:
While GetMessage(@msg, Window_Main, 0, 0)
TranslateMessage(@msg)
Dispat... |
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.
| #Frink | Frink |
g=(new graphics).show[]
|
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... | #Fortran | Fortran | CHARACTER*12345 TEXT
...
DO I = 0,120
WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
END DO |
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... | #XPL0 | XPL0 | string 0; \use zero-terminated strings
int I, Set, HasK, HasOther, HasDup, ECnt, Ch;
char Word(25);
def LF=$0A, CR=$0D, EOF=$1A;
[FSet(FOpen("unixdict.txt", 0), ^I);
OpenI(3);
repeat I:= 0; HasK:= false; HasOther:= false;
ECnt:= 0; Set:= 0; HasDup:= false;
loop [repeat Ch:= ChIn... |
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 ... | #Oz | Oz | declare
proc {Main}
Names = ["April"
"Tam O'Shanter"
"Emily"]
Remarks = ["Bubbly: I'm > Tam and <= Emily"
"Burns: \"When chapman billies leave the street ...\""
"Short & shrift"]
Characters = {List.zip Names Remarks
fun {$ N R}
'Character'(name:N R)
end}
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" /... | #MATLAB | MATLAB | RootXML = com.mathworks.xml.XMLUtils.createDocument('Students');
docRootNode = RootXML.getDocumentElement;
thisElement = RootXML.createElement('Student');
thisElement.setAttribute('Name','April')
thisElement.setAttribute('Gender','F')
thisElement.setAttribute('DateOfBirth','1989-01-02')
docRootNode.appendChild(thisElem... |
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,... | #Vim_Script | Vim Script | " Creating a dynamic array with some initial values
let array = [3, 4]
" Retrieving an element
let four = array[1]
" Modifying an element
let array[0] = 2
" Appending a new element
call add(array, 5)
" Prepending a new element
call insert(array, 1)
" Inserting a new element before another element
call insert(... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | SAVE "myarray" DATA g() |
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... | #Nim | Nim | from strutils import `%`
const numDoors = 100
var doors: array[1..numDoors, bool]
for pass in 1..numDoors:
for door in countup(pass, numDoors, pass):
doors[door] = not doors[door]
for door in 1..numDoors:
echo "Door $1 is $2." % [$door, if doors[door]: "open" else: "closed"] |
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... | #Haskell | Haskell | weirds :: [Int]
weirds = filter abundantNotSemiperfect [1 ..]
abundantNotSemiperfect :: Int -> Bool
abundantNotSemiperfect n =
let ds = descProperDivisors n
d = sum ds - n
in 0 < d && not (hasSum d ds)
hasSum :: Int -> [Int] -> Bool
hasSum _ [] = False
hasSum n (x:xs)
| n < x = hasSum n xs
| otherwise... |
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
| #Nanoquery | Nanoquery | println " ________ ________ ________ ________ ________ ___ ___ _______ ________ ___ ___ "
println "|\\ ___ \\|\\ __ \\|\\ ___ \\|\\ __ \\|\\ __ \\|\\ \\|\\ \\|\\ ___ \\ |\\ __ \\ |\\ \\ / /| "
println "\\ \\ \\\\ \\ \\ \\ \\|\\ \\ \\ \\\\ \\ \\ \\ \\|\\ \\ \\... |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
txt = '';
x = 0
x = x + 1; txt[0] = x; txt[x] = ' * * *****'
x = x + 1; txt[0] = x; txt[x] = ' ** * * * *'
x = x + 1; txt[0] = x; txt[x] = ' * * * *** *** * * *** * * * *'
x = x + 1; txt[0] = x;... |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible,... | #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/regex.hpp>
int main()
{
boost::asio::ip::tcp::iostream s("tycho.usno.navy.mil", "http");
if(!s)
std::cout << "Could not connect to tycho.usno.navy.mil\n";
s << "GET /cgi-bin/timer.pl HTTP/1.0\r\n"
<< "Host: tycho... |
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... | #Wren | Wren | /* window_management.wren */
var GTK_WINDOW_TOPLEVEL = 0
var GTK_ORIENTATION_VERTICAL = 1
var GTK_BUTTONBOX_CENTER = 5
foreign class GtkWindow {
construct new(type) {}
foreign title=(title)
foreign setDefaultSize(width, height)
foreign add(widget)
foreign connectDestroy()
foreign showA... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace WordCount {
class Program {
static void Main(string[] args) {
var text = File.ReadAllText("135-0.txt").ToLower();
var match = Regex.Match(text, "\\w... |
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... | #Forth | Forth | 16 constant w
8 constant h
: rows w * 2* ;
1 rows constant row
h rows constant size
create world size allot
world value old
old w + value new
: init world size erase ;
: age new old to new to old ;
: foreachrow ( xt -- )
size 0 do I over execute row +loop drop ;
0 constant EMPTY
1 constant ... |
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... | #Ruby | Ruby | require "prime"
puts Prime.each(5000).select{|p| 2.pow(p-1 ,p*p) == 1 }
|
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... | #Rust | Rust | // [dependencies]
// primal = "0.3"
// mod_exp = "1.0"
fn wieferich_primes(limit: usize) -> impl std::iter::Iterator<Item = usize> {
primal::Primes::all()
.take_while(move |x| *x < limit)
.filter(|x| mod_exp::mod_exp(2, *x - 1, *x * *x) == 1)
}
fn main() {
let limit = 5000;
println!("Wie... |
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... | #Sidef | Sidef | func is_wieferich_prime(p, base=2) {
powmod(base, p-1, p**2) == 1
}
say ("Wieferich primes less than 5000: ", 5000.primes.grep(is_wieferich_prime)) |
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... | #Swift | Swift | func primeSieve(limit: Int) -> [Bool] {
guard limit > 0 else {
return []
}
var sieve = Array(repeating: true, count: limit)
sieve[0] = false
if limit > 1 {
sieve[1] = false
}
if limit > 4 {
for i in stride(from: 4, to: limit, by: 2) {
sieve[i] = false
... |
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... | #Wren | Wren | import "/math" for Int
import "/big" for BigInt
var primes = Int.primeSieve(5000)
System.print("Wieferich primes < 5000:")
for (p in primes) {
var num = (BigInt.one << (p - 1)) - 1
var den = p * p
if (num % den == 0) System.print(p)
} |
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.
| #Scala | Scala | import scala.swing.{ MainFrame, SimpleSwingApplication }
import scala.swing.Swing.pair2Dimension
object WindowExample extends SimpleSwingApplication {
def top = new MainFrame {
title = "Hello!"
centerOnScreen
preferredSize = ((200, 150))
}
} |
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.
| #Standard_ML | Standard ML | open XWindows ;
val dp = XOpenDisplay "" ;
val w = XCreateSimpleWindow (RootWindow dp) origin (Area {x=0,y=0,w=400,h=300}) 3 0 0xffffff ;
XMapWindow w;
XFlush dp ;
XDrawString w (DefaultGC dp) (XPoint {x=10,y=50}) "Hello World!" ;
XFlush dp ; |
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.
| #FutureBasic | FutureBasic | window 1 |
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.
| #Gambas | Gambas | Public Sub Form_Open()
End |
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... | #FreeBASIC | FreeBASIC | Dim Shared As String texto, dividido()
texto = "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 ... |
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 ... | #Perl | Perl | #! /usr/bin/perl
use strict;
use XML::Mini::Document;
my @students = ( [ "April", "Bubbly: I'm > Tam and <= Emily" ],
[ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" ],
[ "Emily", "Short & shrift" ]
);
my $doc = XML::Mini::Document->new();
my $root = $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" /... | #Neko | Neko | /**
XML/Input in Neko
Tectonics:
nekoc xml-input.neko
neko xml-input | recode html
*/
/* Get the Neko XML parser function */
var parse_xml = $loader.loadprim("std@parse_xml", 2);
/* Load the student.xml file as string */
var file_contents = $loader.loadprim("std@file_contents", 1);
var xmlString = file_cont... |
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,... | #Visual_Basic_.NET | Visual Basic .NET | 'Example of array of 10 int types:
Dim numbers As Integer() = New Integer(9) {}
'Example of array of 4 string types:
Dim words As String() = {"hello", "world", "from", "mars"}
'You can also declare the size of the array and initialize the values at the same time:
Dim more_numbers As Integer() = New Integer(2) {21, 1... |
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... | #Oberon | Oberon | MODULE Doors;
IMPORT Out;
PROCEDURE Do*; (* In Oberon an asterisk after an identifier is an export mark *)
CONST N = 100; len = N + 1;
VAR i, j: INTEGER;
closed: ARRAY len OF BOOLEAN; (* Arrays in Oberon always start with index 0; closed[0] is not used *)
BEGIN
FOR i := 1 TO N DO closed[i] :... |
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... | #J | J |
factor=: [: }: [: , [: */&> [: { [: <@(^ i.@>:)/"1 [: |: __&q:
classify=: 3 : 0
weird =: perfect =: deficient =: abundant =: i. 0
a=: (i. -. 0 , deficient =: 1 , i.&.:(p:inv)) y NB. a are potential semi-perfect numbers
for_n. a do.
if. n e. a do.
factors=. factor n
sf =. +/ factors
if. sf < n do.
... |
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... | #Java | Java |
import java.util.ArrayList;
import java.util.List;
public class WeirdNumbers {
public static void main(String[] args) {
int n = 2;
// n += 2 : No odd weird numbers < 10^21
for ( int count = 1 ; count <= 25 ; n += 2 ) {
if ( isWeird(n) ) {
System.out.printf(... |
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
| #Nim | Nim | import strutils
const nim = """
# # ##### # #
## # # ## ##
# # # # # ## #
# # # # # #
# ## # # #
# # ##### # #
"""
let lines = nim.dedent.multiReplace(("#", "<<<"), (" "... |
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
| #OCaml | OCaml |
print_string "
_|_|_| _|_|_| _|_| _|_| _|_| _|
_| _| _| _| _| _| _| _| _| _|
_| _| _| _|_|_| _| _| _| _| _|
_| _| _| _| _| _| _| _|
... |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible,... | #Cach.C3.A9_ObjectScript | Caché ObjectScript |
Class Utils.Net [ Abstract ]
{
ClassMethod ExtractHTMLData(pHost As %String = "", pPath As %String = "", pRegEx As %String = "", Output list As %List) As %Status
{
// implement error handling
Try {
// some initialisation
Set list="", sc=$$$OK
// check input parameters
If $Match(pHost, "^([a-... |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible,... | #Ceylon | Ceylon | import ceylon.uri {
parse
}
import ceylon.http.client {
get
}
shared void run() {
// apparently the cgi link is deprecated?
value oldUri = "http://tycho.usno.navy.mil/cgi-bin/timer.pl";
value newUri = "http://tycho.usno.navy.mil/timer.pl";
value contents = downloadContents(newUri);
val... |
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... | #C.2B.2B | C++ | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_map>
#include <vector>
int main(int ac, char** av) {
std::ios::sync_with_stdio(false);
int head = (ac > 1) ? std::atoi(av[1]) : 10;
std::istreambuf_iterator<char> it(std::cin)... |
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... | #Fortran | Fortran | program Wireworld
implicit none
integer, parameter :: max_generations = 12
integer :: nrows = 0, ncols = 0, maxcols = 0
integer :: gen, ierr = 0
integer :: i, j
character(1), allocatable :: cells(:,:)
character(10) :: form, sub
character(80) :: buff
! open input file
open(unit=8, file="wwinput.txt... |
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.
| #Tcl | Tcl | package provide xlib 1
package require critcl
critcl::clibraries -L/usr/X11/lib -lX11
critcl::ccode {
#include <X11/Xlib.h>
static Display *d;
static GC gc;
}
# Display connection functions
critcl::cproc XOpenDisplay {Tcl_Interp* interp char* name} ok {
d = XOpenDisplay(name[0] ? name : NULL);
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.
| #Go | Go | package main
import (
"github.com/mattn/go-gtk/glib"
"github.com/mattn/go-gtk/gtk"
)
func main() {
gtk.Init(nil)
window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
window.Connect("destroy",
func(*glib.CallbackContext) { gtk.MainQuit() }, "")
window.Show()
gtk.Main()
} |
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.
| #Groovy | Groovy | import groovy.swing.SwingBuilder
new SwingBuilder().frame(title:'My Window', size:[200,100]).show()
|
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.