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/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #REXX | REXX | /*REXX pgm computes and displays a Sierpinski Arrowhead Curve using the characters: \_/ */
parse arg order . /*obtain optional argument from the CL.*/
if order=='' | order=="," then order= 5 /*Not specified? Then use the default.*/
say ' Sierpinski arrowhead curve of order' order /*display the title. */
say '═════════════════════════════════════════' /* " " separator.*/
$= init() /*initialize a bunch of variables. */
if order//2 then do; call turn +60; call curve order, len, -60; end /*CURVE odd? */
else call curve order, len, +60 /*CURVE even.*/
do row=Ly to Hy; a= /*show arrowhead graph 1 row at a time.*/
do col=Lx to Hx; a= a || @.col.row /*build a row of " " col " " " */
end /*col*/; say strip(a, 'T') /*show " " " " row " " " */
end /*row*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
init: @.=" "; #=0; len=512; x=len; y=x;Hx=x;Hy=y;Lx=x;Ly=y; return '@. # Hx Hy Lx Ly x y'
turn: parse arg angle; #= (#+angle)//360; if #<0 then #= #+360; return /*normalize.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
curve: procedure expose ($); parse arg order,len,angle /*$: list of exposed variables*/
if order==0 then call draw len /*Is ORDER zero? Then draw it.*/
else do; call curve order-1, len/2, -angle; call turn angle
call curve order-1, len/2, +angle; call turn angle
call curve order-1, len/2, -angle
end
return /*The CURVE function is recursive. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
draw: select /*draw part of the curve using a char. */
when #== 0 then do; @.x.y= '_'; x= x + 1; end
when #== 60 then do; @.x.y= '/'; x= x + 1; y= y - 1; end
when #==120 then do; x= x - 1; @.x.y= '\'; y= y - 1; end
when #==180 then do; x= x - 1; @.x.y= '_'; end
when #==240 then do; x= x - 1; y= y + 1; @.x.y= '/'; end
when #==300 then do; y= y + 1; @.x.y= '\'; x= x + 1; end
end /*select*/ /*curve character is based on direction*/
Lx= min(Lx,x); Hx= max(Hx,x); Ly= min(Ly,y); Hy= max(Hy,y) /*min&max of x,y*/
return /*#: heading in degrees of the curve. */ |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "duration.s7i";
const proc: main is func
local
var integer: secondsToSleep is 0;
begin
write("Enter number of seconds to sleep: ");
readln(secondsToSleep);
writeln("Sleeping...");
wait(secondsToSleep . SECONDS);
writeln("Awake!");
end func; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #SenseTalk | SenseTalk |
ask "How long would you like to sleep?" message "Your answer may include any duration, such as 5 seconds, 2 hours, or even 3 centuries!"
get the value of it
if it is a duration then
put it into sleepyTime
else
answer "Sorry, that wasn't a valid duration!"
exit all
end if
put "Sleeping for " & sleepyTime & "..."
wait sleepyTime
put "Awake!"
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Prolog | Prolog | :- dynamic click/1.
dialog('Simple windowed application',
[ object :=
Simple_windowed_application,
parts :=
[ Simple_windowed_application :=
dialog('Simple windowed application'),
Name :=
label(name, 'There have been no clicks yet'),
BtnClick :=
button(button)
],
modifications :=
[ BtnClick := [ label := 'Click me !'
]
],
layout :=
[ area(Name,
area(40, 20, 200, 18)),
area(BtnClick,
area(90, 60, 80, 24))
],
behaviour :=
[
BtnClick := [message := message(@prolog, btnclick, Name)]
]
]).
btnclick(Label) :-
retract(click(V)),
V1 is V+1,
assert(click(V1)),
sformat(A, '~w click(s)', [V1]),
send(Label, selection, A).
simple_windowed :-
retractall(click(_)),
assert(click(0)),
make_dialog(D, 'Simple windowed application'),
send(D, open).
|
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Action.21 | Action! | PROC Main()
INT ARRAY xs=[249 200 96 80 175]
BYTE ARRAY ys=[82 176 159 55 7]
INT x,y
BYTE i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
Graphics(8+16)
Color=1
COLOR1=$0C
COLOR2=$02
x=160+Rand(30)
y=96+Rand(30)
DO
i=Rand(5)
x=x+(xs(i)-x)*62/100
y=y+(ys(i)-y)*62/100
Plot(x,y)
UNTIL CH#$FF
OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Arturo | Arturo | sierpinski: function [order][
s: shl 1 order
loop (s-1)..0 'y [
do.times: y -> prints " "
loop 0..dec s-y 'x [
if? zero? and x y -> prints "* "
else -> prints " "
]
print ""
]
]
sierpinski 4 |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #C.2B.2B | C++ |
#include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class sierpinski {
public:
void draw( int o ) {
colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;
colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;
bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC();
drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );
bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL );
LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );
LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" );
}
private:
void drawTri( HDC dc, float l, float t, float r, float b, int i ) {
float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f;
if( i ) {
drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );
drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );
drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );
}
bmp.setPenColor( colors[i % 6] );
MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL );
LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) );
LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );
LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) );
}
myBitmap bmp;
DWORD colors[6];
};
int main(int argc, char* argv[]) {
sierpinski s; s.draw( 12 );
return 0;
}
|
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Ruby | Ruby |
load_libraries :grammar
attr_reader :points
def setup
sketch_title 'Sierpinski Arrowhead'
sierpinski = SierpinskiArrowhead.new(Vec2D.new(width * 0.15, height * 0.7))
production = sierpinski.generate 6 # 6 generations looks OK
@points = sierpinski.translate_rules(production)
no_loop
end
def draw
background(0)
render points
end
def render(points)
no_fill
stroke 200.0
stroke_weight 3
begin_shape
points.each_slice(2) do |v0, v1|
v0.to_vertex(renderer)
v1.to_vertex(renderer)
end
end_shape
end
def renderer
@renderer ||= GfxRender.new(g)
end
def settings
size(800, 800)
end
# SierpinskiArrowhead class
class SierpinskiArrowhead
include Processing::Proxy
attr_reader :draw_length, :pos, :theta, :axiom, :grammar
DELTA = PI / 3 # 60 degrees
def initialize(pos)
@axiom = 'XF' # Axiom
rules = {
'X' => 'YF+XF+Y',
'Y' => 'XF-YF-X'
}
@grammar = Grammar.new(axiom, rules)
@theta = 0
@draw_length = 200
@pos = pos
end
def generate(gen)
@draw_length = draw_length * 0.6**gen
grammar.generate gen
end
def forward(pos)
pos + Vec2D.from_angle(theta) * draw_length
end
def translate_rules(prod)
[].tap do |pts| # An array to store line vertices as Vec2D
prod.scan(/./) do |ch|
case ch
when 'F'
new_pos = forward(pos)
pts << pos << new_pos
@pos = new_pos
when '+'
@theta += DELTA
when '-'
@theta -= DELTA
when 'X', 'Y'
else
puts("character #{ch} not in grammar")
end
end
end
end
end
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Sidef | Sidef | var sec = read(Number); # any positive number (it may be fractional)
say "Sleeping...";
Sys.sleep(sec); # in seconds
#Sys.usleep(sec); # in microseconds
#Sys.nanosleep(sec); # in nanoseconds
say "Awake!"; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Smalltalk | Smalltalk | t := (FillInTheBlankMorph request: 'Enter time in seconds') asNumber.
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #PureBasic | PureBasic | Define window_0
Define window_0_Text_0, window_0_Button_1
Define clicks, txt$, flags
flags = #PB_Window_SystemMenu | #PB_Window_SizeGadget | #PB_Window_ScreenCentered
window_0 = OpenWindow(#PB_Any, 408, 104, 280, 45, "Simple windowed application", flags)
If window_0
SmartWindowRefresh(window_0, #True)
window_0_Text_0 = TextGadget(#PB_Any, 5, 5, 165, 20, "There have been no clicks yet")
window_0_Button_1 = ButtonGadget(#PB_Any, 190, 10, 85, 30, "Click me")
Repeat
Select WaitWindowEvent()
Case #PB_Event_Gadget
Select EventGadget()
Case window_0_Text_0
Case window_0_Button_1
clicks + 1
txt$ = "You Clicked " + Str(clicks) + " time"
If clicks > 1: txt$ + "s": EndIf
SetGadgetText(window_0_Text_0, txt$)
EndSelect
Case #PB_Event_CloseWindow
End
EndSelect
ForEver
EndIf |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #AutoHotkey | AutoHotkey | W := H := 640
hw := W / 2
margin := 20
radius := hw - 2 * margin
side := radius * Sin(PI := 3.141592653589793 / 5) * 2
order := 5
gdip1()
drawPentagon(hw, 3*margin, side, order, 1)
return
drawPentagon(x, y, side, depth, colorIndex){
global G, hwnd1, hdc, Width, Height
Red := "0xFFFF0000"
Green := "0xFF00FF00"
Blue := "0xFF0000FF"
Magenta := "0xFFFF00FF"
Cyan := "0xFF00FFFF"
Black := "0xFF000000"
Palette := [Red, Green, Blue, Magenta, Cyan]
PI := 3.141592653589793
Deg72 := 72 * PI/180
angle := 3 * Deg72
ScaleFactor := 1 / ( 2 + Cos(Deg72) * 2)
points .= x "," y
if (depth = 1) {
loop 5 {
prevx := x
prevy := y
x += Cos(angle) * side
y -= Sin(angle) * side
points .= "|" x "," y
pPen := Gdip_CreatePen(Black, 2)
Gdip_DrawLines(G, pPen, prevx "," prevy "|" x "," y)
angle += Deg72
}
pBrush := Gdip_BrushCreateSolid(Palette[colorIndex])
Gdip_FillPolygon(G, pBrush, Points)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
}
else{
side *= ScaleFactor
dist := side * (1 + (Cos(Deg72)*2))
loop 5{
x += Cos(angle) * dist
y -= Sin(angle) * dist
colorIndex := Mod(colorIndex+1, 5) + 1
drawPentagon(x, y, side, depth-1, colorIndex)
angle += Deg72
}
}
}
; ---------------------------------------------------------------
gdip1(){
global
If !pToken := Gdip_Startup(){
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, Exit
Width := 640, Height := 640
Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui, 1: Show, NA
hwnd1 := WinExist()
hbm := CreateDIBSection(Width, Height)
hdc := CreateCompatibleDC()
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
Gdip_SetSmoothingMode(G, 4)
blackCanvas := Gdip_BrushCreateSolid(0xFFFFFFFF)
Gdip_FillRectangle(G, blackCanvas, 0, 0, Width, Height)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
}
; ---------------------------------------------------------------
gdip2(){
global
Gdip_DeleteBrush(pBrush)
Gdip_DeletePen(pPen)
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
}
; ---------------------------------------------------------------
Esc::
GuiEscape:
Exit:
gdip2()
Gdip_Shutdown(pToken)
ExitApp
Return |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #ATS | ATS |
(* ****** ****** *)
//
// How to compile:
//
// patscc -DATS_MEMALLOC_LIBC -o sierpinski sierpinski.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
#define SIZE 16
implement
main0 () =
{
//
var x: int
//
val () =
for (x := SIZE-1; x >= 0; x := x-1)
{
var i: int
val () =
for (i := 0; i < x; i := i+1)
{
val () = print_char(' ')
}
var y: int
val () =
for (y := 0; y + x < SIZE; y := y+1)
{
val y = g0int2uint_int_uint(y)
val x = g0int2uint_int_uint(x)
val () = print_string(if (x land y) != 0 then " " else "* ")
}
val ((*flushed*)) = print_newline()
}
//
} (* end of [main0] *)
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #D | D | void main() {
import grayscale_image;
enum order = 8,
margin = 10,
width = 2 ^^ order;
auto im = new Image!Gray(width + 2 * margin, width + 2 * margin);
im.clear(Gray.white);
foreach (immutable y; 0 .. width)
foreach (immutable x; 0 .. width)
if ((x & y) == 0)
im[x + margin, y + margin] = Gray.black;
im.savePGM("sierpinski.pgm");
} |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Rust | Rust | // [dependencies]
// svg = "0.8.0"
const SQRT3_2: f64 = 0.86602540378444;
use svg::node::element::path::Data;
struct Cursor {
x: f64,
y: f64,
angle: i32,
}
impl Cursor {
fn new(x: f64, y: f64) -> Cursor {
Cursor {
x: x,
y: y,
angle: 0,
}
}
fn turn(&mut self, angle: i32) {
self.angle = (self.angle + angle) % 360;
}
fn draw_line(&mut self, data: Data, length: f64) -> Data {
let theta = (self.angle as f64).to_radians();
self.x += length * theta.cos();
self.y += length * theta.sin();
data.line_to((self.x, self.y))
}
}
fn curve(mut data: Data, order: usize, length: f64, cursor: &mut Cursor, angle: i32) -> Data {
if order == 0 {
return cursor.draw_line(data, length);
}
data = curve(data, order - 1, length / 2.0, cursor, -angle);
cursor.turn(angle);
data = curve(data, order - 1, length / 2.0, cursor, angle);
cursor.turn(angle);
curve(data, order - 1, length / 2.0, cursor, -angle)
}
fn write_sierpinski_arrowhead(file: &str, size: usize, order: usize) -> std::io::Result<()> {
use svg::node::element::Path;
use svg::node::element::Rectangle;
let margin = 20.0;
let side = (size as f64) - 2.0 * margin;
let y = 0.5 * (size as f64) + 0.5 * SQRT3_2 * side;
let x = margin;
let mut cursor = Cursor::new(x, y);
if (order & 1) != 0 {
cursor.turn(-60);
}
let mut data = Data::new().move_to((x, y));
data = curve(data, order, side, &mut cursor, 60);
let rect = Rectangle::new()
.set("width", "100%")
.set("height", "100%")
.set("fill", "white");
let mut document = svg::Document::new()
.set("width", size)
.set("height", size)
.add(rect);
let path = Path::new()
.set("fill", "none")
.set("stroke", "black")
.set("stroke-width", "1")
.set("d", data);
document = document.add(path);
svg::save(file, &document)
}
fn main() {
write_sierpinski_arrowhead("sierpinski_arrowhead.svg", 600, 8).unwrap();
} |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Sidef | Sidef | var rules = Hash(
x => 'yF+xF+y',
y => 'xF-yF-x',
)
var lsys = LSystem(
width: 550,
height: 500,
xoff: -20,
yoff: -30,
len: 4,
turn: -90,
angle: 60,
color: 'dark green',
)
lsys.execute('xF', 7, "sierpiński_arrowhead.png", rules) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Standard_ML | Standard ML | (TextIO.print "input a number of seconds please: ";
let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in
TextIO.print "Sleeping...\n";
OS.Process.sleep (Time.fromReal seconds); (* it takes a Time.time data structure as arg,
but in my implementation it seems to round down to the nearest second.
I dunno why; it doesn't say anything about this in the documentation *)
TextIO.print "Awake!\n"
end) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Stata | Stata | program sleep_awake
* pass duration in milliseconds
display "Sleeping..."
sleep `0'
display "Awake!"
end
sleep_awake 2000 |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Python | Python | from functools import partial
import tkinter as tk
def on_click(label: tk.Label,
counter: tk.IntVar) -> None:
counter.set(counter.get() + 1)
label["text"] = f"Number of clicks: {counter.get()}"
def main():
window = tk.Tk()
window.geometry("200x50+100+100")
label = tk.Label(master=window,
text="There have been no clicks yet")
label.pack()
counter = tk.IntVar()
update_counter = partial(on_click,
label=label,
counter=counter)
button = tk.Button(master=window,
text="click me",
command=update_counter)
button.pack()
window.mainloop()
if __name__ == '__main__':
main()
|
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #C | C |
#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
int i,iter,choice,numSides;
printf("Enter number of sides : ");
scanf("%d",&numSides);
printf("Enter polygon side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
initwindow(windowSide,windowSide,"Polygon Chaos");
vertices = (double**)malloc(numSides*sizeof(double*));
for(i=0;i<numSides;i++){
vertices[i] = (double*)malloc(2 * sizeof(double));
vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
sumX+= vertices[i][0];
sumY+= vertices[i][1];
putpixel(vertices[i][0],vertices[i][1],15);
}
srand((unsigned)time(&t));
seedX = sumX/numSides;
seedY = sumY/numSides;
putpixel(seedX,seedY,15);
for(i=0;i<iter;i++){
choice = rand()%numSides;
seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
putpixel(seedX,seedY,15);
}
free(vertices);
getch();
closegraph();
return 0;
}
|
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #AutoHotkey | AutoHotkey | Loop 6
MsgBox % Triangle(A_Index)
Triangle(n,x=0,y=1) { ; Triangle(n) -> string of dots and spaces of Sierpinski triangle
Static t, l ; put chars in a static string
If (x < 1) { ; when called with one parameter
l := 2*x := 1<<(n-1) ; - compute location, string size
VarSetCapacity(t,l*x,32) ; - allocate memory filled with spaces
Loop %x%
NumPut(13,t,A_Index*l-1,"char") ; - new lines in the end of rows
}
If (n = 1) ; at the bottom of recursion
Return t, NumPut(46,t,x-1+(y-1)*l,"char") ; - write "." (better at proportional fonts)
u := 1<<(n-2)
Triangle(n-1,x,y) ; draw smaller triangle here
Triangle(n-1,x-u,y+u) ; smaller triangle down-left
Triangle(n-1,x+u,y+u) ; smaller triangle down right
Return t
} |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Erlang | Erlang |
-module(sierpinski).
-author("zduchac").
-export([start/0]).
sierpinski(DC, Order) ->
Size = 1 bsl Order,
sierpinski(DC, Order, Size, 0, 0).
sierpinski(_, _, Size, _, Y) when Y =:= Size ->
ok;
sierpinski(DC, Order, Size, X, Y) when X =:= Size ->
sierpinski(DC, Order, Size, 0, Y + 1);
sierpinski(DC, Order, Size, X, Y) when X band Y =:= 0 ->
wxDC:drawPoint(DC, {X, Y}),
sierpinski(DC, Order, Size, X + 1, Y);
sierpinski(DC, Order, Size, X, Y) ->
sierpinski(DC, Order, Size, X + 1, Y).
start() ->
Wx = wx:new(),
Frame = wxFrame:new(Wx, -1, "Raytracer", []),
wxFrame:connect(Frame, paint, [{callback,
fun(_Evt, _Obj) ->
DC = wxPaintDC:new(Frame),
sierpinski(DC, 8),
wxPaintDC:destroy(DC)
end
}]),
wxFrame:show(Frame).
|
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Wren | Wren | import "graphics" for Canvas, Color, Point
import "dome" for Window
class Game {
static init() {
Window.title = "Sierpinski Arrowhead Curve"
__width = 770
__height = 770
Window.resize(__width, __height)
Canvas.resize(__width, __height)
var order = 6
__iy = (order&1 == 0) ? -1: 1 // apex will point upwards
__theta = 0
__cx = __width / 2
__cy = __height
__h = __cx / 2
__prev = Point.new(__cx-__width/2 +__h, (__height-__cy)*__iy + 2*__h)
__col = Color.white
arrowhead(order, __cx)
}
static update() {}
static draw(alpha) {}
static arrowhead(order, length) {
// if order is even, we can just draw the curve
if (order&1 == 0) {
curve(order, length, 60)
} else {
turn(60)
curve(order, length, -60)
}
drawLine(length) // needed to make base symmetric
}
static drawLine(length) {
var curr = Point.new(__cx-__width/2 +__h, (__height-__cy)*__iy + 2*__h)
Canvas.line(__prev.x, __prev.y, curr.x, curr.y, __col)
var rads = __theta * Num.pi / 180
__cx = __cx + length*(rads.cos)
__cy = __cy + length*(rads.sin)
__prev = curr
}
static turn(angle) { __theta = (__theta + angle) % 360 }
static curve(order, length, angle) {
if (order == 0) {
drawLine(length)
} else {
curve(order-1, length/2, -angle)
turn(angle)
curve(order-1, length/2, angle)
turn(angle)
curve(order-1, length/2, -angle)
}
}
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Suneido | Suneido | function (time)
{
Print("Sleeping...")
Sleep(time) // time is in milliseconds
Print("Awake!")
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Swift | Swift | import Foundation
println("Enter number of seconds to sleep")
let input = NSFileHandle.fileHandleWithStandardInput()
var amount = NSString(data:input.availableData, encoding: NSUTF8StringEncoding)?.intValue
var interval = NSTimeInterval(amount!)
println("Sleeping...")
NSThread.sleepForTimeInterval(interval)
println("Awake!") |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #R | R | library(gWidgets)
library(gWidgetstcltk)
win <- gwindow()
lab <- glabel("There have been no clicks yet", container=win)
btn <- gbutton("click me", container=win, handle=function(h, ...)
{
val <- as.numeric(svalue(lab))
svalue(lab) <- ifelse(is.na(val) ,"1", as.character(val + 1))
}
) |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Racket | Racket |
#lang racket/gui
(define frame (new frame% [label "There have been no clicks yet"]))
(define num-clicks 0)
(define (cb obj me)
(set! num-clicks (add1 num-clicks))
(send frame set-label (format "~a" num-clicks)))
(new button% [parent frame] [label "Click me"] [callback cb])
(send frame show #t)
|
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
constexpr double degrees(double deg) {
const double tau = 2.0 * M_PI;
return deg * tau / 360.0;
}
const double part_ratio = 2.0 * cos(degrees(72));
const double side_ratio = 1.0 / (part_ratio + 2.0);
/// Define a position
struct Point {
double x, y;
friend std::ostream& operator<<(std::ostream& os, const Point& p);
};
std::ostream& operator<<(std::ostream& os, const Point& p) {
auto f(std::cout.flags());
os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';
std::cout.flags(f);
return os;
}
/// Mock turtle implementation sufficiant to handle "drawing" the pentagons
struct Turtle {
private:
Point pos;
double theta;
bool tracing;
public:
Turtle() : theta(0.0), tracing(false) {
pos.x = 0.0;
pos.y = 0.0;
}
Turtle(double x, double y) : theta(0.0), tracing(false) {
pos.x = x;
pos.y = y;
}
Point position() {
return pos;
}
void position(const Point& p) {
pos = p;
}
double heading() {
return theta;
}
void heading(double angle) {
theta = angle;
}
/// Move the turtle through space
void forward(double dist) {
auto dx = dist * cos(theta);
auto dy = dist * sin(theta);
pos.x += dx;
pos.y += dy;
if (tracing) {
std::cout << pos;
}
}
/// Turn the turtle
void right(double angle) {
theta -= angle;
}
/// Start/Stop exporting the points of the polygon
void begin_fill() {
if (!tracing) {
std::cout << "<polygon points=\"";
tracing = true;
}
}
void end_fill() {
if (tracing) {
std::cout << "\"/>\n";
tracing = false;
}
}
};
/// Use the provided turtle to draw a pentagon of the specified size
void pentagon(Turtle& turtle, double size) {
turtle.right(degrees(36));
turtle.begin_fill();
for (size_t i = 0; i < 5; i++) {
turtle.forward(size);
turtle.right(degrees(72));
}
turtle.end_fill();
}
/// Draw a sierpinski pentagon of the desired order
void sierpinski(int order, Turtle& turtle, double size) {
turtle.heading(0.0);
auto new_size = size * side_ratio;
if (order-- > 1) {
// create four more turtles
for (size_t j = 0; j < 4; j++) {
turtle.right(degrees(36));
double small = size * side_ratio / part_ratio;
auto distList = { small, size, size, small };
auto dist = *(distList.begin() + j);
Turtle spawn{ turtle.position().x, turtle.position().y };
spawn.heading(turtle.heading());
spawn.forward(dist);
// recurse for each spawned turtle
sierpinski(order, spawn, new_size);
}
// recurse for the original turtle
sierpinski(order, turtle, new_size);
} else {
// The bottom has been reached for this turtle
pentagon(turtle, size);
}
if (order > 0) {
std::cout << '\n';
}
}
/// Run the generation of a P(5) sierpinksi pentagon
int main() {
const int order = 5;
double size = 500;
Turtle turtle{ size / 2.0, size };
std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n";
std::cout << "<!DOCTYPE svg PUBLIC \" -//W3C//DTD SVG 1.1//EN\"\n";
std::cout << " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n";
std::cout << " version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n";
size *= part_ratio;
sierpinski(order, turtle, size);
std::cout << "</svg>";
} |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #APL | APL | A←67⍴0⋄A[34]←1⋄' #'[1+32 67⍴{~⊃⍵:⍵,∇(1⌽⍵)≠¯1⌽⍵⋄⍬}A] |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #ERRE | ERRE |
PROGRAM SIERPINSKY
!$INCLUDE="PC.LIB"
BEGIN
ORDER%=8
SIZE%=2^ORDER%
SCREEN(9)
GR_WINDOW(0,0,520,520)
FOR Y%=0 TO SIZE%-1 DO
FOR X%=0 TO SIZE%-1 DO
IF (X% AND Y%)=0 THEN PSET(X%*2,Y%*2,2) END IF
END FOR
END FOR
GET(K$)
END PROGRAM
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Factor | Factor | USING: accessors images images.loader kernel literals math
math.bits math.functions make sequences ;
IN: rosetta-code.sierpinski-triangle-graphical
CONSTANT: black B{ 33 33 33 255 }
CONSTANT: white B{ 255 255 255 255 }
CONSTANT: size $[ 2 8 ^ ] ! edit 8 to change order
! Generate Sierpinksi's triangle sequence. This is sequence
! A001317 in OEIS.
: sierpinski ( n -- seq )
[ [ 1 ] dip [ dup , dup 2 * bitxor ] times ] { } make nip ;
! Convert a number to binary, then append a black pixel for each
! set bit or a white pixel for each unset bit to the image being
! built by make.
: expand ( n -- ) make-bits [ black white ? % ] each ;
! Append white pixels until the end of the row in the image
! being built by make.
: pad ( n -- ) [ size ] dip 1 + - [ white % ] times ;
! Generate the image data for a sierpinski triangle of a given
! size in pixels. The image is square so its dimensions are
! n x n.
: sierpinski-img ( n -- seq )
sierpinski [ [ [ expand ] dip pad ] each-index ] B{ } make ;
: main ( -- )
<image>
${ size size } >>dim
BGRA >>component-order
ubyte-components >>component-type
size sierpinski-img >>bitmap
"sierpinski-triangle.png" save-graphic-image ;
MAIN: main |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #XPL0 | XPL0 | int PosX, PosY;
real Dir;
proc Curve(Order, Length, Angle);
int Order; real Length, Angle;
[if Order = 0 then
[PosX:= PosX + fix(Length*Cos(Dir));
PosY:= PosY - fix(Length*Sin(Dir));
Line(PosX, PosY, $E \yellow\);
]
else [Curve(Order-1, Length/2.0, -Angle);
Dir:= Dir + Angle;
Curve(Order-1, Length/2.0, +Angle);
Dir:= Dir + Angle;
Curve(Order-1, Length/2.0, -Angle);
];
];
def Order=5, Length=300.0, Pi=3.141592654, Sixty=Pi/3.0;
[SetVid($12); \VGA graphics: 640x480x8
PosX:= 640/4; PosY:= 3*480/4;
Move(PosX, PosY);
Dir:= 0.0;
if (Order&1) = 0 then
Curve(Order, Length, +Sixty)
else [Dir:= Dir + Sixty;
Curve(Order, Length, -Sixty);
];
] |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Tcl | Tcl | puts -nonewline "Enter a number of milliseconds to sleep: "
flush stdout
set millis [gets stdin]
puts Sleeping...
after $millis
puts Awake! |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #TI-89_BASIC | TI-89 BASIC | Local dur_secs,st0,st,seconds
Define seconds() = Func
Local hms
getTime()→hms
Return ((hms[1] * 60 + hms[2]) * 60) + hms[3]
EndFunc
ClockOn
Prompt dur_secs
Disp "Sleeping..."
seconds()→st
st→st0
While when(st<st0, st+86400, st) - st0 < dur_secs
seconds()→st
EndWhile
Disp "Awake!" |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Raku | Raku | use GTK::Simple;
use GTK::Simple::App;
my GTK::Simple::App $app .= new(title => 'Simple Windowed Application');
$app.size-request(350, 100);
$app.set-content(
GTK::Simple::VBox.new(
my $label = GTK::Simple::Label.new( text => 'There have been no clicks yet'),
my $button = GTK::Simple::Button.new(label => 'click me'),
)
);
$app.border-width = 40;
$button.clicked.tap: {
state $clicks += 1;
$label.text = "There has been $clicks click{ 's' if $clicks != 1 }";
}
$app.run; |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #D | D | import std.math;
import std.stdio;
/// Convert degrees into radians, as that is the accepted unit for sin/cos etc...
real degrees(real deg) {
immutable tau = 2.0 * PI;
return deg * tau / 360.0;
}
immutable part_ratio = 2.0 * cos(72.degrees);
immutable side_ratio = 1.0 / (part_ratio + 2.0);
/// Use the provided turtle to draw a pentagon of the specified size
void pentagon(Turtle turtle, real size) {
turtle.right(36.degrees);
turtle.begin_fill();
foreach(i; 0..5) {
turtle.forward(size);
turtle.right(72.degrees);
}
turtle.end_fill();
}
/// Draw a sierpinski pentagon of the desired order
void sierpinski(int order, Turtle turtle, real size) {
turtle.setheading(0.0);
auto new_size = size * side_ratio;
if (order-- > 1) {
// create four more turtles
foreach(j; 0..4) {
turtle.right(36.degrees);
real small = size * side_ratio / part_ratio;
auto dist = [small, size, size, small][j];
auto spawn = new Turtle();
spawn.setposition(turtle.position);
spawn.setheading(turtle.heading);
spawn.forward(dist);
// recurse for each spawned turtle
sierpinski(order, spawn, new_size);
}
// recurse for the original turtle
sierpinski(order, turtle, new_size);
} else {
// The bottom has been reached for this turtle
pentagon(turtle, size);
}
}
/// Run the generation of a P(5) sierpinksi pentagon
void main() {
int order = 5;
real size = 500;
auto turtle = new Turtle(size/2, size);
// Write the header to an SVG file for the image
writeln(`<?xml version="1.0" standalone="no"?>`);
writeln(`<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"`);
writeln(` "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">`);
writefln(`<svg height="%s" width="%s" style="fill:blue" transform="translate(%s,%s) rotate(-36)"`, size, size, size/2, size/2);
writeln(` version="1.1" xmlns="http://www.w3.org/2000/svg">`);
// Write the close tag when the interior points have been written
scope(success) writeln("</svg>");
// Scale the initial turtle so that it stays in the inner pentagon
size *= part_ratio;
// Begin rendering
sierpinski(order, turtle, size);
}
/// Define a position
struct Point {
real x;
real y;
/// When a point is written, do it in the form "x,y " to three decimal places
void toString(scope void delegate(const(char)[]) sink) const {
import std.format;
formattedWrite(sink, "%0.3f", x);
sink(",");
formattedWrite(sink, "%0.3f", y);
sink(" ");
}
}
/// Mock turtle implementation sufficiant to handle "drawing" the pentagons
class Turtle {
/////////////////////////////////
private:
Point pos;
real theta;
bool tracing;
/////////////////////////////////
public:
this() {
// empty
}
this(real x, real y) {
pos.x = x;
pos.y = y;
}
// Get/Set the turtle position
Point position() {
return pos;
}
void setposition(Point pos) {
this.pos = pos;
}
// Get/Set the turtle's heading
real heading() {
return theta;
}
void setheading(real angle) {
theta = angle;
}
// Move the turtle through space
void forward(real dist) {
// Calculate both components at once for the specified angle
auto delta = dist * expi(theta);
pos.x += delta.re;
pos.y += delta.im;
if (tracing) {
write(pos);
}
}
// Turn the turle
void right(real angle) {
theta = theta - angle;
}
// Start/Stop exporting the points of the polygon
void begin_fill() {
write(`<polygon points="`);
tracing = true;
}
void end_fill() {
writeln(`"/>`);
tracing = false;
}
} |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #AWK | AWK | # WST.AWK - Waclaw Sierpinski's triangle contributed by Dan Nielsen
# syntax: GAWK -f WST.AWK [-v X=anychar] iterations
# example: GAWK -f WST.AWK -v X=* 2
BEGIN {
n = ARGV[1] + 0 # iterations
if (n !~ /^[0-9]+$/) { exit(1) }
if (n == 0) { width = 3 }
row = split("X,X X,X X,X X X X",A,",") # seed the array
for (i=1; i<=n; i++) { # build triangle
width = length(A[row])
for (j=1; j<=row; j++) {
str = A[j]
A[j+row] = sprintf("%-*s %-*s",width,str,width,str)
}
row *= 2
}
for (j=1; j<=row; j++) { # print triangle
if (X != "") { gsub(/X/,substr(X,1,1),A[j]) }
sub(/ +$/,"",A[j])
printf("%*s%s\n",width-j+1,"",A[j])
}
exit(0)
} |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Forth | Forth | include lib/graphics.4th \ graphics support is needed
520 pic_width ! \ width of the image
520 pic_height ! \ height of the image
9 constant order \ Sierpinski's triangle order
black 255 whiteout \ black ink, white background
grayscale_image \ we're making a gray scale image
\ do we set a pixel or not?
: ?pixel over over and if drop drop else set_pixel then ;
: triangle 1 order lshift dup 0 do dup 0 do i j ?pixel loop loop drop ;
triangle s" triangle.ppm" save_image \ done, save the image |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #gnuplot | gnuplot | # triangle_x(n) and triangle_y(n) return X,Y coordinates for the
# Sierpinski triangle point number n, for integer n.
triangle_x(n) = (n > 0 ? 2*triangle_x(int(n/3)) + digit_to_x(int(n)%3) : 0)
triangle_y(n) = (n > 0 ? 2*triangle_y(int(n/3)) + digit_to_y(int(n)%3) : 0)
digit_to_x(d) = (d==0 ? 0 : d==1 ? -1 : 1)
digit_to_y(d) = (d==0 ? 0 : 1)
# Plot the Sierpinski triangle to "level" many replications.
# "trange" and "samples" are chosen so the parameter t runs through
# integers t=0 to 3**level-1, inclusive.
#
level=6
set trange [0:3**level-1]
set samples 3**level
set parametric
set key off
plot triangle_x(t), triangle_y(t) with points |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #zkl | zkl | order:=7;
sierpinskiArrowheadCurve(order) : turtle(_,order);
fcn sierpinskiArrowheadCurve(n){ // Lindenmayer system --> Data of As & Bs
var [const] A="BF+AF+B", B="AF-BF-A"; // Production rules
var [const] Axiom="AF";
buf1,buf2 := Data(Void,Axiom).howza(3), Data().howza(3); // characters
do(n){
buf1.pump(buf2.clear(),fcn(c){ if(c=="A") A else if(c=="B") B else c });
t:=buf1; buf1=buf2; buf2=t; // swap buffers
}
buf1 // n=7 --> 6,560 characters
}
fcn turtle(curve,order){ // Turtle with that can turn +-60*
const D=10.0, a60=60;
dir:=order.isOdd and a60 or 0; // start direction depends on order
img,color := PPM(1300,1200), 0x00ff00; // green on black
x,y := 10, 10;
foreach c in (curve){ // A & B are no-op during drawing
switch(c){
case("F"){ // draw forward
a,b := D.toRectangular(dir.toFloat().toRad());
img.line(x,y, (x+=a.round()),(y+=b.round()), color)
}
case("+"){ dir=(dir - a60)%360; } // turn left 60*
case("-"){ dir=(dir + a60)%360; } // turn right 60*
}
}
img.writeJPGFile("sierpinskiArrowheadCurve.zkl.jpg");
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Toka | Toka | 1 import sleep as sleep()
[ ." Sleeping...\n" sleep() drop ." Awake!\n" bye ] is sleep
45 sleep |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
secondsrange=2
PRINT "Sleeping ",secondsrange," seconds "
WAIT #secondsrange
PRINT "Awake after Naping ",secondsrange, " seconds"
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #RapidQ | RapidQ | DECLARE SUB buttonClick
CREATE form AS QForm
Center
Height = 120
Width = 300
CREATE text AS QLabel
Caption = "There have been no clicks yet."
Left = 30: Top = 20
END CREATE
CREATE button1 AS QButton
Caption = "Click me"
Left = 100: Top = 50: Height = 25: Width = 100
OnClick = buttonClick
END CREATE
END CREATE
SUB buttonClick
STATIC count AS Integer
count = count+1
text.Caption = "Clicked " + STR$(count) + " times."
END SUB
form.ShowModal |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #REBOL | REBOL | rebol [
Title: "Simple Windowed Application"
URL: http://rosettacode.org/wiki/Simple_Windowed_Application
]
clicks: 0
; Simple GUI's in REBOL can be defined with 'layout', a
; special-purpose language (dialect, in REBOL-speak) for specifying
; interfaces. In the example below, I describe a gradient background
; with a text label and a button. The block in the button section
; details what should happen when it's clicked on -- increment the
; number of clicks and update the label text.
; The 'view' function paints the layout on the screen and listens for
; events.
view layout [
backdrop effect [gradient 0x1 black coal]
label: vtext "There have been no clicks yet."
button maroon "click me" [
clicks: clicks + 1
set-face label reform ["clicks:" clicks]
]
] |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"image/color"
"math"
)
var (
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
)
var (
w, h = 640, 640
dc = gg.NewContext(w, h)
deg72 = gg.Radians(72)
scaleFactor = 1 / (2 + math.Cos(deg72)*2)
palette = [5]color.Color{red, green, blue, magenta, cyan}
colorIndex = 0
)
func drawPentagon(x, y, side float64, depth int) {
angle := 3 * deg72
if depth == 0 {
dc.MoveTo(x, y)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * side
y -= math.Sin(angle) * side
dc.LineTo(x, y)
angle += deg72
}
dc.SetColor(palette[colorIndex])
dc.Fill()
colorIndex = (colorIndex + 1) % 5
} else {
side *= scaleFactor
dist := side * (1 + math.Cos(deg72)*2)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * dist
y -= math.Sin(angle) * dist
drawPentagon(x, y, side, depth-1)
angle += deg72
}
}
}
func main() {
dc.SetRGB(1, 1, 1) // White background
dc.Clear()
order := 5 // Can also set this to 1, 2, 3 or 4
hw := float64(w / 2)
margin := 20.0
radius := hw - 2*margin
side := radius * math.Sin(math.Pi/5) * 2
drawPentagon(hw, 3*margin, side, order-1)
dc.SavePNG("sierpinski_pentagon.png")
} |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #BASH_.28feat._sed_.26_tr.29 | BASH (feat. sed & tr) |
#!/bin/bash
# Basic principle:
#
#
# x -> dxd d -> dd s -> s
# xsx dd s
#
# In the end all 'd' and 's' are removed.
# 0x7F800000
function rec(){
if [ $1 == 0 ]
then
echo "x"
else
rec $[ $1 - 1 ] | while read line ; do
echo "$line" | sed "s/d/dd/g" | sed "s/x/dxd/g"
echo "$line" | sed "s/d/dd/g" | sed "s/x/xsx/g"
done
fi
}
rec $1 | tr 'dsx' ' *'
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Go | Go | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
func main() {
const order = 8
const width = 1 << order
const margin = 10
bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)
im := image.NewGray(bounds)
gBlack := color.Gray{0}
gWhite := color.Gray{255}
draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)
for y := 0; y < width; y++ {
for x := 0; x < width; x++ {
if x&y == 0 {
im.SetGray(x, y, gBlack)
}
}
}
f, err := os.Create("sierpinski.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, im); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #TXR | TXR | (let ((usec (progn (put-string "enter sleep usecs: ")
(tointz (get-line)))))
(put-string "Sleeping ... ")
(flush-stream)
(usleep usec)
(put-line "Awake!")) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #UNIX_Shell | UNIX Shell | printf "Enter a time in seconds to sleep: "
read seconds
echo "Sleeping..."
sleep "$seconds"
echo "Awake!" |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Red | Red | Red[]
clicks: 0
view [
t: text "There have been no clicks yet" return
button "click me" [
clicks: clicks + 1
t/data: rejoin ["clicks: " clicks]
]
] |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Haskell | Haskell | import Graphics.Gloss
pentaflake :: Int -> Picture
pentaflake order = iterate transformation pentagon !! order
where
transformation = Scale s s . foldMap copy [0,72..288]
copy a = Rotate a . Translate 0 x
pentagon = Polygon [ (sin a, cos a) | a <- [0,2*pi/5..2*pi] ]
x = 2*cos(pi/5)
s = 1/(1+x)
main = display dc white (Color blue $ Scale 300 300 $ pentaflake 5)
where dc = InWindow "Pentaflake" (400, 400) (0, 0) |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #BASIC | BASIC | DECLARE SUB triangle (x AS INTEGER, y AS INTEGER, length AS INTEGER, n AS INTEGER)
CLS
triangle 1, 1, 16, 5
SUB triangle (x AS INTEGER, y AS INTEGER, length AS INTEGER, n AS INTEGER)
IF n = 0 THEN
LOCATE y, x: PRINT "*";
ELSE
triangle x, y + length, length / 2, n - 1
triangle x + length, y, length / 2, n - 1
triangle x + length * 2, y + length, length / 2, n - 1
END IF
END SUB |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Haskell | Haskell | import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
triangle = eqTriangle # fc black # lw 0
reduce t = t
===
(t ||| t)
sierpinski = iterate reduce triangle
main = defaultMain $ sierpinski !! 7
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Ursa | Ursa | out "Sleeping..." endl console
# sleep for 5 seconds (5000 milliseconds)
sleep 5000
out "Awake!" endl console |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #VBA | VBA |
Function Sleep(iSecsWait As Integer)
Debug.Print Now(), "Sleeping..."
Application.Wait Now + iSecsWait / 86400 'Time is stored as fractions of 24 hour day
Debug.Print Now(), "Awake!"
End Function
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Ring | Ring |
Load "guilib.ring"
MyApp = New qApp {
num = 0
win1 = new qWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
btn1 = new qpushbutton(win1) {
setGeometry(150,200,100,30)
settext("click me")
setclickevent("clickme()")}
Lineedit1 = new qlineedit(win1) {
setGeometry(10,100,350,30)}
show()}
Exec()}
func clickme
num += 1
lineedit1.settext( "you clicked me " + num + " times")
|
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Java | Java | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
import static java.lang.Math.*;
import java.util.Random;
import javax.swing.*;
public class SierpinskiPentagon extends JPanel {
// exterior angle
final double degrees072 = toRadians(72);
/* After scaling we'll have 2 sides plus a gap occupying the length
of a side before scaling. The gap is the base of an isosceles triangle
with a base angle of 72 degrees. */
final double scaleFactor = 1 / (2 + cos(degrees072) * 2);
final int margin = 20;
int limit = 0;
Random r = new Random();
public SierpinskiPentagon() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
new Timer(3000, (ActionEvent e) -> {
limit++;
if (limit >= 5)
limit = 0;
repaint();
}).start();
}
void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {
double angle = 3 * degrees072; // starting angle
if (depth == 0) {
Path2D p = new Path2D.Double();
p.moveTo(x, y);
// draw from the top
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * side;
y = y - sin(angle) * side;
p.lineTo(x, y);
angle += degrees072;
}
g.setColor(RandomHue.next());
g.fill(p);
} else {
side *= scaleFactor;
/* Starting at the top of the highest pentagon, calculate
the top vertices of the other pentagons by taking the
length of the scaled side plus the length of the gap. */
double distance = side + side * cos(degrees072) * 2;
/* The top positions form a virtual pentagon of their own,
so simply move from one to the other by changing direction. */
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * distance;
y = y - sin(angle) * distance;
drawPentagon(g, x, y, side, depth - 1);
angle += degrees072;
}
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
double radius = w / 2 - 2 * margin;
double side = radius * sin(PI / 5) * 2;
drawPentagon(g, w / 2, 3 * margin, side, limit);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Sierpinski Pentagon");
f.setResizable(true);
f.add(new SierpinskiPentagon(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class RandomHue {
/* Try to avoid random color values clumping together */
final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;
private static double hue = Math.random();
static Color next() {
hue = (hue + goldenRatioConjugate) % 1;
return Color.getHSBColor((float) hue, 1, 1);
}
} |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #BCPL | BCPL | get "libhdr"
manifest $( SIZE = 1 << 4 $)
let start() be
$( for y = SIZE-1 to 0 by -1 do
$( for i=1 to y do wrch(' ')
for x=0 to SIZE-y-1 do
writes((x & y) ~= 0 -> " ", "** ")
wrch('*N')
$)
$) |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Icon_and_Unicon | Icon and Unicon | link wopen
procedure main(A)
local width, margin, x, y
width := 2 ^ (order := (0 < integer(\A[1])) | 8)
wsize := width + 2 * (margin := 30 )
WOpen("label=Sierpinski", "size="||wsize||","||wsize) |
stop("*** cannot open window")
every y := 0 to width - 1 do
every x := 0 to width - 1 do
if iand(x, y) = 0 then DrawPoint(x + margin, y + margin)
Event()
end |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #VBScript | VBScript |
iSeconds=InputBox("Enter a time in seconds to sleep: ","Sleep Example for RosettaCode.org")
WScript.Echo "Sleeping..."
WScript.Sleep iSeconds*1000 'Sleep is done in Milli-Seconds
WScript.Echo "Awake!"
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Vedit_macro_language | Vedit macro language | #1 = Get_Num("Sleep time in 1/10 seconds: ")
Message("Sleeping...\n")
Sleep(#1)
Message("Awake!\n") |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Ruby | Ruby | require 'tk'
str = TkVariable.new("no clicks yet")
count = 0
root = TkRoot.new
TkLabel.new(root, "textvariable" => str).pack
TkButton.new(root) do
text "click me"
command {str.value = count += 1}
pack
end
Tk.mainloop |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Run_BASIC | Run BASIC | msg$ = "There have been no clicks yet"
[loop] cls ' clear screen
print msg$
button #c, "Click Me", [clickMe] 'create a button with handle and goto [tag]
wait
[clickMe]
clicks = clicks + 1
msg$ = "Button has been clicked ";clicks;" times"
goto [loop] |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #ABAP | ABAP | DATA: lv_date TYPE datum.
lv_date = 0.
WRITE: / lv_date.
|
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #JavaScript | JavaScript |
<html>
<head>
<script type="application/x-javascript">
// Globals
var cvs, ctx, scale=500, p0, ord=0, clr='blue', jc=0;
var clrs=['blue','navy','green','darkgreen','red','brown','yellow','cyan'];
function p5f() {
cvs = document.getElementById("cvsid");
ctx = cvs.getContext("2d");
cvs.onclick=iter;
pInit(); //init plot
}
function iter() {
if(ord>5) {resetf(0)};
ctx.clearRect(0,0,cvs.width,cvs.height);
p0.forEach(iter5);
p0.forEach(pIter5);
ord++; document.getElementById("p1id").innerHTML=ord;
}
function iter5(v, i, a) {
if(typeof(v[0][0]) == "object") {a[i].forEach(iter5)}
else {a[i] = meta5(v)}
}
function pIter5(v, i, a) {
if(typeof(v[0][0]) == "object") {v.forEach(pIter5)}
else {pPoly(v)}
}
function pInit() {
p0 = [make5([.5,.5], .5)];
pPoly(p0[0]);
}
function meta5(h) {
c=h[0]; p1=c; p2=h[1]; z1=p1[0]-p2[0]; z2=p1[1]-p2[1];
dist = Math.sqrt(z1*z1 + z2*z2)/2.65;
nP=[];
for(k=1; k<h.length; k++) {
p1=h[k]; p2=c; a=Math.atan2(p2[1]-p1[1], p2[0]-p1[0]);
nP[k] = make5(ppad(a, dist, h[k]), dist)
}
nP[0]=make5(c, dist);
return nP;
}
function make5(c, r) {
vs=[]; j = 1;
for(i=1/10; i<2; i+=2/5) {
vs[j]=ppad(i*Math.PI, r, c); j++;
}
vs[0] = c; return vs;
}
function pPoly(s) {
ctx.beginPath();
ctx.moveTo(s[1][0]*scale, s[1][1]*-scale+scale);
for(i=2; i<s.length; i++)
ctx.lineTo(s[i][0]*scale, s[i][1]*-scale+scale);
ctx.fillStyle=clr; ctx.fill()
}
// a - angle, d - distance, p - point
function ppad(a, d, p) {
x=p[0]; y=p[1];
x2=d*Math.cos(a)+x; y2=d*Math.sin(a)+y;
return [x2,y2]
}
function resetf(rord) {
ctx.clearRect(0,0,cvs.width,cvs.height);
ord=rord; jc++; if(jc>7){jc=0}; clr=clrs[jc];
document.getElementById("p1id").innerHTML=ord;
p5f();
}
</script>
</head>
<body onload="p5f()" style="font-family: arial, helvatica, sans-serif;">
<b>Click Pentaflake to iterate.</b> Order: <label id='p1id'>0</label>
<input type="submit" value="RESET" onclick="resetf(0);">
(Reset anytime: to start new Pentaflake and change color.)
<br /><br />
<canvas id="cvsid" width=640 height=640></canvas>
</body>
</html>
|
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Julia | Julia | using Printf
const sides = 5
const order = 5
const dim = 250
const scale = (3 - order ^ 0.5) / 2
const τ = 8 * atan(1, 1)
const orders = map(x -> ((1 - scale) * dim) * scale ^ x, 0:order-1)
cis(x) = Complex(cos(x), sin(x))
const vertices = map(x -> cis(x * τ / sides), 0:sides-1)
fh = open("sierpinski_pentagon.svg", "w")
print(fh, """<svg height=\"$(dim*2)\" width=\"$(dim*2)\" style=\"fill:blue\" """ *
"""version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n""")
for i in 1:sides^order
varr = [vertices[parse(Int, ch) + 1] for ch in split(string(i, base=sides, pad=order), "")]
vector = sum(map(x -> varr[x] * orders[x], 1:length(orders)))
vprod = map(x -> vector + orders[end] * (1-scale) * x, vertices)
points = join([@sprintf("%.3f %.3f", real(v), imag(v)) for v in vprod], " ")
print(fh, "<polygon points=\"$points\" transform=\"translate($dim,$dim) rotate(-18)\" />\n")
end
print(fh, "</svg>")
close(fh) |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Befunge | Befunge | 41+2>\#*1#2-#<:#\_$:1+v
v:$_:#`0#\\#00#:p#->#1<
>2/1\0p:2/\::>1-:>#v_1v
>8#4*#*+#+,#5^#5g0:< 1
vg11<\*g11!:g 0-1:::<p<
>!*+!!\0g11p\ 0p1-:#^_v
@$$_\#!:#::#-^#1\$,+55< |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #J | J | load 'viewmat'
'rgb'viewmat--. |. (~:_1&|.)^:(<@#) (2^8){.1
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Java | Java | import javax.swing.*;
import java.awt.*;
/**
* SierpinskyTriangle.java
* Draws a SierpinskyTriangle in a JFrame
* The order of complexity is given from command line, but
* defaults to 3
*
* @author Istarnion
*/
class SierpinskyTriangle {
public static void main(String[] args) {
int i = 3; // Default to 3
if(args.length >= 1) {
try {
i = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i);
}
}
final int level = i;
JFrame frame = new JFrame("Sierpinsky Triangle - Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);
}
};
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {
if(level <= 0) return;
g.drawLine(x, y, x+size, y);
g.drawLine(x, y, x, y+size);
g.drawLine(x+size, y, x, y+size);
drawSierpinskyTriangle(level-1, x, y, size/2, g);
drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Visual_Basic_.NET | Visual Basic .NET | Module Program
Sub Main()
Dim millisecondsSleepTime = Integer.Parse(Console.ReadLine(), Globalization.CultureInfo.CurrentCulture)
Console.WriteLine("Sleeping...")
Threading.Thread.Sleep(millisecondsSleepTime)
Console.WriteLine("Awake!")
End Sub
End Module |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Vlang | Vlang | import time
import os
fn main() {
sec := os.input("Enter number of seconds to sleep: ").i64()
println("Sleeping…")
time.sleep(time.Duration(sec * time.second))
println("Awake!")
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Rust | Rust | use iced::{ // 0.2.0
button, Button, Column, Element, Length,
Text, Sandbox, Settings, Space,
};
#[derive(Debug, Copy, Clone)]
struct Pressed;
struct Simple {
value: i32,
button: button::State,
}
impl Sandbox for Simple {
type Message = Pressed;
fn new() -> Simple {
Simple {
value: 0,
button: button::State::new(),
}
}
fn title(&self) -> String {
"Simple Windowed Application".into()
}
fn view(&mut self) -> Element<Self::Message> {
Column::new()
.padding(20)
.push({
let text = match self.value {
0 => "there have been no clicks yet".into(),
1 => "there has been 1 click".into(),
n => format!("there have been {} clicks", n),
};
Text::new(text).size(24)
}).push(
Space::with_height(Length::Fill)
).push(
Button::new(&mut self.button, Text::new("Click Me!"))
.on_press(Pressed)
).into()
}
fn update(&mut self, _: Self::Message) {
self.value += 1;
}
}
fn main() {
let mut settings = Settings::default();
settings.window.size = (600, 400);
Simple::run(settings).unwrap();
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Scala | Scala | import scala.swing.{ BorderPanel, Button, Label, MainFrame, SimpleSwingApplication }
import scala.swing.event.ButtonClicked
object SimpleApp extends SimpleSwingApplication {
def top = new MainFrame {
contents = new BorderPanel {
var nClicks = 0
val (button, label) = (new Button { text = "click me" },
new Label { text = "There have been no clicks yet" })
layout(button) = BorderPanel.Position.South
layout(label) = BorderPanel.Position.Center
listenTo(button)
reactions += {
case ButtonClicked(_) =>
nClicks += 1
label.text = s"There have been ${nClicks} clicks"
}
}
}
} |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar; use Ada.Calendar;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
with Ada.Calendar.Conversions; use Ada.Calendar.Conversions;
procedure ShowEpoch is
etime : Time := To_Ada_Time (0);
begin
Put_Line (Image (Date => etime));
end ShowEpoch; |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
local CocoaEpoch, UnixEpoch
-- Get the date 0 seconds from the Cocoa epoch.
set CocoaEpoch to current application's class "NSDate"'s dateWithTimeIntervalSinceReferenceDate:(0)
-- The way it's rendered in its 'description' is good enough for the current purpose.
set CocoaEpoch to CocoaEpoch's |description|() as text
-- Get the date 0 seconds from the Unix epoch and format it in the same way.
set UnixEpoch to (do shell script "date -ur 0 '+%F %T %z'")
return "Cocoa epoch: " & CocoaEpoch & linefeed & "Unix epoch: " & UnixEpoch |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import java.awt.geom.Path2D
import java.util.Random
import javax.swing.*
class SierpinskiPentagon : JPanel() {
// exterior angle
private val degrees072 = Math.toRadians(72.0)
/* After scaling we'll have 2 sides plus a gap occupying the length
of a side before scaling. The gap is the base of an isosceles triangle
with a base angle of 72 degrees. */
private val scaleFactor = 1.0 / (2.0 + Math.cos(degrees072) * 2.0)
private val margin = 20
private var limit = 0
private val r = Random()
init {
preferredSize = Dimension(640, 640)
background = Color.white
Timer(3000) {
limit++
if (limit >= 5) limit = 0
repaint()
}.start()
}
private fun drawPentagon(g: Graphics2D, x: Double, y: Double, s: Double, depth: Int) {
var angle = 3.0 * degrees072 // starting angle
var xx = x
var yy = y
var side = s
if (depth == 0) {
val p = Path2D.Double()
p.moveTo(xx, yy)
// draw from the top
for (i in 0 until 5) {
xx += Math.cos(angle) * side
yy -= Math.sin(angle) * side
p.lineTo(xx, yy)
angle += degrees072
}
g.color = RandomHue.next()
g.fill(p)
}
else {
side *= scaleFactor
/* Starting at the top of the highest pentagon, calculate
the top vertices of the other pentagons by taking the
length of the scaled side plus the length of the gap. */
val distance = side + side * Math.cos(degrees072) * 2.0
/* The top positions form a virtual pentagon of their own,
so simply move from one to the other by changing direction. */
for (i in 0 until 5) {
xx += Math.cos(angle) * distance
yy -= Math.sin(angle) * distance
drawPentagon(g, xx, yy, side, depth - 1)
angle += degrees072
}
}
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val hw = width / 2
val radius = hw - 2.0 * margin
val side = radius * Math.sin(Math.PI / 5.0) * 2.0
drawPentagon(g, hw.toDouble(), 3.0 * margin, side, limit)
}
private class RandomHue {
/* Try to avoid random color values clumping together */
companion object {
val goldenRatioConjugate = (Math.sqrt(5.0) - 1.0) / 2.0
var hue = Math.random()
fun next(): Color {
hue = (hue + goldenRatioConjugate) % 1
return Color.getHSBColor(hue.toFloat(), 1.0f, 1.0f)
}
}
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "Sierpinski Pentagon"
f.isResizable = true
f.add(SierpinskiPentagon(), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.isVisible = true
}
} |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Burlesque | Burlesque | {JPp{
-.'sgve!
J{JL[2./+.' j.*PppP.+PPj.+}m[
j{J" "j.+.+}m[
.+
}{vv{"*"}}PPie} 's sv
4 'sgve!unsh |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #JavaScript | JavaScript |
<!-- SierpinskiTriangle.html -->
<html>
<head><title>Sierpinski Triangle Fractal</title>
<script>
// HF#1 Like in PARI/GP: return random number 0..max-1
function randgp(max) {return Math.floor(Math.random()*max)}
// HF#2 Random hex color
function randhclr() {
return "#"+
("00"+randgp(256).toString(16)).slice(-2)+
("00"+randgp(256).toString(16)).slice(-2)+
("00"+randgp(256).toString(16)).slice(-2)
}
// HFJS#3: Plot any matrix mat (filled with 0,1)
function pmat01(mat, color) {
// DCLs
var cvs = document.getElementById('cvsId');
var ctx = cvs.getContext("2d");
var w = cvs.width; var h = cvs.height;
var m = mat[0].length; var n = mat.length;
// Cleaning canvas and setting plotting color
ctx.fillStyle="white"; ctx.fillRect(0,0,w,h);
ctx.fillStyle=color;
// MAIN LOOP
for(var i=0; i<m; i++) {
for(var j=0; j<n; j++) {
if(mat[i][j]==1) { ctx.fillRect(i,j,1,1)};
}//fend j
}//fend i
}//func end
// Prime function
// Plotting Sierpinski triangle. aev 4/9/17
// ord - order, fn - file name, ttl - plot title, clr - color
function pSierpinskiT() {
var cvs=document.getElementById("cvsId");
var ctx=cvs.getContext("2d");
var w=cvs.width, h=cvs.height;
var R=new Array(w);
for (var i=0; i<w; i++) {R[i]=new Array(w)
for (var j=0; j<w; j++) {R[i][j]=0}
}
ctx.fillStyle="white"; ctx.fillRect(0,0,w,h);
for (var y=0; y<w; y++) {
for (var x=0; x<w; x++) {
if((x & y) == 0 ) {R[x][y]=1}
}}
pmat01(R, randhclr());
}
</script></head>
<body style="font-family: arial, helvatica, sans-serif;">
<b>Please click to start and/or change color: </b>
<input type="button" value=" Plot it! " onclick="pSierpinskiT();">
<h3>Sierpinski triangle fractal</h3>
<canvas id="cvsId" width="640" height="640" style="border: 2px inset;"></canvas>
<!--canvas id="cvsId" width="1280" height="1280" style="border: 2px inset;"></canvas-->
</body></html>
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #jq | jq | include "turtle" {search: "."};
# Compute the curve using a Lindenmayer system of rules
def rules:
# "H" signfies Horizontal motion
{X: "XX",
H: "H--X++H++X--H",
"": "H--X--X"};
def sierpinski($count):
rules as $rules
| def repeat($count):
if $count == 0 then .
else gsub("X"; $rules["X"]) | gsub("H"; $rules["H"])
| repeat($count-1)
end;
$rules[""] | repeat($count) ;
def interpret($x):
if $x == "+" then turtleRotate(-60)
elif $x == "-" then turtleRotate(60)
else turtleForward(20)
end;
def sierpinski_curve($n):
sierpinski($n)
| split("")
| reduce .[] as $action (
turtle([200,-200]) | turtleDown;
interpret($action) ) ;
# viewBox = <min-x> <min-y> <width> <height>
# Input: {svg, minx, miny, maxx, maxy}
def svg:
"<svg viewBox='\(.minx|floor) \(.miny - 4 |floor) \(.maxx - .minx|ceil) \(6 + .maxy - .miny|ceil)'",
" preserveAspectRatio='xMinYmin meet'",
" xmlns='http://www.w3.org/2000/svg' >",
path("none"; "red"; 1),
"</svg>";
sierpinski_curve(5)
| svg
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Wren | Wren | import "timer" for Timer
import "io" for Stdin, Stdout
System.write("Enter time to sleep in seconds: ")
Stdout.flush()
var secs
while (true) {
secs = Num.fromString(Stdin.readLine())
if (secs == null) {
System.print("Not a number try again.")
} else break
}
System.print("Sleeping...")
Timer.sleep((secs*1000).floor)
System.print("Awake!") |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #X86_Assembly | X86 Assembly |
; x86_64 linux nasm
section .text
Sleep:
mov rsi, 0 ; we wont use the second sleep arg, pass null to syscall
sub rsp, 16
mov qword [rsp], rdi ; number of seconds the caller requested
mov qword [rsp + 8], rsi ; we won't use the nanoseconds
mov rdi, rsp ; pass the struct that's on the stack to
mov rax, 35 ; sys_nanosleep
syscall
add rsp, 16 ; clean up stack
ret
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Scratch | Scratch |
when flag clicked # when program is run
set counter to "0" # initialize counter object to zero
set message to "There have been no clicks"
show variable message # show the message object
when this sprite clicked # when button clicked
hide message # hide the initial message
change counter by 1 # increment the counter object
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Sidef | Sidef | require('Gtk2') -> init
# Window.
var window = %s<Gtk2::Window>.new
window.signal_connect('destroy' => { %s<Gtk2>.main_quit })
# VBox.
var vbox = %s<Gtk2::VBox>.new(0, 0)
window.add(vbox)
# Label.
var label = %s<Gtk2::Label>.new('There have been no clicks yet.')
vbox.add(label)
# Button.
var count = 0
var button = %s<Gtk2::Button>.new(' Click Me ')
vbox.add(button)
button.signal_connect('clicked' => {
label.set_text(++count)
})
# Show.
window.show_all
# Main loop.
%s<Gtk2>.main |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #Arturo | Arturo | print to :date 0 ; convert UNIX timestamp: 0 to date
print now
print to :integer now ; convert current date to UNIX timestamp |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #AWK | AWK |
# syntax: GAWK -f SHOW_THE_EPOCH.AWK
# requires GNU Awk 4.0.1 or later
BEGIN {
print(strftime("%Y-%m-%d %H:%M:%S",0,1))
exit(0)
}
|
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Lua | Lua | Bitmap.chaosgame = function(self, n, r, niters)
local w, h, vertices = self.width, self.height, {}
for i = 1, n do
vertices[i] = {
x = w/2 + w/2 * math.cos(math.pi/2+(i-1)*math.pi*2/n),
y = h/2 - h/2 * math.sin(math.pi/2+(i-1)*math.pi*2/n)
}
end
local x, y = w/2, h/2
for i = 1, niters do
local v = math.random(n)
x = x + r * (vertices[v].x - x)
y = y + r * (vertices[v].y - y)
self:set(x,y,0xFFFFFFFF)
end
end
local bitmap = Bitmap(128, 128)
bitmap:chaosgame(5, 1/((1+math.sqrt(5))/2), 1e6)
bitmap:render({[0x000000]='..', [0xFFFFFFFF]='██'}) |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #BQN | BQN | Sierp ← {" •" ⊏˜ (⌽↕2⋆𝕩)⌽˘∾˘∾⟜0¨∧´∘∨⌜˜⥊↕2⥊˜𝕩} |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Julia | Julia |
using Luxor
function sierpinski(txy, levelsyet)
nxy = zeros(6)
if levelsyet > 0
for i in 1:6
pos = i < 5 ? i + 2 : i - 4
nxy[i] = (txy[i] + txy[pos]) / 2.0
end
sierpinski([txy[1],txy[2],nxy[1],nxy[2],nxy[5],nxy[6]], levelsyet-1)
sierpinski([nxy[1],nxy[2],txy[3],txy[4],nxy[3],nxy[4]], levelsyet-1)
sierpinski([nxy[5],nxy[6],nxy[3],nxy[4],txy[5],txy[6]], levelsyet-1)
else
poly([Point(txy[1],txy[2]),Point(txy[3],txy[4]),Point(txy[5],txy[6])], :fill ,close=true)
end
end
Drawing(800, 800)
sierpinski([400., 100., 700., 500., 100., 500.], 7)
finish()
preview()
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Kotlin | Kotlin | import java.awt.*
import javax.swing.JFrame
import javax.swing.JPanel
fun main(args: Array<String>) {
var i = 8 // Default
if (args.any()) {
try {
i = args.first().toInt()
} catch (e: NumberFormatException) {
i = 8
println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to $i")
}
}
object : JFrame("Sierpinsky Triangle - Kotlin") {
val panel = object : JPanel() {
val size = 800
init {
preferredSize = Dimension(size, size)
}
public override fun paintComponent(g: Graphics) {
g.color = Color.BLACK
if (g is Graphics2D) {
g.drawSierpinskyTriangle(i, 20, 20, size - 40)
}
}
}
init {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
add(panel)
pack()
isResizable = false
setLocationRelativeTo(null)
isVisible = true
}
}
}
internal fun Graphics2D.drawSierpinskyTriangle(level: Int, x: Int, y: Int, size: Int) {
if (level > 0) {
drawLine(x, y, x + size, y)
drawLine(x, y, x, y + size)
drawLine(x + size, y, x, y + size)
drawSierpinskyTriangle(level - 1, x, y, size / 2)
drawSierpinskyTriangle(level - 1, x + size / 2, y, size / 2)
drawSierpinskyTriangle(level - 1, x, y + size / 2, size / 2)
}
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #XPL0 | XPL0 | int Microseconds;
[Microseconds:= IntIn(0);
Text(0, "Sleeping...^m^j");
DelayUS(Microseconds);
Text(0, "Awake!^m^j");
] |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #zig | zig | const std = @import("std");
const time = std.time;
const warn = std.debug.warn;
pub fn main() void {
warn("Sleeping...\n");
time.sleep(1000000000); // `sleep` uses nanoseconds
warn("Awake!\n");
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Smalltalk | Smalltalk | |top clickCount lh button|
clickCount := 0.
lh := ValueHolder with:'There have been no clicks yet'.
top := StandardSystemView label:'Rosetta Simple Window'.
top extent:300@100.
top add:((Label new labelChannel:lh) origin: 0 @ 10 corner: 1.0 @ 40).
top add:((button := Button label:'Eat Me') origin: 10 @ 50 corner: 100 @ 80).
button action:[
clickCount := clickCount + 1.
lh value: ('number of clicks: %1' bindWith:clickCount)
].
top open |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"DATELIB"
PRINT FN_date$(0, "dd-MMM-yyyy") |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
Related task
Date format
| #C | C | #include <time.h>
#include <stdio.h>
int main() {
time_t t = 0;
printf("%s", asctime(gmtime(&t)));
return 0;
} |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | pentaFlake[0] = RegularPolygon[5];
pentaFlake[n_] := GeometricTransformation[pentaFlake[n - 1], TranslationTransform /@ CirclePoints[{GoldenRatio^(2 n - 1), Pi/10}, 5]]
Graphics@pentaFlake[4] |
http://rosettacode.org/wiki/Sierpinski_pentagon | Sierpinski pentagon | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
See also
Sierpinski pentagon
| #MATLAB | MATLAB | [x, x0] = deal(exp(1i*(0.5:.4:2.1)*pi));
for k = 1 : 4
x = x(:) + x0 * (1 + sqrt(5)) * (3 + sqrt(5)) ^(k - 1) / 2 ^ k;
end
patch('Faces', reshape(1 : 5 * 5 ^ k, 5, '')', 'Vertices', [real(x(:)) imag(x(:))])
axis image off |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #C | C | #include <stdio.h>
#define SIZE (1 << 4)
int main()
{
int x, y, i;
for (y = SIZE - 1; y >= 0; y--, putchar('\n')) {
for (i = 0; i < y; i++) putchar(' ');
for (x = 0; x + y < SIZE; x++)
printf((x & y) ? " " : "* ");
}
return 0;
} |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Logo | Logo | to sierpinski :n :length
if :n = 0 [stop]
repeat 3 [sierpinski :n-1 :length/2 fd :length rt 120]
end
seth 30 sierpinski 5 200 |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Lua | Lua | -- The argument 'tri' is a list of co-ords: {x1, y1, x2, y2, x3, y3}
function sierpinski (tri, order)
local new, p, t = {}
if order > 0 then
for i = 1, #tri do
p = i + 2
if p > #tri then p = p - #tri end
new[i] = (tri[i] + tri[p]) / 2
end
sierpinski({tri[1],tri[2],new[1],new[2],new[5],new[6]}, order-1)
sierpinski({new[1],new[2],tri[3],tri[4],new[3],new[4]}, order-1)
sierpinski({new[5],new[6],new[3],new[4],tri[5],tri[6]}, order-1)
else
love.graphics.polygon("fill", tri)
end
end
-- Callback function used to draw on the screen every frame
function love.draw ()
sierpinski({400, 100, 700, 500, 100, 500}, 7)
end |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #zkl | zkl | seconds:=ask("Seconds to sleep: ").toFloat();
println("Sleeping...");
Atomic.sleep(seconds); # float, usually millisecond resolution
println("Awake!"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.