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/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... | #ALGOL_68 | ALGOL 68 | CO
Wireworld implementation.
CO
PROC exception = ([]STRING args)VOID:(
putf(stand error, ($"Exception"$, $", "g$, args, $l$));
stop
);
PROC assertion error = (STRING message)VOID:exception(("assertion error", message));
MODE CELL = CHAR;
MODE WORLD = FLEX[0, 0]CELL;
CELL head="H", tail="t", conductor=".", emp... |
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... | #BASIC | BASIC | print "Wieferich primes less than 5000: "
for i = 1 to 5000
if isWeiferich(i) then print i
next i
end
function isWeiferich(p)
if not isPrime(p) then return False
q = 1
p2 = p ^ 2
while p > 1
q = (2 * q) mod p2
p -= 1
end while
if q = 1 then return True else return False
end... |
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... | #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#define LIMIT 5000
static bool PRIMES[LIMIT];
static void prime_sieve() {
uint64_t p;
int i;
PRIMES[0] = false;
PRIMES[1] = false;
for (i = 2; i < LIMIT; i++) {
PRIMES[i] = true;
}
for (i = 4; i < LIMIT; i += 2) {
... |
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.
| #Forth | Forth |
warnings off
require xlib.fs
0 value X11-D \ Display
0 value X11-S \ Screen
0 value X11-root
0 value X11-GC
0 value X11-W \ Window
0 value X11-Black
0 value X11-White
9 value X11-Top
0 value X11-Left
create X11-ev 96 allot
variable wm_delete
: X... |
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.
| #Go | Go | package main
// Copyright (c) 2013 Alex Kesling
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, ... |
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... | #Java | Java | import java.math.BigInteger;
import java.util.*;
public class WilsonPrimes {
public static void main(String[] args) {
final int limit = 11000;
BigInteger[] f = new BigInteger[limit];
f[0] = BigInteger.ONE;
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i < limit; ++... |
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.
| #BASIC256 | BASIC256 | clg
text (50,50, "I write in the graphics area") |
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.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"WINLIB2"
dlg% = FN_newdialog("GUI Window", 0, 0, 200, 150, 8, 1000)
PROC_showdialog(dlg%) |
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 ... | #Nim | Nim | import random, sequtils, strformat, strutils
const
Dirs = [[1, 0], [ 0, 1], [ 1, 1],
[1, -1], [-1, 0],
[0, -1], [-1, -1], [-1, 1]]
NRows = 10
NCols = 10
GridSize = NRows * NCols
MinWords = 25
type Grid = ref object
numAttempts: Natural
cells: array[NRows, array[NCol... |
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 ... | #Perl | Perl | #!/usr/bin/perl
use strict; # http://www.rosettacode.org/wiki/Word_search
use warnings;
use Path::Tiny;
use List::Util qw( shuffle );
my $size = 10;
my $s1 = $size + 1;
$_ = <<END;
.....R....
......O...
.......S..
........E.
T........T
.A........
..C.......
...O......
....D.....
.....E....
END
my @words = shuffle... |
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.2B.2B | C++ | #include <iostream>
#include <sstream>
#include <string>
const char *text =
{
"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 i... |
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 ... | #REXX | REXX | lower: procedure; parse arg a; @= 'abcdefghijklmnopqrstuvwxyz'; @u= @; upper @u
return translate(a, @, @u) |
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 ... | #Ruby | Ruby | require "set"
Words = File.open("unixdict.txt").read.split("\n").
group_by { |w| w.length }.map { |k, v| [k, Set.new(v)] }.
to_h
def word_ladder(from, to)
raise "Length mismatch" unless from.length == to.length
sized_words = Words[from.length]
work_queue = [[from]]
used = Set.new [from]
while work_que... |
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... | #Pascal | Pascal |
program WordWheel;
{$mode objfpc}{$H+}
uses
SysUtils;
const
WheelSize = 9;
MinLength = 3;
WordListFN = 'unixdict.txt';
procedure search(Wheel : string);
var
Allowed, Required, Available, w : string;
Len, i, p : integer;
WordFile : TextFile;
Match : boolean;
begin
AssignFile(WordFile, WordLis... |
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.
| #REXX | REXX | /*REXX program plots/draws (ASCII) a line using the Xiaolin Wu line algorithm. */
background= '·' /*background character: a middle-dot. */
image.= background /*fill the array with middle-dots. */
plotC= '░▒▓█' ... |
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 ... | #HicEst | HicEst | CHARACTER names="April~Tam O'Shanter~Emily~"
CHARACTER remarks*200/%Bubbly: I'm > Tam and <= Emily~Burns: "When chapman billies leave the street ..."~Short & shrift~%/
CHARACTER XML*1000
EDIT(Text=remarks, Right='&', RePLaceby='&', DO)
EDIT(Text=remarks, Right='>', RePLaceby='>', DO)
EDIT(Text=remarks, Right='... |
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 ... | #J | J | tbl=: ('"e;'; '&'; '<'; '>') (a.i.'"&<>')} <"0 a.
esc=: [:; {&tbl@:i.~&a. |
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" /... | #HicEst | HicEst | CHARACTER in*1000, out*100
READ(ClipBoard) in
EDIT(Text=in, SPR='"', Right='<Student', Right='Name=', Word=1, WordEnd, APpendTo=out, DO) |
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,... | #TXR | TXR | (defvar li (list 1 2 3)) ;; (1 2 3)
(defvar ve (vec 1 2 3)) ;; make vector #(1 2 3)
;; (defvar ve (vector 3)) ;; make #(nil nil nil)
[ve 0] ;; yields 1
[li 0] ;; yields 1
[ve -1] ;; yields 3
[li 5] ;; yields nil
[li -50] ;; yields nil
[ve 50] ;; error
(set [ve 2] 4) ;; changes vector to #(1 2 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... | #Ring | Ring |
# Project : Write float arrays to a text file
decimals(13)
x = [1, 2, 3, 100000000000]
y = [1, 1.4142135623730, 1.7320508075688, 316227.76601683]
str = list(4)
fn = "C:\Ring\calmosoft\output.txt"
fp = fopen(fn,"wb")
for i = 1 to 4
str[i] = string(x[i]) + " | " + string(y[i]) + windowsnl()
fwrite(fp, str[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... | #RLaB | RLaB |
>> x = rand(10,1); y = rand(10,1);
>> writem("mytextfile.txt", [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... | #MOO | MOO | is_open = make(100);
for pass in [1..100]
for door in [pass..100]
if (door % pass)
continue;
endif
is_open[door] = !is_open[door];
endfor
endfor
"output the result";
for door in [1..100]
player:tell("door #", door, " is ", (is_open[door] ? "open" : "closed"), ".");
endfor |
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... | #AppleScript | AppleScript | on run
take(25, weirds())
-- Gets there, but takes about 6 seconds on this system,
-- (logging intermediates through the Messages channel, for the impatient :-)
end run
-- weirds :: Gen [Int]
on weirds()
script
property x : 1
property v : 0
on |λ|()
repeat until 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
| #Go | Go | package main
import (
"fmt"
"strings"
)
var lean = font{
height: 5,
slant: 1,
spacing: 2,
m: map[rune][]string{
'G': []string{
` _/_/_/`,
`_/ `,
`_/ _/_/`,
`_/ _/`,
` _/_/_/`,
},
'o': []string{
... |
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... | #Java | Java | import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
impo... |
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... | #Ada | Ada | with Ada.Command_Line;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Strings.Maps;
with Ada.Strings.Fixed;
with Ada.Characters.Handling;
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Containers.Indefinite_Ordered_Sets;
with Ada.Containers.Ordered_Maps;
procedure Word_Frequency is
package TIO rename... |
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... | #AutoHotkey | AutoHotkey | #SingleInstance, Force
#NoEnv
SetBatchLines, -1
File := "Wireworld.txt"
CellSize := 20
CellSize2 := CellSize - 2
C1 := 0xff000000
C2 := 0xff0066ff
C3 := 0xffd40055
C4 := 0xffffcc00
if (!FileExist(File)) {
MsgBox, % "File(" File ") is not present."
ExitApp
}
; Uncomment if Gdip.ahk is not in your standard library
... |
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... | #C.2B.2B | C++ | #include <cstdint>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(uint64_t limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (uint64_t i = 4; i < limit; i += 2)
sieve[i] = false;
for (ui... |
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.
| #Groovy | Groovy | groovy WindowCreation.groovy
|
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.
| #GUISS | GUISS | Start,Programs,Applications,Editors,Leafpad,Textbox,
Type:[openbox]Hello World[pling][closebox] |
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... | #jq | jq | def emit_until(cond; stream): label $out | stream | if cond then break $out else . end;
# For 0 <= $n <= ., factorials[$n] is $n !
def factorials:
reduce range(1; .+1) as $n ([1];
.[$n] = $n * .[$n-1]);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
def primes: 2, (range(3; infinit... |
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... | #Julia | Julia | using Primes
function wilsonprimes(limit = 11000)
sgn, facts = 1, accumulate(*, 1:limit, init = big"1")
println(" n: Wilson primes\n--------------------")
for n in 1:11
print(lpad(n, 2), ": ")
sgn = -sgn
for p in primes(limit)
if p > n && (facts[n < 2 ? 1 : n - 1] * f... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[WilsonPrime]
WilsonPrime[n_Integer] := Module[{primes, out},
primes = Prime[Range[PrimePi[11000]]];
out = Reap@Do[
If[Divisible[((n - 1)!) ((p - n)!) - (-1)^n, p^2], Sow[p]]
,
{p, primes}
];
First[out[[2]], {}]
]
Do[
Print[WilsonPrime[n]]
,
{n, 1, 11}
] |
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... | #Nim | Nim | import strformat, strutils
import bignum
const Limit = 11_000
# Build list of primes using "nextPrime" function from "bignum".
var primes: seq[int]
var p = newInt(2)
while p < Limit:
primes.add p.toInt
p = p.nextPrime()
# Build list of factorials.
var facts: array[Limit, Int]
facts[0] = newInt(1)
for i in 1..... |
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... | #Perl | Perl | use strict;
use warnings;
use ntheory <primes factorial>;
my @primes = @{primes( 10500 )};
for my $n (1..11) {
printf "%3d: %s\n", $n, join ' ', grep { $_ >= $n && 0 == (factorial($n-1) * factorial($_-$n) - (-1)**$n) % $_**2 } @primes
} |
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.
| #C | C | /*
* Opens an 800x600 16bit color window.
* Done here with ANSI C.
*/
#include <stdio.h>
#include <stdlib.h>
#include "SDL.h"
int main()
{
SDL_Surface *screen;
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
atexit(SDL_Qui... |
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.
| #C.23 | C# | using System;
using System.Windows.Forms;
public class Window {
[STAThread]
static void Main() {
Form form = new Form();
form.Text = "Window";
form.Disposed += delegate { Application.Exit(); };
form.Show();
Application.Run();
}
} |
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 ... | #Phix | Phix | --
-- demo\rosetta\wordsearch.exw
-- ===========================
--
with javascript_semantics
string message = "ROSETTACODE"
sequence words = unix_dict(), solution="", placed
constant grid = split("""
X 0 1 2 3 4 5 6 7 8 9 X
0 X
1 X
2 ... |
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... | #Clojure | Clojure | ;; Wrap line naive version
(defn wrap-line [size text]
(loop [left size line [] lines []
words (clojure.string/split text #"\s+")]
(if-let [word (first words)]
(let [wlen (count word)
spacing (if (== left size) "" " ")
alen (+ (count spacing) wlen)]
(if (<= alen left... |
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 ... | #Swift | Swift | import Foundation
func oneAway(string1: [Character], string2: [Character]) -> Bool {
if string1.count != string2.count {
return false
}
var result = false
var i = 0
while i < string1.count {
if string1[i] != string2[i] {
if result {
return false
... |
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 ... | #Wren | Wren | import "io" for File
import "/sort" for Find
var words = File.read("unixdict.txt").trim().split("\n")
var oneAway = Fn.new { |a, b|
var sum = 0
for (i in 0...a.count) if (a[i] != b[i]) sum = sum + 1
return sum == 1
}
var wordLadder = Fn.new { |a, b|
var l = a.count
var poss = words.where { |w|... |
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... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Word_wheel
use warnings;
$_ = <<END;
N D E
O K G
E L W
END
my $file = do { local(@ARGV, $/) = 'unixdict.txt'; <> };
my $length = my @letters = lc =~ /\w/g;
my $center = $letters[@letters / ... |
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... | #Phix | Phix | with javascript_semantics
requires("1.0.1") -- (fixed another glitch in unique())
constant wheel = "ndeokgelw",
musthave = wheel[5]
sequence words = unix_dict(),
word9 = {} -- (for the optional extra part)
integer found = 0
for i=1 to length(words) do
string word = lower(words[i])
integer lw =... |
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.
| #Ruby | Ruby | def ipart(n); n.truncate; end
def fpart(n); n - ipart(n); end
def rfpart(n); 1.0 - fpart(n); end
class Pixmap
def draw_line_antialised(p1, p2, colour)
x1, y1 = p1.x, p1.y
x2, y2 = p2.x, p2.y
steep = (y2 - y1).abs > (x2 - x1).abs
if steep
x1, y1 = y1, x1
x2, y2 = y2, x2
end
if x... |
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 ... | #Java | Java | import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamR... |
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" /... | #J | J | load'xml/sax'
saxclass 'Students'
startElement =: ([: smoutput 'Name' getAttribute~ [)^:('Student'-:])
cocurrent'base'
process_Students_ XML |
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,... | #uBasic.2F4tH | uBasic/4tH | Let @(0) = 5 : Print @(0) |
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... | #Ruby | Ruby | # prepare test data
x = [1, 2, 3, 1e11]
y = x.collect { |xx| Math.sqrt xx }
xprecision = 3
yprecision = 5
# write the arrays
open('sqrt.dat', 'w') do |f|
x.zip(y) { |xx, yy| f.printf("%.*g\t%.*g\n", xprecision, xx, yprecision, yy) }
end
# print the result file
open('sqrt.dat', 'r') { |f| puts f.read } |
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... | #Run_BASIC | Run BASIC | x$ = "1, 2, 3, 1e11"
y$ = "1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791"
open "filename" for output as #f ' Output to "filename"
for i = 1 to 4
print #f, using("##############.###",val(word$(x$,i,",")));"|";using("#######.#####",val(word$(y$,i,",")))
next i
close #f |
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... | #MoonScript | MoonScript | is_open = [false for door = 1,100]
for pass = 1,100
for door = pass,100,pass
is_open[door] = not is_open[door]
for i,v in ipairs is_open
print "Door #{i}: " .. if v then '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... | #C | C | #include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
#include "string.h"
struct int_a {
int *ptr;
size_t size;
};
struct int_a divisors(int n) {
int *divs, *divs2, *out;
int i, j, c1 = 0, c2 = 0;
struct int_a array;
divs = malloc(n * sizeof(int) / 2);
divs2 = malloc(n * sizeof(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
| #Groovy | Groovy | 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
| #Haskell | Haskell | module Main where
{-
__ __ __ ___ ___
/\ \/\ \ /\ \ /\_ \ /\_ \
\ \ \_\ \ __ ____\ \ \/'\ __\//\ \ \//\ \
\ \ _ \ /'__`\ /',__\\ \ , < /'__`\\ \ \ \ \ \
\ \ \ \ \/\ \L\.\_/\__, `\\ \ \\`\ /\ __/ \_\ \_ \_\ \_
\ \_\ \_\ \__/.... |
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... | #Julia | Julia | using Gtk
function controlwindow(win, lab)
sleep(4)
set_gtk_property!(lab, :label, "Hiding...")
sleep(1)
println("Hiding widow")
set_gtk_property!(win, :visible, false)
sleep(5)
set_gtk_property!(lab, :label, "Showing...")
println("Showing window")
set_gtk_property!(win, :visible, ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | nb=NotebookCreate[]; (*Create a window and store in a variable*)
nb===nb2 (*test for equality with another window object*)
SetOptions[nb,Visible->False](*Hide*)
SetOptions[nb,Visible->True](*Show*)
NotebookClose[nb] (*Close*)
SetOptions[nb,WindowMargins->{{x,Automatic},{y,Automatic}}](*Move to x,y screen position*)
Set... |
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... | #ALGOL_68 | ALGOL 68 | # find the n most common words in a file #
# use the associative array in the Associate array/iteration task #
# but with integer values #
PR read "aArrayBase.a68" PR
MODE AAKEY = STRING;
MODE AAVALUE = INT;
AAVALUE init element value = 0;
# re... |
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... | #AutoIt | AutoIt |
$ww = ""
$ww &= "tH........." & @CR
$ww &= ". . " & @CR
$ww &= " ... " & @CR
$ww &= ". . " & @CR
$ww &= "Ht.. ......"
$rows = StringSplit($ww, @CR)
$cols = StringSplit($rows[1], "")
Global $Wireworldarray[$rows[0]][$cols[0]]
For $I = 1 To $rows[0]
$cols = StringSplit($rows[$I], "")
For $k = 1 To... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace WieferichPrimes {
class Program {
static long ModPow(long @base, long exp, long mod) {
if (mod == 1) {
return 0;
}
long result = 1;
@base %= mod;
for (... |
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.
| #Haskell | Haskell | import Graphics.X11.Xlib
import Control.Concurrent (threadDelay)
main = do
display <- openDisplay ""
let defScr = defaultScreen display
rw <- rootWindow display defScr
xwin <- createSimpleWindow display rw
0 0 400 200 1
(blackPixel display defScr)
(whitePixel display defScr)
setTextPro... |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
W1 := open("X-Window","g","size=250,250","bg=black","fg=red") | stop("unable to open window")
FillRectangle(W1,50,50,150,150)
WDone(W1)
end
link graphics |
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... | #Phix | Phix | with javascript_semantics
constant limit = 11000
include mpfr.e
mpz f = mpz_init()
sequence primes = get_primes_le(limit),
facts = mpz_inits(limit,1) -- (nb 0!==1!, same slot)
for i=2 to limit do mpz_mul_si(facts[i],facts[i-1],i) end for
integer sgn = 1
printf(1," n: Wilson primes\n")
printf(1,"--------------... |
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... | #Prolog | Prolog | main:-
wilson_primes(11000).
wilson_primes(Limit):-
writeln(' n | Wilson primes\n---------------------'),
make_factorials(Limit),
find_prime_numbers(Limit),
wilson_primes(1, 12, -1).
wilson_primes(N, N, _):-!.
wilson_primes(N, M, S):-
wilson_primes(N, S),
S1 is -S,
N1 is N + 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.
| #C.2B.2B | C++ | #include <QApplication>
#include <QMainWindow>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow window;
window.show();
return app.exec();
} |
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.
| #Clojure | Clojure | (import '(javax.swing JFrame))
(let [frame (JFrame. "A Window")]
(doto frame
(.setSize 600 800)
(.setVisible true))) |
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 ... | #Python | Python |
import re
from random import shuffle, randint
dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
class Grid:
def __init__(self):
self.num_attempts = 0
self.cells = [['' for _ in range(n_cols)] for _... |
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... | #Commodore_BASIC | Commodore BASIC | 10 rem word wrap - commodore basic
20 rem rosetta code
30 s$="":co=40:gosub 200
35 print chr$(147);chr$(14)
40 print "The current string is:"
41 print chr$(18);s$;chr$(146)
42 print:print "Enter a string, blank to keep previous,"
43 print "or type 'sample' to use a preset"len(z$)" character string."
44 print:input 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... | #Picat | Picat | main =>
MinLen = 3,
MaxLen = 9,
Chars = "ndeokgelw",
MustContain = 'k',
WordList = "unixdict.txt",
Words = read_file_lines(WordList),
Res = word_wheel(Chars,Words,MustContain,MinLen, MaxLen),
println(Res),
println(len=Res.len),
nl.
word_wheel(Chars,Words,MustContain,MinLen,MaxLen) = Res.reverse ... |
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... | #PureBasic | PureBasic | Procedure.b check_word(word$)
Shared letters$
If Len(word$)<3 Or FindString(word$,"k")<1
ProcedureReturn #False
EndIf
For i=1 To Len(word$)
If CountString(letters$,Mid(word$,i,1))<CountString(word$,Mid(word$,i,1))
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedu... |
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.
| #Scala | Scala | import java.awt.Color
import math.{floor => ipart, round, abs}
case class Point(x: Double, y: Double) {def swap = Point(y, x)}
def plotter(bm: RgbBitmap, c: Color)(x: Double, y: Double, v: Double) = {
val X = round(x).toInt
val Y = round(y).toInt
val V = v.toFloat
// tint the existing pixels
val c1 = c.ge... |
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 ... | #Joy | Joy |
DEFINE subst ==
[[['< "<" putchars]
['> ">" putchars]
['& "&" putchars]
[putch]] case] step;
XMLOutput ==
"<CharacterRemarks>\n" putchars
[ "<Character name=\"" putchars uncons swap putchars "\">" putchars first subst "</Character>\n" putchars] step
"</CharacterRemarks>\n" putchars.
[ [ "April"... |
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 ... | #Julia | Julia | using LightXML
dialog = [("April", "Bubbly: I'm > Tam and <= Emily"),
("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""),
("Emily", "Short & shrift")]
const xdoc = XMLDocument()
const xroot = create_root(xdoc, "CharacterRemarks")
for (name, remarks) in dialog
xs1 = n... |
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" /... | #Java | Java | import java.io.IOException;
import java.io.StringReader;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
public class StudentHandler extends DefaultHand... |
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,... | #Unicon_2 | Unicon | L := list(100); L[12] := 7; a := array(100, 0.0); a[3] +:= a[1]+a[2] |
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... | #SAS | SAS | data _null_;
input x y;
file "output.txt";
put x 12.3 " " y 12.5;
cards;
1 1
2 1.4142135623730951
3 1.7320508075688772
1e11 316227.76601683791
;
run; |
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... | #Scala | Scala | import java.io.{File, FileWriter, IOException}
object FloatArray extends App {
val x: List[Float] = List(1f, 2f, 3f, 1e11f)
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
using(new FileWriter(file, appending))(_.write(data))
def using[A <: {def close() : Unit}, B](resource... |
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... | #MUMPS | MUMPS | doors new door,pass
For door=1:1:100 Set door(door)=0
For pass=1:1:100 For door=pass:pass:100 Set door(door)='door(door)
For door=1:1:100 If door(door) Write !,"Door",$j(door,4)," is open"
Write !,"All other doors are closed."
Quit
Do doors
Door 1 is open
Door 4 is open
Door 9 is open
Door 16 is open
Door ... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WeirdNumbers {
class Program {
static List<int> Divisors(int n) {
List<int> divs = new List<int> { 1 };
List<int> divs2 = new List<int>();
for... |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
write(ExpandText(
if !arglist == "icon" then
"14/\\\n14\\/\n12/\\\n11/1/\n10/1/1/\\\n10\\/1/2\\\n12/1/\\1\\\n_
12\\1\\1\\/\n10/\\1\\1\\2/\\\n9/2\\1\\/1/2\\\n_
8/1/\\1\\2/1/\\1\\2/\\\n8\\1\\/1/2\\1\\/1/2\\1\\\n_
6/\\1\\2/4\\2/1/\\1\\1\\\n5/1/2\\/6\\/1/2\\1\\/\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,... | #8th | 8th | \ Web-scrape sample: get UTC time from the US Naval Observatory:
: read-url \ -- s
"http://tycho.usno.navy.mil/cgi-bin/timer.pl" net:get
not if "Could not connect" throw then
>s ;
: get-time
read-url
/<BR>.*?(\d{2}:\d{2}:\d{2})\sUTC/
tuck r:match if
1 r:@ . cr
then ;
get-time bye
|
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... | #Nim | Nim | import os
import gintro/[glib, gobject, gtk, gio]
from gintro/gdk import processAllUpdates
type MyWindow = ref object of ApplicationWindow
isShifted: bool
#---------------------------------------------------------------------------------------------------
proc wMaximize(button: Button; window: MyWindow) =
win... |
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... | #Oz | Oz | declare
[QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
%% The messages that can be sent to the windows.
WindowActions =
[hide show close
iconify deiconify
maximize restore
set(minsize:minsize(width:400 height:400))
set(minsize:minsize(width:200 height:200))
set(geometry:geometry(x:0 y:0))
... |
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... | #APL | APL |
⍝⍝ NOTE: input text is assumed to be encoded in ISO-8859-1
⍝⍝ (The suggested example '135-0.txt' of Les Miserables on
⍝⍝ Project Gutenberg is in UTF-8.)
⍝⍝
⍝⍝ Use Unix 'iconv' if required
⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝⍝
∇r ← lowerAndStrip s;stripped;mixedCase
⍝⍝ Convert text to lowercase, punctuation and newlines to... |
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... | #AppleScript | AppleScript | (*
For simplicity here, words are considered to be uninterrupted sequences of letters and/or digits.
The set text is too messy to warrant faffing around with anything more sophisticated.
The first letter in each word is upper-cased and the rest lower-cased for case equivalence and presentation.
Where mo... |
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... | #BBC_BASIC | BBC BASIC | Size% = 20
DIM P&(Size%-1,Size%-1), Q&(Size%-1,Size%-1)
VDU 23,22,Size%*8;Size%*8;64,64,16,0
OFF
DATA "tH........."
DATA ". . "
DATA " ... "
DATA ". . "
DATA "Ht.. ......"
FOR Y% = 12 TO 8 STEP -1
READ A$
FOR X% = 1 TO... |
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... | #C | C | /* 2009-09-27 <kaz@kylheku.com> */
#define ANIMATE_VT100_POSIX
#include <stdio.h>
#include <string.h>
#ifdef ANIMATE_VT100_POSIX
#include <time.h>
#endif
char world_7x14[2][512] = {
{
"+-----------+\n"
"|tH.........|\n"
"|. . |\n"
"| ... |\n"
"|. . |\n"
"|Ht.. ......|\n"
... |
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... | #F.23 | F# |
// Weiferich primes: Nigel Galloway. June 2nd., 2021
primes32()|>Seq.takeWhile((>)5000)|>Seq.filter(fun n->(2I**(n-1)-1I)%(bigint(n*n))=0I)|>Seq.iter(printfn "%d")
|
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... | #Factor | Factor | USING: io kernel math math.functions math.primes prettyprint
sequences ;
"Wieferich primes less than 5000:" print
5000 primes-upto [ [ 1 - 2^ 1 - ] [ sq divisor? ] bi ] filter . |
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... | #fermat | fermat |
Func Iswief(p)=Isprime(p)*Divides(p^2, 2^(p-1)-1).
for i=2 to 5000 do if Iswief(i) then !!i fi od
|
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... | #Forth | Forth | : prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
: prime_sieve { n -- }
here n erase
0 notprime!
1 notprime!
n 4 > if
n 4 do i notprime! 2 +loop
then
3
begin
dup dup * n <
while
dup prime? if
n over dup * do
i notprime!
dup 2* +loop
then
... |
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.
| #Java | Java | javac WindowExample.java
|
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.
| #Julia | Julia |
using Xlib
function x11demo()
# Open connection to the server.
dpy = XOpenDisplay(C_NULL)
dpy == C_NULL && error("unable to open display")
scr = DefaultScreen(dpy)
# Create a window.
win = XCreateSimpleWindow(dpy, RootWindow(dpy, scr), 10, 10, 300, 100, 1,
Bla... |
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.
| #Kotlin | Kotlin | // Kotlin Native v0.3
import kotlinx.cinterop.*
import Xlib.*
fun main(args: Array<String>) {
val msg = "Hello, World!"
val d = XOpenDisplay(null)
if (d == null) {
println("Cannot open display")
return
}
val s = XDefaultScreen(d)
val w = XCreateSimpleWindow(d, XRootWindow(d... |
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... | #Racket | Racket | #lang racket
(require math/number-theory)
(define ((wilson-prime? n) p)
(and (>= p n)
(prime? p)
(divides? (sqr p)
(- (* (factorial (- n 1))
(factorial (- p n)))
(expt -1 n)))))
(define primes<11000 (filter prime? (range 1 11000)))
(for... |
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... | #Raku | Raku | # Factorial
sub postfix:<!> (Int $n) { (constant f = 1, |[\×] 1..*)[$n] }
# Invisible times
sub infix:<> is tighter(&infix:<**>) { $^a * $^b };
# Prime the iterator for thread safety
sink 11000!;
my @primes = ^1.1e4 .grep: *.is-prime;
say
' n: Wilson primes
────────────────────';
.say for (1..40).hyper(:1ba... |
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.
| #Common_Lisp | Common Lisp | (capi:display (make-instance 'capi:interface :title "A 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.
| #D | D | module Window;
import fltk4d.all;
void main() {
auto window = new Window(300, 300, "A window");
window.show;
FLTK.run;
} |
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 ... | #QB64 | QB64 | OPTION _EXPLICIT
_TITLE "Puzzle Builder for Rosetta" 'by B+ started 2018-10-31
' 2018-11-02 Now that puzzle is working with basic and plus starters remove them and make sure puzzle works as well.
' Added Direction legend to printout.
' OverHauled LengthLimit()
' Reorgnize this to try a couple of... |
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... | #Common_Lisp | Common Lisp | ;; Greedy wrap line
(defun greedy-wrap (str width)
(setq str (concatenate 'string str " ")) ; add sentinel
(do* ((len (length str))
(lines nil)
(begin-curr-line 0)
(prev-space 0 pos-space)
(pos-space (position #\Space str) (when (< (1+ prev-space) len) (position #\Space str :start ... |
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... | #Python | Python | import urllib.request
from collections import Counter
GRID = """
N D E
O K G
E L W
"""
def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):
"Return lowercased words of 3 to 9 characters"
words = urllib.request.urlopen(url).read().decode().strip().lower().split()
return (w f... |
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... | #q | q | ce:count each
lc:ce group@ / letter count
dict:"\n"vs .Q.hg "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
// dictionary of 3-9 letter words
d39:{x where(ce x)within 3 9}{x where all each x in .Q.a}dict
solve:{[grid;dict]
i:where(grid 4)in'dict;
dict i where all... |
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.