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/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.
| #Sidef | Sidef | func plot(x, y, c) {
c && printf("plot %d %d %.1f\n", x, y, c);
}
func fpart(x) {
x - int(x);
}
func rfpart(x) {
1 - fpart(x);
}
func drawLine(x0, y0, x1, y1) {
var p = plot;
if (abs(y1 - y0) > abs(x1 - x0)) {
p = {|arg| plot(arg[1, 0, 2]) };
(x0, y0, x1, y1) = (y0, x0, y1, 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 ... | #Kotlin | Kotlin | // version 1.1.3
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.dom.DOMSource
import java.io.StringWriter
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.TransformerFactory
fun main(args: Array<String>) {
val names = listOf("April", "Tam O'Shanter", "Emily")... |
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" /... | #JavaScript | JavaScript |
var xmlstr = '<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" Nam... |
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,... | #UNIX_Shell | UNIX Shell | alist=( item1 item2 item3 ) # creates a 3 item array called "alist"
declare -a list2 # declare an empty list called "list2"
declare -a list3[0] # empty list called "list3"; the subscript is ignored
# create a 4 item list, with a specific order
list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry) |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const proc: main is func
local
const array float: numbers is [] (1.0, 2.0, 3.0, 1.0e11);
var float: aFloat is 0.0;
var file: aFile is STD_NULL;
begin
aFile := open("filename", "w");
for aFloat range numbers do
writeln... |
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... | #Sidef | Sidef | func writedat(filename, x, y, x_precision=3, y_precision=5) {
var fh = File(filename).open_w
for a,b in (x ~Z y) {
fh.printf("%.*g\t%.*g\n", x_precision, a, y_precision, b)
}
fh.close
}
var x = [1, 2, 3, 1e11]
var y = x.map{.sqrt}
writedat('sqrt.dat', x, y) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Myrddin | Myrddin |
use std
const main = {
var isopen : bool[100]
std.slfill(isopen[:], false)
for var i = 0; i < isopen.len; i++
for var j = i; j < isopen.len; j += i + 1
isopen[j] = !isopen[j]
;;
;;
for var i = 0; i < isopen.len; i++
if isopen[i]
std.put("door {} is open\n", i + 1)
;;
;;
}
|
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.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs = { 1 };
std::vector<int> divs2;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
int j = n / i;
divs.push_back(i);
if (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
| #J | J | require 'vrml.ijs' NB. Due to Andrew Nikitin
view 5#.^:_1]21-~a.i.'j*ez`C3\toy.G)' NB. Due to Oleg Kobchenko
________________________
|\ \ \ \ \
| \_____\_____\_____\_____\
| | | | |\ \
|\| | | | \_____... |
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
| #Java | Java | public class F5{
char[]z={' ',' ','_','/',};
long[][]f={
{87381,87381,87381,87381,87381,87381,87381,},
{349525,375733,742837,742837,375733,349525,349525,},
{742741,768853,742837,742837,768853,349525,349525,},
{349525,375733,742741,742741,375733,349525,349525,},
{349621,37... |
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,... | #Ada | Ada | with AWS.Client, AWS.Response, AWS.Resources, AWS.Messages;
with Ada.Text_IO, Ada.Strings.Fixed;
use Ada, AWS, AWS.Resources, AWS.Messages;
procedure Get_UTC_Time is
Page : Response.Data;
File : Resources.File_Type;
Buffer : String (1 .. 1024);
Position, Last : Natural := 0;... |
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... | #Perl | Perl | #!perl
use strict;
use warnings;
use Tk;
my $mw;
my $win;
my $lab;
# How to open a window.
sub openWin {
if( $win ) {
$win->deiconify;
$win->wm('state', 'normal');
} else {
eval { $win->destroy } if $win;
$win = $mw->Toplevel;
$win->Label(-text => "This is the window being manipulated")
->pack(-fill ... |
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... | #Arturo | Arturo | findFrequency: function [file, count][
freqs: #[]
r: {/[[:alpha:]]+/}
loop flatten map split.lines read file 'l -> match lower l r 'word [
if not? key? freqs word -> freqs\[word]: 0
freqs\[word]: freqs\[word] + 1
]
freqs: sort.values.descending freqs
result: new []
loop 0..de... |
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.23 | C# | #include <ggi/ggi.h>
#include <set>
#include <map>
#include <utility>
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h> // for usleep
enum cell_type { none, wire, head, tail };
// *****************
// * display class *
// *****************
// this is just a small wrapper for the ggi 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... | #FreeBASIC | FreeBASIC |
#include "isprime.bas"
function iswief( byval p as uinteger ) as boolean
if not isprime(p) then return 0
dim as integer q = 1, p2 = p^2
while p>1
q=(2*q) mod p2
p = p - 1
wend
if q=1 then return 1 else return 0
end function
for i as uinteger = 1 to 5000
if iswief(i) then pr... |
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... | #Go | Go | package main
import (
"fmt"
"math/big"
"rcu"
)
func main() {
primes := rcu.Primes(5000)
zero := new(big.Int)
one := big.NewInt(1)
num := new(big.Int)
fmt.Println("Wieferich primes < 5,000:")
for _, p := range primes {
num.Set(one)
num.Lsh(num, uint(p-1))
n... |
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.
| #M2000_Interpreter | M2000 Interpreter |
\\ M2000 froms (windows) based on a flat, empty with no title bar, vb6 window and a user control.
\\ title bar is a user control in M2000 form
\\ On linux, wine application run M2000 interpreter traslating vb6 calls to window system.
Module SquareAndText2Window {
Const black=0, white=15
Declare form1 form
\\ defau... |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Needs["GUIKit`"]
ref = GUIRun[Widget["Panel", {
Widget[
"ImageLabel", {"data" ->
Script[ExportString[Graphics[Rectangle[{0, 0}, {1, 1}]],
"GIF"]]}],
Widget["Label", { "text" -> "Hello World!"}]}
]] |
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... | #REXX | REXX | /*REXX program finds and displays Wilson primes: a prime P such that P**2 divides:*/
/*────────────────── (n-1)! * (P-n)! - (-1)**n where n is 1 ──◄ 11, and P < 18.*/
parse arg oLO oHI hip . /*obtain optional argument from the CL.*/
if oLO=='' | oLO=="," then oLO= 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.
| #Delphi | Delphi |
// The project file (Project1.dpr)
program Project1;
uses
Forms,
// Include file with Window class declaration (see below)
Unit0 in 'Unit1.pas' {Form1};
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
// The Window class declaration
unit Un... |
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.
| #Dragon | Dragon | select "GUI"
window = newWindow("Window")
window.setSize(400,600)
window.setVisible()
|
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 ... | #Racket | Racket | #lang racket
;; ---------------------------------------------------------------------------------------------------
(module+ main
(display-puzzle (create-word-search))
(newline)
(parameterize ((current-min-words 50))
(display-puzzle (create-word-search #:n-rows 20 #:n-cols 20))))
;; ------------------------... |
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... | #D | D | void main() {
immutable frog =
"In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and u... |
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... | #Racket | Racket | use Terminal::Boxer;
my %*SUB-MAIN-OPTS = :named-anywhere;
unit sub MAIN ($wheel = 'ndeokgelw', :$dict = './unixdict.txt', :$min = 3);
my $must-have = $wheel.comb[4].lc;
my $has = $wheel.comb».lc.Bag;
my %words;
$dict.IO.slurp.words».lc.map: {
next if not .contains($must-have) or .chars < $min;
%words... |
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.
| #Swift | Swift | import Darwin
// apply pixel of color at x,y with an OVER blend to the bitmap
public func pixel(color: Color, x: Int, y: Int) {
let idx = x + y * self.width
if idx >= 0 && idx < self.bitmap.count {
self.bitmap[idx] = self.blendColors(bot: self.bitmap[idx], top: color)
}
}
// return the fractional ... |
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 ... | #Lasso | Lasso | define character2xml(names::array, remarks::array) => {
fail_if(#names -> size != #remarks -> size, -1, 'Input arrays not of same size')
local(
domimpl = xml_domimplementation,
doctype = #domimpl -> createdocumenttype(
'svg:svg',
'-//W3C//DTD SVG 1.1//EN',
'http://www.w3.org/Graphics/SVG/1.1/DTD/svg1... |
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 ... | #Lua | Lua | require("LuaXML")
function addNode(parent, nodeName, key, value, content)
local node = xml.new(nodeName)
table.insert(node, content)
parent:append(node)[key] = value
end
root = xml.new("CharacterRemarks")
addNode(root, "Character", "name", "April", "Bubbly: I'm > Tam and <= Emily")
addNode(root, "Charac... |
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" /... | #Julia | Julia | using LightXML
let docstr = """<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">
<Pe... |
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" /... | #Kotlin | Kotlin | // version 1.1.3
import javax.xml.parsers.DocumentBuilderFactory
import org.xml.sax.InputSource
import java.io.StringReader
import org.w3c.dom.Node
import org.w3c.dom.Element
val xml =
"""
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1... |
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,... | #.E0.AE.89.E0.AE.AF.E0.AE.BF.E0.AE.B0.E0.AF.8D.2FUyir | உயிர்/Uyir |
இருபரிமாணணி வகை எண் அணி {3, 3};
இருபரிமாணணி2 வகை எண் அணி {3} அணி {3};
என்_எண்கள் வகை எண் {#5.2} அணி {5} = {3.14, 2.83, 5.32, 10.66, 14};
சொற்கள் வகை சரம் {25} அணி {100};
உயரங்கள் = அணி {10, 45, 87, 29, 53};
பெயர்கள் = அணி {"இராஜன்", "சுதன்", "தானி"};
தேதிகள் = அ... |
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... | #Smalltalk | Smalltalk | x := #( 1 2 3 1e11 ).
y := x collect:#sqrt.
xprecision := 3.
yprecision := 5.
'sqrt.dat' asFilename writingFileDo:[:fileStream |
x with:y do:[:xI :yI |
'%.*g\t%.*g\n' printf:{ xprecision . xI . yprecision . yI } on:fileStream
]
] |
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... | #SPL | SPL | x = [1, 2, 3, 10^11]
y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]
xprecision = 3
yprecision = 5
> i, 1..4
s1 = #.str(x[i],"g"+xprecision)
s2 = #.str(y[i],"g"+yprecision)
#.writeline("file.txt",s1+#.tab+s2)
< |
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... | #MySQL | MySQL |
DROP PROCEDURE IF EXISTS one_hundred_doors;
DELIMITER |
CREATE PROCEDURE one_hundred_doors (n INT)
BEGIN
DROP TEMPORARY TABLE IF EXISTS doors;
CREATE TEMPORARY TABLE doors (
id INTEGER NOT NULL,
open BOOLEAN DEFAULT FALSE,
PRIMARY KEY (id)
);
SET @i = 1;
create_doors: LOOP
INSERT INTO... |
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... | #Crystal | Crystal | def divisors(n : Int32) : Array(Int32)
divs = [1]
divs2 = [] of Int32
i = 2
while i * i < n
if n % i == 0
j = n // i
divs << i
divs2 << j if i != j
end
i += 1
end
i = divs.size - 1
# TODO: Use reverse
while i >= 0
divs2 << divs[i]
i -= 1
end
divs2
end
... |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #jq | jq | def jq:
"\("
#
#
# # ###
# # # #
# # # #
# # # # ####
# ### #
#
")";
def banner3D:
jq | split("\n") | map( gsub("#"; "╔╗") | gsub(... |
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
| #Julia | Julia | println(replace(raw"""
xxxxx
x x
x x x
x x x x
x x x x x xxx
x x x x x x x
x x x x x x x xx
xx xx x x x x xx
""", "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,... | #ALGOL_68 | ALGOL 68 | STRING
domain="tycho.usno.navy.mil",
page="cgi-bin/timer.pl";
STRING # search for the needle in the haystack #
needle = "UTC",
hay stack = "http://"+domain+"/"+page,
re success="^HTTP/[0-9.]* 200",
re result description="^HTTP/[0-9.]* [0-9]+ [a-zA-Z ]*",
re doctype ="\s\s<![Dd][Oo][Cc][Tt][Yy]... |
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... | #Phix | Phix | -- demo\rosetta\Window_management.exw
include pGUI.e
Ihandle dlg
function doFull(Ihandle /*ih*/)
IupSetAttribute(dlg,"FULLSCREEN","YES")
return IUP_DEFAULT
end function
function doMax(Ihandle /*ih*/)
IupSetAttribute(dlg,"PLACEMENT","MAXIMIZED")
-- this is a work-around to get the dialog minimised ... |
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... | #AutoHotkey | AutoHotkey | URLDownloadToFile, http://www.gutenberg.org/files/135/135-0.txt, % A_temp "\tempfile.txt"
FileRead, H, % A_temp "\tempfile.txt"
FileDelete, % A_temp "\tempfile.txt"
words := []
while pos := RegExMatch(H, "\b[[:alpha:]]+\b", m, A_Index=1?1:pos+StrLen(m))
words[m] := words[m] ? words[m] + 1 : 1
for word, count in words... |
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.2B.2B | C++ | #include <ggi/ggi.h>
#include <set>
#include <map>
#include <utility>
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h> // for usleep
enum cell_type { none, wire, head, tail };
// *****************
// * display class *
// *****************
// this is just a small wrapper for the ggi 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... | #Haskell | Haskell | isPrime :: Integer -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Integer
root = toInteger $ floor $ sqrt $ fromIntegral n
isWieferichPrime :: Integer -> Bool
isWieferichPrime n = isPrime n && mod ( 2 ^ ( n - 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... | #Java | Java | import java.util.*;
public class WieferichPrimes {
public static void main(String[] args) {
final int limit = 5000;
System.out.printf("Wieferich primes less than %d:\n", limit);
for (Integer p : wieferichPrimes(limit))
System.out.println(p);
}
private static boole... |
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.
| #Nim | Nim | import x11/[xlib,xutil,x]
const
windowWidth = 1000
windowHeight = 600
borderWidth = 5
eventMask = ButtonPressMask or KeyPressMask or ExposureMask
var
display: PDisplay
window: Window
deleteMessage: Atom
graphicsContext: GC
proc init() =
display = XOpenDisplay(nil)
if display == nil:
quit "... |
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.
| #OCaml | OCaml | ocaml -I +Xlib Xlib.cma script.ml
|
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... | #Ruby | Ruby | require "prime"
module Modulo
refine Integer do
def factorial_mod(m) = (1..self).inject(1){|prod, n| (prod *= n) % m }
end
end
using Modulo
primes = Prime.each(11000).to_a
(1..11).each do |n|
res = primes.select do |pr|
prpr = pr*pr
((n-1).factorial_mod(prpr) * (pr-n).factorial_mod(prpr) - (-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... | #Rust | Rust | // [dependencies]
// rug = "1.13.0"
use rug::Integer;
fn generate_primes(limit: usize) -> Vec<usize> {
let mut sieve = vec![true; limit >> 1];
let mut p = 3;
let mut sq = p * p;
while sq < limit {
if sieve[p >> 1] {
let mut q = sq;
while q < limit {
si... |
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... | #Sidef | Sidef | func is_wilson_prime(p, n = 1) {
var m = p*p
(factorialmod(n-1, m) * factorialmod(p-n, m) - (-1)**n) % m == 0
}
var primes = 1.1e4.primes
say " n: Wilson primes\n────────────────────"
for n in (1..11) {
printf("%3d: %s\n", n, primes.grep {|p| is_wilson_prime(p, n) })
} |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #E | E | when (currentVat.morphInto("awt")) -> {
def w := <swing:makeJFrame>("Window")
w.setContentPane(<swing:makeJLabel>("Contents"))
w.pack()
w.show()
}
|
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.
| #Eiffel | Eiffel | class
APPLICATION
inherit
EV_APPLICATION
create
make_and_launch
feature {NONE} -- Initialization
make_and_launch
-- Initialize and launch application
do
default_create
create first_window
first_window.show
launch
end
feature {NO... |
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 ... | #Raku | Raku | my $rows = 10;
my $cols = 10;
my $message = q:to/END/;
.....R....
......O...
.......S..
........E.
T........T
.A........
..C.......
...O......
....D.....
.....E....
END
my %dir =
'→' => (1,0),
'↘' => (1,1),
'↓' => (0,1),
'↙' => (-1,1),
'←' => (-1,0),
... |
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... | #Dyalect | Dyalect | 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 cursus. Cum soci... |
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... | #Elena | Elena | import extensions;
import system'routines;
import extensions'text;
string 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 in her face. Cl... |
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... | #Raku | Raku | use Terminal::Boxer;
my %*SUB-MAIN-OPTS = :named-anywhere;
unit sub MAIN ($wheel = 'ndeokgelw', :$dict = './unixdict.txt', :$min = 3);
my $must-have = $wheel.comb[4].lc;
my $has = $wheel.comb».lc.Bag;
my %words;
$dict.IO.slurp.words».lc.map: {
next if not .contains($must-have) or .chars < $min;
%words... |
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.
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
proc ::tcl::mathfunc::ipart x {expr {int($x)}}
proc ::tcl::mathfunc::fpart x {expr {$x - int($x)}}
proc ::tcl::mathfunc::rfpart x {expr {1.0 - fpart($x)}}
proc drawAntialiasedLine {image colour p1 p2} {
lassign $p1 x1 y1
lassign $p2 x2 y2
set steep [expr {abs... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | c = {"April", "Tam O'Shanter","Emily"};
r = {"Bubbly:I'm > Tam and <= Emily" ,
StringReplace["Burns:\"When chapman billies leave the street ...\"", "\"" -> ""], "Short & shrift"};
ExportString[ XMLElement[ "CharacterRemarks", {},
{XMLElement["Character", {"name" -> c[[1]]}, {r[[1]]}],
XMLElement["Character", {"na... |
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 ... | #MATLAB | MATLAB | RootXML = com.mathworks.xml.XMLUtils.createDocument('CharacterRemarks');
docRootNode = RootXML.getDocumentElement;
thisElement = RootXML.createElement('Character');
thisElement.setAttribute('Name','April')
thisElement.setTextContent('Bubbly: I''m > Tam and <= Emily');
docRootNode.appendChild(thisElement);
thisElement =... |
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" /... | #Lasso | Lasso | // makes extracting attribute values easier
define xml_attrmap(in::xml_namedNodeMap_attr) => {
local(out = map)
with attr in #in
do #out->insert(#attr->name = #attr->value)
return #out
}
local(
text = '<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" Da... |
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,... | #Vala | Vala |
int[] array = new int[10];
array[0] = 1;
array[1] = 3;
stdout.printf("%d\n", array[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... | #Standard_ML | Standard ML | fun writeDat (filename, x, y, xprec, yprec) = let
val os = TextIO.openOut filename
fun write_line (a, b) =
TextIO.output (os, Real.fmt (StringCvt.GEN (SOME xprec)) a ^ "\t" ^
Real.fmt (StringCvt.GEN (SOME yprec)) b ^ "\n")
in
ListPair.appEq write_line (x, y);
TextIO.closeOut os
end; |
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... | #Stata | Stata | * Create the dataset
clear
mat x=1\2\3\1e11
svmat double x
ren *1 *
gen y=sqrt(x)
format %10.1g x
format %10.5g y
* Save as text file
export delim file.txt, delim(" ") novar datafmt replace |
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... | #Nanoquery | Nanoquery | // allocate a boolean array with all closed doors (false)
// we need 101 since there will technically be a door 0
doors = {false} * 101
// loop through all the step lengths (1-100)
for step in range(1, 100)
// loop through all the doors, stepping by step
for door in range(0, len(doors) - 1, step)
// change the st... |
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... | #D | D | import std.algorithm;
import std.array;
import std.stdio;
int[] divisors(int n) {
int[] divs = [1];
int[] divs2;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
int j = n / i;
divs ~= i;
if (i != j) {
divs2 ~= j;
}
}
... |
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
| #Kotlin | Kotlin | // version 1.1
class Ascii3D(s: String) {
val z = charArrayOf(' ', ' ', '_', '/')
val f = arrayOf(
longArrayOf(87381, 87381, 87381, 87381, 87381, 87381, 87381),
longArrayOf(349525, 375733, 742837, 742837, 375733, 349525, 349525),
longArrayOf(742741, 768853, 742837, 742837, 768853, 34... |
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,... | #App_Inventor | App Inventor |
when ScrapeButton.Click do
set ScrapeWeb.Url to SourceTextBox.Text
call ScrapeWeb.Get
when ScrapeWeb.GotText url,responseCode,responseType,responseContent do
initialize local Left to split at first text (text: get responseContent, at: PreTextBox.Text)
initialize local Right to "" in
set Right to select ... |
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,... | #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on firstDateonWebPage(URLText)
set |⌘| to current application
set pageURL to |⌘|'s class "NSURL"'s URLWithString:(URLText)
-- Fetch the page HTML as data.
-- The Xcode documentation advises against using dataWit... |
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... | #PicoLisp | PicoLisp | $ ersatz/pil +
: (setq
JFrame "javax.swing.JFrame"
MAXIMIZED_BOTH (java (public JFrame 'MAXIMIZED_BOTH))
ICONIFIED (java (public JFrame 'ICONIFIED))
Win (java JFrame T "Window") )
-> $JFrame
# Compare for equality
: (== Win Win)
-> T
# Set window visible
(java Win 'setLocation 10... |
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... | #PureBasic | PureBasic | ;- Create a linked list to store created windows.
NewList Windows()
Define i, j, dh, dw, flags, err$, x, y
;- Used sub-procedure to simplify the error handling
Procedure HandleError(Result, Text.s,ErrorLine=0,ExitCode=0)
If Not Result
MessageRequester("Error",Text)
End ExitCode
EndIf
ProcedureReturn Res... |
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... | #AWK | AWK |
# syntax: GAWK -f WORD_FREQUENCY.AWK [-v show=x] LES_MISERABLES.TXT
#
# A word is anything separated by white space.
# Therefor "this" and "this." are different.
# But "This" and "this" are identical.
# As I am "free to define what a letter is" I have chosen to allow
# numerics and all special characters as they are ... |
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... | #Ceylon | Ceylon | abstract class Cell(shared Character char) of emptyCell | head | tail | conductor {
shared Cell output({Cell*} neighbors) =>
switch (this)
case (emptyCell) emptyCell
case (head) tail
case (tail) conductor
case (conductor) (neighbors.count(head.equals) in... |
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... | #Common_Lisp | Common Lisp | (defun electron-neighbors (wireworld row col)
(destructuring-bind (rows cols) (array-dimensions wireworld)
(loop for off-row from (max 0 (1- row)) to (min (1- rows) (1+ row)) sum
(loop for off-col from (max 0 (1- col)) to (min (1- cols) (1+ col)) count
(and (not (and (= off-row row) (= off-col col... |
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... | #jq | jq | def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17... |
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... | #Julia | Julia | using Primes
println(filter(p -> (big"2"^(p - 1) - 1) % p^2 == 0, primes(5000))) # [1093, 3511]
|
http://rosettacode.org/wiki/Wieferich_primes | Wieferich primes |
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In number theory, a Wieferich prime is a prime number p such th... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[WieferichPrimeQ]
WieferichPrimeQ[n_Integer] := PrimeQ[n] && Divisible[2^(n - 1) - 1, n^2]
Select[Range[5000], WieferichPrimeQ] |
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... | #Nim | Nim | import math
import bignum
func isPrime(n: Positive): bool =
if n mod 2 == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
while d <= sqrt(n.toFloat).int:
if n mod d == 0: return false
inc d, 2
if n mod d == 0: return false
inc d, 4
result = true
echo "Wieferich primes less than 5... |
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... | #PARI.2FGP | PARI/GP | iswief(p)=if(isprime(p)&&(2^(p-1)-1)%p^2==0,1,0)
for(N=1,5000,if(iswief(N),print(N))) |
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.
| #Pascal | Pascal | program xshowwindow;
{$mode objfpc}{$H+}
uses
xlib, x, ctypes;
procedure ModalShowX11Window(AMsg: string);
var
d: PDisplay;
w: TWindow;
e: TXEvent;
msg: PChar;
s: cint;
begin
msg := PChar(AMsg);
{ open connection with the server }
d := XOpenDisplay(nil);
if (d = nil) then
begin
WriteLn('... |
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... | #Wren | Wren | import "/math" for Int
import "/big" for BigInt
import "/fmt" for Fmt
var limit = 11000
var primes = Int.primeSieve(limit)
var facts = List.filled(limit, null)
facts[0] = BigInt.one
for (i in 1...11000) facts[i] = facts[i-1] * i
var sign = 1
System.print(" n: Wilson primes")
System.print("--------------------")
for ... |
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.
| #Emacs_Lisp | Emacs Lisp | (make-frame) |
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.
| #Euphoria | Euphoria | include arwen.ew
constant win = create(Window, "ARWEN window", 0, 0,100,100,640,480,{0,0})
WinMain(win, SW_NORMAL)
|
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
ReadOnly Dirs As Integer(,) = {
{1, 0}, {0, 1}, {1, 1},
{1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}
}
Const RowCount = 10
Const ColCount = 10
Const GridSize = RowCount * ColCount
Const MinWords = 25
Class Grid
Public cells(RowCount - 1, C... |
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... | #Elixir | Elixir | defmodule Word_wrap do
def paragraph( string, max_line_length ) do
[word | rest] = String.split( string, ~r/\s+/, trim: true )
lines_assemble( rest, max_line_length, String.length(word), word, [] )
|> Enum.join( "\n" )
end
defp lines_assemble( [], _, _, line, acc ), do: [line | acc] |> Enum.revers... |
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... | #Erlang | Erlang |
-module( word_wrap ).
-export( [paragraph/2, task/0] ).
paragraph( String, Max_line_length ) ->
Lines = lines( string:tokens(String, " "), Max_line_length ),
string:join( Lines, "\n" ).
task() ->
Paragraph = "Even today, with proportional fonts and complex layouts, there are still cases where you ne... |
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... | #REXX | REXX | /*REXX pgm finds (dictionary) words which can be found in a specified word wheel (grid).*/
parse arg grid minL iFID . /*obtain optional arguments from the CL*/
if grid==''|grid=="," then grid= 'ndeokgelw' /*Not specified? Then use the default.*/
if minL==''|minL=="," then minL= 3 ... |
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.
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math
class XiaolinWu {
construct new(width, height) {
Window.title = "Xiaolin Wu's line algorithm"
Window.resize(width, height)
Canvas.resize(width, height)
}
init() {
Canvas.cls(Color.white)
... |
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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
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
... |
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" /... | #Lingo | Lingo | q = QUOTE
r = RETURN
xml = "<Students>"&r&\
" <Student Name="&q&"April"&q&" Gender="&q&"F"&q&" DateOfBirth="&q&"1989-01-02"&q&" />"&r&\
" <Student Name="&q&"Bob"&q&" Gender="&q&"M"&q&" DateOfBirth="&q&"1990-03-04"&q&" />"&r&\
" <Student Name="&q&"Chad"&q&" Gender="&q&"M"&q&" DateOfBirth="&q&"1991-05-06"&q&" />"&r&\
... |
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" /... | #LiveCode | LiveCode | put revXMLCreateTree(fld "FieldXML",true,true,false) into currTree
put revXMLAttributeValues(currTree,"Students","Student","Name",return,-1) |
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,... | #VBA | VBA | Option Base {0|1} |
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... | #Tcl | Tcl | set x {1 2 3 1e11}
foreach a $x {lappend y [expr {sqrt($a)}]}
set fh [open sqrt.dat w]
foreach a $x b $y {
puts $fh [format "%.*g\t%.*g" $xprecision $a $yprecision $b]
}
close $fh
set fh [open sqrt.dat]
puts [read $fh [file size sqrt.dat]]
close $fh |
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... | #VBA | VBA | Public Sub main()
x = [{1, 2, 3, 1e11}]
y = [{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}]
Dim TextFile As Integer
TextFile = FreeFile
Open "filename" For Output As TextFile
For i = 1 To UBound(x)
Print #TextFile, Format(x(i), "0.000E-000"), Format(y(i), "0.00000E-000"... |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
True = Rexx(1 == 1)
False = Rexx(\True)
doors = False
loop i_ = 1 to 100
loop j_ = 1 to 100
if 0 = (j_ // i_) then doors[j_] = \doors[j_]
end j_
end i_
loop d_ = 1 to 100
if doors[d_] then state = 'open'
else state = '... |
http://rosettacode.org/wiki/Weird_numbers | Weird numbers | In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors su... | #F.23 | F# | let divisors n = [1..n/2] |> List.filter (fun x->n % x = 0)
let abundant (n:int) divs = Seq.sum(divs) > n
let rec semiperfect (n:int) (divs:List<int>) =
if divs.Length > 0 then
let h = divs.Head
let t = divs.Tail
if n < h then
semiperfect n t
else
n = h ||... |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #Lasso | Lasso | local(lasso = "
---------------------------------------------------------------
| ,--, |
| ,---.'| ,----.. |
| | | : ,---, .--.--. .--.--. / / \\ |
| : : | ' .' \\ / / '. / / ... |
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
| #Lua | Lua | io.write(" /$$\n")
io.write("| $$\n")
io.write("| $$ /$$ /$$ /$$$$$$\n")
io.write("| $$ | $$ | $$ |____ $$\n")
io.write("| $$ | $$ | $$ /$$$$$$$\n")
io.write("| $$ | $$ | $$ /$$__ $$\n")
io.write("| $$$$$$$$| $$$$$$/| $$$$$$$\n")
io.write("|________/ \______/ \_______/\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,... | #AutoHotkey | AutoHotkey | UrlDownloadToFile, http://tycho.usno.navy.mil/cgi-bin/timer.pl, time.html
FileRead, timefile, time.html
pos := InStr(timefile, "UTC")
msgbox % time := SubStr(timefile, pos - 9, 8) |
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,... | #AWK | AWK | 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/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... | #Python | Python |
from tkinter import *
import tkinter.messagebox
def maximise():
"""get screenwidth and screenheight, and resize window to that size.
Also move to 0,0"""
root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))
def minimise():
"""Iconify window to the taskbar. When reopen... |
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... | #BASIC | BASIC |
OPTION _EXPLICIT
' SUBs and FUNCTIONs
DECLARE SUB CountWords (FromString AS STRING)
DECLARE SUB QuickSort (lLeftN AS LONG, lRightN AS LONG, iMode AS INTEGER)
DECLARE SUB ShowResults ()
DECLARE SUB ShowCompletion ()
DECLARE SUB TopCounted ()
DECLARE FUNCTION InsertWord& (WhichWord AS STRING)
DECLARE FUNCTION BinaryS... |
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... | #D | D | import std.stdio, std.algorithm;
void wireworldStep(char[][] W1, char[][] W2) pure nothrow @safe @nogc {
foreach (immutable r; 1 .. W1.length - 1)
foreach (immutable c; 1 .. W1[0].length - 1)
switch (W1[r][c]) {
case 'H': W2[r][c] = 't'; break;
case 't': W2[r][c... |
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... | #Perl | Perl | use feature 'say';
use ntheory qw(is_prime powmod);
say 'Wieferich primes less than 5000: ' . join ', ', grep { is_prime($_) and powmod(2, $_-1, $_*$_) == 1 } 1..5000; |
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.