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/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
| #C.23 | C# | using System;
using System.Text;
namespace Language_name_in_3D_ascii
{
public class F5
{
char[] z = { ' ', ' ', '_', '/', };
long[,] f ={
{87381,87381,87381,87381,87381,87381,87381,},
{349525,375733,742837,742837,375733,349525,349525,},
{742741,768853,742837... |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Yabasic | Yabasic | open "output.txt" for writing as #1
print #1 "This is a string"
close #1 |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #zkl | zkl | // write returns bytes written, GC will close the file (eventually)
File("foo","wb").write("this is a test",1,2,3); //-->17
f:=File("bar",wb");
data.pump(f,g); // use g to process data as it is written to file
f.close(); // don't wait for GC |
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... | #360_Assembly | 360 Assembly | * Word wrap 29/01/2017
WORDWRAP CSECT
USING WORDWRAP,R13
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR ... |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #C.2B.2B | C++ | #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using word_map = std::map<size_t, std::vector<std::string>>;
// Returns true if strings s1 and s2 differ by one character.
bool one_away(const std::string& s1, const std::string& s2) {
if (s1.size() !=... |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the w... | #C | C | #include <stdbool.h>
#include <stdio.h>
#define MAX_WORD 80
#define LETTERS 26
bool is_letter(char c) { return c >= 'a' && c <= 'z'; }
int index(char c) { return c - 'a'; }
void word_wheel(const char* letters, char central, int min_length, FILE* dict) {
int max_count[LETTERS] = { 0 };
for (const char* p... |
http://rosettacode.org/wiki/Wordiff | Wordiff | Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from
the last by a change in one letter.
The change can be either:
a deletion of one letter;
addition of one letter;
or change in one letter.
Note:
All words must be in the... | #Vlang | Vlang | import os
import rand
import time
import arrays
fn is_wordiff(guesses []string, word string, dict []string) bool {
if word !in dict {
println('That word is not in the dictionary')
return false
}
if word in guesses {
println('That word has already been used')
return false
... |
http://rosettacode.org/wiki/Wordiff | Wordiff | Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from
the last by a change in one letter.
The change can be either:
a deletion of one letter;
addition of one letter;
or change in one letter.
Note:
All words must be in the... | #Wren | Wren | import "random" for Random
import "/ioutil" for File, Input
import "/str" for Str
import "/sort" for Find
var rand = Random.new()
var words = File.read("unixdict.txt").trim().split("\n")
var player1 = Input.text("Player 1, please enter your name : ", 1)
var player2 = Input.text("Player 2, please enter your name : "... |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Java | Java | import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;
public class XiaolinWu extends JPanel {
public XiaolinWu() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
}
void plot(Graphics2D g, double x, double y, double... |
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 ... | #Delphi | Delphi |
//You need to use these units
uses
Classes,
Dialogs,
XMLIntf,
XMLDoc;
//..............................................
//This function creates the XML
function CreateXML(aNames, aRemarks: TStringList): string;
var
XMLDoc: IXMLDocument;
Root: IXMLNode;
i: Integer;
begin
//Input check
if (aNames ... |
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" /... | #Common_Lisp | Common Lisp | (defparameter *xml-blob*
"<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 T... |
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,... | #Standard_ML | Standard ML |
(* create first array and assign elements *)
-val first = Array.tabulate (10,fn x=>x+10) ;
val first = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array
(* assign to array 'second' *)
-val second=first ;
val second = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array
(* retrieve 5th element *)
... |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat... | #Raku | Raku | constant scoring = 0, 1, 3;
my @histo = [0 xx 10] xx 4;
for [X] ^3 xx 6 -> @results {
my @s;
for @results Z (^4).combinations(2) -> ($r, @g) {
@s[@g[0]] += scoring[$r];
@s[@g[1]] += scoring[2 - $r];
}
for @histo Z @s.sort -> (@h, $v) {
++@h[$v];
}
}
say .fmt('%3d',' '... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #NewLISP | NewLISP | ; file: write-float-array.lsp
; url: http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
; author: oofoe 2012-01-30
; The "transpose" function is used to flip the joined lists around so
; that it's easier to iterate through them together.
(define (write-float-array x xp y yp filename)
(let ((f (fo... |
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... | #Microsoft_Small_Basic | Microsoft Small Basic |
For offset = 1 To 100
For i = 0 To 100 Step offset
a[i] = a[i] + 1
EndFor
EndFor
' Print "opened" doors
For i = 1 To 100
If math.Remainder(a[i], 2) = 1 Then
TextWindow.WriteLine(i)
EndIf
EndFor
|
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Python | Python | from xml.dom.minidom import getDOMImplementation
dom = getDOMImplementation()
document = dom.createDocument(None, "root", None)
topElement = document.documentElement
firstElement = document.createElement("element")
topElement.appendChild(firstElement)
textNode = document.createTextNode("Some text here")
firstElemen... |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Racket | Racket |
#lang at-exp racket
(require xml)
(define xml-str
@~a{<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>})
;; read & parse to get an xml value
(define xml (read-xml/document (open-input-string xml-str)))
;; print it out in xml form, which... |
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
| #C.2B.2B | C++ |
#include <windows.h>
#include <iostream>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
cout <<
" ... |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may ... | #11l | 11l | -V
dirs = [[1, 0], [ 0, 1], [ 1, 1],
[1, -1], [-1, 0],
[0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
T Grid
num_attempts = 0
[[String]] cells = [[‘’] * :n_cols] * :n_rows
[String] solutions
F read_words(filena... |
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... | #Action.21 | Action! | CHAR ARRAY text(1000)
CARD length
PROC AppendText(CHAR ARRAY part)
BYTE i
FOR i=1 TO part(0)
DO
text(length)=part(i)
length==+1
OD
RETURN
INT FUNC GetPosForWrap(BYTE lineLen INT start)
INT pos
pos=start+lineLen
IF pos>=length THEN
RETURN (length-1)
FI
WHILE pos>start AND text(pos... |
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... | #Ada | Ada | generic
with procedure Put_Line(Line: String);
package Word_Wrap is
type Basic(Length_Of_Output_Line: Positive) is tagged private;
procedure Push_Word(State: in out Basic; Word: String);
procedure New_Paragraph(State: in out Basic);
procedure Finish(State: in out Basic);
private
type Basic(Lengt... |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #F.23 | F# |
// Word ladder: Nigel Galloway. June 5th., 2021
let fG n g=n|>List.partition(fun n->2>Seq.fold2(fun z n g->z+if n=g then 0 else 1) 0 n g)
let wL n g=let dict=seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(Seq.length>>(=)(Seq.length n))|>List.ofSeq|>List... |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the w... | #C.2B.2B | C++ | #include <array>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
// A multiset specialized for strings consisting of lowercase
// letters ('a' to 'z').
class letterset {
public:
letterset() {
count_.fill(0);
}
explicit ... |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Julia | Julia | using Images
fpart(x) = mod(x, one(x))
rfpart(x) = one(x) - fpart(x)
function drawline!(img::Matrix{Gray{N0f8}}, x0::Integer, y0::Integer, x1::Integer, y1::Integer)
steep = abs(y1 - y0) > abs(x1 - x0)
if steep
x0, y0 = y0, x0
x1, y1 = y1, x1
end
if x0 > x1
x0, x1 = x1, x0
... |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import javax.swing.*
class XiaolinWu: JPanel() {
init {
preferredSize = Dimension(640, 640)
background = Color.white
}
private fun plot(g: Graphics2D, x: Double, y: Double, c: Double) {
g.color = Color(0f, 0f, 0f, c.toFloat())
g.fillOv... |
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 ... | #Erlang | Erlang |
-module( xml_output ).
-export( [task/0] ).
-include_lib("xmerl/include/xmerl.hrl").
task() ->
Data = {'CharacterRemarks', [], [{'Character', [{name, X}], [[Y]]} || {X, Y} <- contents()]},
lists:flatten( xmerl:export_simple([Data], xmerl_xml) ).
contents() -> [{"April", "Bubbly: I'm > Tam and <= 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" /... | #D | D | import kxml.xml;
char[]xmlinput =
"<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/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,... | #Stata | Stata | matrix a = 2,9,4\7,5,3\6,1,8
display det(a)
matrix svd u d v = a
matrix b = u*diag(d)*v'
matrix list b
* store the u and v matrices in the current dataset
svmat u
svmat v |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat... | #REXX | REXX | /* REXX -------------------------------------------------------------------*/
results = '000000' /*start with left teams all losing */
games = '12 13 14 23 24 34'
points.=0
records.=0
Do Until nextResult(results)=0
records.=0
Do i=1 To 6
r=substr(results,i,1)
g=word(games,i); Parse Var ... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #Nim | Nim | import strutils, math, sequtils
const OutFileName = "floatarr2file.txt"
const
XPrecision = 3
Yprecision = 5
let a = [1.0, 2.0, 3.0, 100_000_000_000.0]
let b = [sqrt(a[0]), sqrt(a[1]), sqrt(a[2]), sqrt(a[3])]
var res = ""
for t in zip(a, b):
res.add formatFloat(t[0], ffDefault, Xprecision) & " " &
... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #OCaml | OCaml | let write_dat filename x y ?(xprec=3) ?(yprec=5) () =
let oc = open_out filename in
let write_line a b = Printf.fprintf oc "%.*g\t%.*g\n" xprec a yprec b in
List.iter2 write_line x y;
close_out oc |
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... | #MiniScript | MiniScript | d = {}
for p in range(1, 100)
for t in range(p, 100, p)
if d.hasIndex(t) then d.remove t else d.push t
end for
end for
print d.indexes.sort |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Raku | Raku | use XML;
use XML::Writer;
say my $document = XML::Document.new(
XML::Writer.serialize( :root[ :element['Some text here', ], ] )
); |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Rascal | Rascal | import lang::xml::DOM;
public void main(){
x = document(element(none(), "root", [element(none(), "element", [charData("Some text here")])]));
return println(xmlPretty(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
| #Clojure | Clojure | (use 'clj-figlet.core)
(println
(render-to-string
(load-flf "ftp://ftp.figlet.org/pub/figlet/fonts/contributed/larry3d.flf")
"Clojure")) |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Wordseach
{
static class Program
{
readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
class Grid
{
... |
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... | #AppleScript | AppleScript | on wrapParagraph(para, lineWidth)
if (para is "") then return para
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to {space, tab} -- Doesn't include character id 160 (NO-BREAK SPACE).
script o
property wrds : para's text items -- Space- or tab-delimited ch... |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #Go | Go | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func contains(a []string, s string) bool {
for _, e := range a {
if e == s {
return true
}
}
return false
}
func oneAway(a, b string) bool {
sum := 0
for i := 0; i < len(a); i++ {
... |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the w... | #Delphi | Delphi |
program Word_wheel;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes;
function IsInvalid(s: string): Boolean;
var
c: char;
leters: set of char;
firstE: Boolean;
begin
Result := (s.Length < 3) or (s.IndexOf('k') = -1) or (s.Length > 9);
if not Result then
begin
leters := [... |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Liberty_BASIC | Liberty BASIC |
NoMainWin
WindowWidth = 270
WindowHeight = 290
UpperLeftX=int((DisplayWidth-WindowWidth)/2)
UpperLeftY=int((DisplayHeight-WindowHeight)/2)
Global variablesInitialized : variablesInitialized = 0
Global BackColor$ : BackColor$ = "0 0 0"
' BackColor$ = "255 255 255"
'now, right click randomizes BG
Global size :... |
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 ... | #Euphoria | Euphoria | function xmlquote(sequence s)
sequence r
r = ""
for i = 1 to length(s) do
if s[i] = '<' then
r &= "<"
elsif s[i] = '>' then
r &= ">"
elsif s[i] = '&' then
r &= "&"
elsif s[i] = '"' then
r &= """
elsif s[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" /... | #Delphi | Delphi |
//You need to use these units
uses
SysUtils,
Dialogs,
XMLIntf,
XMLDoc;
//..............................................
//This function process the XML
function GetStudents(aXMLInput: string): string;
var
XMLDoc: IXMLDocument;
i: Integer;
begin
//Creating the TXMLDocument instance
XMLDoc:= TXMLDoc... |
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,... | #Suneido | Suneido | array = Object('zero', 'one', 'two')
array.Add('three')
array.Add('five', at: 5)
array[4] = 'four'
Print(array[3]) --> 'three' |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat... | #Ruby | Ruby | teams = [:a, :b, :c, :d]
matches = teams.combination(2).to_a
outcomes = [:win, :draw, :loss]
gains = {win:[3,0], draw:[1,1], loss:[0,3]}
places_histogram = Array.new(4) {Array.new(10,0)}
# The Array#repeated_permutation method generates the 3^6 different
# possible outcomes
outcomes.repeated_permutation(6).each do |o... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #PARI.2FGP | PARI/GP | f(x,pr)={
Strprintf(if(x>=10^pr,
Str("%.",pr-1,"e")
,
Str("%.",pr-#Str(x\1),"f")
),x)
};
wr(x,y,xprec,yprec)={
for(i=1,#x,
write("filename",f(x[i],xprec),"\t",f(y[i],yprec))
)
}; |
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... | #MIPS_Assembly | MIPS Assembly | .data
doors: .space 100
num_str: .asciiz "Number "
comma_gap: .asciiz " is "
newline: .asciiz "\n"
.text
main:
# Clear all the cells to zero
li $t1, 100
la $t2, doors
clear_loop:
sb $0, ($t2)
add $t2, $t2, 1
sub $t1, $t1, 1
bnez $t1, clear_loop
# Now start the loops
li $t0, 1 #... |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Ruby | Ruby | require("rexml/document")
include REXML
(doc = Document.new) << XMLDecl.new
root = doc.add_element('root')
element = root.add_element('element')
element.add_text('Some text here')
# save to a string
# (the first argument to write() needs an object that understands "<<")
serialized = String.new
doc.write(serialized, ... |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Scala | Scala | val xml = <root><element>Some text here</element></root>
scala.xml.XML.save(filename="output.xml", node=xml, enc="UTF-8", xmlDecl=true, doctype=null) |
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
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. cobol-3d.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 cobol-area.
03 cobol-text-data PIC X(1030) VALUE "________/\\\\\\\\\____
- "____/\\\\\________/\\\\\\\\\\\\\__________/\\\\\________
- "/\\\_____________ ... |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may ... | #C.2B.2B | C++ |
#include <iomanip>
#include <ctime>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;
class Cell {
public:
Cell() : val( 0 ), cntOverlap( 0 ) {}
char val; int cntOverlap;
};
class Word {
public... |
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... | #Arturo | Arturo | txt: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia... |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #Haskell | Haskell | import System.IO (readFile)
import Control.Monad (foldM)
import Data.List (intercalate)
import qualified Data.Set as S
distance :: String -> String -> Int
distance s1 s2 = length $ filter not $ zipWith (==) s1 s2
wordLadders :: [String] -> String -> String -> [[String]]
wordLadders dict start end
| length start /... |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the w... | #F.23 | F# |
// Word Wheel: Nigel Galloway. May 25th., 2021
let fG k n g=g|>Seq.exists(fun(n,_)->n=k) && g|>Seq.forall(fun(k,g)->Map.containsKey k n && g<=n.[k])
let wW n g=let fG=fG(Seq.item 4 g)(g|>Seq.countBy id|>Map.ofSeq) in seq{use n=System.IO.File.OpenText(n) in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(fu... |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the w... | #Factor | Factor | USING: assocs io.encodings.ascii io.files kernel math
math.statistics prettyprint sequences sorting ;
! Only consider words longer than two letters and words that
! contain elt.
: pare ( elt seq -- new-seq )
[ [ member? ] keep length 2 > and ] with filter ;
: words ( input-str path -- seq )
[ [ midpoint@ ] ... |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[ReverseFractionalPart, ReplacePixelWithAlpha, DrawEndPoint, DrawLine]
ReverseFractionalPart[x_] := 1 - FractionalPart[x]
ReplacePixelWithAlpha[img_Image, pos_ -> colvals : {_, _, _},
alpha_] := Module[{vals,},
vals = PixelValue[img, pos];
vals = (1 - alpha) vals + alpha colvals;
ReplacePixelValue[img,... |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Nim | Nim | import math
import imageman
template ipart(x: float): float = floor(x)
template fpart(x: float): float = x - ipart(x)
template rfpart(x: float): float = 1 - fpart(x)
const
BG = ColorRGBF64([0.0, 0.0, 0.0])
FG = ColorRGBF64([1.0, 1.0, 1.0])
func plot(img: var Image; x, y: int; c: float) =
## Draw a point wit... |
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 ... | #F.23 | F# | #light
open System.Xml
type Character = {name : string; comment : string }
let data = [
{ name = "April"; comment = "Bubbly: I'm > Tam and <= Emily"}
{ name = "Tam O'Shanter"; comment = "Burns: \"When chapman billies leave the street ...\""}
{ name = "Emily"; comment = "Short & shrift"} ]
let doxml (c... |
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" /... | #Erlang | Erlang |
-module( xml_input ).
-export( [task/0] ).
-include_lib("xmerl/include/xmerl.hrl").
task() ->
{XML, []} = xmerl_scan:string( xml(), [{encoding, "iso-10646-utf-1"}] ),
Attributes = lists:flatten( [X || #xmlElement{name='Student', attributes=X} <- XML#xmlElement.content] ),
[io:fwrite("~s~n", [X]) || ... |
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,... | #Swift | Swift | // Arrays are typed in Swift, however, using the Any object we can add any type. Swift does not support fixed length arrays
var anyArray = [Any]()
anyArray.append("foo") // Adding to an Array
anyArray.append(1) // ["foo", 1]
anyArray.removeAtIndex(1) // Remove object
anyArray[0] = "bar" // ["bar"] |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat... | #Scala | Scala | object GroupStage extends App { //team left digit vs team right digit
val games = Array("12", "13", "14", "23", "24", "34")
val points = Array.ofDim[Int](4, 10) //playing 3 games, points range from 0 to 9
var results = "000000" //start with left teams all losing
private def nextResult: Boolean = {
if (res... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #Pascal | Pascal | Program WriteNumbers;
const
x: array [1..4] of double = (1, 2, 3, 1e11);
xprecision = 3;
yprecision = 5;
baseDigits = 7;
var
i: integer;
filename: text;
begin
assign (filename, 'filename');
rewrite (filename);
for i := 1 to 4 do
writeln (filename, x[i]:baseDigits+xprecision, sqrt(x[i]):baseD... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #Perl | Perl | use autodie;
sub writedat {
my ($filename, $x, $y, $xprecision, $yprecision) = @_;
open my $fh, ">", $filename;
for my $i (0 .. $#$x) {
printf $fh "%.*g\t%.*g\n", $xprecision||3, $x->[$i], $yprecision||5, $y->[$i];
}
close $fh;
}
my @x = (1, 2, 3, 1e11);
my @y = map sqrt, @x;
wri... |
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... | #Mirah | Mirah | import java.util.ArrayList
class Door
:state
def initialize
@state=false
end
def closed?; !@state; end
def open?; @state; end
def close; @state=false; end
def open; @state=true; end
def toggle
if closed?
open
else
close
end
end
def toString; Boolean.toString(@state); end
end
doors=... |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Sidef | Sidef | require('XML::Simple');
print %S'XML::Simple'.XMLout(
:(root => :( element => 'Some text here' )),
NoAttr => 1, RootName => '',
); |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Tcl | Tcl | package require tdom
set d [dom createDocument root]
set root [$d documentElement]
$root appendChild [$d createElement element]
[$root firstChild] appendChild [$d createTextNode "Some text here"]
$d asXML |
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
| #Common_Lisp | Common Lisp |
(ql:quickload :cl-ppcre)
(defvar txt
"
xxxx xxxx x x x x xxxx x x x x xxxx xxxxx
x x x x xx xx xx xx x x xx x x x x x x
x x x x xx x x xx x x x x x x x x xxx x x
x x x x x x x x x x... |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may ... | #D | D | import std.random : Random, uniform, randomShuffle;
import std.stdio;
immutable int[][] dirs = [
[1, 0], [ 0, 1], [ 1, 1],
[1, -1], [-1, 0],
[0, -1], [-1, -1], [-1, 1]
];
enum nRows = 10;
enum nCols = 10;
enum gridSize = nRows * nCols;
enum minWords = 25;
auto rnd = Random();
class Grid ... |
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... | #AutoHotkey | AutoHotkey | MsgBox, % "72`n" WrapText(Clipboard, 72) "`n`n80`n" WrapText(Clipboard, 80)
return
WrapText(Text, LineLength) {
StringReplace, Text, Text, `r`n, %A_Space%, All
while (p := RegExMatch(Text, "(.{1," LineLength "})(\s|\R+|$)", Match, p ? p + StrLen(Match) : 1))
Result .= Match1 ((Match2 = A_Space || Matc... |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #Java | Java | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadd... |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the w... | #FreeBASIC | FreeBASIC |
#include "file.bi"
Function String_Split(s_in As String,chars As String,result() As String) As Long
Dim As Long ctr,ctr2,k,n,LC=Len(chars)
Dim As boolean tally(Len(s_in))
#macro check_instring()
n=0
While n<Lc
If chars[n]=s_in[k] Then
tally(k)=true
If (ctr2-1) Th... |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Pascal | Pascal |
program wu;
uses
SDL2,
math;
const
FPS = 1000 div 60;
SCALE = 6;
var
win: PSDL_Window;
ren: PSDL_Renderer;
mouse_x, mouse_y: longint;
origin: TSDL_Point;
event: TSDL_Event;
line_alpha: byte = 255;
procedure SDL_RenderDrawWuLine(renderer: PSDL_Renderer; x1, y1, x2, y2: longint);
var
r, g, b... |
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 ... | #Factor | Factor | USING: sequences xml.syntax xml.writer ;
: print-character-remarks ( names remarks -- )
[ [XML <Character name=<-> ><-></Character> XML] ] 2map
[XML <CharacterRemarks><-></CharacterRemarks> XML] pprint-xml ; |
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 ... | #Fantom | Fantom |
using xml
class XmlOutput
{
public static Void main ()
{
Str[] names := ["April", "Tam O'Shanter", "Emily"]
Str[] remarks := ["Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift"]
doc := XDoc()
root := XElem("CharacterRema... |
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" /... | #F.23 | F# | open System.IO
open System.Xml
open System.Xml.Linq
let xn s = XName.Get(s)
let xd = XDocument.Load(new StringReader("""
<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"... |
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,... | #Tailspin | Tailspin |
// arrays are created as literals, by simply listing elements, or by a generator expression, or a combination.
def a: [1, 2, 3..7:2, 11];
$a -> !OUT::write
'
' -> !OUT::write
// Natural indexes start at 1
$a(1) -> !OUT::write
'
' -> !OUT::write
// You can select a range
$a(3..last) -> !OUT::write
'
' -> !OUT::wri... |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat... | #Tcl | Tcl | package require Tcl 8.6
proc groupStage {} {
foreach n {0 1 2 3} {
set points($n) {0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0}
}
set results 0
set games {0 1 0 2 0 3 1 2 1 3 2 3}
while true {
set R {0 0 1 0 2 0 3 0}
foreach r [split [format %06d $results] ""] {A B} $games {
switch $r {
2 {dic... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #Phix | Phix | constant x = {1, 2, 3, 1e11},
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}
integer fn = open("filename","w")
for i=1 to length(x) do
printf(fn,"%.3g\t%.5g\n",{x[i],y[i]})
end for
close(fn)
|
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #PicoLisp | PicoLisp | (setq *Xprecision 3 *Yprecision 5)
(scl 7)
(mapc
'((X Y)
(prinl
(round X *Xprecision)
" "
(round Y *Yprecision) ) )
(1.0 2.0 3.0)
(1.0 1.414213562 1.732050807) ) |
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... | #mIRC_Scripting_Language | mIRC Scripting Language | var %d = $str(0 $+ $chr(32),100), %m = 1
while (%m <= 100) {
var %n = 1
while ($calc(%n * %m) <= 100) {
var %d = $puttok(%d,$iif($gettok(%d,$calc(%n * %m),32),0,1),$calc(%n * %m),32)
inc %n
}
inc %m
}
echo -ag All Doors (Boolean): %d
var %n = 1
while (%n <= $findtok(%d,1,0,32)) {
var %t = %t $findtok(... |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Wren | Wren | class XmlDocument {
construct new(root) {
_root = root
}
toString { "<?xml version=\"1.0\" ?>\n%(_root.toString(0))" }
}
class XmlElement {
construct new(name, text) {
_name = name
_text = text
_children = []
}
name { _name }
text { _text }
c... |
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
| #ContextFree | ContextFree |
startshape START
shape START {
loop i = 6 [y -1 x -1 z 10] NAME [b 1-((i+1)*0.11)]
}
shape NAME {
C [ x 34 z 1]
O [ x 46 z 2]
N [ x 64 z 3]
T [ x 85 z 4]
E [ x 95 z 5]
X [ x 106 z 6]
T [ x 125 z 7]
HYPHEN[x 135]
F [ x 145 z 8]
R [ x 158 z 9]
E [ x 175 z 10]
E [ x 188 z 11]
}
shape C {
ARC... |
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
| #D | D | // Derived from AA3D - ASCII art stereogram generator
// by Jan Hubicka and Thomas Marsh
// (GNU General Public License)
// http://aa-project.sourceforge.net/aa3d/
// http://en.wikipedia.org/wiki/ASCII_stereogram
import std.stdio, std.string, std.random;
immutable image = "
111111111111111
... |
http://rosettacode.org/wiki/Window_management | Window management | Treat windows or at least window identities as first class objects.
Store window identities in variables, compare them for equality.
Provide examples of performing some of the following:
hide,
show,
close,
minimize,
maximize,
move, and
resize a window.
The window of interest may or may not have b... | #AutoHotkey | AutoHotkey | F1:: ;; when user hits the F1 key, do the following
WinGetTitle, window, A ; get identity of active window into a variable
WinMove, %window%, , 100, 100, 800, 800 ; move window to coordinates, 100, 100
; and change size to 800 x 800 pixels
sleep, 2000
WinHide, % window ; hid... |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program creatFenX1164.s */
/* link with gcc options -lX11 -L/usr/lpp/X11/lib */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in lang... |
http://rosettacode.org/wiki/Wilson_primes_of_order_n | Wilson primes of order n | Definition
A Wilson prime of order n is a prime number p such that p2 exactly divides:
(n − 1)! × (p − n)! − (− 1)n
If n is 1, the latter formula reduces to the more familiar: (p - n)! + 1 where the only known examples for p are 5, 13, and 563.
Task
Calculate and show on thi... | #ALGOL_68 | ALGOL 68 | BEGIN # find Wilson primes of order n, primes such that: #
# ( ( n - 1 )! x ( p - n )! - (-1)^n ) mod p^2 = 0 #
INT limit = 5 508; # max prime to consider #
# Build list of primes. #
[]INT primes =
BEGIN
# sieve the primes to limit^2 which wi... |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may ... | #FreeBASIC | FreeBASIC | Randomize Timer ' OK getting a good puzzle every time
#Macro TrmSS (n)
LTrim(Str(n))
#EndMacro
'overhauled
Dim Shared As ULong LengthLimit(3 To 10) 'reset in Initialize, track and limit longer words
'LoadWords opens file of words and sets
Dim Shared As ULong NWORDS 'set in LoadWords, number of words with leng... |
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... | #AWK | AWK | function wordwrap_paragraph(p)
{
if ( length(p) < 1 ) return
split(p, words)
spaceLeft = lineWidth
line = words[1]
delete words[1]
for (i = 1; i <= length(words); i++) {
word = words[i]
if ( (length(word) + 1) > spaceLeft ) {
print line
line = word
spaceLeft = lineWidth - leng... |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #jq | jq | def count(stream): reduce stream as $i (0; .+1);
def words: [inputs]; # one way to read the word list
def oneAway($a; $b):
($a|explode) as $ax
| ($b|explode) as $bx
| 1 == count(range(0; $a|length) | select($ax[.] != $bx[.]));
# input: the word list
def wordLadder($a; $b):
($a|length) as $len
| { p... |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #Julia | Julia | const dict = Set(split(read("unixdict.txt", String), r"\s+"))
function targeted_mutations(str::AbstractString, target::AbstractString)
working, tried = [[str]], Set{String}()
while all(a -> a[end] != target, working)
newworking = Vector{Vector{String}}()
for arr in working
s = arr[... |
http://rosettacode.org/wiki/Word_ladder | Word ladder | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[3]]]]];
sel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&];
g=Graph[db,UndirectedEdge@@@sel];
FindShortestPath[g,"boy","man"]
db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLe... |
http://rosettacode.org/wiki/Word_wheel | Word wheel | A "word wheel" is a type of word game commonly found on the "puzzle" page of
newspapers. You are presented with nine letters arranged in a circle or 3×3
grid. The objective is to find as many words as you can using only the letters
contained in the wheel or grid. Each word must contain the letter in the centre
of the w... | #Go | Go | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
letters := "deegklnow"
wordsAll := bytes.Split(b, []byte{'\n'})
// get rid of wor... |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Perl | Perl | #!perl
use strict;
use warnings;
sub plot {
my ($x, $y, $c) = @_;
printf "plot %d %d %.1f\n", $x, $y, $c if $c;
}
sub ipart {
int shift;
}
sub round {
int( 0.5 + shift );
}
sub fpart {
my $x = shift;
$x - int $x;
}
sub rfpart {
1 - fpart(shift);
}
sub drawLine {
my ($x0, $y0, $x1, $y1) = @_;
my $... |
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 ... | #Forth | Forth | include ffl/est.fs
include ffl/xos.fs
\ Input lists
0 value names
here ," Emily"
here ," Tam O'Shanter"
here ," April"
here to names
, , ,
0 value remarks
here ," Short & shrift"
here ,\" Burns: \"When chapman billies leave the street ...\""
here ," Bubbly: I'm > Tam and <= Emily"
here to remarks
, , ,
: s++ ( ... |
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" /... | #Factor | Factor | USING: io multiline sequences xml xml.data xml.traversal ;
: print-student-names ( string -- )
string>xml "Student" tags-named [ "Name" attr print ] each ;
[[ <Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="... |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /... | #Fantom | Fantom |
using xml
class XmlInput
{
public static Void main ()
{
// create the XML parser
parser := XParser(File("sample-xml.xml".toUri).in)
// parse the document, creating an XML document
XDoc doc := parser.parseDoc
// walk through each child element from the root of the document
doc.root.elems... |
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,... | #Tcl | Tcl | set ary {}
lappend ary 1
lappend ary 3
lset ary 0 2
puts [lindex $ary 0] |
http://rosettacode.org/wiki/World_Cup_group_stage | World Cup group stage | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Dim games As New List(Of String) From {"12", "13", "14", "23", "24", "34"}
Dim results = "000000"
Function FromBase3(num As String) As Integer
Dim out = 0
For Each c In num
Dim d = Asc(c) - Asc("0"c)
out = 3 * out + d
N... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #PL.2FI | PL/I | *Process source attributes xref;
aaa: Proc Options(main);
declare X(5) float (9) initial (1, 2, 3, 4, 5),
Y(5) float (18) initial (9, 8, 7, 6, 1e9);
declare (x_precision, y_precision) fixed binary;
Dcl out stream output;
open file(out) title('/OUT.TXT,type(text),recsize(100)');
x_precision = 9;
y_preci... |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #PowerShell | PowerShell | $x = @(1, 2, 3, 1e11)
$y = @(1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791)
$xprecision = 3
$yprecision = 5
$arr = foreach($i in 0..($x.count-1)) {
[pscustomobject]@{x = "{0:g$xprecision}" -f $x[$i]; y = "{0:g$yprecision}" -f $y[$i]}
}
($arr | format-table -HideTableHeaders | Out-String).Trim() >... |
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... | #ML.2FI | ML/I | MCSKIP "WITH" NL
"" 100 doors
MCINS %.
MCSKIP MT,<>
"" Doors represented by P1-P100, 0 is closed
MCPVAR 100
"" Set P variables to 0
MCDEF ZEROPS WITHS NL AS <MCSET T1=1
%L1.MCSET PT1=0
MCSET T1=T1+1
MCGO L1 UNLESS T1 EN 101
>
ZEROPS
"" Generate door state
MCDEF STATE WITHS () AS <MCSET T1=%A1.
MCGO L1 UNLESS T1 EN 0
cl... |
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.