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_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #JavaScript | JavaScript | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.he... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Phix | Phix | constant m = {{7, 8, 7},{4, 0, 9}},
m2 = {{4, 5, 1},{6, 2, 1}}
?{m,"+",m2,"=",sq_add(m,m2)}
?{m,"-",m2,"=",sq_sub(m,m2)}
?{m,"*",m2,"=",sq_mul(m,m2)}
?{m,"/",m2,"=",sq_div(m,m2)}
?{m,"^",m2,"=",sq_power(m,m2)}
?{m,"+ 3 =",sq_add(m,3)}
?{m,"- 3 =",sq_sub(m,3)}
?{m,"* 3 =",sq_mul(m,3)}
?{m,"/ 3 =",sq_div(m,3)}
?... |
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
| #BASIC | BASIC | clg
color white
rect 0,0,graphwidth, graphheight
for n = 1 to 100
color rgb(2*n,2*n,2*n)
circle 150-2*n/3,150-n/2,150-n
next n |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #FreeBASIC | FreeBASIC | #define FIL 1
#define DATO 2
#define LPREV 3
#define LNEXT 4
Dim Shared As Integer countNodes, Nodes
countNodes = 0
Nodes = 10
Dim Shared As Integer list(Nodes, 4)
list(0, LNEXT) = 1
Function searchNode(node As Integer) As Integer
Dim As Integer Node11
For i As Integer = 0 To node-1
Node1... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Delphi | Delphi | uses system ;
type
// declare the list pointer type
plist = ^List ;
// declare the list type, a generic data pointer prev and next pointers
List = record
data : pointer ;
prev : pList ;
next : pList ;
end;
// since this task is just showing the traversal I am not allocating the ... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #E | E | def traverse(list) {
var node := list.atFirst()
while (true) {
println(node[])
if (node.hasNext()) {
node := node.next()
} else {
break
}
}
while (true) {
println(node[])
if (node.hasPrev()) {
node := node.prev()
... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #C.23 | C# | class Link
{
public int Item { get; set; }
public Link Prev { get; set; }
public Link Next { get; set; }
//A constructor is not neccessary, but could be useful
public Link(int item, Link prev = null, Link next = null) {
Item = item;
Prev = prev;
Next = next;
}
} |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #C.2B.2B | C++ | template <typename T>
struct Node
{
Node* next;
Node* prev;
T data;
}; |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #Ceylon | Ceylon | import ceylon.random {
DefaultRandom
}
abstract class Colour(name, ordinal) of red | white | blue satisfies Comparable<Colour> {
shared String name;
shared Integer ordinal;
string => name;
compare(Colour other) => this.ordinal <=> other.ordinal;
}
object red extends Colour("red", 0) {}
object white extends ... |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #Clojure | Clojure | (defn dutch-flag-order [color]
(get {:red 1 :white 2 :blue 3} color))
(defn sort-in-dutch-flag-order [balls]
(sort-by dutch-flag-order balls))
;; Get a collection of 'n' balls of Dutch-flag colors
(defn random-balls [num-balls]
(repeatedly num-balls
#(rand-nth [:red :white :blue])))
;; Get ran... |
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... | #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
void vsub(double *v1, double *v2, double *s) {
s[0] = v1[0] - v2[0];
s[1] = v1[1] - v2[1];
s[2] = v1[2] - v2[2];
}
double normalize(double * v) {
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #PicoLisp | PicoLisp | (de userVariable ()
(prin "Enter a variable name: ")
(let Var (line T) # Read transient symbol
(prin "Enter a value: ")
(set Var (read)) # Set symbol's value
(println 'Variable Var 'Value (val Var)) ) ) # Print them |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #PowerShell | PowerShell | $variableName = Read-Host
New-Variable $variableName 'Foo'
Get-Variable $variableName |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #ProDOS | ProDOS | editvar /newvar /value=a /userinput=1 /title=Enter a variable name:
editvar /newvar /value=b /userinput=1 /title=Enter a variable title:
editvar /newvar /value=-a- /title=-b- |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Oberon | Oberon | MODULE pixel;
IMPORT XYplane;
BEGIN
XYplane.Open;
XYplane.Dot(100, 100, XYplane.draw);
REPEAT UNTIL XYplane.Key() = "q"
END pixel.
|
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Objeck | Objeck | use Game.SDL2;
use Game.Framework;
class DrawPixel {
@framework : GameFramework;
function : Main(args : String[]) ~ Nil {
DrawPixel->New()->Run();
}
New() {
@framework := GameFramework->New(320, 240, "RGB");
@framework->SetClearColor(Color->New(0, 0, 0));
}
method : Run() ~ Nil {
if(... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #Racket | Racket | #lang racket
(define (quotient/remainder-egyptian dividend divisor (trace? #f))
(define table
(for*/list ((power_of_2 (sequence-map (curry expt 2) (in-naturals)))
(doubling (in-value (* divisor power_of_2)))
#:break (> doubling dividend))
(list power_of_2 doubling)))
(w... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #Raku | Raku | sub egyptian-divmod (Real $dividend is copy where * >= 0, Real $divisor where * > 0) {
my $accumulator = 0;
([1, $divisor], { [.[0] + .[0], .[1] + .[1]] } … ^ *.[1] > $dividend)
.reverse.map: { $dividend -= .[1], $accumulator += .[0] if $dividend >= .[1] }
$accumulator, $dividend;
}
#TESTING
for 580... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #Raku | Raku | role Egyptian {
method gist {
join ' + ',
("[{self.floor}]" if self.abs >= 1),
map {"1/$_"}, self.denominators;
}
method denominators {
my ($x, $y) = self.nude;
$x %= $y;
my @denom = gather ($x, $y) = -$y % $x, $y * take ($y / $x).ceiling
while $x;
}
}
say .nude.join('/'), " = ", $_... |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #UNIX_Shell | UNIX Shell | halve()
{
expr "$1" / 2
}
double()
{
expr "$1" \* 2
}
is_even()
{
expr "$1" % 2 = 0 >/dev/null
}
ethiopicmult()
{
plier=$1
plicand=$2
r=0
while [ "$plier" -ge 1 ]; do
is_even "$plier" || r=`expr $r + "$plicand"`
plier=`halve "$plier"`
plicand=`double "$plicand"`
done
echo $r... |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #Wren | Wren | import "/fmt" for Conv
var SIZE = 32
var LINES = SIZE / 2
var RULE = 90
var ruleTest = Fn.new { |x| (RULE & (1 << (7 & x))) != 0 }
var bshl = Fn.new { |b, bitCount| Conv.btoi(b) << bitCount }
var evolve = Fn.new { |s|
var t = List.filled(SIZE, false)
t[SIZE-1] = ruleTest.call(bshl.call(s[0], 2) | bshl... |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #Wrapl | Wrapl | DEF fac(n) n <= 1 | PROD 1:to(n); |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #REALbasic | REALbasic |
Class EchoSocket
Inherits TCPSocket
Sub DataAvailable()
If Instr(Me.LookAhead, EndofLine.Windows) > 0 Then
Dim data As String = Me.ReadAll
Dim lines() As String = Split(data, EndofLine.Windows)
For i As Integer = 0 To Ubound(lines)
Me.Write(lines(i) + EndOfLine.Windows)
Print(l... |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #Ruby | Ruby | def main
intervals = [
[2, 1000, true],
[1000, 4000, true],
[2, 10000, false],
[2, 100000, false],
[2, 1000000, false],
[2, 10000000, false],
[2, 100000000, false],
[2, 1000000000, false]
]
for intv in intervals
(start, ending, display)... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Julia | Julia | using Makie, LinearAlgebra
N = 40
interval = 0.10
scene = mesh(FRect3D(Vec3f0(-0.5), Vec3f0(1)), color = :skyblue2)
rect = scene[end]
for rad in 0.5:1/N:8.5
arr = normalize([cospi(rad/2), 0, sinpi(rad/2), -sinpi(rad/2)])
Makie.rotate!(rect, Quaternionf0(arr[1], arr[2], arr[3], arr[4]))
sleep(interval)... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #PicoLisp | PicoLisp | (de elementWiseMatrix (Fun Mat1 Mat2)
(mapcar '((L1 L2) (mapcar Fun L1 L2)) Mat1 Mat2) )
(de elementWiseScalar (Fun Mat Scalar)
(elementWiseMatrix Fun Mat (circ (circ Scalar))) ) |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #PL.2FI | PL/I | declare (matrix(3,3), vector(3), scalar) fixed;
declare (m(3,3), v(3) fixed;
m = scalar * matrix;
m = vector * matrix;
m = matrix * matrix;
v = scalar * vector;
v = vector * vector; |
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
| #Batch_File | Batch File | :: Draw a Sphere Task from Rosetta Code
:: Batch File Implementation
@echo off
rem -------------- define arithmetic "functions"
rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=6744
rem integer sqrt arithmetic function by Aacini and penpen
rem source: https://www.dostips.com/forum/viewtopic.php?f=3&t... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Go | Go | package main
import "fmt"
type dlNode struct {
string
next, prev *dlNode
}
type dlList struct {
head, tail *dlNode
}
func (list *dlList) String() string {
if list.head == nil {
return fmt.Sprint(list.head)
}
r := "[" + list.head.string
for p := list.head.next; p != nil; p = p... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Haskell | Haskell |
insert _ Leaf = Leaf
insert nv l@(Node pl v r) = (\(Node c _ _) -> c) new
where new = updateLeft left . updateRight right $ Node l nv r
left = Node pl v new
right = case r of
Leaf -> Leaf
Node _ v r -> Node new v r
|
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Erlang | Erlang |
open System.Collections.Generic
let first (l: LinkedList<char>) = l.First
let last (l: LinkedList<char>) = l.Last
let next (l: LinkedListNode<char>) = l.Next
let prev (l: LinkedListNode<char>) = l.Previous
let traverse g f (ls: LinkedList<char>) =
let rec traverse (l: LinkedListNode<char>) =
match l... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #F.23 | F# |
open System.Collections.Generic
let first (l: LinkedList<char>) = l.First
let last (l: LinkedList<char>) = l.Last
let next (l: LinkedListNode<char>) = l.Next
let prev (l: LinkedListNode<char>) = l.Previous
let traverse g f (ls: LinkedList<char>) =
let rec traverse (l: LinkedListNode<char>) =
match l... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Clojure | Clojure | (defrecord Node [prev next data])
(defn new-node [prev next data]
(Node. (ref prev) (ref next) data)) |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Common_Lisp | Common Lisp | (defstruct dlist head tail)
(defstruct dlink content prev next) |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #D | D | struct Node(T) {
T data;
typeof(this)* prev, next;
}
void main() {
alias N = Node!int;
N* n = new N(10);
} |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #D | D | import std.stdio, std.random, std.algorithm, std.traits, std.array;
enum DutchColors { red, white, blue }
void dutchNationalFlagSort(DutchColors[] items) pure nothrow @nogc {
int lo, mid, hi = items.length - 1;
while (mid <= hi)
final switch (items[mid]) {
case DutchColors.red:
... |
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... | #C.23 | C# | using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Cuboid
{
public partial class Form1 : Form
{
double[][] nodes = {
new double[] {-1, -1, -1}, new double[] {-1, -1, 1}, new double[] {-1, 1, -1},
new double[] {-1, 1, 1}, ne... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Prolog | Prolog | test :- read(Name), atomics_to_string([Name, "= 50, writeln('", Name, "' = " , Name, ")"], String), term_string(Term, String), Term. |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Python | Python | >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42 |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #OCaml | OCaml | module G = Graphics
let () =
G.open_graph "";
G.resize_window 320 240;
G.set_color G.red;
G.plot 100 100;
ignore (G.read_key ()) |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Ol | Ol |
(import (lib gl))
(import (OpenGL version-1-0))
; init
(glClearColor 0.3 0.3 0.3 1)
(glOrtho 0 320 0 240 0 1)
; draw loop
(gl:set-renderer (lambda (mouse)
(glClear GL_COLOR_BUFFER_BIT)
(glBegin GL_POINTS)
(glColor3f 255 0 0)
(glVertex2f 100 100)
(glEnd)))
|
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #REXX | REXX | /*REXX program performs division on positive integers using the Egyptian division method*/
numeric digits 1000 /*support gihugic numbers & be gung-ho.*/
parse arg n d . /*obtain optional arguments from the CL*/
if d=='' | d=="," then do; n= 580; d= 34 ... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #Ring | Ring |
load "stdlib.ring"
table = newlist(32, 2)
dividend = 580
divisor = 34
i = 1
table[i][1] = 1
table[i][2] = divisor
while table[i] [2] < dividend
i = i + 1
table[i][1] = table[i -1] [1] * 2
table[i][2] = table[i -1] [2] * 2
end
i = i - 1
answer = table[i][1]
accumulator = table[i][2]
while i ... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #REXX | REXX | /*REXX program converts a fraction (can be improper) to an Egyptian fraction. */
parse arg fract '' -1 t; z=$egyptF(fract) /*compute the Egyptian fraction. */
if t\==. then say fract ' ───► ' z /*show Egyptian fraction from C.L.*/
return z /*stick a fork in it, we're done... |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #Ursala | Ursala | odd = ~&ihB
double = ~&iNiCB
half = ~&itB |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #zkl | zkl | fcn rule(n){ n=n.toString(2); "00000000"[n.len() - 8,*] + n }
fcn applyRule(rule,cells){
cells=String(cells[-1],cells,cells[0]); // wrap cell ends
(cells.len() - 2).pump(String,'wrap(n){ rule[7 - cells[n,3].toInt(2)] })
} |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #Wren | Wren | import "/fmt" for Fmt
import "/big" for BigInt
class Factorial {
static iterative(n) {
if (n < 2) return BigInt.one
var fact = BigInt.one
for (i in 2..n.toSmall) fact = fact * i
return fact
}
static recursive(n) {
if (n < 2) return BigInt.one
return n * re... |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #REBOL | REBOL | server-port: open/lines tcp://:12321
forever [
connection-port: first server-port
until [
wait connection-port
error? try [insert connection-port first connection-port]
]
close connection-port
]
close server-port |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #Scala | Scala | object EbanNumbers {
class ERange(s: Int, e: Int, p: Boolean) {
val start: Int = s
val end: Int = e
val print: Boolean = p
}
def main(args: Array[String]): Unit = {
val rgs = List(
new ERange(2, 1000, true),
new ERange(1000, 4000, true),
new ERange(2, 10000, false),
new... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Kotlin | Kotlin | // version 1.1
import java.awt.*
import javax.swing.*
class RotatingCube : JPanel() {
private val nodes = arrayOf(
doubleArrayOf(-1.0, -1.0, -1.0),
doubleArrayOf(-1.0, -1.0, 1.0),
doubleArrayOf(-1.0, 1.0, -1.0),
doubleArrayOf(-1.0, 1.0, 1.0),
doubleArrayOf( 1.0, -1.0,... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Python | Python | >>> import random
>>> from operator import add, sub, mul, floordiv
>>> from pprint import pprint as pp
>>>
>>> def ewise(matrix1, matrix2, op):
return [[op(e1,e2) for e1,e2 in zip(row1, row2)] for row1,row2 in zip(matrix1, matrix2)]
>>> m,n = 3,4 # array dimensions
>>> a0 = [[random.randint(1,9) for y in range(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
| #Befunge | Befunge | 45*65*65*"2"30p20p10p::00p2*40p4*5vv<
>60p140g->:::*00g50g*60g40g-:*-\-v0>1
^_@#`\g0<|`\g04:+1, <*84$$_v#`\0:<>p^
>v>g2+:5^$>g:*++*/7g^>*:9$#<"~"/:"~"v
g:^06,+55<^03*<v09p07%"~"p09/"~"p08%<
^>#0 *#12#<0g:^>+::"~~"90g*80g+*70gv|
g-10g*+:9**00gv|!*`\2\`-20::/2-\/\+<>
%#&eo*!:..^g05<>$030g-*9/\20g*+60g40^ |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Icon_and_Unicon | Icon and Unicon |
class DoubleLink (value, prev_link, next_link)
# insert given node after this one, losing its existing connections
method insert_after (node)
node.prev_link := self
if (\next_link) then next_link.prev_link := node
node.next_link := next_link
self.next_link := node
end
initially (value, pre... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #J | J | (pred;succ;<data) conew 'DoublyLinkedListElement'
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Java | Java |
import java.util.LinkedList;
@SuppressWarnings("serial")
public class DoublyLinkedListInsertion<T> extends LinkedList<T> {
public static void main(String[] args) {
DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();
list.addFirst("Add First 1");
list.addFi... |
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... | #ActionScript | ActionScript |
package {
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Clock extends Sprite {
// Changes of hands (in degrees) per second
priv... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Fortran | Fortran | Dim As Integer i, MiLista()
For i = 0 To Int(Rnd * 100)+25
Redim Preserve MiLista(i)
MiLista(i) = Rnd * 314
Next
'Tour from the beginning
For i = Lbound(MiLista) To Ubound(MiLista)
Print MiLista(i)
Next i
Print
'Travel from the end
For i = Ubound(MiLista) To Lbound(MiLista) Step -1
Print MiLista... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #FreeBASIC | FreeBASIC | Dim As Integer i, MiLista()
For i = 0 To Int(Rnd * 100)+25
Redim Preserve MiLista(i)
MiLista(i) = Rnd * 314
Next
'Tour from the beginning
For i = Lbound(MiLista) To Ubound(MiLista)
Print MiLista(i)
Next i
Print
'Travel from the end
For i = Ubound(MiLista) To Lbound(MiLista) Step -1
Print MiLista... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Delphi | Delphi | struct Node(T) {
type
pList = ^List ;
list = record
data : pointer ;
prev : pList ;
next : pList ;
end;
} |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #E | E | def makeElement(var value, var next, var prev) {
def element {
to setValue(v) { value := v }
to getValue() { return value }
to setNext(n) { next := n }
to getNext() { return next }
to setPrev(p) { prev := p }
to getPrev() { return prev }
}
return el... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Erlang | Erlang |
new( Data ) -> erlang:spawn( fun() -> loop( Data, noprevious, nonext ) end ).
|
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #Elixir | Elixir | defmodule Dutch_national_flag do
defp ball(:red), do: 1
defp ball(:white), do: 2
defp ball(:blue), do: 3
defp random_ball, do: Enum.random([:red, :white, :blue])
defp random_ball(n), do: (for _ <- 1..n, do: random_ball())
defp is_dutch([]), do: true
defp is_dutch([_]), do: true
defp is_dutch([b... |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #Erlang | Erlang | -module(dutch).
-export([random_balls/1, is_dutch/1, dutch/1]).
ball(red) -> 1;
ball(white) -> 2;
ball(blue) -> 3.
random_ball() -> lists:nth(random:uniform(3), [red, white, blue]).
random_balls(N) -> random_balls(N,[]).
random_balls(0,L) -> L;
random_balls(N,L) when N > 0 ->
B = random_ball(),
random_ba... |
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... | #C.2B.2B | C++ |
#include<graphics.h>
#include<iostream>
int main()
{
int k;
initwindow(1500,810,"Rosetta Cuboid");
do{
std::cout<<"Enter ratio of sides ( 0 or -ve to exit) : ";
std::cin>>k;
if(k>0){
bar3d(100, 100, 100 + 2*k, 100 + 4*k, 3*k, 1);
}
}while(k>0);
... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Quackery | Quackery | [ say "The word "
dup echo$
names find names found iff
[ say " exists." ]
else
[ say " does not exist." ] ] is exists? ( $ --> )
[ $ "Please enter a name: " input
cr
dup exists?
cr cr
dup say "Creating " echo$
say "..."
$ "[ stack ] is " over join quacke... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #R | R | # Read the name in from a command prompt
varname <- readline("Please name your variable >")
# Make sure the name is valid for a variable
varname <- make.names(varname)
message(paste("The variable being assigned is '", varname, "'"))
# Assign the variable (with value 42) into the user workspace (global environment)
assi... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Racket | Racket |
-> (begin (printf "Enter some name: ")
(namespace-set-variable-value! (read) 123))
Enter some name: bleh
-> bleh
123
|
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Perl | Perl | use Gtk3 '-init';
my $window = Gtk3::Window->new();
$window->set_default_size(320, 240);
$window->set_border_width(10);
$window->set_title("Draw a Pixel");
$window->set_app_paintable(TRUE);
my $da = Gtk3::DrawingArea->new();
$da->signal_connect('draw' => \&draw_in_drawingarea);
$window->add($da);
$window->show_all(... |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Phix | Phix | with javascript_semantics
include pGUI.e
cdCanvas cdcanvas
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
cdCanvasActivate(cdcanvas)
cdCanvasPixel(cdcanvas, 100, 100, CD_RED)
cdCanvasFlush(cdcanvas)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas =... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #Ruby | Ruby | def egyptian_divmod(dividend, divisor)
table = [[1, divisor]]
table << table.last.map{|e| e*2} while table.last.first * 2 <= dividend
answer, accumulator = 0, 0
table.reverse_each do |pow, double|
if accumulator + double <= dividend
accumulator += double
answer += pow
end
end
[answer, di... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #Rust | Rust | fn egyptian_divide(dividend: u32, divisor: u32) -> (u32, u32) {
let dividend = dividend as u64;
let divisor = divisor as u64;
let pows = (0..32).map(|p| 1 << p);
let doublings = (0..32).map(|p| divisor << p);
let (answer, sum) = doublings
.zip(pows)
.rev()
.skip_while(|(i... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #Ruby | Ruby | def ef(fr)
ans = []
if fr >= 1
return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1
intfr = fr.to_i
ans, fr = [intfr], fr - intfr
end
x, y = fr.numerator, fr.denominator
while x != 1
ans << Rational(1, (1/fr).ceil)
fr = Rational(-y % x, y * (1/fr).ceil)
x, y = fr.numerator, fr.de... |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #VBA | VBA | Private Function lngHalve(Nb As Long) As Long
lngHalve = Nb / 2
End Function
Private Function lngDouble(Nb As Long) As Long
lngDouble = Nb * 2
End Function
Private Function IsEven(Nb As Long) As Boolean
IsEven = (Nb Mod 2 = 0)
End Function |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #x86_Assembly | x86 Assembly | global factorial
section .text
; Input in ECX register (greater than 0!)
; Output in EAX register
factorial:
mov eax, 1
.factor:
mul ecx
loop .factor
ret |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Ruby | Ruby | require 'socket'
server = TCPServer.new(12321)
while (connection = server.accept)
Thread.new(connection) do |conn|
port, host = conn.peeraddr[1,2]
client = "#{host}:#{port}"
puts "#{client} is connected"
begin
loop do
line = conn.readline
puts "#{client} says: #{line}"
... |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #Tailspin | Tailspin |
templates isEban
def number: $;
'$;' -> \(<'([246]|[3456][0246])(0[03456][0246])*'> $ !\) -> $number !
end isEban
|
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Structure Interval
Dim start As Integer
Dim last As Integer
Dim print As Boolean
Sub New(s As Integer, l As Integer, p As Boolean)
start = s
last = l
print = p
End Sub
End Structure
Sub Main()
Dim interv... |
http://rosettacode.org/wiki/Draw_a_rotating_cube | Draw a rotating cube | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
Related ... | #Lua | Lua | local abs,atan,cos,floor,pi,sin,sqrt = math.abs,math.atan,math.cos,math.floor,math.pi,math.sin,math.sqrt
local bitmap = {
init = function(self, w, h, value)
self.w, self.h, self.pixels = w, h, {}
for y=1,h do self.pixels[y]={} end
self:clear(value)
end,
clear = function(self, value)
for y=1,self.h... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #R | R | # create a 2-times-2 matrix
mat <- matrix(1:4, 2, 2)
# matrix with scalar
mat + 2
mat * 2
mat ^ 2
# matrix with matrix
mat + mat
mat * mat
mat ^ mat |
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
| #Brlcad | Brlcad | opendb balls.g y # Create a database to hold our shapes
units cm # Set the unit of measure
in ball.s sph 0 0 0 3 # Create a sphere of radius 3 cm named ball.s with its centre at 0,0,0 |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #JavaScript | JavaScript | DoublyLinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {
if (this._value == searchValue) {
var after = this.next();
this.next(nodeToInsert);
nodeToInsert.prev(this);
nodeToInsert.next(after);
after.prev(nodeToInsert);
}
else if (this.next() == nu... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #Julia | Julia | mutable struct DLNode{T}
value::T
pred::Union{DLNode{T}, Nothing}
succ::Union{DLNode{T}, Nothing}
DLNode(v) = new{typeof(v)}(v, nothing, nothing)
end
function insertpost(prevnode, node)
succ = prevnode.succ
prevnode.succ = node
node.pred = prevnode
node.succ = succ
if succ != nothi... |
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... | #Ada | Ada | with Ada.Numerics.Elementary_Functions;
with Ada.Calendar.Formatting;
with Ada.Calendar.Time_Zones;
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
procedure Draw_A_Clock is
use Ada.Calendar;
use Ada.Calendar.Formatting;
Window : SDL.Video.Windows.Window;
Render... |
http://rosettacode.org/wiki/Doubly-linked_list/Traversal | Doubly-linked list/Traversal | Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Def... | #Go | Go | package main
import "fmt"
type dlNode struct {
string
next, prev *dlNode
}
type dlList struct {
head, tail *dlNode
}
func (list *dlList) String() string {
if list.head == nil {
return fmt.Sprint(list.head)
}
r := "[" + list.head.string
for p := list.head.next; p != nil; p = p... |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #F.23 | F# |
type 'a DLElm = {
mutable prev: 'a DLElm option
data: 'a
mutable next: 'a DLElm option
}
|
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Factor | Factor | TUPLE: node data next prev ; |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #Fortran | Fortran | type node
real :: data
type(node), pointer :: next => null(), previous => null()
end type node
!
! . . . .
!
type( node ), target :: head |
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition | Doubly-linked list/Element definition | Task
Define the data structure for a doubly-linked list element.
The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.
The pointers should be mutable.
See also
Array
Associative array: Creation, Iteration
Collections
... | #FreeBASIC | FreeBASIC | type node
nxt as node ptr
prv as node ptr
dat as any ptr 'points to any kind of data; user's responsibility
'to keep track of what's actually in it
end type |
http://rosettacode.org/wiki/Dutch_national_flag_problem | Dutch national flag problem |
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla... | #F.23 | F# | (* Since the task description here does not impose Dijsktra's original restrictions
* Changing the order is only allowed by swapping 2 elements
* Every element must only be inspected once
we have several options ...
One way -- especially when we work with immutable data structures --
is to scan the uno... |
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... | #Clojure | Clojure |
(use 'quil.core)
(def w 500)
(def h 400)
(defn setup []
(background 0))
(defn draw []
(push-matrix)
(translate (/ w 2) (/ h 2) 0)
(rotate-x 0.7)
(rotate-z 0.5)
(box 100 150 200) ; 2x3x4 relative dimensions
(pop-matrix))
(defsketch main
:title "cuboid"
:setup setup
:size [w h]
:draw draw... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Raku | Raku | our $our-var = 'The our var';
my $my-var = 'The my var';
my $name = prompt 'Variable name: ';
my $value = $::('name'); # use the right sigil, etc
put qq/Var ($name) starts with value 「$value」/;
$::('name') = 137;
put qq/Var ($name) ends with value 「{$::('name')}」/;
|
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #REBOL | REBOL | rebol [
Title: "Dynamic Variable Name"
URL: http://rosettacode.org/wiki/Dynamic_variable_names
]
; Here, I ask the user for a name, then convert it to a word and
; assign the value "Hello!" to it. To read this phrase, realize that
; REBOL collects terms from right to left, so "Hello!" is stored for
; future use, th... |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Processing | Processing | size(320, 240);
set(100, 100, color(255,0,0)); |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #PureBasic | PureBasic |
If OpenWindow(0, 0, 0, 320, 240, "Rosetta Code Draw A Pixel in PureBasic")
If CreateImage(0, 320, 240) And StartDrawing(ImageOutput(0))
Plot(100, 100,RGB(255,0,0))
StopDrawing()
ImageGadget(0, 0, 0, 320, 240, ImageID(0))
EndIf
Repeat
Event = WaitWindowEvent()
Until Event... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #Scala | Scala | object EgyptianDivision extends App {
private def divide(dividend: Int, divisor: Int): Unit = {
val powersOf2, doublings = new collection.mutable.ListBuffer[Integer]
//populate the powersof2- and doublings-columns
var line = 0
while ((math.pow(2, line) * divisor) <= dividend) {
val powerOf2 ... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #Sidef | Sidef | func egyptian_divmod(dividend, divisor) {
var table = [[1, divisor]]
table << table[-1].map{|e| 2*e } while (2*table[-1][0] <= dividend)
var (answer, accumulator) = (0, 0)
table.reverse.each { |pair|
var (pow, double) = pair...
if (accumulator + double <= dividend) {
accumulator += double
an... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #Rust | Rust |
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Zero};
use std::fmt;
#[derive(Debug, Clone, PartialEq, PartialOrd)]
struct Rational {
nominator: BigInt,
denominator: BigInt,
}
impl Rational {
fn new(n: &BigInt, d: &BigInt) -> Rational {
assert!(!d.is_zero(), "denominato... |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #VBScript | VBScript | option explicit
class List
private theList
private nOccupiable
private nTop
sub class_initialize
nTop = 0
nOccupiable = 100
redim theList( nOccupiable )
end sub
public sub store( x )
if nTop >= nOccupiable then
nOccupiable = nOccupiable + 100
redim preserve theList( nOccupiable )
end if
th... |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #XL | XL | 0! -> 1
N! -> N * (N-1)! |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Rust | Rust |
use std::net::{TcpListener, TcpStream};
use std::io::{BufReader, BufRead, Write};
use std::thread;
fn main() {
let listener = TcpListener::bind("127.0.0.1:12321").unwrap();
println!("server is running on 127.0.0.1:12321 ...");
for stream in listener.incoming() {
let stream = stream.unwrap();
... |
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.