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/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Ruby | Ruby | X, Y, Z = 6, 2, 3
DIR = {"-" => [1,0], "|" => [0,1], "/" => [1,1]}
def cuboid(nx, ny, nz)
puts "cuboid %d %d %d:" % [nx, ny, nz]
x, y, z = X*nx, Y*ny, Z*nz
area = Array.new(y+z+1){" " * (x+y+1)}
draw_line = lambda do |n, sx, sy, c|
dx, dy = DIR[c]
(n+1).times do |i|
xi, yi = sx+i*dx, sy+i*dy
... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #jq | jq | include "simple-turtle" {search: "."};
def rules:
{ F: "F+S",
S: "F-S" };
def dragon($count):
rules as $rules
| def p($count):
if $count <= 0 then .
else gsub("S"; "s") | gsub("F"; $rules["F"]) | gsub("s"; $rules["S"])
| p($count-1)
end;
"F" | p($count) ;
def interpret($x):
... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Perl | Perl | use strict;
use warnings;
my $x = my $y = 255;
$x |= 1; # must be odd
my $depth = 255;
my $light = Vector->new(rand, rand, rand)->normalized;
print "P2\n$x $y\n$depth\n";
my ($r, $ambient) = (($x - 1)/2, 0);
my ($r2) = $r ** 2;
{
for my $x (-$r .. $r) {
my $x2 = $x**2;
for my $y (-$r .. $r) {
my $y2 ... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #PicoLisp | PicoLisp | (de draw Lst
(for L Lst
(for X L
(cond
((num? X) (space X))
((sym? X) (prin X))
(T (do (car X) (prin (cdr X)))) ) )
(prinl) ) )
(de bigBox (N)
(do 2
(prin "|")
(for I 4
(prin (if (> I N) " |" " ======== |")) )
(prinl) )... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Scala | Scala | import java.awt._
import java.awt.event.{MouseAdapter, MouseEvent}
import javax.swing._
import scala.math.{Pi, cos, sin}
object Cuboid extends App {
SwingUtilities.invokeLater(() => {
class Cuboid extends JPanel {
private val nodes: Array[Array[Double]] =
Array(Array(-1, -1, -1), Array(-1, -... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Julia | Julia |
using Luxor
function dragon(turtle::Turtle, level=4, size=200, direction=45)
if level != 0
Turn(turtle, -direction)
dragon(turtle, level-1, size/sqrt(2), 45)
Turn(turtle, direction*2)
dragon(turtle, level-1, size/sqrt(2), -45)
Turn(turtle, -direction)
else
Forwa... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Phix | Phix | --
-- demo\rosetta\Draw_a_sphere.exw
-- ==============================
--
with javascript_semantics
include pGUI.e
constant title = "Draw a sphere"
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function dot(sequence x, y)
return sum(sq_mul(x,y))
end function
function normalize(sequence v)
atom len = sqrt(... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Processing | Processing | void draw() {
drawClock();
}
void drawClock() {
background(192);
translate(width/2, height/2);
float s = second() * TWO_PI / 60.0;
float m = minute() * TWO_PI / 60.0;
float h = hour() * TWO_PI / 12.0;
rotate(s);
strokeWeight(1);
line(0, 0, 0, -width*0.5);
rotate(-s+m);
strokeWeight(2);
line(0, 0... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Sidef | Sidef | const dirs = Hash("-" => [1,0], "|" => [0,1], "/" => [1,1])
func cuboid(nx, ny, nz) {
say("cuboid %d %d %d:" % [nx, ny, nz])
var(x, y, z) = (8*nx, 2*ny, 4*nz)
var area = []
var line = func(n, sx, sy, c) {
var(dx, dy) = dirs{c}...
for i (0..n) {
var (xi, yi) = (sx + i*dx, sy + i*dy)
area[yi... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Kotlin | Kotlin | // version 1.0.6
import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame
class DragonCurve(iter: Int) : JFrame("Dragon Curve") {
private val turns: MutableList<Int>
private val startingAngle: Double
private val side: Double
init {
setBounds(100, 100, 800, 600)
defa... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #PicoLisp | PicoLisp | (load "@lib/openGl.l")
(glutInit)
(glutInitDisplayMode (| GLUT_RGBA GLUT_DOUBLE GLUT_ALPHA GLUT_DEPTH))
(glutInitWindowSize 400 400)
(glutCreateWindow "Sphere")
(glEnable GL_LIGHTING)
(glEnable GL_LIGHT0)
(glLightiv GL_LIGHT0 GL_POSITION (10 10 -10 0))
(glEnable GL_COLOR_MATERIAL)
(glColorMaterial GL_FRONT_AND_BA... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #PureBasic | PureBasic | #MiddleX = 90 + 1 ;x,y must be odd numbers, minimum width is 67
#MiddleY = #MiddleX
#len_sh = (#MiddleX - 8) * 0.97 ;length of second-hand
#len_mh = (#MiddleX - 8) * 0.88 ;length of minute-hand
#len_hh = (#MiddleX - 8) * 0.66 ;length of hour-hand
#clockFace_img = 0
#clock_gad = 0
#clock_win = 0
Define cx = #MiddleX, ... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Tcl | Tcl | package require Tcl 8.5
package require Tk
package require math::linearalgebra
package require math::constants
# Helper for constructing a rectangular face in 3D
proc face {px1 py1 pz1 px2 py2 pz2 px3 py3 pz3 px4 py4 pz4 color} {
set centroidX [expr {($px1+$px2+$px3+$px4)/4.0}]
set centroidY [expr {($py1+$py2... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Lambdatalk | Lambdatalk |
{def dcr
{lambda {:step :length}
{let { {:step {- :step 1}}
{:length {/ :length 1.41421}}
} {if {> :step 0}
then T45
{dcr :step :length}
T-90
{dcl :step :length}
T45
else T45
M:length
T-90
... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #PostScript | PostScript | %!PS-Adobe-3.0
%%BoundingBox 0 0 300 300
150 150 translate 0 0 130 0 360 arc
/Pattern setcolorspace
<< /PatternType 2
/Shading <<
/ShadingType 3
/ColorSpace /DeviceRGB
/Coords [-60 60 0 0 0 100]
/Function <<
... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Python | Python | import time
def chunks(l, n=5):
return [l[i:i+n] for i in range(0, len(l), n)]
def binary(n, digits=8):
n=int(n)
return '{0:0{1}b}'.format(n, digits)
def secs(n):
n=int(n)
h='x' * n
return "|".join(chunks(h))
def bin_bit(h):
h=h.replace("1","x")
h=h.replace("0"," ")
return "|... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #VBScript | VBScript | x = 6 : y = 2 : z = 3
Sub cuboid(nx, ny, nz)
WScript.StdOut.WriteLine "Cuboid " & nx & " " & ny & " " & nz & ":"
lx = X * nx : ly = y * ny : lz = z * nz
'define the array
Dim area(): ReDim area(ly+lz, lx+ly)
For i = 0 to ly+lz
For j = 0 to lx+ly : area(i,j) = " " : Next
Next
'drawing li... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Liberty_BASIC | Liberty BASIC | nomainwin
mainwin 50 20
WindowHeight =620
WindowWidth =690
open "Graphics library" for graphics as #a
#a, "trapclose [quit]"
#a "down"
Turn$ ="R"
Pace =100
s = 16
[again]
print Turn$
#a "cls ; home ; north ; down ; fill black"
for i =1 to len( Turn$)... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #POV-Ray | POV-Ray |
camera { location <0.0 , .8 ,-3.0> look_at 0}
light_source{< 3,3,-3> color rgb 1}
sky_sphere { pigment{ gradient <0,1,0> color_map {[0 color rgb <.2,.1,0>][.5 color rgb 1]} scale 2}}
plane {y,-2 pigment { hexagon color rgb .7 color rgb .5 color rgb .6 }}
sphere { 0,1
texture {
pigment{ color rgbft <.8... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Racket | Racket |
#lang racket/gui
(require racket/date slideshow/pict)
(define (clock h m s [r 100])
(define (draw-hand length angle
#:width [width 1]
#:color [color "black"])
(dc (λ (dc dx dy)
(define old-pen (send dc get-pen))
(send dc set-pen (new pen% [width... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Wren | Wren | import "/fmt" for Fmt
var cubLine = Fn.new { |n, dx, dy, cde|
Fmt.write("$*s", n + 1, cde[0])
for (d in 9*dx - 1...0) System.write(cde[1])
System.write(cde[0])
Fmt.print("$*s", dy + 1, cde[2..-1])
}
var cuboid = Fn.new { |dx, dy, dz|
Fmt.print("cuboid $d $d $d:", dx, dy, dz)
cubLine.call(dy+... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Logo | Logo | to dcr :step :length
make "step :step - 1
make "length :length / 1.41421
if :step > 0 [rt 45 dcr :step :length lt 90 dcl :step :length rt 45]
if :step = 0 [rt 45 fd :length lt 90 fd :length rt 45]
end
to dcl :step :length
make "step :step - 1
make "length :length / 1.41421
if :step > 0 [lt 45 dcr :step ... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Processing | Processing | void setup() {
size(500, 500, P3D);
}
void draw() {
background(192);
translate(width/2, height/2);
// optional color and lighting style
stroke(200);
fill(255);
lights();
// draw sphere
sphere(200);
} |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Raku | Raku | my ($rows,$cols) = qx/stty size/.words;
my $v = floor $rows / 2;
my $h = floor $cols / 2 - 16;
my @t = < ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀>;
my @b = < ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀>;
loop {
my @x = DateTime.now.Str.substr(11,8).ords X- ord('0');
print "\e[H\e[J";
print "\e[$v;{$h... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #X86_Assembly | X86 Assembly | 1 ;Assemble with: tasm, tlink /t
2 0000 .model tiny
3 0000 .code
4 .386
5 org 100h
6 ... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Lua | Lua | function dragon()
local l = "l"
local r = "r"
local inverse = {l = r, r = l}
local field = {r}
local num = 1
local loop_limit = 6 --increase this number to render a bigger curve
for discard=1,loop_limit do
field[num+1] = r
for i=1,num do
field[i+num+1] = inverse... |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #11l | 11l | F linear(x)
V a = enumerate(x).filter2((i, v) -> v != 0).map2((i, v) -> ‘#.e(#.)’.format(I v == -1 {‘-’} E I v == 1 {‘’} E String(v)‘*’, i + 1))
R (I !a.empty {a} E [String(‘0’)]).join(‘ + ’).replace(‘ + -’, ‘ - ’)
L(x) [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], ... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #6502_Assembly | 6502 Assembly | with Ada.Text_Io; use Ada.Text_Io;
generic
SortName : in String;
type DataType is (<>);
type SortArrayType is array (Integer range <>) of DataType;
with procedure Sort (SortArray : in out SortArrayType;
Comp, Write, Ex : in out Natural);
package Instrument is
-- This generic p... |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #11l | 11l | F average_square_diff(a, predictions)
R sum(predictions.map(x -> (x - @a) ^ 2)) / predictions.len
F diversity_theorem(truth, predictions)
V average = sum(predictions) / predictions.len
print(‘average-error: ’average_square_diff(truth, predictions)"\n"‘’
‘crowd-error: ’((truth - average) ^ 2)"\n"‘’... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Python | Python | import math
shades = ('.',':','!','*','o','e','&','#','%','@')
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.fl... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Red | Red | Red [Needs: 'View]
view [t: h4 rate 1 on-time [t/data: now/time]]
|
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ... | #Ada | Ada | package Server is
pragma Remote_Call_Interface;
procedure Foo;
function Bar return Natural;
end Server; |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Sockets; use GNAT.Sockets;
procedure DNSQuerying is
Host : Host_Entry_Type (1, 1);
Inet_Addr_V4 : Inet_Addr_Type (Family_Inet);
begin
Host := Get_Host_By_Name (Name => "www.kame.net");
Inet_Addr_V4 := Addresses (Host);
Put ("IPv4: " & Im... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
real X, Y, Z, Farthest; \arrays: 3D coordinates of vertices
int I, J, K, SI, Segment;
def Size=50.0, Sz=0.008, Sx=-0.013; \drawing size and tumbling speeds
[X:= [-2.0, +2.0, +2.0, -2.0, -2.0, +2.0, +2.0, -2.0];
Y:= [-1.5, -1.5... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #zkl | zkl | var [const] M=50.0;
fcn cuboid(w,h,z){
w*=M; h*=M; z*=M; // relative to abs dimensions
bitmap:=PPM(400,400);
clr:=0xff0000; // red facing rectangle
bitmap.line(0,0, w,0, clr); bitmap.line(0,0, 0,h, clr);
bitmap.line(0,h, w,h, clr); bitmap.line(w,0, w,h, clr);
r,a:=(w+z).toFloat().toPolar(0); // ... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
def double angle, d45, d90, change=5000
const sr2 as double= .70710676237
Cls 0
Pen 14
\\ move console full screen to second monitor
Window 12, 1
\\ reduce size (tv as second monitor cut pixels from edges)
Window 12, scale.x*.9, scale.y*.9;
\\ op... |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #Ada | Ada | with Ada.Text_Io;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
procedure Display_Linear is
subtype Position is Positive;
type Coefficient is new Integer;
type Combination is array (Position range <>) of Coefficient;
function Linear_Combination (Comb : Combination) return String is
use Ada... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
generic
SortName : in String;
type DataType is (<>);
type SortArrayType is array (Integer range <>) of DataType;
with procedure Sort (SortArray : in out SortArrayType;
Comp, Write, Ex : in out Natural);
package Instrument is
-- This generic p... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Arturo | Arturo | f: function [x :integer, y :integer][
;; description: « takes two integers and adds them up
;; options: [
;; double: « also multiply by two
;; ]
;; returns: :integer
result: x+y
if not? null? attr 'double -> result: result * 2
return result
]
info'f |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #Ada | Ada | with Ada.Text_IO;
with Ada.Command_Line;
procedure Diversity_Prediction is
type Real is new Float;
type Real_Array is array (Positive range <>) of Real;
package Real_IO is new Ada.Text_Io.Float_IO (Real);
use Ada.Text_IO, Ada.Command_Line, Real_IO;
function Mean (Data : Real_Array) return Real is... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Racket | Racket |
#lang typed/racket
(require plot/typed)
(plot3d (polar3d (λ (θ ρ) 1)) #:altitude 25)
|
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #REXX | REXX | /*REXX program displays the current (local) time as a digital clock on the terminal.*/
trace off /*turn off tracing/possible host errors*/
parse arg ! /*obtain optional arguments from the CL*/
if !all(arg()) then exit ... |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ... | #AutoHotkey | AutoHotkey | #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("S... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program dnsquery.s */
/************************************/
/* Constantes */
/************************************/
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall END PR... |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET width=50: LET height=width*1.5: LET depth=width*2
20 LET x=80: LET y=10
30 PLOT x,y
40 DRAW 0,height: DRAW width,0: DRAW 0,-height: DRAW -width,0: REM Front
50 PLOT x,y+height: DRAW depth/2,height: DRAW width,0: DRAW 0,-height: DRAW -width,-height
60 PLOT x+width,y+height: DRAW depth/2,height |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #M4 | M4 | # The macros which return a pair of values x,y expand to an unquoted 123,456
# which is suitable as arguments to a further macro. The quoting is slack
# because the values are always integers and so won't suffer unwanted macro
# expansion.
# 0,1 Vertex and segment x,y numbering.
# ... |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<math.h> /*Optional, but better if included as fabs, labs and abs functions are being used. */
int main(int argC, char* argV[])
{
int i,zeroCount= 0,firstNonZero = -1;
double* vector;
if(argC == 1){
printf("Usage : %s <Vector component coefficients seperated b... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #AutoHotkey | AutoHotkey | ;
; Function: example_add
; Description:
; Adds two or three numbers (see [url=http://en.wikipedia.org/Number]Number [/url])
; Syntax: example_add(number1, number2[, number3=0])
; Parameters:
; number1 - First number to add.
; number2 - Second number to add.
; number3 - (Optional) Third number to add. You can ju... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #C | C | /**
* \brief Perform addition on \p a and \p b.
*
* \param a One of the numbers to be added.
* \param b Another number to be added.
* \return The sum of \p a and \p b.
* \code
* int sum = add(1, 2);
* \endcode
*/
int add(int a, int b) {
return a + b;
}
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #C.23 | C# | /// <summary>
/// The XMLSystem class is here to help handle XML items in this site.
/// </summary>
public static class XMLSystem
{
static XMLSystem()
{
// Constructor
}
/// <summary>
/// A function to get the contents of an XML document.
/// </summary>
/// <param name="name">A val... |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #C | C |
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
float mean(float* arr,int size){
int i = 0;
float sum = 0;
while(i != size)
sum += arr[i++];
return sum/size;
}
float variance(float reference,float* arr, int size){
int i=0;
float* newArr = (float*)malloc(size*sizeof(float));
for(;i<size;i+... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Raku | Raku | my $width = my $height = 255; # must be odd
my @light = normalize([ 3, 2, -5 ]);
my $depth = 255;
sub MAIN ($outfile = 'sphere-perl6.pgm') {
spurt $outfile, "P5\n$width $height\n$depth\n"; # .pgm header
my $out = open( $outfile, :a, :bin ) orelse .die;
$out.write( Blob.new(draw_sphere( ($width-1)/2, .... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Ruby | Ruby | Shoes.app(:width=>205, :height => 228, :title => "A Clock") do
def draw_ray(width, start, stop, ratio)
angle = Math::PI * 2 * ratio - Math::PI/2
strokewidth width
cos = Math::cos(angle)
sin = Math::sin(angle)
line 101+cos*start, 101+sin*start, 101+cos*stop, 101+sin*stop
end
def update
t ... |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("S... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #AutoHotkey | AutoHotkey | Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log"
Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide
FileRead, Contents, %LogFile%
FileDelete, %LogFile%
RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match)
MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])") |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Batch_File | Batch File | :: DNS Query Task from Rosetta Code Wiki
:: Batch File Implementation
@echo off
set "domain=www.kame.net"
echo DOMAIN: "%domain%"
echo(
call :DNS_Lookup "%domain%"
pause
exit /b
::Main Procedure
::Uses NSLOOKUP Command. Also uses a dirty "parsing" to detect IP addresses.
:DNS_Lookup [domain]
::Define Variables an... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | FoldOutLine[{a_,b_}]:={{a,#},{b,#}}&[a+0.5(b-a)+{{0.,0.5},{-0.5,0.}}.(b-a)]
NextStep[in_]:=Flatten[FoldOutLine/@in,1]
lines={{{0.,0.},{1.,0.}}};
Graphics[Line/@Nest[NextStep,lines,11]] |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Text;
namespace DisplayLinearCombination {
class Program {
static string LinearCombo(List<int> c) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < c.Count; i++) {
int n = c[i];
... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Clojure | Clojure | (def
#^{:doc "Metadata can contain documentation and can be added to vars like this."}
test1)
(defn test2
"defn and some other macros allow you add documentation like this. Works the same way"
[]) |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #COBOL | COBOL |
*>****L* cobweb/cobweb-gtk [0.2]
*> Author:
*> Author details
*> Colophon:
*> Part of the GnuCobol free software project
*> Copyright (C) 2014 person
*> Date 20130308
*> Modified 20141003
*> License GNU General Public License, GPL, 3.0 or great... |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #C.23 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass {
static double Square(double x) => x * x;
static double AverageSquareDiff(double a, IEnumerable<double> predictions)
=> predictions.Select(x => Square(x - a)).Average();
static void DiversityTheorem(do... |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #C.2B.2B | C++ |
#include <iostream>
#include <vector>
#include <numeric>
float sum(const std::vector<float> &array)
{
return std::accumulate(array.begin(), array.end(), 0.0);
}
float square(float x)
{
return x * x;
}
float mean(const std::vector<float> &array)
{
return sum(array) / array.size();
}
float averageSq... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #REXX | REXX | /*REXX program expresses a lighted sphere with simple characters used for shading. */
call drawSphere 19, 4, 2/10, '30 30 -50' /*draw a sphere with a radius of 19. */
call drawSphere 10, 2, 4/10, '30 30 -50' /* " " " " " " " ten. */
exit ... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Run_BASIC | Run BASIC | ' --------------------------------------------
' clock. I got nothing but time
' ---------------------------------------------
n = 12 ' num of points
r = 95 ' radius
pi = 22/7
alpha = pi * 2 / n
dim points(n)
graphic #g2, 200, 200
' --------------------------------------
' Draw the clock
' -----------------------------... |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ... | #C.23 | C# |
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecti... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #BBC_BASIC | BBC BASIC | name$ = "www.kame.net"
AF_INET = 2
AF_INET6 = 23
WSASYS_STATUS_LEN = 128
WSADESCRIPTION_LEN = 256
SYS "LoadLibrary", "WS2_32.DLL" TO ws2%
SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup`
SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup`
SYS "Get... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #C | C | #include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h> /* getaddrinfo, getnameinfo */
#include <stdio.h> /* fprintf, printf */
#include <stdlib.h> /* exit */
#include <string.h> /* memset */
int
main()
{
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
/*
* Request only one... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Metafont | Metafont | mode_setup;
dragoniter := 8;
beginchar("D", 25pt#, 25pt#, 0pt#);
pickup pencircle scaled .5pt;
x1 = 0; x2 = w; y1 = y2 = .5h;
mstep := .5; sg := -1;
for i = 1 upto dragoniter:
for v = 1 step mstep until (2-mstep):
if unknown z[v+mstep]:
pair t;
t := .7071[ z[v], z[v+2mstep] ];
z[v+mstep] = t rotate... |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Common_Lisp | Common Lisp | CL-USER 83 > (defun add (a b)
"add two numbers a and b"
(+ a b))
ADD
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Crystal | Crystal | # Any block of comments *directly* before (no blank lines) a module, class, or method is used as a doc comment
# This one is for a module
module Documentation
# This comment documents a class, *and* it uses markdown
class Foo
# This comment doesn't do anything, because it isn't directly above a module, clas... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #D | D | /**
This is a documentation comment for someFunc and someFunc2.
$(DDOC_COMMENT comment inside a documentation comment
(results in a HTML comment not displayed by the browser))
Header:
content (does not need to be tabbed out; this is done for clarity
of the comments and has no effect on the resulting documenta... |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #Clojure | Clojure |
(defn diversity-theorem [truth predictions]
(let [square (fn[x] (* x x))
mean (/ (reduce + predictions) (count predictions))
avg-sq-diff (fn[a] (/ (reduce + (for [x predictions] (square (- x a)))) (count predictions)))]
{:average-error (avg-sq-diff truth)
:crowd-error (square (- truth mean)... |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #D | D | import std.algorithm;
import std.stdio;
auto square = (real x) => x * x;
auto meanSquareDiff(R)(real a, R predictions) {
return predictions.map!(x => square(x - a)).mean;
}
void diversityTheorem(R)(real truth, R predictions) {
auto average = predictions.mean;
writeln("average-error: ", meanSquareDiff(... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Ruby | Ruby | Shoes.app :width => 500, :height => 500, :resizable => false do
image 400, 470, :top => 30, :left => 50 do
nostroke
fill "#127"
image :top => 230, :left => 0 do
oval 70, 130, 260, 40
blur 30
end
oval 10, 10, 380, 380
image :top => 0, :left => 0 do
fill "#46D"
oval 30, 3... |
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table | Display an outline as a nested table |
Display an outline as a nested table.
Parse the outline to a tree,
count the leaves descending from each node,
and write out a table with 'colspan' values
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
defining the width of a ... | #AutoHotkey | AutoHotkey | outline2table(db, Delim:= "`t"){
oNum:=[], oMID:=[], oNod := [], oKid := [], oPnt := [], oMbr := [], oLvl := []
oCrl := ["#ffffe6;", "#ffebd2;", "#f0fff0;", "#e6ffff;", "#ffeeff;"]
col := 0, out := "", anc := ""
; create numerical index for each line
for i, line in StrSplit(db, "`n", "`r")
{
RegExMatch(line, ... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Rust | Rust | // cargo-deps: time="0.1"
extern crate time;
use std::thread;
use std::time::Duration;
const TOP: &str = " ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀";
const BOT: &str = " ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀";
fn main() {
let top: Vec<&str> = TOP.split_whitespace().collect();
let bot: Vec<&str> =... |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ... | #D | D | import arsd.rpc;
struct S1 {
int number;
string name;
}
struct S2 {
string name;
int number;
}
interface ExampleNetworkFunctions {
string sayHello(string name);
int add(in int a, in int b) const pure nothrow;
S2 structTest(S1);
void die();
}
// The server must implement the inter... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #C.23 | C# |
private string LookupDns(string s)
{
try
{
System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);
string result = ip.AddressList[0].ToString();
for (int i = 1; i < ip.AddressList.Length; ++i)
result +=... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #C.2B.2B | C++ |
#include <boost/asio.hpp>
#include <iostream>
int main() {
int rc {EXIT_SUCCESS};
try {
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver {io_service};
auto entries = resolver.resolve({"www.kame.net", ""});
boost::asio::ip::tcp::resolver::iterator entries_end;
for (... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Nim | Nim | import math
import imageman
const
## Separation of the two endpoints.
## Make this a power of 2 for prettier output.
Sep = 512
## Depth of recursion. Adjust as desired for different visual effects.
Depth = 18
S = sqrt(2.0) / 2
Sin = [float 0, S, 1, S, 0, -S, -1, -S]
Cos = [float 1, S, 0, -S, -1, -S,... |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #D | D | import std.array;
import std.conv;
import std.format;
import std.math;
import std.stdio;
string linearCombo(int[] c) {
auto sb = appender!string;
foreach (i, n; c) {
if (n==0) continue;
string op;
if (n < 0) {
if (sb.data.empty) {
op = "-";
} els... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Delphi | Delphi | type
/// <summary>Sample class.</summary>
TMyClass = class
public
/// <summary>Converts a string into a number.</summary>
/// <param name="aValue">String parameter</param>
/// <returns>Numeric equivalent of aValue</returns>
/// <exception cref="EConvertError">aValue is not a valid integer.</except... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #E | E | ? /** This is an object with documentation */
> def foo {
> # ...
> }
# value: <foo>
? foo.__getAllegedType().getDocComment()
# value: " This is an object with documentation " |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Eiffel | Eiffel | note
description: "Objects that model Times of Day: 00:00:00 - 23:59:59"
author: "Eiffel Software Construction Students"
class
TIME_OF_DAY
create
make
feature -- Initialization
make
-- Initialize to 00:00:00
do
hour := 0
minute := 0
second := 0... |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #Factor | Factor | USING: kernel math math.statistics math.vectors prettyprint ;
TUPLE: div avg-err crowd-err diversity ;
: diversity ( x seq -- obj )
[ n-v dup v* mean ] [ mean swap - sq ]
[ nip dup mean v-n dup v* mean ] 2tri div boa ;
49 { 48 47 51 } diversity .
49 { 48 47 51 42 } diversity . |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Rust | Rust | // [dependencies]
// image = "0.23"
use image::{GrayImage, Luma};
type Vector = [f64; 3];
fn normalize(v: &mut Vector) {
let inv_len = 1.0/dot_product(v, v).sqrt();
v[0] *= inv_len;
v[1] *= inv_len;
v[2] *= inv_len;
}
fn dot_product(v1: &Vector, v2: &Vector) -> f64 {
v1.iter().zip(v2.iter())... |
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table | Display an outline as a nested table |
Display an outline as a nested table.
Parse the outline to a tree,
count the leaves descending from each node,
and write out a table with 'colspan' values
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
defining the width of a ... | #Go | Go | package main
import (
"fmt"
"strings"
)
type nNode struct {
name string
children []nNode
}
type iNode struct {
level int
name string
}
func toNest(iNodes []iNode, start, level int, n *nNode) {
if level == 0 {
n.name = iNodes[0].name
}
for i := start + 1; i < len(... |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #Scala | Scala | import java.util.{ Timer, TimerTask }
import java.time.LocalTime
import scala.math._
object Clock extends App {
private val (width, height) = (80, 35)
def getGrid(localTime: LocalTime): Array[Array[Char]] = {
val (minute, second) = (localTime.getMinute, localTime.getSecond())
val grid = Array.fill[Char]... |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ... | #E | E | def storage := [].diverge()
def logService {
to log(line :String) {
storage.push([timer.now(), line])
}
to search(substring :String) {
var matches := []
for [time, line] ? (line.startOf(substring) != -1) in storage {
matches with= [time, line]
}
return matches
}
}
introducer.onTheA... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript |
Class Utils.Net Extends %RegisteredObject
{
ClassMethod QueryDNS(pHost As %String, Output ip As %List) As %Status
{
// some initialisation
K ip S ip=""
// check host operating system and input parameters
S OS=$SYSTEM.Version.GetOS()
I '$LF($LB("Windows","UNIX"), OS) Q $$$ERROR($$$GeneralError, "Not implement... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Clojure | Clojure | (import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address)
(doseq [addr (InetAddress/getAllByName "www.kame.net")]
(cond
(instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr))
(instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr)))) |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #OCaml | OCaml | (* This constant does not seem to be defined anywhere in the standard modules *)
let pi = acos (-1.0);
(*
** CLASS dragon_curve_computer:
** ----------------------------
** Computes the coordinates for the line drawing the curve.
** - initial_x initial_y: coordinates for starting point for curve
** - total_length: to... |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #EchoLisp | EchoLisp |
;; build an html string from list of coeffs
(define (linear->html coeffs)
(define plus #f)
(or*
(for/fold (html "") ((a coeffs) (i (in-naturals 1)))
(unless (zero? a)
(set! plus (if plus "+" "")))
(string-append html
(cond
((= a 1) (format "%a e<sub>%d</sub> " plus i))
((= a -... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Elixir | Elixir |
def project do
[app: :repo
version: "0.1.0-dev",
name: "REPO",
source_url: "https://github.com/USER/REPO",
homepage_url: "http://YOUR_PROJECT_HOMEPAGE"
deps: deps]
end
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Emacs_Lisp | Emacs Lisp | (defun hello (n)
"Say hello to the user."
(message "hello %d" n)) |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Erlang | Erlang | def class Foo {
"""
This is a docstring. Every object in Fancy can have it's own docstring.
Either defined in the source code, like this one, or by using the Object#docstring: method
"""
def a_method {
"""
Same for methods. They can have docstrings, too.
"""
}
}
Foo docstring println # prints do... |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func averageSquareDiff(f float64, preds []float64) (av float64) {
for _, pred := range preds {
av += (pred - f) * (pred - f)
}
av /= float64(len(preds))
return
}
func diversityTheorem(truth float64, preds []float64) (float64, float64, float64) {
av := 0.0
... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Scala | Scala | object Sphere extends App {
private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))
private def drawSphere(r: Double, k: Double, ambient: Double): Unit = {
def dot(x: Array[Double], y: Array[Double]) = {
val d = x.head * y.head + x(1) * y(1) + x.last ... |
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table | Display an outline as a nested table |
Display an outline as a nested table.
Parse the outline to a tree,
count the leaves descending from each node,
and write out a table with 'colspan' values
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
defining the width of a ... | #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
module OutlineTree where
import Data.Bifunctor (first)
import Data.Bool (bool)
import Data.Char (isSpace)
import Data.List (find, intercalate)
import Data.Tree (Tree (..), foldTree, levels)
---------------- NESTED TABLES FROM OUTLINE --------------
wikiTablesFromOutline :: [String... |
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.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
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.