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/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...
#Factor
Factor
  USING: ascii io math.statistics prettyprint sequences splitting ; IN: rosetta-code.word-count   lines " " join " .,?!:;()\"-" split harvest [ >lower ] map sorted-histogram <reversed> 10 head .  
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...
#FreeBASIC
FreeBASIC
  #Include "file.bi" type tally as string s as long l end type   Sub quicksort(array() As String,begin As Long,Finish As Long) Dim As Long i=begin,j=finish Dim As String x =array(((I+J)\2)) While I <= J While array(I) < X :I+=1:Wend While array(J) > X :J-=1:Wend If I<=J Then Swap array(I),array(J): ...
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...
#Java
Java
<!DOCTYPE html><html><head><meta charset="UTF-8"> <title>Wireworld</title> <script src="wireworld.js"></script></head><body> <input type='file' accept='text/plain' onchange='openFile( event )' /> <br /></body></html>
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.
#mIRC_Scripting_Language
mIRC Scripting Language
alias CreateMyWindow { .window -Cp +d @WindowName 600 480 }
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.
#Nanoquery
Nanoquery
w = new(Nanoquery.Util.Windows.Window).setSize(300,300).setTitle("Nanoquery").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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import javax.swing.JFrame import javax.swing.JLabel import java.awt.BorderLayout import java.awt.Font import java.awt.Color   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ parse arg showText . select when s...
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...
#jq
jq
# Simple greedy algorithm. # Note: very long words are not truncated. # input: a string # output: an array of strings def wrap_text(width): reduce splits("\\s+") as $word ([""]; .[length-1] as $current | ($word|length) as $wl | (if $current == "" then 0 else 1 end) as $pad | if $wl + $pad + ($...
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...
#Julia
Julia
using TextWrap   text = """Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available...
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 ...
#Rust
Rust
extern crate xml;   use std::collections::HashMap; use std::str;   use xml::writer::{EmitterConfig, XmlEvent};   fn characters_to_xml(characters: HashMap<String, String>) -> String { let mut output: Vec<u8> = Vec::new(); let mut writer = EmitterConfig::new() .perform_indent(true) .create_writer(...
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 ...
#Scala
Scala
val names = List("April", "Tam O'Shanter", "Emily")   val remarks = List("Bubbly: I'm > Tam and <= Emily", """Burns: "When chapman billies leave the street ..."""", "Short & shrift")   def characterRemarks(names: List[String], remarks: List[String]) = <CharacterRemarks> { names zip remarks map { case (name, remark) =...
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" /...
#PHP
PHP
<?php $data = '<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Stude...
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Yabasic
Yabasic
dim a(10) // create a numeric array with 11 elements, from 0 to 10 // Indexed at your preference (0 to 9 or 1 to 10) print arraysize(a(), 1) // this function return the element's higher number of an array   a(7) = 12.3 // access to an element of the array redim a(20) // alias of 'dim'. Grouth size of array  ...
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...
#ooRexx
ooRexx
doors = .array~new(100) -- array containing all of the doors do i = 1 to doors~size -- initialize with a collection of closed doors doors[i] = .door~new(i) end   do inc = 1 to doors~size do d = inc to doors~size by inc doors[d]~toggle end end say "The open doors after 100 passes:" do door over doors ...
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...
#Quackery
Quackery
[ stack ] is target ( --> s ) [ stack ] is success ( --> s ) [ stack ] is makeable ( --> s )   [ bit makeable take 2dup & 0 != dip [ | makeable put ] ] is made ( n --> b )   [ ' [ 0 ] swap dup ...
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...
#Racket
Racket
#lang racket   (require math/number-theory)   (define (abundant? n proper-divisors) (> (apply + proper-divisors) n))   (define (semi-perfect? n proper-divisors) (let recur ((ds proper-divisors) (n n)) (or (zero? n) (and (positive? n) (pair? ds) (or (recur (cdr ds) 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
#Raven
Raven
[ " ##### #### # # #### # #" " # # # # # # # ## #" " # # # # # # ### # # #" " ##### ###### # # ### # # #" " # # # # # # # # ##" " # # # # # #### # #" ] as $str   "/" as $r1 ">" as $r2   #$str each "%s\n" print   $str each...
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
#REXX
REXX
/*REXX program that displays a "REXX" 3D "ASCII art" as a logo. */ signal . /* Uses left-hand shadows, slightly raised view. 0=5~2?A?2?A? @)E)3@)B)1)2)8()2)1)2)8()2) @]~")2@]0`)0@)%)6{)%)0@)%)6{)%) #E)1#A@0}2)4;2(1}2)4;2( #3??3@0#2??@1}2)2;2(3}2)2;2( #2@5@)@2@0#2@A}2)0;2(5}2)0;2( #2@?"@)@2@0#2@?7...
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,...
#Gambas
Gambas
Public Sub Main() Dim sWeb, sTemp, sOutput As String 'Variables   Shell "wget -O /tmp/web http://tycho.usno.navy.mil/cgi-bin/timer.pl" Wait 'Use 'wget' to save the web file in /tmp/   sWeb = File.Load("/tmp/web") 'Open file and st...
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...
#Frink
Frink
d = new dict for w = select[wordList[read[normalizeUnicode["https://www.gutenberg.org/files/135/135-0.txt", "UTF-8"]]], %r/[[:alnum:]]/ ] d.increment[lc[w], 1]   println[join["\n", first[reverse[sort[array[d], {|a,b| a@1 <=> b@1}]], 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...
#FutureBasic
FutureBasic
  include "NSLog.incl"   local fn WordFrequency( textStr as CFStringRef, caseSensitive as Boolean, ascendingOrder as Boolean ) as CFStringRef '~'1 CFStringRef wrd CFDictionaryRef dict   // Depending on the value of the caseSensitive Boolean function parameter above, lowercase incoming text if caseSensitive == NO th...
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...
#JavaScript
JavaScript
<!DOCTYPE html><html><head><meta charset="UTF-8"> <title>Wireworld</title> <script src="wireworld.js"></script></head><body> <input type='file' accept='text/plain' onchange='openFile( event )' /> <br /></body></html>
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...
#jq
jq
def lines: split("\n")|length;   def cols: split("\n")[0]|length + 1; # allow for the newline   # Is there an "H" at [x,y] relative to position i, assuming the width is w? # Input is an array; 72 is "H" def isH(x; y; i; w): if .[i+ w*y + x] == 72 then 1 else 0 end;   def neighborhood(i;w): isH(-1; -1; i; w) + isH(0;...
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Nim
Nim
import gintro/[glib, gobject, gtk, gio]   proc activate(app: Application) = ## Activate the application. let window = newApplicationWindow(app) window.setTitle("Window for Rosetta") window.setSizeRequest(640, 480) window.showAll()   let app = newApplication(Application, "Rosetta.Window") discard app.connect("...
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.
#Objeck
Objeck
  use Gtk2;   bundle Default { class GtkHello { function : Main(args : String[]) ~ Nil { window := GtkWindow->New(); delete_callback := Events->DeleteEvent(GtkWidget) ~ Nil; window->SignalConnect(Signal->Destroy, window->As(GtkWidget), delete_callback); window->SetTitle("Title"); win...
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...
#Klingphix
Klingphix
:wordwrap %long !long  %ps 0 !ps   split len [ drop pop swap len $ps + !ps $ps $long > [ len !ps nl ] if print " " print $ps 1 + !ps ] for drop ;     "tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH. boQchugh Hoch, mu'ghom Dun mojlaH. tlhIngan m...
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 ...
#SenseTalk
SenseTalk
put ("April", "Tam O'Shanter", "Emily") into names put ("Bubbly: I'm > Tam and <= Emily", <<Burns: "When chapman billies leave the street ...">>, "Short & shrift") into remarks put (_tag: "CharacterRemarks") as tree into document repeat for each item name in names insert (_tag: "Character", name: name, _children: item...
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 ...
#Sidef
Sidef
require('XML::Mini::Document');   var students = [ ["April", "Bubbly: I'm > Tam and <= Emily"], ["Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""], ["Emily", "Short & shrift"] ];   var doc = %s'XML::Mini::Document'.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" /...
#PicoLisp
PicoLisp
(load "@lib/xm.l")   (mapcar '((L) (attr L 'Name)) (body (in "file.xml" (xml))) )
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Z80_Assembly
Z80 Assembly
Array: ;an array located in RAM. Its values can be updated freely. byte 0,0,0,0,0 byte 0,0,0,0,0 byte 0,0,0,0,0 byte 0,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...
#OpenEdge.2FProgress
OpenEdge/Progress
DEFINE VARIABLE lopen AS LOGICAL NO-UNDO EXTENT 100. DEFINE VARIABLE idoor AS INTEGER NO-UNDO. DEFINE VARIABLE ipass AS INTEGER NO-UNDO. DEFINE VARIABLE cresult AS CHARACTER NO-UNDO.   DO ipass = 1 TO 100: idoor = 0. DO WHILE idoor <= 100: idoor = idoor + ipass. IF idoor <= 100 THE...
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...
#Raku
Raku
sub abundant (\x) { my @l = x.is-prime ?? 1 !! flat 1, (2 .. x.sqrt.floor).map: -> \d { my \y = x div d; next if y * d !== x; d !== y ?? (d, y) !! d }; (my $s = @l.sum) > x ?? ($s, |@l.sort(-*)) !! (); }   my @weird = (2, 4, {|($_ + 4, $_ + 6)} ... *).map: -> $n { my ($sum...
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
#Ruby
Ruby
text = <<EOS #### # # # # # # # #### # # ### # # # # # # # # # # # # # # # # # # # ### ### # # # EOS   def banner3D_1(text, shift=-1) txt = text.each_line.map{|line| line.gsub('#','__/').gsub(' ',' ')} offset = Array.new(txt.size){|i...
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,...
#Go
Go
package main   import ( "bytes" "encoding/xml" "fmt" "io" "net/http" "regexp" "time" )   func main() { resp, err := http.Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl") if err != nil { fmt.Println(err) // connection or request fail return } defer resp.Body....
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...
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" "regexp" "sort" "strings" )   type keyval struct { key string val int }   func main() { reg := regexp.MustCompile(`\p{Ll}+`) bs, err := ioutil.ReadFile("135-0.txt") if err != nil { log.Fatal(err) } text := string...
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...
#Julia
Julia
function surround2D(b, i, j) h, w = size(b) [b[x,y] for x in i-1:i+1, y in j-1:j+1 if (0 < x <= h && 0 < y <= w)] end   surroundhas1or2(b, i, j) = 0 < sum(map(x->Char(x)=='H', surround2D(b, i, j))) <= 2 ? 'H' : '.'   function boardstep!(currentboard, nextboard) x, y = size(currentboard) for j in 1:y, i ...
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...
#Liberty_BASIC
Liberty BASIC
  WindowWidth = 840 WindowHeight = 600   dim p$( 40, 25), q$( 40, 25)   empty$ = " " ' white tail$ = "t" ' yellow head$ = "H" ' black conductor$ = "." ' red   jScr = 0   nomainwin   menu #m, "File", "Load", [load], "Quit", [quit]   open "wire world" for graphics_nf_nsb as #m #...
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.
#Objective-C
Objective-C
#include <Foundation/Foundation.h> #include <AppKit/AppKit.h>   @interface Win : NSWindow { } - (void)applicationDidFinishLaunching: (NSNotification *)notification; - (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification; @end     @implementation Win : NSWindow -(instancetype) init { i...
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...
#Kotlin
Kotlin
// version 1.1.3   val 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. Close by the king's castle lay...
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 ...
#Slate
Slate
lobby define: #remarks -> ( {'April' -> 'Bubbly: I\'m > Tam and <= Emily'. 'Tam O\'Shanter' -> 'Burns: "When chapman billies leave the street ..."'. 'Emily' -> 'Short & shrift'. } as: Dictionary).   define: #writer -> (Xml Writer newOn: '' new writer). writer inTag: 'CharacterRemarks' do: [| :w | lobby remarks key...
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 ...
#Tcl
Tcl
proc xquote string { list [string map "' &apos; \\\" &quot; < &gt; > &lt; & &amp;" $string] } proc < {name attl args} { set res <$name foreach {att val} $attl { append res " $att='$val'" } if {[llength $args]} { append res > set sep "" foreach a $args { ap...
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" /...
#Pike
Pike
  string in = "<Students>\n" " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" " <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n" " <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n" " <Student Name=\"Dave\"...
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,...
#zkl
zkl
var array=List(); // array of size 0 array=(0).pump(10,List().write,5).copy(); // [writable] array of size 10 filled with 5 array[3]=4; array[3] //-->4 array+9; //append a 9 to the end, same as array.append(9)
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...
#OxygenBasic
OxygenBasic
def doors 100 int door[doors],i ,j, c string cr,tab,pr ' for i=1 to doors for j=i to doors step i door[j]=1-door[j] if door[j] then c++ else c-- next next ' cr=chr(13) chr(10) pr="Doors Open: " c cr cr ' for i=1 to doors if door[i] then pr+=i cr next print pr
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...
#REXX
REXX
/*REXX program finds and displays N weird numbers in a vertical format (with index).*/ parse arg n cols . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 25 /*Not specified? Then use the default.*/ if cols=='' | cols=="," then cols= 10 ...
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
#Rust
Rust
pub fn char_from_id(id: u8) -> char { [' ', '#', '/', '_', 'L', '|', '\n'][id as usize] }   const ID_BITS: u8 = 3;   pub fn decode(code: &[u8]) -> String { let mut ret = String::new(); let mut carry = 0; let mut carry_bits = 0; for &b in code { let mut bit_pos = ID_BITS - carry_bits; ...
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
#Scala
Scala
def ASCII3D = {   val name = """ * ** ** * * * * * * * * * * * * * * * * * * * *** * *** * * * * * * * * * * * * * * ** ** * * *** * * * * """   // Create Array   def getMaxSize(s: String): (Int, Int)...
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,...
#Groovy
Groovy
def time = "unknown" def text = new URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl').eachLine { line -> def matcher = (line =~ "<BR>(.+) UTC") if (matcher.find()) { time = matcher[0][1] } } println "UTC Time was '$time'"
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,...
#Haskell
Haskell
import Data.List import Network.HTTP (simpleHTTP, getResponseBody, getRequest)   tyd = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"   readUTC = simpleHTTP (getRequest tyd)>>= fmap ((!!2).head.dropWhile ("UTC"`notElem`).map words.lines). getResponseBody>>=putStrLn
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...
#Groovy
Groovy
def topWordCounts = { String content, int n -> def mapCounts = [:] content.toLowerCase().split(/\W+/).each { mapCounts[it] = (mapCounts[it] ?: 0) + 1 } def top = (mapCounts.sort { a, b -> b.value <=> a.value }.collect{ it })[0..<n] println "Rank Word Frequency\n==== ==== =========" (0..<...
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...
#Logo
Logo
to wireworld :filename :speed ;speed in n times per second, approximated Make "speed 60/:speed wireworldread :filename Make "bufferfield (mdarray (list :height :width) 0) for [i 0 :height-1] [for [j 0 :width-1] [mdsetitem (list :i :j) :bufferfield mditem (list :i :j) :field]] pu ht Make "gen 0 while ["true] [ ;The user...
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.
#OCaml
OCaml
let () = let top = Tk.openTk() in Wm.title_set top "An Empty Window"; Wm.geometry_set top "240x180"; Tk.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.
#OpenEdge_ABL.2FProgress_4GL
OpenEdge ABL/Progress 4GL
    DEFINE VAR C-Win AS WIDGET-HANDLE NO-UNDO.   CREATE WINDOW C-Win ASSIGN HIDDEN = YES TITLE = "OpenEdge Window Display" HEIGHT = 10.67 WIDTH = 95.4 MAX-HEIGHT = 16 MAX-WIDTH = 95.4 VI...
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...
#Lambdatalk
Lambdatalk
  {def text Personne n’a sans doute oublié le terrible coup de vent de nord-est qui se déchaîna au milieu de l’équinoxe de cette année, et pendant lequel le baromètre tomba à sept cent dix millimètres. Ce fut un ouragan, sans intermittence, qui dura du 18 au 26 mars. Les ravages qu’il produisit furent immenses en Amér...
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...
#Lasso
Lasso
define wordwrap( text::string, row_length::integer = 75 ) => { return regexp(`(?is)(.{1,` + #row_length + `})(?:$|\W)+`, '$1<br />\n', #text, true) -> replaceall }   local(text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat ornare lectus, dignissim iaculis libero consequat sed....
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 ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT STRUCTURE xmloutput DATA '<CharacterRemarks>' DATA * ' <Character name="' names +'">' remarks +'</Character>' DATA = '</CharacterRemarks>' ENDSTRUCTURE BUILD X_TABLE entitysubst=" >> &gt; << &lt; & &amp; " ERROR/STOP CREATE ("dest",seq-o,-std-) ACCESS d: WRITE/ERASE/STRUCTURE "dest" num,str str="xm...
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 ...
#VBScript
VBScript
  Set objXMLDoc = CreateObject("msxml2.domdocument")   Set objRoot = objXMLDoc.createElement("CharacterRemarks") objXMLDoc.appendChild objRoot   Call CreateNode("April","Bubbly: I'm > Tam and <= Emily") Call CreateNode("Tam O'Shanter","Burns: ""When chapman billies leave the street ...""") Call CreateNode("Emily","Shor...
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" /...
#PowerShell
PowerShell
  [xml]$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-07-08"> <Pet Type="dog" Name="Rover" /> </Stu...
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" /...
#PureBasic
PureBasic
Define studentNames.String, src$   src$ = "<Students>" src$ + "<Student Name='April' Gender='F' DateOfBirth='1989-01-02' />" src$ + "<Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' />" src$ + "<Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' />" src$ + "<Student Name='Dave' Gender='M' DateOfBirth='19...
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,...
#zonnon
zonnon
  var a: array 10 of integer; da: array * of cardinal;  
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...
#Oz
Oz
declare NumDoors = 100 NumPasses = 100   fun {NewDoor} closed end   fun {Toggle Door} case Door of closed then open [] open then closed end end   fun {Pass Doors I} {List.mapInd Doors fun {$ Index Door} if Index mod I == 0 then {Toggle Door} else Door end...
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...
#Ruby
Ruby
def divisors(n) divs = [1] divs2 = []   i = 2 while i * i <= n if n % i == 0 then j = (n / i).to_i divs.append(i) if i != j then divs2.append(j) end end   i = i + 1 end   divs2 += divs.reverse return divs...
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
#Seed7
Seed7
$include "seed7_05.s7i";   const array string: name is [] ( " *** * ***** ", "* * * ", "* *** *** **** * ", "* * * * * * * * ", " *** * * * * * * * ", " * ***** ***** * * * ", " * * * * * *...
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
#Sidef
Sidef
var text = <<'EOT';   *** * * * ** * * * * * * *** ** *** * **** * * * * * * * ***** * * * * * * * * * * * * * *** * **** *** * EOT   func banner3D(text, shift=-1) { var txt = text.lines.map{|line| line...
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,...
#Icon_and_Unicon
Icon and Unicon
procedure main() m := open(url := "http://tycho.usno.navy.mil/cgi-bin/timer.pl","m") | stop("Unable to open ",url) every (p := "") ||:= |read(m) # read the page into a single string close(m)   map(p) ? ( tab(find("<br>")), ="<br>", write("UTC time=",p[&pos:find(" utc"...
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,...
#J
J
require 'web/gethttp'   _8{. ' UTC' taketo gethttp 'http://tycho.usno.navy.mil/cgi-bin/timer.pl' 04:32:44
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...
#Haskell
Haskell
module Main where   import Control.Category -- (>>>) import Data.Char -- toLower, isSpace import Data.List -- sortBy, (Foldable(foldl')), filter -- ' import Data.Ord -- Down import System.IO -- stdin, ReadMode, openFile, hClose import System.Environment -- getArgs   -- containers ...
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...
#Lua
Lua
  local map = {{'t', 'H', '.', '.', '.', '.', '.', '.', '.', '.', '.'}, {'.', ' ', ' ', ' ', '.'}, {' ', ' ', ' ', '.', '.', '.'}, {'.', ' ', ' ', ' ', '.'}, {'H', 't', '.', '.', ' ', '.', '.', '.', '.', '.', '.'}}   function step(map) local next = {} for i = ...
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Oz
Oz
functor import Application QTk at 'x-oz://system/wp/QTk.ozf' define proc {OnClose} {Application.exit 0} end   %% Descripe the GUI in a declarative style. GUIDescription = td(label(text:"Hello World!") action:OnClose %% Exit app when window closes. )   %% Create a window objec...
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.
#Pascal
Pascal
Program WindowCreation_SDL;   {$linklib SDL}   uses SDL, SysUtils;   var screen: PSDL_Surface;   begin SDL_Init(SDL_INIT_VIDEO); screen := SDL_SetVideoMode( 800, 600, 16, (SDL_SWSURFACE or SDL_HWPALETTE) ); sleep(2000); SDL_Quit; end.
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#LFE
LFE
  (defun wrap-text (text) (wrap-text text 78))   (defun wrap-text (text max-len) (string:join (make-wrapped-lines (string:tokens text " ") max-len) "\n"))   (defun make-wrapped-lines (((cons word rest) max-len) (let ((`#(,_ ,_ ,last-line ,lines) (assemble-lines max-len word rest))) (lists:...
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 ...
#Vedit_macro_language
Vedit macro language
// Replace special characters with entities: Replace("&", "&amp;", BEGIN+ALL+NOERR) // this must be the first replace! Replace("<", "&lt;", BEGIN+ALL+NOERR) Replace(">", "&gt;", BEGIN+ALL+NOERR) Replace("'", "&apos;", BEGIN+ALL+NOERR) Replace('"', "&quot;", BEGIN+ALL+NOERR)   // Insert XML marking BOF IT("<Cha...
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" /...
#Python
Python
import xml.dom.minidom   doc = """<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="...
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,...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DIM a(5) 20 LET a(2)=128 30 PRINT a(2)
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...
#PARI.2FGP
PARI/GP
  v=vector(d=100);/*set 100 closed doors*/ for(i=1,d,forstep(j=i,d,i,v[j]=1-v[j])); for(i=1,d,if(v[i],print("Door ",i," is open.")))  
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...
#Sidef
Sidef
func is_pseudoperfect(n, d = n.divisors.slice(0, -2), s = d.sum, m = d.end) {   return false if (m < 0)   while (d[m] > n) { s -= d[m--] }   return true if (n == s) return true if (d[m] == n)   __FUNC__(n-d[m], d, s-d[m], m-1) || __FUNC__(n, d, s-d[m], m-1) }   func is_weird(n) { (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
#SQL
SQL
SELECT ' SSS\ ' AS s, ' QQQ\ ' AS q, 'L\ ' AS l FROM dual UNION ALL SELECT 'S \|', 'Q Q\ ', 'L | ' FROM dual UNION ALL SELECT '\SSS ', 'Q Q |', 'L | ' FROM dual UNION ALL SELECT ' \ S\', 'Q Q Q |', 'L | ' from dual union all select ' SSS |', ...
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,...
#Java
Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection;     public class WebTime{ public static void main(String[] args){ try{ URL address = new URL( "http://tycho.usno.navy.mil/cgi-bin/timer.pl"); URLCo...
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...
#J
J
10{.\:~(#;{.)/.~;:tolower((e.&(a.-.Alpha_j_,' '))`(,:&' '))}1!:1<jpath'~/downloads/books/LesMis.txt' ┌─────┬────┐ │41093│the │ ├─────┼────┤ │19954│of │ ├─────┼────┤ │14943│and │ ├─────┼────┤ │14558│a │ ├─────┼────┤ │13953│to │ ├─────┼────┤ │11219│in │ ├─────┼────┤ │9649 │he │ ├─────┼────┤ │8622 │was │ ├─────┼─...
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...
#Java
Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;   public class WordCount { public ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DynamicModule[{data = ArrayPad[PadRight[Characters /@ StringSplit["tH......... . . ... . . Ht.. ......", "\n"]] /. {" " -> 0, "t" -> 2, "H" -> 1, "." -> 3}, 1]}, Dynamic@ArrayPlot[ data = CellularAutomaton[{{{_, _, _}, {_, 0, _}, {_, _, _}} -> 0, {{_, _, _}...
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Perl
Perl
use Tk;   MainWindow->new(); 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.
#Phix
Phix
-- demo\rosetta\Window_creation.exw with javascript_semantics include pGUI.e IupOpen() IupShow(IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200"),"TITLE=Hello")) if platform()!=JS then IupMainLoop() IupClose() end if
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...
#Lingo
Lingo
-- in some movie script   ---------------------------------------- -- Wraps specified text into lines of specified width (in px), returns lines as list of strings -- @param {string} str -- @param {integer} pixelWidth -- @param {propList} [style] -- @return {list} ---------------------------------------- on hardWrapText...
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...
#Lua
Lua
function splittokens(s) local res = {} for w in s:gmatch("%S+") do res[#res+1] = w end return res end   function textwrap(text, linewidth) if not linewidth then linewidth = 75 end   local spaceleft = linewidth local res = {} local line = {}   for _, word in ipairs...
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 ...
#Visual_Basic_.NET
Visual Basic .NET
Module XMLOutput Sub Main() Dim charRemarks As New Dictionary(Of String, String) charRemarks.Add("April", "Bubbly: I'm > Tam and <= Emily") charRemarks.Add("Tam O'Shanter", "Burns: ""When chapman billies leave the street ...""") charRemarks.Add("Emily", "Short & shrift")   Di...
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" /...
#R
R
library(XML) #Read in XML string str <- readLines(tc <- textConnection('<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="1...
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" /...
#Racket
Racket
  #lang racket (require xml xml/path)   (define input #<<END <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">...
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...
#Pascal
Pascal
Program OneHundredDoors;   var doors : Array[1..100] of Boolean; i, j : Integer;   begin for i := 1 to 100 do doors[i] := False; for i := 1 to 100 do begin j := i; while j <= 100 do begin doors[j] := not doors[j]; j := j + i end end; for i := 1 to 100 do begin Write(...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Dim resu As New List(Of Integer)   Function TestAbundant(n As Integer, ByRef divs As List(Of Integer)) As Boolean divs = New List(Of Integer) Dim sum As Integer = -n : For i As Integer = Math.Sqrt(n) To 1 Step -1 If n Mod i = 0 Then divs.Add(i) : Dim j As Integer = 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
#Tcl
Tcl
package require Tcl 8.5   proc mergeLine {upper lower} { foreach u [split $upper ""] l [split $lower ""] { lappend result [expr {$l in {" " ""} ? $u : $l}] } return [join $result ""] } proc printLines lines { set n [llength $lines] foreach line $lines { set indent [string repeat " " $n] lappend u...
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,...
#JavaScript
JavaScript
var req = new XMLHttpRequest(); req.onload = function () { var re = /[JFMASOND].+ UTC/; //beginning of month name to 'UTC' console.log(this.responseText.match(re)[0]); }; req.open('GET', 'http://tycho.usno.navy.mil/cgi-bin/timer.pl', true); req.send();
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,...
#jq
jq
#!/bin/bash curl -Ss 'http://tycho.usno.navy.mil/cgi-bin/timer.pl' |\ jq -R -r 'if index(" UTC") then .[4:] else empty end'
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...
#jq
jq
  < 135-0.txt jq -nR --argjson n 10 ' def bow(stream): reduce stream as $word ({}; .[($word|tostring)] += 1);   bow(inputs | gsub("[^-a-zA-Z]"; " ") | splits(" *") | ascii_downcase | select(test("^[a-z][-a-z]*$"))) | to_entries | sort_by(.value) | .[- $n :] | reverse | from_entries '  
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...
#Julia
Julia
  using FreqTables   txt = read("les-mis.txt", String) words = split(replace(txt, r"\P{L}"i => " ")) table = sort(freqtable(words); rev=true) println(table[1:10])
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...
#Nim
Nim
import strutils, os   var world, world2 = """ +-----------+ |tH.........| |. . | | ... | |. . | |Ht.. ......| +-----------+"""   let h = world.splitLines.len let w = world.splitLines[0].len   template isH(x, y): int = int(s[i + w * y + x] == 'H')   proc next(o: var string, s: string, w: int) = for...
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...
#OCaml
OCaml
let w = [| " ......tH "; " . ...... "; " ...Ht... . "; " .... "; " . ..... "; " .... "; " tH...... . "; " . ...... "; " ...Ht... "; |]   let is_head 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.
#PicoLisp
PicoLisp
(load "@lib/openGl.l")   (glutInit) (glutCreateWindow "Goodbye, World!") (keyboardFunc '(() (bye))) (glutMainLoop)
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.
#PowerShell
PowerShell
New-Window -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.
#Processing
Processing
  size(1000,1000);  
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...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ leading space from begin of paragraph stay as is a$={ 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 sho...