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/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #GUISS | GUISS | Start,Programs,Accessories,Notepad |
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... | #Go | Go | package main
import (
"fmt"
"strings"
)
func wrap(text string, lineWidth int) (wrapped string) {
words := strings.Fields(text)
if len(words) == 0 {
return
}
wrapped = words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spac... |
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 ... | #Phix | Phix | with javascript_semantics
constant {hchars,hsubs} = columnize({{"<","<"},
{">",">"},
{"&","&"},
{"\"","""},
{"\'","'"}})
function xmlquote_all(sequence ... |
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" /... | #newLISP | newLISP |
(set 'xml-input "<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />
<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />
<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">
<Pet Type=\"d... |
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,... | #Vlang | Vlang | // Arrays, in V
// Tectonics: v run arrays.v
module main
// A little bit about V variables. V does not allow uninitialized data.
// If an identifier exists, there is a valid value. "Empty" arrays have
// values in all positions, and V provides defaults for base types if not
// explicitly specified. E.g. 0 for numbe... |
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... | #Objeck | Objeck |
bundle Default {
class Doors {
function : Main(args : String[]) ~ Nil {
doors := Bool->New[100];
for(pass := 0; pass < 10; pass += 1;) {
doors[(pass + 1) * (pass + 1) - 1] := true;
};
for(i := 0; i < 100; i += 1;) {
IO.Console->GetInstance()->Print("Door #")->Prin... |
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... | #JavaScript | JavaScript | (() => {
'use strict';
// main :: IO ()
const main = () =>
take(25, weirds());
// weirds :: Gen [Int]
function* weirds() {
let
x = 1,
i = 1;
while (true) {
x = until(isWeird, succ, x)
console.log(i.toString() + ' -> ' + x)... |
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
| #Pascal | Pascal |
program WritePascal;
const
i64: int64 = 1055120232691680095; (* This defines "Pascal" *)
cc: array[-1..15] of string = (* Here are all string-constants *)
('_______v---',
'__', '\_', '___', '\__',
' ', ' ', ' ', ' ',
'/ ', ' ', '_/ ', '\/ ',
' _', '__', ' _', ' _');
var
x, y: inte... |
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,... | #Clojure | Clojure |
(second (re-find #" (\d{1,2}:\d{1,2}:\d{1,2}) UTC" (slurp "http://tycho.usno.navy.mil/cgi-bin/timer.pl")))
|
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,... | #CoffeeScript | CoffeeScript |
http = require 'http'
CONFIG =
host: 'tycho.usno.navy.mil'
path: '/cgi-bin/timer.pl'
# Web scraping code tends to be brittle, and this is no exception.
# The tycho time page does not use highly structured markup, so
# we do a real dirty scrape.
scrape_tycho_ust_time = (text) ->
for line in text.split '\n'
... |
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... | #Clojure | Clojure | (defn count-words [file n]
(->> file
slurp
clojure.string/lower-case
(re-seq #"\w+")
frequencies
(sort-by val >)
(take n))) |
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... | #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. WordFrequency.
AUTHOR. Bill Gunshannon.
DATE-WRITTEN. 30 Jan 2020.
************************************************************
** Program Abstract:
** Given a text file and an integer n, print the n most
** common words 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... | #FreeBASIC | FreeBASIC | #define MAXX 319
#define MAXY 199
enum state
E=0, C=8, H=9, T=4 'doubles as colours: black, grey, bright blue, red
end enum
dim as uinteger world(0 to 1, 0 to MAXX, 0 to MAXY), active = 0, buffer = 1
dim as double rate = 1./3. 'seconds per frame
dim as double tick
dim as uinteger x, y
function turn_on( wor... |
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.
| #TXR | TXR | /* window_creation_x11.wren */
var KeyPressMask = 1 << 0
var ExposureMask = 1 << 15
var KeyPress = 2
var Expose = 12
foreign class XGC {
construct default(display, screenNumber) {}
}
foreign class XEvent {
construct new() {}
foreign eventType
}
foreign class XDisplay {
construct open... |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #Haskell | Haskell | import Graphics.HGL
aWindow = runGraphics $
withWindow_ "Rosetta Code task: Creating a window" (300, 200) $ \ w -> do
drawInWindow w $ text (100, 100) "Hello World"
getKey w |
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.
| #HicEst | HicEst | WINDOW(WINdowhandle=handle, Width=80, Height=-400, X=1, Y=1/2, TItle="Rosetta Window_creation Example")
! window units: as pixels < 0, as relative window size 0...1, ascurrent character sizes > 1
WRITE(WINdowhandle=handle) '... some output ...' |
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... | #Groovy | Groovy | def wordWrap(text, length = 80) {
def sb = new StringBuilder()
def line = ''
text.split(/\s/).each { word ->
if (line.size() + word.size() > length) {
sb.append(line.trim()).append('\n')
line = ''
}
line += " $word"
}
sb.append(line.trim()).toString(... |
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 ... | #PicoLisp | PicoLisp | (load "@lib/xml.l")
(de characterRemarks (Names Remarks)
(xml
(cons
'CharacterRemarks
NIL
(mapcar
'((Name Remark)
(list 'Character (list (cons 'name Name)) Remark) )
Names
Remarks ) ) ) )
(characterRemarks
'("April" "Tam O'Sha... |
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 ... | #PureBasic | PureBasic | DataSection
dataItemCount:
Data.i 3
names:
Data.s "April", "Tam O'Shanter", "Emily"
remarks:
Data.s "Bubbly: I'm > Tam and <= Emily",
~"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift"
EndDataSection
Structure characteristic
name.s
remark.s
EndStructure
... |
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" /... | #Nim | Nim | import xmlparser, xmltree, streams
let doc = newStringStream """<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... |
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" /... | #Objeck | Objeck |
use XML;
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
in := String->New();
in->Append("<Students>");
in->Append("<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />");
in->Append("<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />... |
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,... | #Wee_Basic | Wee Basic | dim array$(2)
let array$(1)="Hello!"
let array$(2)="Goodbye!"
print 1 array$(1) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Objective-C | Objective-C |
@import Foundation;
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Create a mutable array
NSMutableArray *doorArray = [@[] mutableCopy];
// Fill the doorArray with 100 closed doors
for (NSInteger i = 0; i < 100; ++i) {
doorArray[i] = @NO;
... |
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... | #Julia | Julia | using Primes
function nosuchsum(revsorted, num)
if sum(revsorted) < num
return true
end
for (i, n) in enumerate(revsorted)
if n > num
continue
elseif n == num
return false
elseif !nosuchsum(revsorted[i+1:end], num - n)
return false
... |
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... | #Kotlin | Kotlin | // Version 1.3.21
fun divisors(n: Int): List<Int> {
val divs = mutableListOf(1)
val divs2 = mutableListOf<Int>()
var i = 2
while (i * i <= n) {
if (n % i == 0) {
val j = n / i
divs.add(i)
if (i != j) divs2.add(j)
}
i++
}
divs2.addAll(... |
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
| #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
for my $tuple ([" ", 2], ["_", 1], [" ", 1], ["\\", 1], [" ", 11], ["|", 1], ["\n", 1],
[" ", 1], ["|", 1], [" ", 3], ["|", 1], [" ", 1], ["_", 1], [" ", 1], ["\\", 1], [" ", 2], ["_", 2], ["|", 1], [" ", 1], ["|", 1], ["\n", 1],
[" ", 1], ["_"... |
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,... | #Common_Lisp | Common Lisp | BOA> (let* ((url "http://tycho.usno.navy.mil/cgi-bin/timer.pl")
(regexp (load-time-value
(cl-ppcre:create-scanner "(?m)^.{4}(.+? UTC)")))
(data (drakma:http-request url)))
(multiple-value-bind (start end start-regs end-regs)
(cl-ppcre:scan regexp data)
... |
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... | #Common_Lisp | Common Lisp |
(defun count-word (n pathname)
(with-open-file (s pathname :direction :input)
(loop for line = (read-line s nil nil) while line
nconc (list-symb (drop-noise line)) into words
finally (return (subseq (sort (pair words)
#'> :key #'cdr)
... |
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... | #GML | GML | //Create event
/*
Wireworld first declares constants and then reads a wireworld from a textfile.
In order to implement wireworld in GML a single array is used.
To make it behave properly, there need to be states that are 'in-between' two states:
0 = empty
1 = conductor from previous state
2 = electronhead from previous... |
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.
| #Wren | Wren | /* window_creation_x11.wren */
var KeyPressMask = 1 << 0
var ExposureMask = 1 << 15
var KeyPress = 2
var Expose = 12
foreign class XGC {
construct default(display, screenNumber) {}
}
foreign class XEvent {
construct new() {}
foreign eventType
}
foreign class XDisplay {
construct open... |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #IDL | IDL | Id = WIDGET_BASE(TITLE='Window Title',xsize=200,ysize=100)
WIDGET_CONTROL, /REALIZE, id
|
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.
| #Icon_and_Unicon | Icon and Unicon | link graphics
procedure main(arglist)
WOpen("size=300, 300", "fg=blue", "bg=light gray")
WDone()
end |
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.
| #J | J | wdinfo 'Hamlet';'To be, or not to be: that is the question:' |
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... | #Haskell | Haskell | ss =
concat
[ "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"
... |
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 ... | #Python | Python | >>> from xml.etree import ElementTree as ET
>>> from itertools import izip
>>> def characterstoxml(names, remarks):
root = ET.Element("CharacterRemarks")
for name, remark in izip(names, remarks):
c = ET.SubElement(root, "Character", {'name': name})
c.text = remark
return ET.tostring(root)
>>> print characterst... |
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" /... | #OCaml | OCaml | # #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;;
# #load "xml-light.cma" ;;
# let x = Xml.parse_string "
<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... |
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,... | #Wren | Wren | var arr = []
arr.add(1)
arr.add(2)
arr.count // 2
arr.clear()
arr.add(0)
arr.add(arr[0])
arr.add(1)
arr.add(arr[-1]) // [0, 0, 1, 1]
arr[-1] = 0
arr.insert(-1, 0) // [0, 0, 1, 0, 0]
arr.removeAt(2) // [0, 0, 0, 0] |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #OCaml | OCaml | let max_doors = 100
let show_doors =
Array.iteri (fun i x -> Printf.printf "Door %d is %s\n" (i+1)
(if x then "open" else "closed"))
let flip_doors doors =
for i = 1 to max_doors do
let rec flip idx =
if idx < max_doors then begin
doors.(idx) <- not 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... | #Lua | Lua | function make(n, d)
local a = {}
for i=1,n do
table.insert(a, d)
end
return a
end
function reverse(t)
local n = #t
local i = 1
while i < n do
t[i],t[n] = t[n],t[i]
i = i + 1
n = n - 1
end
end
function tail(list)
return { select(2, unpack(list)) }
e... |
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
| #Phix | Phix | constant s = """
------*** *
-----* * *
----* * * *
---*** *
--* *** * * *
-* * * * *
* * * * * *
"""
puts(1,substitute_all(s,"* ",{"_/"," "}))
|
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,... | #D | D | void main() {
import std.stdio, std.string, std.net.curl, std.algorithm;
foreach (line; "http://tycho.usno.navy.mil/cgi-bin/timer.pl".byLine)
if (line.canFind(" UTC"))
line[4 .. $].writeln;
} |
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,... | #Delphi | Delphi |
program WebScrape;
{$APPTYPE CONSOLE}
{.$DEFINE DEBUG}
uses
Classes,
Winsock;
{ Function to connect to host, send HTTP request and retrieve response }
function DoHTTPGET(const hostName: PAnsiChar; const resource: PAnsiChar; HTTPResponse: TStrings): Boolean;
const
Port: integer = 80;
CRLF = #13#10;... |
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... | #Crystal | Crystal | require "http/client"
require "regex"
# Get the text from the internet
response = HTTP::Client.get "https://www.gutenberg.org/files/135/135-0.txt"
text = response.body
text
.downcase
.scan(/[a-zA-ZáéíóúÁÉÍÓÚâêôäüöàèìòùñ']+/)
.reduce({} of String => Int32) { |hash, match|
word = match[0]
hash[word] = h... |
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... | #Go | Go | package main
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
)
var rows, cols int // extent of input configuration
var rx, cx int // grid extent (includes border)
var mn []int // offsets of moore neighborhood
func main() {
// read input configuration from file
src, err := ioutil.Rea... |
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.
| #Java | Java | import javax.swing.JFrame;
public class Main {
public static void main(String[] args) throws Exception {
JFrame w = new JFrame("Title");
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(800,600);
w.setVisible(true);
}
} |
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.
| #JavaScript | JavaScript | window.open("webpage.html", "windowname", "width=800,height=600");
|
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... | #Icon_and_Unicon | Icon and Unicon |
procedure main(A)
ll := integer(A[1]) | 72
wordWrap(&input, ll)
end
procedure wordWrap(f, ll)
every (sep := "", s := "", w := words(f)) do
if w == "\n" then write(1(.s, s := sep := ""),"\n")
else if (*s + *w) >= ll then write(1(.s, s := w, sep := " "))
else (... |
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 ... | #R | R | library(XML)
char2xml <- function(names, remarks){
tt <- xmlHashTree()
head <- addNode(xmlNode("CharacterRemarks"), character(), tt)
node <- list()
for (i in 1:length(names)){
node[[i]] <- addNode(xmlNode("Character", attrs=c(name=names[i])), head, tt)
addNode(xmlTextNode(remarks[i]), node[[i]], tt)
}
return(... |
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 ... | #Racket | Racket |
#lang racket
(require xml)
(define (make-character-xexpr characters remarks)
`(CharacterRemarks
,@(for/list ([character characters]
[remark remarks])
`(Character ((name ,character)) ,remark))))
(display-xml/content
(xexpr->xml
(make-character-xexpr
'("April" "Tam O'Shanter" "Emi... |
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" /... | #OpenEdge_ABL.2FProgress_4GL | OpenEdge ABL/Progress 4GL |
/** ==== Definitions ===== **/
DEFINE VARIABLE chXMLString AS LONGCHAR NO-UNDO.
DEFINE TEMP-TABLE ttStudent NO-UNDO XML-NODE-NAME 'Student'
FIELD StudentName AS CHARACTER XML-NODE-TYPE 'attribute' XML-NODE-NAME 'Name' LABEL 'Name'
FIELD Gender AS CHARACTER XML-NODE-TYPE 'attribute' XML-NODE-NAME '... |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /... | #OpenEdge.2FProgress | OpenEdge/Progress |
DEF VAR lcc AS LONGCHAR.
DEF VAR hxdoc AS HANDLE.
DEF VAR hxstudents AS HANDLE.
DEF VAR hxstudent AS HANDLE.
DEF VAR hxname AS HANDLE.
DEF VAR ii AS INTEGER EXTENT 2.
DEF VAR cstudents AS CHARACTER.
lcc = '<Students>'
+ '<Student Name="April" Gender="F" DateOfBirth=... |
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,... | #X86_Assembly | X86 Assembly |
section .text
global _start
_print:
mov ebx, 1
mov eax, 4
int 0x80
ret
_start:
;print out our byte array. ergo, String.
mov edx, sLen
mov ecx, sArray
call _print
mov edx, f_len
mov ecx, f_msg
call _print
mov edx, 6 ;our array members length.
xor ecx, ecx
mov ecx, 4
;turnicate th... |
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... | #Octave | Octave | doors = false(100,1);
for i = 1:100
for j = i:i:100
doors(j) = !doors(j);
endfor
endfor
for i = 1:100
if ( doors(i) )
s = "open";
else
s = "closed";
endif
printf("%d %s\n", i, s);
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[WeirdNumberQ, HasSumQ]
HasSumQ[n_Integer, xs_List] := HasSumHelperQ[n, ReverseSort[xs]]
HasSumHelperQ[n_Integer, xs_List] := Module[{h, t},
If[Length[xs] > 0,
h = First[xs];
t = Drop[xs, 1];
If[n < h,
HasSumHelperQ[n, t]
,
n == h \[Or] HasSumHelperQ[n - h, t] \[Or] HasSumHelperQ[n, t]
... |
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... | #Nim | Nim | import algorithm, math, strutils
func divisors(n: int): seq[int] =
var smallDivs = @[1]
for i in 2..sqrt(n.toFloat).int:
if n mod i == 0:
let j = n div i
smallDivs.add i
if i != j: result.add j
result.add reversed(smallDivs)
func abundant(n: int; divs: seq[int]): bool {.inline.}=
sum(d... |
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
| #PicoLisp | PicoLisp | (de Lst
"***** * "
"* * * * * "
"* * **** **** * **** ****"
"***** * * * * * * * * * *"
"* * * * * * * * ****"
"* * * * * * * * * "
"* * * * * * * * * * "
"* * **** **** **** * ***... |
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
| #PureBasic | PureBasic | If OpenConsole()
PrintN(" ////\ ////\ ////| ")
PrintN(" //// \ __ //// \ __ |XX|_/ ")
PrintN(" //// /| | ////\ ////\//// |//// /| | //// | ////\ ////\ ")
PrintN("|XX| |X| ////\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,... | #E | E | interp.waitAtTop(when (def html := <http://tycho.usno.navy.mil/cgi-bin/timer.pl>.getText()) -> {
def rx`(?s).*>(@time.*? UTC).*` := html
println(time)
}) |
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... | #D | D | import std.algorithm : sort;
import std.array : appender, split;
import std.range : take;
import std.stdio : File, writefln, writeln;
import std.typecons : Tuple;
import std.uni : toLower;
//Container for a word and how many times it has been seen
alias Pair = Tuple!(string, "k", int, "v");
void main() {
int[st... |
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... | #Haskell | Haskell | import Data.List
import Control.Monad
import Control.Arrow
import Data.Maybe
states=" Ht."
shiftS=" t.."
borden bc xs = bs: (map (\x -> bc:(x++[bc])) xs) ++ [bs]
where r = length $ head xs
bs = replicate (r+2) bc
take3x3 = ap ((.). taken. length) (taken. length. head) `ap` borden '*'
where taken 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.
| #Julia | Julia | # v0.6
using Tk
w = Toplevel("Example") |
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.
| #Kotlin | Kotlin | import javax.swing.JFrame
fun main(args : Array<String>) {
JFrame("Title").apply {
setSize(800, 600)
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
isVisible = true
}
} |
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... | #IS-BASIC | IS-BASIC | 100 TEXT 80
110 CALL WRITE(12,68,0)
120 PRINT :CALL WRITE(10,70,1)
130 DEF WRITE(LEFTMARGIN,RIGHTMARGIN,JUSTIFIED)
140 STRING S$*254
150 RESTORE
160 PRINT TAB(LEFTMARGIN);CHR$(243);
170 PRINT TAB(RIGHTMARGIN-1);CHR$(251)
180 DO
190 READ IF MISSING EXIT DO:S$
200 PRINT S$;
210 LOOP
220 IF JUSTIF... |
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... | #J | J | ww =: 75&$: : wrap
wrap =: (] turn edges) ,&' '
turn =: LF"_`]`[}
edges =: (_1 + ] #~ 1 ,~ 2 >/\ |) [: +/\ #;.2 |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling ... | #Raku | Raku | use XML::Writer;
my @students =
[ Q[April], Q[Bubbly: I'm > Tam and <= Emily] ],
[ Q[Tam O'Shanter], Q[Burns: "When chapman billies leave the street ..."] ],
[ Q[Emily], Q[Short & shrift] ]
;
my @lines = map { :Character[:name(.[0]), .[1]] }, @students;
say XML::Writer.serialize( Chara... |
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" /... | #Oz | Oz | declare
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
Parser = {New XMLParser.parser init}
Data =
"<Students>"
#" <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"
#" <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />"
#" <Student Name=\"Chad\" Gender=... |
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,... | #XBS | XBS | set Array = ["Hello","World"];
log(Array[0]);
Array.push("Test");
log(?Array);
log(Array[?Array-1]); |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Oforth | Oforth | : doors
| i j l |
100 false Array newWith dup ->l
100 loop: i [
i 100 i step: j [ l put ( j , j l at not ) ]
]
;
|
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... | #Perl | Perl | use strict;
use feature 'say';
use List::Util 'sum';
use POSIX 'floor';
use Algorithm::Combinatorics 'subsets';
use ntheory <is_prime divisors>;
sub abundant {
my($x) = @_;
my $s = sum( my @l = is_prime($x) ? 1 : grep { $x != $_ } divisors($x) );
$s > $x ? ($s, sort { $b <=> $a } @l) : ();
}
my(@weird... |
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
| #Python | Python | py = '''\
##### # # ##### # # #### # #
# # # # # # # # # ## #
# # # # ###### # # # # #
##### # # # # # # # # #
# # # # # # # # ##
# # # # # #### # #
'''
lines = py.repla... |
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,... | #Erlang | Erlang | -module(scraping).
-export([main/0]).
-define(Url, "http://tycho.usno.navy.mil/cgi-bin/timer.pl").
-define(Match, "<BR>(.+ UTC)").
main() ->
inets:start(),
{ok, {_Status, _Header, HTML}} = httpc:request(?Url),
{match, [Time]} = re:run(HTML, ?Match, [{capture, all_but_first, binary}]),
io:format("~s~n",[Time])... |
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... | #Delphi | Delphi |
program Word_frequency;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IOUtils,
System.Generics.Collections,
System.Generics.Defaults,
System.RegularExpressions;
type
TWords = TDictionary<string, Integer>;
TFreqPair = TPair<string, Integer>;
TFreq = TArray<TFreqPair>;
function CreateValue... |
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... | #Icon_and_Unicon | Icon and Unicon | link graphics
$define EDGE -1
$define EMPTY 0
$define HEAD 1
$define TAIL 2
$define COND 3
global Colours,Width,Height,World,oldWorld
procedure main() # wire world modified from forestfire
Height := 400 # Window height
Width := 400 # Window width
Rounds := 500 ... |
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.
| #Liberty_BASIC | Liberty BASIC | nomainwin
open "GUI Window" for window as #1
wait
|
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.
| #Lingo | Lingo | win = window().new("New Window")
w = 320
h = 240
firstScreen = _system.deskTopRectList[1]
x = firstScreen.width/2 - w/2
y = firstScreen.height/2- h/2
win.rect = rect(x,y,x+w,y+h)
-- Director needs a binary movie file (*.dir) for opening new windows. But this
-- movie file can be totally empty, and if it's write protect... |
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... | #Java | Java |
package rosettacode;
import java.util.StringTokenizer;
public class WordWrap
{
int defaultLineWidth=80;
int defaultSpaceWidth=1;
void minNumLinesWrap(String text)
{
minNumLinesWrap(text,defaultLineWidth);
}
void minNumLinesWrap(String text,int LineWidth)
{
StringTokeni... |
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 ... | #Rascal | Rascal | import Prelude;
import lang::xml::DOM;
list[str] charnames = ["April", "Tam O\'Shanter", "Emily"];
list[str] remarks = ["Bubbly: I\'m \> Tam and \<= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"];
public void xmloutput(list[str] n,list[str] r){
if(size(n) != size(r)){
throw "n ... |
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 ... | #REXX | REXX | /*REXX program creates an HTML (XML) list of character names and corresponding remarks. */
charname. =
charname.1 = "April"
charname.2 = "Tam O'Shanter"
charname.3 = "Emily"
do i=1 while charname.i\==''
say 'charname' i '=' charname.i
... |
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" /... | #Perl | Perl | use utf8;
use XML::Simple;
my $ref = XMLin('<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=... |
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,... | #XLISP | XLISP | [1] (define a (make-vector 10)) ; vector of 10 elements initialized to the empty list
A
[2] (define b (make-vector 10 5)) ; vector of 10 elements initialized to 5
B
[3] (define c #(1 2 3 4 5 6 7 8 9 10)) ; vector literal
C
[4] (vector-ref c 3) ; retrieve a value -- NB. indexed from 0
4
[5] (vector-set! a 5 1) ;... |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Ol | Ol |
(define (flip doors every)
(map (lambda (door num)
(mod (+ door (if (eq? (mod num every) 0) 1 0)) 2))
doors
(iota (length doors) 1)))
(define doors
(let loop ((doors (repeat 0 100)) (n 1))
(if (eq? n 100)
doors
(loop (flip doors n) (+ n 1)))))
(print "100th do... |
http://rosettacode.org/wiki/Weird_numbers | Weird numbers | In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors su... | #Phix | Phix | with javascript_semantics
function abundant(integer n, sequence divs)
return sum(divs) > n
end function
function semiperfect(integer n, sequence divs)
if length(divs)=0 then return false end if
integer h = divs[1]; divs = divs[2..$]
return n=h
or (n>h and semiperfect(n-h, divs))
or ... |
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
| #Quackery | Quackery | say " ________ ___ ___ ________ ________ ___ __ _______ ________ ___ ___" cr
say "|\ __ \|\ \|\ \|\ __ \|\ ____\|\ \|\ \ |\ ___ \ |\ __ \|\ \ / /|" cr
say "\ \ \|\ \ \ \ \ \ \ \|\ \ \ \___|\ \ \/ /|\ \ __/|\ \ \|\ \ \ \/ / /" cr
say " \ \ \ \ \ \ \ \ \ \ __ \ \ \... |
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
| #Racket | Racket |
#lang racket/gui
;; Get the language name
(define str (cadr (regexp-match #rx"Welcome to (.*?) *v[0-9.]+\n*$" (banner))))
;; Font to use
(define font (make-object font% 12 "MiscFixed" 'decorative 'normal 'bold))
;; (get-face-list) -> get a list of faces to try in the above
;; Calculate the needed size (leave sp... |
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,... | #F.23 | F# |
open System
open System.Net
open System.Text.RegularExpressions
async {
use wc = new WebClient()
let! html = wc.AsyncDownloadString(Uri("http://tycho.usno.navy.mil/cgi-bin/timer.pl"))
return Regex.Match(html, @"<BR>(.+ UTC)").Groups.[1].Value
}
|> Async.RunSynchronously
|> printfn "%s"
|
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,... | #Factor | Factor | USING: http.client io sequences ;
"http://tycho.usno.navy.mil/cgi-bin/timer.pl" http-get nip
[ "UTC" swap start [ 9 - ] [ 1 - ] bi ] keep subseq print |
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... | #F.23 | F# |
open System.IO
open System.Text.RegularExpressions
let g=Regex("[A-Za-zÀ-ÿ]+").Matches(File.ReadAllText "135-0.txt")
[for n in g do yield n.Value.ToLower()]|>List.countBy(id)|>List.sortBy(fun n->(-(snd n)))|>List.take 10|>List.iter(fun n->printfn "%A" n)
|
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... | #J | J | circ0=:}: ] ;. _1 LF, 0 : 0
tH........
. .
...
. .
Ht.. .....
) |
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.
| #Lua | Lua | local iup = require "iuplua"
iup.dialog{
title = "Window";
iup.vbox{
margin = "10x10";
iup.label{title = "A window"}
}
}:show()
iup.MainLoop()
|
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.
| #M2000_Interpreter | M2000 Interpreter |
Module DisplayWindow {
Declare MyForm Form
Method MyForm,"Show",1
}
DisplayWindow
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | CreateDocument[] |
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... | #JavaScript | JavaScript |
function wrap (text, limit) {
if (text.length > limit) {
// find the last space within limit
var edge = text.slice(0, limit).lastIndexOf(' ');
if (edge > 0) {
var line = text.slice(0, edge);
var remainder = text.slice(edge + 1);
return line + '\n' + wrap(remainder, limit);
}
}
... |
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 ... | #Ruby | Ruby | require 'rexml/document'
include REXML
remarks = {
%q(April) => %q(Bubbly: I'm > Tam and <= Emily),
%q(Tam O'Shanter) => %q(Burns: "When chapman billies leave the street ..."),
%q(Emily) => %q(Short & shrift),
}
doc = Document.new
root = doc.add_element("CharacterRemarks")
remarks.each do |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" /... | #Phix | Phix | with javascript_semantics
include builtins/xml.e
constant xml = """
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-... |
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,... | #XPL0 | XPL0 | include c:\cxpl\codes;
char A(10); \creates a static array of 10 bytes, pointed to by "A"
char B; \declares a variable for a pointer to a dynamic array
[A(3):= 14;
B:= Reserve(10); \reserve 10 bytes and point to their starting address
B(7):= 28;
IntOut(0, A(3)+B(7)); \displays 42
] |
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... | #Onyx | Onyx | $Door dict def
1 1 100 {Door exch false put} for
$Toggle {dup Door exch get not Door up put} def
$EveryNthDoor {dup 100 {Toggle} for} def
$Run {1 1 100 {EveryNthDoor} for} def
$ShowDoor {dup `Door no. ' exch cvs cat ` is ' cat
exch Door exch get {`open.\n'}{`shut.\n'} ifelse cat
print flush} def
Run 1 1 100 {ShowDo... |
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... | #Python | Python | '''Weird numbers'''
from itertools import chain, count, islice, repeat
from functools import reduce
from math import sqrt
from time import time
# weirds :: Gen [Int]
def weirds():
'''Non-finite stream of weird numbers.
(Abundant, but not semi-perfect)
OEIS: A006037
'''
def go(n):
... |
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII | Write language name in 3D ASCII | Task
Write/display a language's name in 3D ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
Related tasks
draw a sphere
draw a cuboid
draw a rotating cube
draw a Deathstar
| #Raku | Raku | # must be evenly padded with white-space$
my $text = q:to/END/;
@@@@@ @@
@ @ @ @@@
@ @ @ @@
@ @ @@@ @ @@ @ @@
@@@@@ @ @ @@ @ @ @@@@@
@ @@@@@ @ @ @@ @@
@ @ @ @ @@ @@
@ @@@ @... |
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,... | #Forth | Forth | include unix/socket.fs
: extract-time ( addr len type len -- time len )
dup >r
search 0= abort" that time not present!"
dup >r
begin -1 /string over 1- c@ [char] > = until \ seek back to <BR> at start of line
r> - r> + ;
s" tycho.usno.navy.mil" 80 open-socket
dup s\" GET /cgi-bin/timer.pl HTTP/1.0\... |
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,... | #FunL | FunL | import io.Source
case Source.fromURL( 'http://tycho.usno.navy.mil/cgi-bin/timer.pl', 'UTF-8' ).getLines().find( ('Eastern' in) ) of
Some( time ) -> println( time.substring(4) )
None -> error( 'Easter time not found' ) |
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.