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/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #SQL | SQL |
-- save these lines in a file called
-- setupworld.sql
-- turn off feedback for cleaner display
SET feedback off
-- 3 x 3 world
-- alive has coordinates of living cells
DROP TABLE alive;
CREATE TABLE alive (x NUMBER,y NUMBER);
-- three alive up the middle
-- *
-- *
-- *
INSERT INTO alive VALUES (2,1);
INSERT INTO alive VALUES (2,2);
INSERT INTO alive VALUES (2,3);
commit;
-- save these lines in a file called
newgeneration.SQL
-- adjact contains one row for each pair of
-- coordinates that is adjacent to a living cell
DROP TABLE adjacent;
CREATE TABLE adjacent (x NUMBER,y NUMBER);
-- add row for each of the 8 adjacent squares
INSERT INTO adjacent SELECT x-1,y-1 FROM alive;
INSERT INTO adjacent SELECT x-1,y FROM alive;
INSERT INTO adjacent SELECT x-1,y+1 FROM alive;
INSERT INTO adjacent SELECT x,y-1 FROM alive;
INSERT INTO adjacent SELECT x,y+1 FROM alive;
INSERT INTO adjacent SELECT x+1,y-1 FROM alive;
INSERT INTO adjacent SELECT x+1,y FROM alive;
INSERT INTO adjacent SELECT x+1,y+1 FROM alive;
commit;
-- delete rows for squares that are outside the world
DELETE FROM adjacent WHERE x<1 OR y<1 OR x>3 OR y>3;
commit;
-- table counts is the number of live cells
-- adjacent to that point
DROP TABLE counts;
CREATE TABLE counts AS
SELECT x,y,COUNT(*) n
FROM adjacent a
GROUP BY x,y;
-- C N new C
-- 1 0,1 -> 0 # Lonely
-- 1 4,5,6,7,8 -> 0 # Overcrowded
-- 1 2,3 -> 1 # Lives
-- 0 3 -> 1 # It takes three to give birth!
-- 0 0,1,2,4,5,6,7,8 -> 0 # Barren
-- delete the ones who die
DELETE FROM alive a
WHERE
((a.x,a.y) NOT IN (SELECT x,y FROM counts)) OR
((SELECT c.n FROM counts c WHERE a.x=c.x AND a.y=c.y) IN
(1,4,5,6,7,8));
-- insert the ones that are born
INSERT INTO alive a
SELECT x,y FROM counts c
WHERE c.n=3 AND
((c.x,c.y) NOT IN (SELECT x,y FROM alive));
commit;
-- create output table
DROP TABLE output;
CREATE TABLE output AS
SELECT rownum y,' ' x1,' ' x2,' ' x3
FROM dba_tables WHERE rownum < 4;
UPDATE output SET x1='*'
WHERE (1,y) IN
(SELECT x,y FROM alive);
UPDATE output SET x2='*'
WHERE (2,y) IN
(SELECT x,y FROM alive);
UPDATE output SET x3='*'
WHERE (3,y) IN
(SELECT x,y FROM alive);
commit
-- output configuration
SELECT x1||x2||x3 WLD
FROM output
ORDER BY y DESC;
|
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #ARM_Assembly | ARM Assembly | .org 0x08000000 ;cartridge ROM begins here
b ProgramStart ;branch around the cartridge header
;;;; cartridge header goes here
.equ SCREEN_WIDTH,240 ;some labels for convenience
.equ SCREEN_HEIGHT,160
ProgramStart:
mov sp,#0x03000000 ;set up stack pointer (we won't be using it but it's a good practice to do so anyway
mov r4,#0x04000000 ;DISPCNT (LCD Control Register)
mov r2,#0x403 ;4= Layer 2 on / 3= ScreenMode 3 (Bitmap Graphics, vram at 0x06000000)
str r2,[r4] ;now the screen is visible.
mov r0,#0x06000000 ;VRAM BASE (2 BYTES PER PIXEL)
mov r1,#0 ;COLOR TO STORE (INIT TO ZERO, WILL GET FILLED IN LATER)
adr r4,palArray ;get address of palette
mov r5,#0 ;index into palArray
mov r6,#19200 ;this is one quarter of the screen
add r7,r0,r6 ;MOV R7, #0x06004B00
add r8,r7,r6 ;MOV R8, #0x06009600
add r9,r8,r6 ;MOV R9, #0x0600E100
add r10,r9,r6 ;MOV R10,#0x06012C00
loop_pinstripe_firstQuarter:
ldrH r1,[r4,r5]
strH r1,[r0],#2 ;store into video memory and post-inc by 2.
add r5,r5,#2 ;next color in palette
and r5,r5,#0x0F ;prevents indexing out of bounds
cmp r0,r7 ;have we reached the end of this quarter of the screen?
blt loop_pinstripe_firstQuarter ;if not, keep drawing
loop_pinstripe_secondQuarter:
ldrH r1,[r4,r5]
strH r1,[r0],#2 ;post-inc by 2 after the store
strH r1,[r0],#2 ;post-inc by 2 after the store
add r5,r5,#2
and r5,r5,#0x0F
cmp r0,r8
blt loop_pinstripe_secondQuarter
loop_pinstripe_thirdQuarter:
ldrH r1,[r4,r5]
strH r1,[r0],#2 ;post-inc by 2 after the store
strH r1,[r0],#2
strH r1,[r0],#2
add r5,r5,#2
and r5,r5,#0x0F
cmp r0,r9
blt loop_pinstripe_thirdQuarter
; the last quarter works differently. We'll need to use a different
; loop counter to get the last pinstripe
mov r2,#SCREEN_WIDTH/4 ;inner loop counter
mov r3,#48 ;outer loop counter
loop_pinstripe_lastQuarter:
ldrH r1,[r4,r5]
strH r1,[r0],#2
strH r1,[r0],#2
strH r1,[r0],#2
strH r1,[r0],#2
add r5,r5,#2
and r5,r5,#0x0F
subs r2,r2,#1
bne loop_pinstripe_lastQuarter
mov r5,#0 ;reset the palette pointer
mov r2,#SCREEN_WIDTH/4 ;reset the inner loop counter
subs r3,r3,#1 ;decrement the outer loop counter
bne loop_pinstripe_lastQuarter ;if we're not done, keep going
forever:
b forever ;end of program
palArray: ;GAME BOY ADVANCE USES 15-BIT COLOR. WE WON'T USE THE TOP BIT.
.word 0x0000 ;black
.word 0b0000000000011111 ;red
.word 0b0000001111100000 ;green
.word 0b0111110000000000 ;blue
.word 0b0111110000011111 ;magenta
.word 0b0111111111100000 ;cyan
.word 0b0000001111111111 ;yellow
.word 0x7FFF ;white |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #C.23 | C# | using System;
using System.Drawing;
using System.Windows.Forms;
class Program
{
static Color GetPixel(Point position)
{
using (var bitmap = new Bitmap(1, 1))
{
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(position, new Point(0, 0), new Size(1, 1));
}
return bitmap.GetPixel(0, 0);
}
}
static void Main()
{
Console.WriteLine(GetPixel(Cursor.Position));
}
} |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #C.2B.2B.2FCLI | C++/CLI | using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
[STAThreadAttribute]
int main()
{
Point^ MousePoint = gcnew Point();
Control^ TempControl = gcnew Control();
MousePoint = TempControl->MousePosition;
Bitmap^ TempBitmap = gcnew Bitmap(1,1);
Graphics^ g = Graphics::FromImage(TempBitmap);
g->CopyFromScreen((Point)MousePoint, Point(0, 0), Size(1, 1));
Color color = TempBitmap->GetPixel(0,0);
Console::WriteLine("R: "+color.R.ToString());
Console::WriteLine("G: "+color.G.ToString());
Console::WriteLine("B: "+color.B.ToString());
} |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #FreeBASIC | FreeBASIC | #include "fbgfx.bi"
Sub HSVtoRGB(h As Single, s As Integer, v As Integer, Byref r As Integer, Byref g As Integer, Byref b As Integer)
If s = 0 Then
r = v
g = v
b = v
Return
End If
h = h Mod 360
Dim As Single hue = h
Select Case h
Case 0f To 51.5f
hue = ((hue ) * (30f / (51.5f )))
Case 51.5f To 122f
hue = ((hue - 51.5f) * (30f / (122f - 51.5f))) + 30
Case 122f To 142.5f
hue = ((hue - 122f) * (30f / (142.5f - 122f))) + 60
Case 142.5f To 165.5f
hue = ((hue - 142.5f) * (30f / (165.5f - 142.5f))) + 90
Case 165.5f To 192f
hue = ((hue - 165.5f) * (30f / (192f - 165.5f))) + 120
Case 192f To 218.5f
hue = ((hue - 192f) * (30f / (218.5f - 192f))) + 150
Case 218.5f To 247f
hue = ((hue - 218.5f) * (30f / (247f - 218.5f))) + 180
Case 247f To 275.5f
hue = ((hue - 247f) * (30f / (275.5f - 247f))) + 210
Case 275.5f To 302.5f
hue = ((hue - 275.5f) * (30f / (302.5f - 275.5f))) + 240
Case 302.5f To 330f
hue = ((hue - 302.5f) * (30f / (330f - 302.5f))) + 270
Case 330f To 344.5f
hue = ((hue - 330f) * (30f / (344.5f - 330f))) + 300
Case 344.5f To 360f
hue = ((hue - 344.5f) * (30f / (360f - 344.5f))) + 330
End Select
h = hue
h = h Mod 360
Dim As Single h1 = h / 60
Dim As Integer i = Int(h1)
Dim As Single f = h1 - i
Dim As Integer p = v * (255 - s) / 256
Dim As Integer q = v * (255 - f * s) / 256
Dim As Integer t = v * (255 - (1 - f) * s) / 256
Select Case As Const i
Case 0
r = v
g = t
b = p
Return
Case 1
r = q
g = v
b = p
Return
Case 2
r = p
g = v
b = t
Return
Case 3
r = p
g = q
b = v
Return
Case 4
r = t
g = p
b = v
Return
Case 5
r = v
g = p
b = q
Return
End Select
End Sub
Const pi As Single = 4 * Atn(1)
Const radius = 160
Const xres = (radius * 2) + 1, yres = xres
Screenres xres, yres, 32
Windowtitle "Color wheel"
Dim As Integer r,g,b
Dim As Single dx, dy, dist, angle
Do
Screenlock
Cls
For x As Integer = 0 To (radius * 2) - 1
For y As Integer = 0 To (radius * 2) - 1
dx = x - radius
dy = radius - y
dist = Sqr(dx * dx + dy * dy)
If dist < radius Then
angle = Atan2(dy, dx) * (180/pi)
If angle < 0 Then angle += 360
If angle > 360 Then angle -= 360
HSVtoRGB(angle, (dist / radius) * 255, 255, r, g, b)
Pset(x, y), Rgb(r, g, b)
End If
Next y
Next x
Screenunlock
Loop Until Inkey = Chr(27) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #LSE | LSE | SI A ET B ALORS
AFFICHER [4X, 'A ET B = .VRAI.',/]
SINON
AFFICHER [4X, 'A ET B = .FAUX.',/]
FIN SI
SI A ET QUE B ALORS
AFFICHER [4X, 'A ET QUE B = .VRAI.',/]
SINON
AFFICHER [4X, 'A ET QUE B = .FAUX.',/]
FIN SI |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Neko | Neko | // Single line comment, of course!
/*
Multi line comment!
*/
/**
Documentation block
<doc>can include XML parsed nodes between doc tags</doc>
**/ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Nemerle | Nemerle | // This comment goes up to the end of the line
/* This
is
a
multiline
comment */ |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Swift | Swift | struct Cell: Hashable {
var x: Int
var y: Int
}
struct Colony {
private var height: Int
private var width: Int
private var cells: Set<Cell>
init(cells: Set<Cell>, height: Int, width: Int) {
self.cells = cells
self.height = height
self.width = width
}
private func neighborCounts() -> [Cell: Int] {
var counts = [Cell: Int]()
for cell in cells.flatMap(Colony.neighbors(for:)) {
counts[cell, default: 0] += 1
}
return counts
}
private static func neighbors(for cell: Cell) -> [Cell] {
return [
Cell(x: cell.x - 1, y: cell.y - 1),
Cell(x: cell.x, y: cell.y - 1),
Cell(x: cell.x + 1, y: cell.y - 1),
Cell(x: cell.x - 1, y: cell.y),
Cell(x: cell.x + 1, y: cell.y),
Cell(x: cell.x - 1, y: cell.y + 1),
Cell(x: cell.x, y: cell.y + 1),
Cell(x: cell.x + 1, y: cell.y + 1),
]
}
func printColony() {
for y in 0..<height {
for x in 0..<width {
let char = cells.contains(Cell(x: x, y: y)) ? "0" : "."
print("\(char) ", terminator: "")
}
print()
}
}
mutating func run(iterations: Int) {
print("(0)")
printColony()
print()
for i in 1...iterations {
print("(\(i))")
runGeneration()
printColony()
print()
}
}
private mutating func runGeneration() {
cells = Set(neighborCounts().compactMap({keyValue in
switch (keyValue.value, cells.contains(keyValue.key)) {
case (2, true), (3, _):
return keyValue.key
case _:
return nil
}
}))
}
}
let blinker = [Cell(x: 1, y: 0), Cell(x: 1, y: 1), Cell(x: 1, y: 2)] as Set
var col = Colony(cells: blinker, height: 3, width: 3)
print("Blinker: ")
col.run(iterations: 3)
let glider = [
Cell(x: 1, y: 0),
Cell(x: 2, y: 1),
Cell(x: 0, y: 2),
Cell(x: 1, y: 2),
Cell(x: 2, y: 2)
] as Set
col = Colony(cells: glider, height: 8, width: 8)
print("Glider: ")
col.run(iterations: 20) |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #AutoHotkey | AutoHotkey | h := A_ScreenHeight
w := A_ScreenWidth
pToken := gdip_Startup()
hdc := CreateCompatibleDC()
hbm := CreateDIBSection(w, h)
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
OnExit, Exit
Gui -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui Show, NA
hwnd := WinExist()
colors := [0xFF000000, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF
, 0xFFFF00FF, 0xFF00FFFF, 0xFFFFFF00, 0xFFFFFFFF] ; ARGB
pBrush := []
Loop % colors.MaxIndex()
pBrush[A_Index] := Gdip_BrushCreateSolid(colors[A_Index])
Loop 4
{
n := A_Index
Loop % w
Gdip_FillRectangle(G, pBrush[Mod(A_Index-1, colors.MaxIndex())+1]
, A_Index*n-n, (n-1)*h/4, n, h/4)
}
UpdateLayeredWindow(hwnd, hdc, 0, 0, W, H)
Loop % colors.MaxIndex()
Gdip_DeleteBrush(pBrush[A_Index])
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
Return
Esc::
Exit:
Gdip_Shutdown(pToken)
ExitApp |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Clojure | Clojure | (defn get-color-at [x y]
(.getPixelColor (java.awt.Robot.) x y)) |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Common_Lisp | Common Lisp | (in-package :cg-user)
(defun print-hex (n)
(let ((*print-base* 16.) (*print-radix* t))
(print n)) t)
(defun get-byte (n byte)
(logand (ash n (* byte -8)) #xFF))
(defun get-pixel (x y)
(let ((pixval (caar (contents (get-screen-pixmap :box (make-box x y (+ x 1) (+ y 1)))))))
(mapcar #'(lambda (i) (get-byte pixval i)) '(2 1 0 3))))
(defun get-mouse-pixel ()
(let ((pos (cursor-position (screen *system*))))
(get-pixel (position-x pos) (position-y pos))))
(print-hex (get-mouse-pixel)) |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #GML | GML |
for (var i = 1; i <= 360; i++) {
for (var j = 0; j < 255; j++) {
var hue = 255*(i/360);
var saturation = j;
var value = 255;
var c = make_colour_hsv(hue,saturation,value);
//size of circle determined by how far from the center it is
//if you just draw them too small the circle won't be full.
//it will have patches inside it that didn't get filled in with color
var r = max(1,3*(j/255));
//Math for built-in GMS functions
//lengthdir_x(len,dir) = +cos(degtorad(direction))*length;
//lengthdir_y(len,dir) = -sin(degtorad(direction))*length;
draw_circle_colour(x+lengthdir_x(m_radius*(j/255),i),y+lengthdir_y(m_radius*(j/255),i),r,c,c,false);
}
}
|
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"math"
)
const tau = 2 * math.Pi
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func colorWheel(dc *gg.Context) {
width, height := dc.Width(), dc.Height()
centerX, centerY := width/2, height/2
radius := centerX
if centerY < radius {
radius = centerY
}
for y := 0; y < height; y++ {
dy := float64(y - centerY)
for x := 0; x < width; x++ {
dx := float64(x - centerX)
dist := math.Sqrt(dx*dx + dy*dy)
if dist <= float64(radius) {
theta := math.Atan2(dy, dx)
hue := (theta + math.Pi) / tau
r, g, b := hsb2rgb(hue, 1, 1)
dc.SetRGB255(r, g, b)
dc.SetPixel(x, y)
}
}
}
}
func main() {
const width, height = 480, 480
dc := gg.NewContext(width, height)
dc.SetRGB(1, 1, 1) // set background color to white
dc.Clear()
colorWheel(dc)
dc.SavePNG("color_wheel.png")
} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #LSE64 | LSE64 | t : " true" ,t
f : " false" ,t
true if t
false ifnot f
true ifelse t f |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #NESL | NESL | % This is a comment. % |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #NetRexx | NetRexx | /*
NetRexx comment block
*/
-- NetRexx line comment
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #SystemVerilog | SystemVerilog | module gol;
parameter NUM_ROWS = 20;
parameter NUM_COLS = 32;
bit [NUM_COLS:1] cell[1:NUM_ROWS];
bit clk;
initial begin
cell[10][10:8] = 3'b111;
cell[11][10:8] = 3'b100;
cell[12][10:8] = 3'b010;
repeat(8) #5 clk = ~clk;
end
always @(posedge clk) begin
foreach (cell[y,x]) begin
automatic int count = $countones({ cell[y-1][x-1+:3], cell[y][x-1], cell[y][x+1], cell[y+1][x-1+:3] });
if (count == 3) cell[y][x] <= 1'b1;
else if (count != 2) cell[y][x] <= 1'b0;
end
end
always @(negedge clk) begin
$display("--");
foreach (cell[y]) $display( " %b", cell[y] );
end
endmodule |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #BASIC256 | BASIC256 | w = 640 : h = 480
graphsize w, h
dim k = {black, red, green, blue, purple, cyan, yellow, white}
h /= 4
for i = 1 to 4
col = 0
y = (i-1) * h
for x = 1 to w step i
if col mod 8 = 0 then col = 0
colour k[col]
rect (x, y, x + i, y + h)
col += 1
next x
next i |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #BBC_BASIC | BBC BASIC | SW_MAXIMIZE = 3
SYS "ShowWindow", @hwnd%, SW_MAXIMIZE
VDU 26
W% = @vdu%!208 * 2
H% = @vdu%!212 / 2
COLOUR 1,9
COLOUR 2,10
COLOUR 3,12
COLOUR 4,13
COLOUR 5,14
COLOUR 6,11
COLOUR 7,15
Y% = H%*4
FOR P% = 1 TO 4
Y% -= H%
FOR X% = 0 TO W% STEP 4*P%
C% = (C% + 1) MOD 8
GCOL C%
RECTANGLE FILL X%, Y%, 2*P%, H%
NEXT
NEXT P%
|
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Befunge | Befunge | "%":*3-"`"8*>4/::8%00p8/10p4*\55+"3P",,,:.\.5v
5+:,1vv\%2:%8/-g025:\-1_$$55+,\:v1+*8g01g00_@>
024,.<>2/:2%\2/...1+\:>^<:\0:\-1_$20g1-:20p^1p |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Delphi | Delphi |
program ScreenPixel;
{$APPTYPE CONSOLE}
uses
Windows,
SysUtils,
Graphics;
// Use this function in a GUI application to return the color
function GetPixelColourAsColor(const PixelCoords: TPoint): TColor;
var
dc: HDC;
begin
// Get Device Context of windows desktop
dc := GetDC(0);
// Read the color of the pixel at the given coordinates
Result := GetPixel(dc,PixelCoords.X,PixelCoords.Y);
end;
// Use this function to get a string representation of the current colour
function GetPixelColourAsString(const PixelCoords: TPoint): string;
var
r,g,b: Byte;
col: TColor;
begin
col := GetPixelColourAsColor(PixelCoords);
// Convert the Delphi TColor value to it's RGB components
r := col and $FF;
g := (col shr 8) and $FF;
b := (col shr 16) and $FF;
// Format the result
Result := 'R('+IntToStr(r)+') G('+IntToStr(g)+') G('+IntToStr(b)+')';
{
Alternatively, format the result as follows to get a
string representation of the Delphi TColor value
Result := ColorToString(GetPixel(dc,curP.X,curP.Y));
}
end;
var
s: string;
P: TPoint;
begin
s := '';
Writeln('Move mouse over a pixel. Hit return to get colour of selected pixel.');
repeat
Readln(s);
if s = '' then
begin
GetCursorPos(P);
Writeln('Colour at cursor position X:'+
IntToStr(P.X)+' Y:'+
IntToStr(P.Y) +' = '+
GetPixelColourAsString(P)
);
Writeln('');
Writeln('Move mouse and hit enter again.');
end;
until
SameText(s,'quit');
end.
|
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #J | J | rgbc=: {{1-x*0>.1<.(<.4&-)6|m+y%60}}
hsv=: 5 rgbc(,"0 1) 3 rgbc(,"0) 1 rgbc
degrees=: {{180p_1*{:"1+.^.y}}
wheel=: {{((1>:|)*|hsv degrees)j./~y%~i:y}}
require'viewmat'
'rgb' viewmat 256#.<.255*wheel 400 |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Java | Java | import java.awt.*;
import javax.swing.*;
public class ColorWheel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ColorWheelFrame frame = new ColorWheelFrame();
frame.setVisible(true);
}
});
}
private static class ColorWheelFrame extends JFrame {
private ColorWheelFrame() {
super("Color Wheel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ColorWheelPanel());
pack();
}
}
private static class ColorWheelPanel extends JComponent {
private ColorWheelPanel() {
setPreferredSize(new Dimension(400, 400));
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
int margin = 10;
int radius = (Math.min(w, h) - 2 * margin)/2;
int cx = w/2;
int cy = h/2;
float[] dist = {0.F, 1.0F};
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, w, h);
for (int angle = 0; angle < 360; ++angle) {
Color color = hsvToRgb(angle, 1.0, 1.0);
Color[] colors = {Color.WHITE, color};
RadialGradientPaint paint = new RadialGradientPaint(cx, cy,
radius, dist, colors);
g2.setPaint(paint);
g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,
angle, 1);
}
}
}
private static Color hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - Math.abs(hp % 2.0 - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
} |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #11l | 11l | F comb(arr, k)
I k == 0
R [[Int]()]
[[Int]] result
L(x) arr
V i = L.index
L(suffix) comb(arr[i+1..], k-1)
result [+]= x [+] suffix
R result
print(comb([0, 1, 2, 3, 4], 3)) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Lua | Lua |
--if-then-elseif-then-else
if a then
b()
elseif c then
d()
else
e()
end
for var = start, _end, step do --note: end is a reserved word
something()
end
for var, var2, etc in iteratorfunction do
something()
end
while somethingistrue() do
something()
end
repeat
something()
until somethingistrue()
cases = {
key1 = dothis,
key2 = dothat,
key3 = dotheother
}
cases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #NewLISP | NewLISP | ; This is a comment |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Nim | Nim | # Nim supports single-line comments
var x = 0 ## Documentation comments start with double hash characters.
var y = 0 ## Documentation comments are a proper part of the syntax (they're not discarded by parser, and a real part of AST).
#[
There are also multi-line comments
Everything inside of #[]# is commented.
]#
# You can also discard multiline statements:
discard """This can be considered as a "comment" too
This is multi-line"""
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Tcl | Tcl | package require Tcl 8.5
proc main {} {
evolve 3 blinker [initialize_tableau {3 3} {{0 1} {1 1} {2 1}}]
evolve 5 glider [initialize_tableau {4 4} {{0 1} {1 2} {2 0} {2 1} {2 2}}]
}
proc evolve {generations name tableau} {
for {set gen 1} {$gen <= $generations} {incr gen} {
puts "$name generation $gen:"
print $tableau
set tableau [next_generation $tableau]
}
puts ""
}
proc initialize_tableau {size initial_life} {
lassign $size ::max_x ::max_y
set tableau [blank_tableau]
foreach point $initial_life {
lset tableau {*}$point 1
}
return $tableau
}
proc blank_tableau {} {
return [lrepeat $::max_x [lrepeat $::max_y 0]]
}
proc print {tableau} {
foreach row $tableau {puts [string map {0 . 1 #} [join $row]]}
}
proc next_generation {tableau} {
set new [blank_tableau]
for {set x 0} {$x < $::max_x} {incr x} {
for {set y 0} {$y < $::max_y} {incr y} {
lset new $x $y [fate [list $x $y] $tableau]
}
}
return $new
}
proc fate {point tableau} {
set current [value $point $tableau]
set neighbours [sum_neighbours $point $tableau]
return [expr {($neighbours == 3) || ($neighbours == 2 && $current == 1)}]
}
proc value {point tableau} {
return [lindex $tableau {*}$point]
}
proc sum_neighbours {point tableau} {
set sum 0
foreach neighbour [get_neighbours $point] {
incr sum [value $neighbour $tableau]
}
return $sum
}
proc get_neighbours {point} {
lassign $point x y
set results [list]
foreach x_off {-1 0 1} {
foreach y_off {-1 0 1} {
if { ! ($x_off == 0 && $y_off == 0)} {
set i [expr {$x + $x_off}]
set j [expr {$y + $y_off}]
if {(0 <= $i && $i < $::max_x) && (0 <= $j && $j < $::max_y)} {
lappend results [list $i $j]
}
}
}
}
return $results
}
main |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #C | C |
#include<graphics.h>
#include<conio.h>
#define sections 4
int main()
{
int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;
initgraph(&d,&m,"c:/turboc3/bgi");
maxX = getmaxx();
maxY = getmaxy();
for(y=0;y<maxY;y+=maxY/sections)
{
for(x=0;x<maxX;x+=increment)
{
setfillstyle(SOLID_FILL,(colour++)%16);
bar(x,y,x+increment,y+maxY/sections);
}
increment++;
colour = 0;
}
getch();
closegraph();
return 0;
}
|
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #C.2B.2B | C++ |
#include <windows.h>
//--------------------------------------------------------------------------------------------------
class pinstripe
{
public:
pinstripe() { createColors(); }
void setDimensions( int x, int y ) { _mw = x; _mh = y; }
void createColors()
{
colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );
colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 );
colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 );
colors[7] = RGB( 255, 255, 255 );
}
void draw( HDC dc )
{
HPEN pen;
int lh = _mh / 4, row, cp;
for( int lw = 1; lw < 5; lw++ )
{
cp = 0;
row = ( lw - 1 ) * lh;
for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )
{
pen = CreatePen( PS_SOLID, lw, colors[cp] );
++cp %= 8;
SelectObject( dc, pen );
MoveToEx( dc, x, row, NULL );
LineTo( dc, x, row + lh );
DeleteObject( pen );
}
}
}
private:
int _mw, _mh;
DWORD colors[8];
};
//--------------------------------------------------------------------------------------------------
pinstripe pin;
//--------------------------------------------------------------------------------------------------
void PaintWnd( HWND hWnd )
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint( hWnd, &ps );
pin.draw( hdc );
EndPaint( hWnd, &ps );
}
//--------------------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_PAINT: PaintWnd( hWnd ); break;
default:
return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
//--------------------------------------------------------------------------------------------------
HWND InitAll( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_CLR_PS_";
RegisterClassEx( &wcex );
return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );
}
//--------------------------------------------------------------------------------------------------
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
srand( GetTickCount() );
HWND hwnd = InitAll( hInstance );
if( !hwnd ) return -1;
int mw = GetSystemMetrics( SM_CXSCREEN ),
mh = GetSystemMetrics( SM_CYSCREEN );
pin.setDimensions( mw, mh );
RECT rc = { 0, 0, mw, mh };
AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );
int w = rc.right - rc.left,
h = rc.bottom - rc.top;
int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),
posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );
SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );
ShowWindow( hwnd, nCmdShow );
UpdateWindow( hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_CLR_PS_", hInstance );
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #F.23 | F# | open System.Drawing
open System.Windows.Forms
let GetPixel x y =
use img = new Bitmap(1,1)
use g = Graphics.FromImage(img)
g.CopyFromScreen(new Point(x,y), new Point(0,0), new Size(1,1))
let clr = img.GetPixel(0,0)
(clr.R, clr.G, clr.B)
let GetPixelAtMouse () =
let pt = Cursor.Position
GetPixel pt.X pt.Y |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Go | Go | package main
import (
"fmt"
"github.com/go-vgo/robotgo"
)
func main() {
// get position of mouse cursor
x, y := robotgo.GetMousePos()
// get color of pixel at that position
color := robotgo.GetPixelColor(x, y)
fmt.Printf("Color of pixel at (%d, %d) is 0x%s\n", x, y, color)
} |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Julia | Julia | using Gtk, Graphics, Colors
const win = GtkWindow("Color Wheel", 450, 450) |> (const can = @GtkCanvas())
set_gtk_property!(can, :expand, true)
@guarded draw(can) do widget
ctx = getgc(can)
h = height(can)
w = width(can)
center = (x = w / 2, y = h / 2)
anglestep = 1/w
for θ in 0:0.1:360
rgb = RGB(HSV(θ, 1, 1))
set_source_rgb(ctx, rgb.r, rgb.g, rgb.b)
line_to(ctx, center...)
arc(ctx, center.x, center.y, w/2.2, 2π * θ / 360, anglestep)
line_to(ctx, center...)
stroke(ctx)
end
end
show(can)
const condition = Condition()
endit(w) = notify(condition)
signal_connect(endit, win, :destroy)
wait(condition)
|
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Kotlin | Kotlin | // Version 1.2.41
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.math.*
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
fun colorWheel() {
val centerX = image.width / 2
val centerY = image.height / 2
val radius = minOf(centerX, centerY)
for (y in 0 until image.height) {
val dy = (y - centerY).toDouble()
for (x in 0 until image.width) {
val dx = (x - centerX).toDouble()
val dist = sqrt(dx * dx + dy * dy)
if (dist <= radius) {
val theta = atan2(dy, dx)
val hue = (theta + PI) / (2.0 * PI)
val rgb = Color.HSBtoRGB(hue.toFloat(), 1.0f, 1.0f)
setPixel(x, y, Color(rgb))
}
}
}
}
}
fun main(args: Array<String>) {
val bbs = BasicBitmapStorage(480, 480)
with (bbs) {
fill(Color.white)
colorWheel()
val cwFile = File("Color_wheel.png")
ImageIO.write(image, "png", cwFile)
}
}
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #360_Assembly | 360 Assembly | * Combinations 26/05/2016
COMBINE CSECT
USING COMBINE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
SR R3,R3 clear
LA R7,C @c(1)
LH R8,N v=n
LOOPI1 STC R8,0(R7) do i=1 to n; c(i)=n-i+1
LA R7,1(R7) @c(i)++
BCT R8,LOOPI1 next i
LOOPBIG LA R10,PG big loop {------------------
LH R1,N n
LA R7,C-1(R1) @c(i)
LH R6,N i=n
LOOPI2 IC R3,0(R7) do i=n to 1 by -1; r2=c(i)
XDECO R3,PG+80 edit c(i)
MVC 0(2,R10),PG+90 output c(i)
LA R10,3(R10) @pgi=@pgi+3
BCTR R7,0 @c(i)--
BCT R6,LOOPI2 next i
XPRNT PG,80 print buffer
LA R7,C @c(1)
LH R8,M v=m
LA R6,1 i=1
LOOPI3 LR R1,R6 do i=1 by 1; r1=i
IC R3,0(R7) c(i)
CR R3,R8 while c(i)>=m-i+1
BL ELOOPI3 leave i
CH R6,N if i>=n
BNL ELOOPBIG exit loop
BCTR R8,0 v=v-1
LA R7,1(R7) @c(i)++
LA R6,1(R6) i=i+1
B LOOPI3 next i
ELOOPI3 LR R1,R6 i
LA R4,C-1(R1) @c(i)
IC R3,0(R4) c(i)
LA R3,1(R3) c(i)+1
STC R3,0(R4) c(i)=c(i)+1
BCTR R7,0 @c(i)--
LOOPI4 CH R6,=H'2' do i=i to 2 by -1
BL ELOOPI4 leave i
IC R3,1(R7) c(i)
LA R3,1(R3) c(i)+1
STC R3,0(R7) c(i-1)=c(i)+1
BCTR R7,0 @c(i)--
BCTR R6,0 i=i-1
B LOOPI4 next i
ELOOPI4 B LOOPBIG big loop }------------------
ELOOPBIG L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
M DC H'5' <=input
N DC H'3' <=input
C DS 64X array of 8 bit integers
PG DC CL92' ' buffer
YREGS
END COMBINE |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Luna | Luna | if char == "<" then Prepend "<" acc else acc |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Nix | Nix | # This comment goes up to the end of the line
/* This
is
a
multiline
comment */ |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #NSIS | NSIS |
# This is a comment that goes from the # to the end of the line.
; This is a comment that goes from the ; to the end of the
/* This is a
multi-line
comment */
|
http://rosettacode.org/wiki/Color_quantization | Color quantization | full color
Example: Gimp 16 color
Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.
Task: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should not use a fixed palette such as Web colors or Windows system palette. Dithering is not required.
Note: the funny color bar on top of the frog image is intentional.
| #C | C | typedef struct oct_node_t oct_node_t, *oct_node;
struct oct_node_t{
/* sum of all colors represented by this node. 64 bit in case of HUGE image */
uint64_t r, g, b;
int count, heap_idx;
oct_node kids[8], parent;
unsigned char n_kids, kid_idx, flags, depth;
};
/* cmp function that decides the ordering in the heap. This is how we determine
which octree node to fold next, the heart of the algorithm. */
inline int cmp_node(oct_node a, oct_node b)
{
if (a->n_kids < b->n_kids) return -1;
if (a->n_kids > b->n_kids) return 1;
int ac = a->count * (1 + a->kid_idx) >> a->depth;
int bc = b->count * (1 + b->kid_idx) >> b->depth;
return ac < bc ? -1 : ac > bc;
}
/* adding a color triple to octree */
oct_node node_insert(oct_node root, unsigned char *pix)
{
# define OCT_DEPTH 8
/* 8: number of significant bits used for tree. It's probably good enough
for most images to use a value of 5. This affects how many nodes eventually
end up in the tree and heap, thus smaller values helps with both speed
and memory. */
unsigned char i, bit, depth = 0;
for (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) {
i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);
if (!root->kids[i])
root->kids[i] = node_new(i, depth, root);
root = root->kids[i];
}
root->r += pix[0];
root->g += pix[1];
root->b += pix[2];
root->count++;
return root;
}
/* remove a node in octree and add its count and colors to parent node. */
oct_node node_fold(oct_node p)
{
if (p->n_kids) abort();
oct_node q = p->parent;
q->count += p->count;
q->r += p->r;
q->g += p->g;
q->b += p->b;
q->n_kids --;
q->kids[p->kid_idx] = 0;
return q;
}
/* traverse the octree just like construction, but this time we replace the pixel
color with color stored in the tree node */
void color_replace(oct_node root, unsigned char *pix)
{
unsigned char i, bit;
for (bit = 1 << 7; bit; bit >>= 1) {
i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);
if (!root->kids[i]) break;
root = root->kids[i];
}
pix[0] = root->r;
pix[1] = root->g;
pix[2] = root->b;
}
/* Building an octree and keep leaf nodes in a bin heap. Afterwards remove first node
in heap and fold it into its parent node (which may now be added to heap), until heap
contains required number of colors. */
void color_quant(image im, int n_colors)
{
int i;
unsigned char *pix = im->pix;
node_heap heap = { 0, 0, 0 };
oct_node root = node_new(0, 0, 0), got;
for (i = 0; i < im->w * im->h; i++, pix += 3)
heap_add(&heap, node_insert(root, pix));
while (heap.n > n_colors + 1)
heap_add(&heap, node_fold(pop_heap(&heap)));
double c;
for (i = 1; i < heap.n; i++) {
got = heap.buf[i];
c = got->count;
got->r = got->r / c + .5;
got->g = got->g / c + .5;
got->b = got->b / c + .5;
printf("%2d | %3llu %3llu %3llu (%d pixels)\n",
i, got->r, got->g, got->b, got->count);
}
for (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3)
color_replace(root, pix);
node_free();
free(heap.buf);
} |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Ursala | Ursala | #import std
#import nat
rule = -: ^(~&,~&l?(~&r-={2,3},~&r-={3})^|/~& length@F)* pad0 iota512
neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*
evolve "n" = next"n" rule**+ neighborhoods |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Common_Lisp | Common Lisp | (in-package :cg-user)
;;; We only need a bitmap pane - nothing fancy
(defclass draw-pane (bitmap-pane)())
;;; close it down by clicking on it
(defmethod mouse-left-down ((pane draw-pane) buttons data)
(declare (ignore buttons data))
(close pane))
;;; Create the window and draw the pinstripes
(defun make-draw-window ()
(let ((win (make-window :one :class 'draw-pane :width 300 :height 200)))
(draw win)))
;;; Function to draw the pinstripes. The lines are a bit ragged at the intersections
;;; between pinstripe sections due to the fact that common graphics uses round line
;;; caps and there doesn't appear any way to change that. Could be fixed by using
;;; rectangles rather than lines or, perhaps, by setting rectangular clipping regions.
(defun draw (win)
(do ((lwidth 1 (+ 1 lwidth))
(top 0 bottom)
(colors (make-array 8 :initial-contents
'(black red green blue magenta cyan yellow white)))
(bottom (/ (height win) 4) (+ (/ (height win) 4) bottom)))
((eql 5 lwidth) t)
(with-line-width (win lwidth)
(do ((xpos 0 (+ xpos lwidth))
(clr-ndx 0 (mod (+ clr-ndx 1) 8)))
((> xpos (width win)) t)
(with-foreground-color (win (aref colors clr-ndx))
(draw-line win
(make-position xpos top)
(make-position xpos bottom))))))) |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Groovy | Groovy | import java.awt.Robot
class GetPixelColor {
static void main(args) {
println getColorAt(args[0] as Integer, args[1] as Integer)
}
static getColorAt(x, y) {
new Robot().getPixelColor(x, y)
}
}
|
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Icon_and_Unicon | Icon and Unicon | link graphics,printf
procedure main()
WOpen("canvas=hidden") # hide for query
height := WAttrib("displayheight") - 45 # adjust for ...
width := WAttrib("displaywidth") - 20 # ... window 7 borders
WClose(&window)
W := WOpen("size="||width||","||height,"bg=black") |
stop("Unable to open window")
every 1 to 10 do { # generate some random rectangles within the frame
x := ?width
y := ?(height-100)
WAttrib("fg="||?["red","green","blue","purple","yellow"])
FillRectangle(x,x+50,y,y+50)
}
while Event() do
printf("x=%d,y=%d pixel=%s\n",&x,&y,Pixel(&x,&y,&x,&y))
WDone(W) # q to exit
end
|
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Lua | Lua |
local function hsv_to_rgb (h, s, v) -- values in ranges: [0, 360], [0, 1], [0, 1]
local r = math.min (math.max (3*math.abs (((h )/180)%2-1)-1, 0), 1)
local g = math.min (math.max (3*math.abs (((h -120)/180)%2-1)-1, 0), 1)
local b = math.min (math.max (3*math.abs (((h +120)/180)%2-1)-1, 0), 1)
local k1 = v*(1-s)
local k2 = v - k1
return k1+k2*r, k1+k2*g, k1+k2*b -- values in ranges: [0, 1], [0, 1], [0, 1]
end
function love.load()
local w, h, r = 256, 256, 128-0.5
local cx, cy = w/2, h/2
canvas = love.graphics.newCanvas ()
love.graphics.setCanvas(canvas)
for x = 0, w do
for y = 0, h do
local dx, dy = x-cx, y-cy
if dx*dx + dy*dy <= r*r then
local h = math.deg(math.atan2(dy, dx))
local s = (dx*dx + dy*dy)^0.5/r
local v = 1
love.graphics.setColor (hsv_to_rgb (h, s, v))
love.graphics.points (x, y)
end
end
end
love.graphics.setCanvas()
end
function love.draw()
love.graphics.setColor (1,1,1)
love.graphics.draw (canvas)
end
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Action.21 | Action! | PROC PrintComb(BYTE ARRAY c BYTE len)
BYTE i
Put('()
FOR i=0 TO len-1
DO
IF i>0 THEN Put(',) FI
PrintB(c(i))
OD
Put(')) PutE()
RETURN
BYTE FUNC Increasing(BYTE ARRAY c BYTE len)
BYTE i
IF len<2 THEN RETURN (1) FI
FOR i=0 TO len-2
DO
IF c(i)>=c(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
BYTE FUNC NextComb(BYTE ARRAY c BYTE n,k)
INT pos,i
DO
pos=k-1
DO
c(pos)==+1
IF c(pos)<n THEN
EXIT
ELSE
pos==-1
IF pos<0 THEN RETURN (0) FI
FI
FOR i=pos+1 TO k-1
DO
c(i)=c(pos)
OD
OD
UNTIL Increasing(c,k)
OD
RETURN (1)
PROC Comb(BYTE n,k)
BYTE ARRAY c(10)
BYTE i
IF k>n THEN
Print("Error! k is greater than n.")
Break()
FI
FOR i=0 TO k-1
DO
c(i)=i
OD
DO
PrintComb(c,k)
UNTIL NextComb(c,n,k)=0
OD
RETURN
PROC Main()
Comb(5,3)
RETURN |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Read a
If a>1 then {
Print "Top"
} else.if a>=-4 then {
Print "Middle"
} else {
Print "Bottom"
}
}
CheckIt 100
CheckIt 0
CheckIt -100
Module CheckIt {
Read a
\\ using end if without blocks
If a>1 then
Print "Top"
else.if a>=-4 then
Print "Middle"
else
Print "Bottom"
End If
}
CheckIt 100
CheckIt 0
CheckIt -100
Module CheckIt {
Read a
\\ without use of END IF in one line
If a>1 then Print "Top" else.if a>=-4 then Print "Middle" else Print "Bottom"
}
CheckIt 100
CheckIt 0
CheckIt -100
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Oberon-2 | Oberon-2 |
(* this is a comment *)
(*
and this is a
multiline comment
(* with a nested comment *)
*)
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Objeck | Objeck |
#This is a comment.
# This is other comment.
#~ This is a comment too. ~#
#~ This is a
multi-line
comment ~#
|
http://rosettacode.org/wiki/Color_quantization | Color quantization | full color
Example: Gimp 16 color
Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.
Task: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should not use a fixed palette such as Web colors or Windows system palette. Dithering is not required.
Note: the funny color bar on top of the frog image is intentional.
| #Common_Lisp | Common Lisp | (defpackage #:quantize
(:use #:cl
#:opticl))
(in-package #:quantize)
(defun image->pixels (image)
(check-type image 8-bit-rgb-image)
(let (pixels)
(do-pixels (y x) image
(push (pixel* image y x) pixels))
pixels))
(defun greatest-color-range (pixels)
(loop for (r g b) in pixels
minimize r into r-min
minimize g into g-min
minimize b into b-min
maximize r into r-max
maximize g into g-max
maximize b into b-max
finally
(return (let* ((r-range (- r-max r-min))
(g-range (- g-max g-min))
(b-range (- b-max b-min))
(max-range (max r-range g-range b-range)))
(cond ((= r-range max-range) 0)
((= g-range max-range) 1)
(t 2))))))
(defun median-cut (pixels target-num-colors)
(assert (zerop (mod (log target-num-colors 2) 1)))
(if (or (= target-num-colors 1) (null (rest pixels)))
(list pixels)
(let* ((channel (greatest-color-range pixels))
(sorted (sort pixels #'< :key (lambda (pixel) (nth channel pixel))))
(half (floor (length sorted) 2))
(next-target (/ target-num-colors 2)))
(nconc (median-cut (subseq sorted 0 half) next-target)
(median-cut (subseq sorted half) next-target)))))
(defun quantize-colors (pixels target-num-colors)
(let ((color-map (make-hash-table :test #'equal)))
(dolist (bucket (median-cut pixels target-num-colors) color-map)
(loop for (r g b) in bucket
sum r into r-sum
sum g into g-sum
sum b into b-sum
count t into num-pixels
finally (let ((average (list (round r-sum num-pixels)
(round g-sum num-pixels)
(round b-sum num-pixels))))
(dolist (pixel bucket)
(setf (gethash pixel color-map) average)))))))
(defun quantize-image (input-file output-file target-num-colors)
(let* ((image (read-png-file input-file))
(pixels (image->pixels image))
(color-map (quantize-colors pixels target-num-colors))
(result-image (with-image-bounds (height width) image
(make-8-bit-rgb-image height width :initial-element 0))))
(set-pixels (y x) result-image
(let* ((original (multiple-value-list (pixel image y x)))
(quantized (gethash original color-map)))
(values-list quantized)))
(write-png-file output-file result-image))) |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Vedit_macro_language | Vedit macro language | IT("Generation 0 ") IN
IT(".O.") IN
IT(".O.") IN
IT(".O.")
#9 = 2 // number of generations to calculate
#10 = Cur_Line
#11 = Cur_Col-1
for (#2 = 1; #2 <= #9; #2++) {
Update()
Get_Key("Next gen...", STATLINE)
Call("calculate")
itoa(#2, 20, LEFT)
GL(1) GC(12) Reg_Ins(20, OVERWRITE)
}
EOF
Return
// Calculate one generation
:calculate:
Goto_Line(2)
While (At_EOF == 0) {
Search("|A",ERRBREAK) // find next living cell
#3 = Cur_Line
#4 = #7 = #8 = Cur_Col
if (#4 > 1) { // increment cell at left
#7 = #4-1
Goto_Col(#7)
Ins_Char(Cur_Char+1,OVERWRITE)
}
if (#4 < #11) { // increment cell at right
#8 = #4+1
Goto_Col(#8)
Ins_Char(Cur_Char+1,OVERWRITE)
}
if (#3 > 2) { // increment 3 cells above
Goto_Line(#3-1)
Call("inc_3")
}
if (#3 < #10) { // increment 3 cells below
Goto_Line(#3+1)
Call("inc_3")
}
Goto_Line(#3)
Goto_Col(#4+1)
}
Replace("[1QR]", "O", REGEXP+BEGIN+ALL) // these cells alive
Replace("[/-7P-X]", ".", REGEXP+BEGIN+ALL) // these cells dead
Return
// increment values of 3 characters in a row
:inc_3:
for (#1 = #7; #1 <= #8; #1++) {
Goto_Col(#1)
Ins_Char(Cur_Char+1,OVERWRITE)
}
Return |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Factor | Factor | USING: accessors arrays colors.constants kernel locals math
math.ranges opengl sequences ui ui.gadgets ui.render ;
CONSTANT: palette
{
COLOR: black
COLOR: red
COLOR: green
COLOR: blue
COLOR: magenta
COLOR: cyan
COLOR: yellow
COLOR: white
}
CONSTANT: bands 4
TUPLE: pinstripe < gadget ;
: <pinstripe> ( -- pinstripe ) pinstripe new ;
M: pinstripe pref-dim* drop { 400 400 } ;
: set-color ( n -- ) palette length mod palette nth gl-color ;
:: draw-pinstripe ( pinstripe n -- )
pinstripe dim>> first2 :> ( w h )
h 4 /i :> quarter
quarter n * :> y2
y2 quarter - :> y1
0 w n <range> [| x |
x n / set-color x y1 2array x n + y2 2array gl-fill-rect
] each ;
M: pinstripe draw-gadget*
bands [1,b] [ draw-pinstripe ] with each ;
<pinstripe> "Color pinstripe" open-window |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #FreeBASIC | FreeBASIC | ' version 14-03-2017
' compile with: fbc -s console
' or compile with: fbc -s gui
Dim As UInteger ps, col, h, w, x, y1, y2
ScreenInfo w, h
' create display size window, 8bit color (palette), no frame
ScreenRes w, h, 8,, 8
h = h \ 4 : y2 = h -1
For ps = 1 To 4
col = 0
For x = 0 To (w - ps -1) Step ps
Line (x, y1) - (x + ps -1, y2), col, bf
col = (col +1) And 255
Next
y1 += h : y2 += h
Next
' empty keyboard buffer
While Inkey <> "" : Wend
'Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #J | J | GetDC=: 'user32.dll GetDC >i i'&cd NB. hdx: GetDC hwnd
GetPixel=: 'gdi32.dll GetPixel >l i i i'&cd NB. rgb: GetPixel hdc x y
GetCursorPos=: 'user32.dll GetCursorPos i *i'&cd NB. success: point |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Java | Java | public static Color getColorAt(int x, int y){
return new Robot().getPixelColor(x, y);
} |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Julia | Julia |
# Windows GDI version
function getpixelcolors(x, y)
hdc = ccall((:GetDC, "user32.dll"), UInt32, (UInt32,), 0)
pxl = ccall((:GetPixel, "gdi32.dll"), UInt32, (UInt32, Cint, Cint), hdc, Cint(x), Cint(y))
return pxl & 0xff, (pxl >> 8) & 0xff, (pxl >> 16) & 0xff
end
const x = 120
const y = 100
cols = getpixelcolors(x, y)
println("At screen point (x=$x, y=$y) the color RGB components are red: $(cols[1]), green: $(cols[2]), and blue: $(cols[3])")
|
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #M2000_Interpreter | M2000 Interpreter |
Module Check {
\\ we use an internal object for Math functions (here for Atan2)
Declare Math Math
Const tau=2*Pi, Center=2
\\ change console size, and center it ( using ;) to current monitor
Window 12, 800*twipsX,600*twipsY;
\\ actual size maybe less (so can fit text exactly)
Double ' Double height characters
Report Center, "Color wheel"
Normal ' restore to normal
Atan2=Lambda Math (a, b) ->{
Method Math, "Atan2", a, b As ret
=ret
}
\\ brightness=1 for this program
hsb2rgb=Lambda (hue, sat) ->{
If sat == 0 Then {
= 255, 255, 255
} Else {
h=frac(hue+1)*6
f = frac(h)
p = Int((1-sat)*255 + 0.5)
q = Int((1-sat*f)*255 + 0.5)
t = Int((1-sat*(1-f))*255 + 0.5)
Select Case Int(h)
Case 1
= q, 255, p
Case 2
= p, 255, t
Case 3
= p, q, 255
Case 4
= t, p, 255
Case 5
= 255, p, q
Else Case
= 255, t, p
End Select
}
}
Let OffsetX=X.twips/2-128*TwipsX, OffsetY=Y.twips/2-128*TwipsY
\\ a pixel has a size of TwipsX x TwipsY
OffsetX=(OffsetX div TwipsX)*TwipsX
OffsetY=(OffsetY div TwipsY)*TwipsY
\\ We set hsb2rgb, OffsetX, OffsetY as closures to PrintPixel
\\ We send to stack the R G B values using Stack ! array
\\ hsb2rgb() return an array of values
\\ we pop these values using Number
PrintPixel = Lambda hsb2rgb, OffsetX, OffsetY (x,y, theta, sat) -> {
Stack ! hsb2rgb(theta,sat)
PSet Color(number, number, number), x*TwipsX+offsetX, y*TwipsY+offsetY
}
\\ set Atan2, tau as closures to HueCircle
\\ we can rotate/flip the wheel by changing signs in Atan2() and
\\ by changing order of arguments (dx,dy) or (dy,dx). 8 combinations
HueCircle= Lambda Atan2, tau (PrintPixel) -> {
Let c_width=256, c_height=256
Let cx=c_width/2, cy=c_height/2
Let radius=If(cx<=cy->cx, cy)
c_width--
c_height--
dy=-cy
For y=0 To c_height {
dy++ : dy2=dy*dy : dx=-cx
For x=0 To c_width {
dx++ : dist=Sqrt(dx^2+dy2)
If dist>radius Then continue
Call PrintPixel(x,y, Atan2(dx, -dy)/tau, dist/radius)
}
}
}
Call HueCircle(PrintPixel)
Scr$="" ' we use this string to load an image
Move 0,0
\\ scale.x, scale.y are twips height and width, of current layer
Copy scale.x, scale.y to Scr$
Clipboard Scr$ ' save window to clipboard
}
Check
|
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | r = 100;
Image[Table[
If[x^2 + y^2 <= r^2,
angle = Mod[ArcTan[N@x, y]/(2 Pi), 1];
List @@ RGBColor[Hue[angle, Sqrt[x^2 + y^2]/N[r], 1.0]]
,
{1, 1, 1}
], {x, -r, r}, {y, -r, r}]
] |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Nim | Nim | import math
import imageman
#---------------------------------------------------------------------------------------------------
func hsvToRgb(h, s, v: float): ColorRGBU =
## Convert HSV values to RGB values.
let hp = h / 60
let c = s * v
let x = c * (1 - abs(hp mod 2 - 1))
let m = v - c
var r, g, b = 0.0
if hp <= 1:
r = c
g = x
elif hp <= 2:
r = x
g = c
elif hp <= 3:
g = c
b = x
elif hp <= 4:
g = x
b= c
elif hp <= 5:
r = x
b = c
else:
r = c
b = x
r += m
g += m
b += m
result = ColorRGBU [byte(r * 255), byte(g * 255), byte(b * 255)]
#---------------------------------------------------------------------------------------------------
func buildColorWheel(image: var Image) =
## Build a color wheel into the image.
const Margin = 10
let diameter = min(image.w, image.h) - 2 * Margin
let xOffset = (image.w - diameter) div 2
let yOffset = (image.h - diameter) div 2
let radius = diameter / 2
for x in 0..diameter:
let rx = x.toFloat - radius
for y in 0..diameter:
let ry = y.toFloat - radius
let r = hypot(rx, ry) / radius
if r > 1: continue
let a = 180 + arctan2(ry, -rx).radToDeg()
image[x + xOffset, y + yOffset] = hsvToRgb(a, r, 1)
#———————————————————————————————————————————————————————————————————————————————————————————————————
const
Side = 400
Output = "color_wheel.png"
var image = initImage[ColorRGBU](Side, Side)
image.buildColorWheel()
image.savePNG(Output, compression = 9) |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Combinations is
generic
type Integers is range <>;
package Combinations is
type Combination is array (Positive range <>) of Integers;
procedure First (X : in out Combination);
procedure Next (X : in out Combination);
procedure Put (X : Combination);
end Combinations;
package body Combinations is
procedure First (X : in out Combination) is
begin
X (1) := Integers'First;
for I in 2..X'Last loop
X (I) := X (I - 1) + 1;
end loop;
end First;
procedure Next (X : in out Combination) is
begin
for I in reverse X'Range loop
if X (I) < Integers'Val (Integers'Pos (Integers'Last) - X'Last + I) then
X (I) := X (I) + 1;
for J in I + 1..X'Last loop
X (J) := X (J - 1) + 1;
end loop;
return;
end if;
end loop;
raise Constraint_Error;
end Next;
procedure Put (X : Combination) is
begin
for I in X'Range loop
Put (Integers'Image (X (I)));
end loop;
end Put;
end Combinations;
type Five is range 0..4;
package Fives is new Combinations (Five);
use Fives;
X : Combination (1..3);
begin
First (X);
loop
Put (X); New_Line;
Next (X);
end loop;
exception
when Constraint_Error =>
null;
end Test_Combinations; |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Make | Make | # make -f do.mk C=mycond if
C=0
if:
-@expr $(C) >/dev/null && make -f do.mk true; exit 0
-@expr $(C) >/dev/null || make -f do.mk false; exit 0
true:
@echo "was true."
false:
@echo "was false." |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Objective-C | Objective-C | (* This a comment
(* containing nested comment *)
*)
(** This an OCamldoc documentation comment *) |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #OCaml | OCaml | (* This a comment
(* containing nested comment *)
*)
(** This an OCamldoc documentation comment *) |
http://rosettacode.org/wiki/Color_quantization | Color quantization | full color
Example: Gimp 16 color
Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.
Task: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should not use a fixed palette such as Web colors or Windows system palette. Dithering is not required.
Note: the funny color bar on top of the frog image is intentional.
| #D | D | import core.stdc.stdio, std.stdio, std.algorithm, std.typecons,
std.math, std.range, std.conv, std.string, bitmap;
struct Col { float r, g, b; }
alias Cluster = Tuple!(Col, float, Col, Col[]);
enum Axis { R, G, B }
enum round = (in float x) pure nothrow @safe @nogc => cast(int)floor(x + 0.5);
enum roundRGB = (in Col c) pure nothrow @safe @nogc =>
RGB(cast(ubyte)round(c.r),
cast(ubyte)round(c.g),
cast(ubyte)round(c.b));
enum addRGB = (in Col c1, in Col c2) pure nothrow @safe @nogc =>
Col(c1.r + c2.r, c1.g + c2.g, c1.b + c2.b);
Col meanRGB(in Col[] pxList) pure nothrow @safe @nogc {
immutable tot = reduce!addRGB(Col(0, 0, 0), pxList);
immutable n = pxList.length;
return Col(tot.r / n, tot.g / n, tot.b / n);
}
enum minC = (in Col c1, in Col c2) pure nothrow @safe @nogc =>
Col(min(c1.r, c2.r), min(c1.g, c2.g), min(c1.b, c2.b));
enum maxC = (in Col c1, in Col c2) pure nothrow @safe @nogc =>
Col(max(c1.r, c2.r), max(c1.g, c2.g), max(c1.b, c2.b));
Tuple!(Col, Col) extrems(in Col[] lst) pure nothrow @safe @nogc {
enum FI = float.infinity;
auto mmRGB = typeof(return)(Col(FI, FI, FI), Col(-FI, -FI, -FI));
return reduce!(minC, maxC)(mmRGB, lst);
}
Tuple!(float, Col) volumeAndDims(in Col[] lst) pure nothrow @safe @nogc {
immutable e = lst.extrems;
immutable r = Col(e[1].r - e[0].r,
e[1].g - e[0].g,
e[1].b - e[0].b);
return typeof(return)(r.r * r.g * r.b, r);
}
Cluster makeCluster(Col[] pixelList) pure nothrow @safe @nogc {
immutable vol_dims = pixelList.volumeAndDims;
immutable int len = pixelList.length;
return typeof(return)(pixelList.meanRGB,
len * vol_dims[0],
vol_dims[1],
pixelList);
}
enum fCmp = (in float a, in float b) pure nothrow @safe @nogc =>
(a > b) ? 1 : (a < b ? -1 : 0);
Axis largestAxis(in Col c) pure nothrow @safe @nogc {
immutable int r1 = fCmp(c.r, c.g);
immutable int r2 = fCmp(c.r, c.b);
if (r1 == 1 && r2 == 1) return Axis.R;
if (r1 == -1 && r2 == 1) return Axis.G;
if (r1 == 1 && r2 == -1) return Axis.B;
return (fCmp(c.g, c.b) == 1) ? Axis.G : Axis.B;
}
Tuple!(Cluster, Cluster) subdivide(in Col c, in float nVolProd,
in Col vol, Col[] pixels)
pure nothrow @safe @nogc {
Col[] px2;
final switch (largestAxis(vol)) {
case Axis.R: px2 = pixels.partition!(c1 => c1.r < c.r); break;
case Axis.G: px2 = pixels.partition!(c1 => c1.g < c.g); break;
case Axis.B: px2 = pixels.partition!(c1 => c1.b < c.b); break;
}
auto px1 = pixels[0 .. $ - px2.length];
return typeof(return)(px1.makeCluster, px2.makeCluster);
}
uint RGB2uint(in RGB c) pure nothrow @safe @nogc {
return c.r | (c.g << 8) | (c.b << 16);
}
enum uintToRGB = (in uint c) pure nothrow @safe @nogc =>
RGB(c & 0xFF, (c >> 8) & 0xFF, (c >> 16) & 0xFF);
Image!RGB colorQuantize(in Image!RGB img, in int n) pure nothrow /*@safe*/ {
immutable width = img.nx;
immutable height = img.ny;
auto cols = new Col[width * height];
foreach (immutable i, ref c; img.image)
cols[i] = Col(c.tupleof);
immutable dumb = Col(0, 0, 0);
Cluster unused = Cluster(dumb, -float.infinity, dumb, (Col[]).init);
auto clusters = [cols.makeCluster];
while (clusters.length < n) {
// Cluster cl = clusters.reduce!(max!q{ a[1] })(unused);
Cluster cl = reduce!((c1, c2) => c1[1] > c2[1] ? c1 : c2)
(unused, clusters);
clusters = [cl[].subdivide[]] ~
clusters.remove!(c => c == cl, SwapStrategy.unstable); //**
}
uint[uint] pixMap; // Faster than RGB[RGB].
ubyte[4] u4a, u4b;
foreach (const cluster; clusters) {
immutable ubyteMean = cluster[0].roundRGB.RGB2uint;
foreach (immutable col; cluster[3])
pixMap[col.roundRGB.RGB2uint] = ubyteMean;
}
auto result = new Image!RGB;
result.allocate(height, width);
foreach (immutable i, immutable p; img.image) {
immutable u3a = p.tupleof.RGB;
result.image[i] = pixMap[RGB2uint(u3a)].uintToRGB;
}
return result;
}
void main(in string[] args) {
string fileName;
int nCols;
switch (args.length) {
case 1:
fileName = "quantum_frog.ppm";
nCols = 16;
break;
case 3:
fileName = args[1];
nCols = args[2].to!int;
break;
default:
"Usage: color_quantization image.ppm ncolors".writeln;
return;
}
auto im = new Image!RGB;
im.loadPPM6(fileName);
const imq = colorQuantize(im, nCols);
imq.savePPM6("quantum_frog_quantized.ppm");
} |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Wortel | Wortel | @let {
life &m ~!* m &[a y] ~!* a &[v x] @let {
neigh @sum [
@`-x 1 @`-y 1 m @`x @`-y 1 m @`+x 1 @`-y 1 m
@`-x 1 @`y m @`+x 1 @`y m
@`-x 1 @`+y 1 m @`x @`+y 1 m @`+x 1 @`+y 1 m
]
@+ || = neigh 3 && v = neigh 2
}
blinker [
[0 0 0 0 0]
[0 0 0 0 0]
[0 1 1 1 0]
[0 0 0 0 0]
[0 0 0 0 0]
]
[[
!^life 0 blinker
!^life 1 blinker
!^life 2 blinker
]]
} |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Gambas | Gambas | 'WARNING this takes a time to display
Public Sub Form_Open()
Dim iColour As Integer[] = [Color.Black, Color.red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.white]
Dim hPanel As Panel
Dim siCount, siCounter, siSet As Short
With Me
.Arrangement = Arrange.Row
.Border = False
.Height = 1080
.Width = 400
.Fullscreen = True
End With
For siCounter = 1 To 4
For siCount = 0 To Desktop.Width Step siCounter
hpanel = New Panel(Me)
hpanel.Width = siCounter
hpanel.Height = Desktop.Height / 4
HPanel.Background = iColour[siSet]
Inc siSet
If siSet > 6 Then siSet = 0
Next
Next
End
|
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Kotlin | Kotlin | import java.awt.*
fun getMouseColor(): Color {
val location = MouseInfo.getPointerInfo().location
return getColorAt(location.x, location.y)
}
fun getColorAt(x: Int, y: Int): Color {
return Robot().getPixelColor(x, y)
} |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Lingo | Lingo | on getScreenPixelColor (x, y)
sx = xtra("ScrnXtra3").new()
img = sx.ScreenToImage(rect(x, y, x+1, y+1))
return img.getPixel(0, 0)
end |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Perl | Perl | use Imager;
use Math::Complex qw(cplx i pi);
my ($width, $height) = (300, 300);
my $center = cplx($width/2, $height/2);
my $img = Imager->new(xsize => $width,
ysize => $height);
foreach my $y (0 .. $height - 1) {
foreach my $x (0 .. $width - 1) {
my $vec = $center - $x - $y * i;
my $mag = 2 * abs($vec) / $width;
my $dir = (pi + atan2($vec->Re, $vec->Im)) / (2 * pi);
$img->setpixel(x => $x, y => $y,
color => {hsv => [360 * $dir, $mag, $mag < 1 ? 1 : 0]});
}
}
$img->write(file => 'color_wheel.png'); |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
COMMENT REQUIRED BY "prelude_combinations_generative.a68"
MODE COMBDATA = ~;
PROVIDES:
# COMBDATA*=~* #
# comb*=~ list* #
END COMMENT
MODE COMBDATALIST = REF[]COMBDATA;
MODE COMBDATALISTYIELD = PROC(COMBDATALIST)VOID;
PROC comb gen combinations = (INT m, COMBDATALIST list, COMBDATALISTYIELD yield)VOID:(
CASE m IN
# case 1: transpose list #
FOR i TO UPB list DO yield(list[i]) OD
OUT
[m + LWB list - 1]COMBDATA out;
INT index out := 1;
FOR i TO UPB list DO
COMBDATA first = list[i];
# FOR COMBDATALIST sub recombination IN # comb gen combinations(m - 1, list[i+1:] #) DO (#,
## (COMBDATALIST sub recombination)VOID:(
out[LWB list ] := first;
out[LWB list+1:] := sub recombination;
yield(out)
# OD #))
OD
ESAC
);
SKIP |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Maple | Maple | if x > 0 then
res := x;
else
res := -x;
end if; |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Octave | Octave | # I am a comment till the end of line
% I am a comment till the end of line
%{
This comment spans
multiple lines
%}
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Oforth | Oforth | // This is a comment... |
http://rosettacode.org/wiki/Color_quantization | Color quantization | full color
Example: Gimp 16 color
Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.
Task: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should not use a fixed palette such as Web colors or Windows system palette. Dithering is not required.
Note: the funny color bar on top of the frog image is intentional.
| #Go | Go | package main
import (
"container/heap"
"image"
"image/color"
"image/png"
"log"
"math"
"os"
"sort"
)
func main() {
f, err := os.Open("Quantum_frog.png")
if err != nil {
log.Fatal(err)
}
img, err := png.Decode(f)
if ec := f.Close(); err != nil {
log.Fatal(err)
} else if ec != nil {
log.Fatal(ec)
}
fq, err := os.Create("frog16.png")
if err != nil {
log.Fatal(err)
}
if err = png.Encode(fq, quant(img, 16)); err != nil {
log.Fatal(err)
}
}
// Organize quatization in some logical steps.
func quant(img image.Image, nq int) image.Image {
qz := newQuantizer(img, nq) // set up a work space
qz.cluster() // cluster pixels by color
return qz.Paletted() // generate paletted image from clusters
}
// A workspace with members that can be accessed by methods.
type quantizer struct {
img image.Image // original image
cs []cluster // len is the desired number of colors
px []point // list of all points in the image
ch chValues // buffer for computing median
eq []point // additional buffer used when splitting cluster
}
type cluster struct {
px []point // list of points in the cluster
widestCh int // rx, gx, bx const for channel with widest value range
chRange uint32 // value range (vmax-vmin) of widest channel
}
type point struct{ x, y int }
type chValues []uint32
type queue []*cluster
const (
rx = iota
gx
bx
)
func newQuantizer(img image.Image, nq int) *quantizer {
b := img.Bounds()
npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
// Create work space.
qz := &quantizer{
img: img,
ch: make(chValues, npx),
cs: make([]cluster, nq),
}
// Populate initial cluster with all pixels from image.
c := &qz.cs[0]
px := make([]point, npx)
c.px = px
i := 0
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
px[i].x = x
px[i].y = y
i++
}
}
return qz
}
func (qz *quantizer) cluster() {
// Cluster by repeatedly splitting clusters.
// Use a heap as priority queue for picking clusters to split.
// The rule will be to spilt the cluster with the most pixels.
// Terminate when the desired number of clusters has been populated
// or when clusters cannot be further split.
pq := new(queue)
// Initial cluster. populated at this point, but not analyzed.
c := &qz.cs[0]
for i := 1; ; {
qz.setColorRange(c)
// Cluster cannot be split if all pixels are the same color.
// Only enqueue clusters that can be split.
if c.chRange > 0 {
heap.Push(pq, c) // add new cluster to queue
}
// If no clusters have any color variation, mark the end of the
// cluster list and quit early.
if len(*pq) == 0 {
qz.cs = qz.cs[:i]
break
}
s := heap.Pop(pq).(*cluster) // get cluster to split
c = &qz.cs[i] // set c to new cluster
i++
m := qz.Median(s)
qz.Split(s, c, m) // split s into c and s
// If that was the last cluster, we're done.
if i == len(qz.cs) {
break
}
qz.setColorRange(s)
if s.chRange > 0 {
heap.Push(pq, s) // return to queue
}
}
}
func (q *quantizer) setColorRange(c *cluster) {
// Find extents of color values in each channel.
var maxR, maxG, maxB uint32
minR := uint32(math.MaxUint32)
minG := uint32(math.MaxUint32)
minB := uint32(math.MaxUint32)
for _, p := range c.px {
r, g, b, _ := q.img.At(p.x, p.y).RGBA()
if r < minR {
minR = r
}
if r > maxR {
maxR = r
}
if g < minG {
minG = g
}
if g > maxG {
maxG = g
}
if b < minB {
minB = b
}
if b > maxB {
maxB = b
}
}
// See which channel had the widest range.
s := gx
min := minG
max := maxG
if maxR-minR > max-min {
s = rx
min = minR
max = maxR
}
if maxB-minB > max-min {
s = bx
min = minB
max = maxB
}
c.widestCh = s
c.chRange = max - min // also store the range of that channel
}
func (q *quantizer) Median(c *cluster) uint32 {
px := c.px
ch := q.ch[:len(px)]
// Copy values from appropriate channel to buffer for computing median.
switch c.widestCh {
case rx:
for i, p := range c.px {
ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA()
}
case gx:
for i, p := range c.px {
_, ch[i], _, _ = q.img.At(p.x, p.y).RGBA()
}
case bx:
for i, p := range c.px {
_, _, ch[i], _ = q.img.At(p.x, p.y).RGBA()
}
}
// Median algorithm.
sort.Sort(ch)
half := len(ch) / 2
m := ch[half]
if len(ch)%2 == 0 {
m = (m + ch[half-1]) / 2
}
return m
}
func (q *quantizer) Split(s, c *cluster, m uint32) {
px := s.px
var v uint32
i := 0
lt := 0
gt := len(px) - 1
eq := q.eq[:0] // reuse any existing buffer
for i <= gt {
// Get pixel value of appropriate channel.
r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA()
switch s.widestCh {
case rx:
v = r
case gx:
v = g
case bx:
v = b
}
// Categorize each pixel as either <, >, or == median.
switch {
case v < m:
px[lt] = px[i]
lt++
i++
case v > m:
px[gt], px[i] = px[i], px[gt]
gt--
default:
eq = append(eq, px[i])
i++
}
}
// Handle values equal to the median.
if len(eq) > 0 {
copy(px[lt:], eq) // move them back between the lt and gt values.
// Then, if the number of gt values is < the number of lt values,
// fix up i so that the split will include the eq values with
// the gt values.
if len(px)-i < lt {
i = lt
}
q.eq = eq // squirrel away (possibly expanded) buffer for reuse
}
// Split the pixel list.
s.px = px[:i]
c.px = px[i:]
}
func (qz *quantizer) Paletted() *image.Paletted {
cp := make(color.Palette, len(qz.cs))
pi := image.NewPaletted(qz.img.Bounds(), cp)
for i := range qz.cs {
px := qz.cs[i].px
// Average values in cluster to get palette color.
var rsum, gsum, bsum int64
for _, p := range px {
r, g, b, _ := qz.img.At(p.x, p.y).RGBA()
rsum += int64(r)
gsum += int64(g)
bsum += int64(b)
}
n64 := int64(len(px))
cp[i] = color.NRGBA64{
uint16(rsum / n64),
uint16(gsum / n64),
uint16(bsum / n64),
0xffff,
}
// set image pixels
for _, p := range px {
pi.SetColorIndex(p.x, p.y, uint8(i))
}
}
return pi
}
// Implement sort.Interface for sort in median algorithm.
func (c chValues) Len() int { return len(c) }
func (c chValues) Less(i, j int) bool { return c[i] < c[j] }
func (c chValues) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
// Implement heap.Interface for priority queue of clusters.
func (q queue) Len() int { return len(q) }
// Less implements rule to select cluster with greatest number of pixels.
func (q queue) Less(i, j int) bool {
return len(q[j].px) < len(q[i].px)
}
func (q queue) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
}
func (pq *queue) Push(x interface{}) {
c := x.(*cluster)
*pq = append(*pq, c)
}
func (pq *queue) Pop() interface{} {
q := *pq
n := len(q) - 1
c := q[n]
*pq = q[:n]
return c
} |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #VBScript | VBScript |
option explicit
const tlcr=3, tlcc=3
const maxdim=15
dim a(15,15)
dim b(15,15)
dim ans0:ans0=chr(27)&"["
dim gen,n
erase a
'glider
a(0,1)=true:a(1,2)=true:a(2,0)=true:a(2,1)=true:a(2,2)=true
'blinker
a(3,13)=true:a(4,13)=true:a(5,13)=true
'beacon
a(11,1)=true:a(11,2)=true: a(12,1)=true:a(12,2)=true
a(13,3)=true:a(13,4)=true: a(14,3)=true:a(14,4)=true
gen=0
doframe
do
display
wscript.sleep(100)
n=newgen
loop until n=0
display
sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub 'hide cursor too
sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub
function iif(a,b,c) if a then iif=b else iif=c end if :end function
sub doframe
dim r,c,s
const frame="@"
cls
toxy 1,tlcc-1, "Conway's Game of Life"
toxy tlcr-1,tlcc-1,string(maxdim+3,frame)
s=frame&space(maxdim+1)&frame
for r=0 to maxdim
toxy tlcr+r,tlcc-1,s
next
toxy tlcr+maxdim+1,tlcc-1,string(maxdim+3,frame)
end sub
sub display
dim r,c
const pix="#"
for r=0 to maxdim
for c=0 to maxdim
toxy tlcr+r,tlcc+c,iif (a(r,c),pix," ")
next
next
toxy tlcr+maxdim+2,tlcc-1,gen & " " & n
toxy tlcr+maxdim+3,tlcc-1,""
gen=gen+1
end sub
function newgen
dim r,c,cnt,cp,cm,rp,rm
for r=0 to maxdim
for c=0 to maxdim
cp=(c+1) and maxdim 'wrap around
cm=(c-1) and maxdim
rp=(r+1) and maxdim
rm=(r-1) and maxdim
cnt=0
cnt=- a(rp,cp) - a(rp,c) - a(rp,cm) 'true =-1
cnt=cnt- a(r,cp)- a(r,cm)
cnt=cnt- a(rm,cp)- a(rm,c) - a(rm,cm)
if a(r,c) then
b(r,c)=iif (cnt=2 or cnt=3,true,false)
else
b(r,c)=iif (cnt=3,true,false)
end if
next
next
for r=0 to maxdim
for c=0 to maxdim
a(r,c)=b(r,c)
newgen=newgen- b(r,c)
next
next
end function
|
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Go | Go | package main
import "github.com/fogleman/gg"
var palette = [8]string{
"000000", // black
"FF0000", // red
"00FF00", // green
"0000FF", // blue
"FF00FF", // magenta
"00FFFF", // cyan
"FFFF00", // yellow
"FFFFFF", // white
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 4
for b := 1; b <= 4; b++ {
for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
dc.SetHexColor(palette[ci%8])
y := h * (b - 1)
dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
dc.Fill()
}
}
}
func main() {
dc := gg.NewContext(900, 600)
pinstripe(dc)
dc.SavePNG("color_pinstripe.png")
} |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Icon_and_Unicon | Icon and Unicon | link graphics,numbers,printf
procedure main() # pinstripe
&window := open("Colour Pinstripe","g","bg=black") |
stop("Unable to open window")
WAttrib("canvas=hidden")
WAttrib(sprintf("size=%d,%d",WAttrib("displaywidth"),WAttrib("displayheight")))
WAttrib("canvas=maximal")
Colours := ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]
height := WAttrib("height")
width := WAttrib("width")
maxbands := 4 # bands to draw
bandheight := height / maxbands # height of each band
every bands := 1 to maxbands do { # for each band
top := 1 + bandheight * (bands-1) # .. top of band
every c := 1 to width do {
colour := Colours[ceil((c+0.)/bands)%*Colours+1]
if colour == "black" then next # skip black
else {
Fg(colour)
DrawLine(c,top,c,top+bandheight-1)
}
}
}
WDone()
end |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Logo | Logo | CLEARSCREEN
SHOW PIXEL
[255 255 255]
|
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckColor {
\\ Print hex code for color, and html code for color
Every 25 {
move mouse.x, mouse.y
color$=Hex$(-point, 3) ' point has a negative value
Print Over "0x"+color$+", #"+Right$(color$,2)+Mid$(color$, 3,2)+Left$(color$,2)
if mouse<>0 then exit
}
Print
}
CheckColor
|
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | getPixel[{x_?NumberQ, y_?NumberQ}, screenNumber_Integer: 1] := ImageValue[CurrentScreenImage[n], {x, y}] |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Phix | Phix | --
-- demo\rosetta\Colour_wheel.exw
-- =============================
--
-- Note: Made non-resizeable since maximising this is far too slow.
--
with javascript_semantics
include pGUI.e
constant title = "Colour wheel"
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cddbuffer)
integer radius = floor(min(w,h)/2)
integer cx = floor(w/2),
cy = floor(h/2)
for x=1 to w do
for y=1 to h do
integer rx = x - cx,
ry = y - cy
atom s = sqrt(rx*rx+ry*ry) / radius
if s <= 1.0 then
atom hue = ((atan2(ry, rx) / PI) + 1.0) / 2.0
cdCanvasPixel(cddbuffer, x, h-y, hsv_to_rgb(hue, s, 1))
end if
end for
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_MAGENTA)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "300x300")
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
dlg = IupDialog(canvas,`TITLE="%s",RESIZE=NO`,{title})
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
IupShowXY(dlg,IUP_CENTER,IUP_CENTER)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AppleScript | AppleScript | on comb(n, k)
set c to {}
repeat with i from 1 to k
set end of c to i's contents
end repeat
set r to {c's contents}
repeat while my next_comb(c, k, n)
set end of r to c's contents
end repeat
return r
end comb
on next_comb(c, k, n)
set i to k
set c's item i to (c's item i) + 1
repeat while (i > 1 and c's item i ≥ n - k + 1 + i)
set i to i - 1
set c's item i to (c's item i) + 1
end repeat
if (c's item 1 > n - k + 1) then return false
repeat with i from i + 1 to k
set c's item i to (c's item (i - 1)) + 1
end repeat
return true
end next_comb
return comb(5, 3) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | if x == 1
disp 'x==1';
elseif x > 1
disp 'x>1';
else
disp 'x<1';
end |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #ooRexx | ooRexx | /*
Multi-line comment block
*/
-- this type of comment works in ooRexx, NetRexx and some of the more popular REXX implementations like Regina
hour = 0 -- which is, like midnight, dude.
hour = 12 /* time for lunch! works as well (and really everywhere) */
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Openscad | Openscad |
// This is a single line comment
/*
This comment spans
multiple lines
*/
|
http://rosettacode.org/wiki/Color_quantization | Color quantization | full color
Example: Gimp 16 color
Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.
Task: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should not use a fixed palette such as Web colors or Windows system palette. Dithering is not required.
Note: the funny color bar on top of the frog image is intentional.
| #Haskell | Haskell | import qualified Data.ByteString.Lazy as BS
import qualified Data.Foldable as Fold
import qualified Data.List as List
import Data.Ord
import qualified Data.Sequence as Seq
import Data.Word
import System.Environment
import Codec.Picture
import Codec.Picture.Types
type Accessor = PixelRGB8 -> Pixel8
-- Getters for pixel components, as the constructor does not
-- provide any public ones.
red, blue, green :: Accessor
red (PixelRGB8 r _ _) = r
green (PixelRGB8 _ g _) = g
blue (PixelRGB8 _ _ b) = b
-- Get all of the pixels in the image in list form.
getPixels :: Pixel a => Image a -> [a]
getPixels image =
[pixelAt image x y
| x <- [0..(imageWidth image - 1)]
, y <- [0..(imageHeight image - 1)]]
-- Compute the color-space extents of a list of pixels.
extents :: [PixelRGB8] -> (PixelRGB8, PixelRGB8)
extents pixels = (extent minimum, extent maximum)
where
bound f g = f $ map g pixels
extent f = PixelRGB8 (bound f red) (bound f green) (bound f blue)
-- Compute the average value of a list of pixels.
average :: [PixelRGB8] -> PixelRGB8
average pixels = PixelRGB8 (avg red) (avg green) (avg blue)
where
len = toInteger $ length pixels
avg c = fromIntegral $ (sum $ map (toInteger . c) pixels) `div` len
-- Perform a componentwise pixel operation.
compwise :: (Word8 -> Word8 -> Word8) -> PixelRGB8 -> PixelRGB8 -> PixelRGB8
compwise f (PixelRGB8 ra ga ba) (PixelRGB8 rb gb bb) =
PixelRGB8 (f ra rb) (f ga gb) (f ba bb)
-- Compute the absolute difference of two pixels.
diffPixel :: PixelRGB8 -> PixelRGB8 -> PixelRGB8
diffPixel = compwise (\x y -> max x y - min x y)
-- Compute the Euclidean distance squared between two pixels.
distPixel :: PixelRGB8 -> PixelRGB8 -> Integer
distPixel x y = (rr ^ 2) + (gg ^ 2) + (bb ^ 2)
where
PixelRGB8 r g b = diffPixel x y
rr = toInteger r
gg = toInteger g
bb = toInteger b
-- Determine the dimension of the longest axis of the extents.
longestAccessor :: (PixelRGB8, PixelRGB8) -> Accessor
longestAccessor (l, h) =
snd $ Fold.maximumBy (comparing fst) $ zip [r, g, b] [red, green, blue]
where
PixelRGB8 r g b = diffPixel h l
-- Find the index of a pixel to its respective palette.
nearestIdx :: PixelRGB8 -> [PixelRGB8] -> Int
nearestIdx pixel px = ans
where
Just ans = List.findIndex (== near) px
near = List.foldl1 comp px
comp a b = if distPixel a pixel <= distPixel b pixel then a else b
-- Sort a list of pixels on its longest axis and then split by the mean.
-- It is intentional that the mean is chosen by all dimensions
-- instead of the given one.
meanSplit :: [PixelRGB8] -> Accessor -> ([PixelRGB8], [PixelRGB8])
meanSplit l f = List.splitAt index sorted
where
sorted = List.sortBy (comparing f) l
index = nearestIdx (average l) sorted
-- Perform the Median Cut algorithm on an image producing
-- an index map image and its respective palette.
meanCutQuant :: Image PixelRGB8 -> Int -> (Image Pixel8, Palette)
meanCutQuant image numRegions = (indexmap, palette)
where
extentsP p = (p, extents p)
regions = map (\(p, e) -> (average p, e))
$ search $ Seq.singleton $ extentsP $ getPixels image
palette = snd $ generateFoldImage (\(x:xs) _ _ -> (xs, x))
(map fst regions) numRegions 1
indexmap = pixelMap
(\pixel -> fromIntegral $ nearestIdx pixel $ map fst regions)
image
search queue =
case Seq.viewl queue of
(pixels, extent) Seq.:< queueB ->
let (left, right) = meanSplit pixels $ longestAccessor extent
queueC = Fold.foldl (Seq.|>) queueB $ map extentsP [left, right]
in if Seq.length queueC >= numRegions
then List.take numRegions $ Fold.toList queueC
else search queueC
Seq.EmptyL -> error "Queue should never be empty."
quantizeIO :: FilePath -> FilePath -> Int -> IO ()
quantizeIO path outpath numRegions = do
dynimage <- readImage path
case dynimage of
Left err -> putStrLn err
Right (ImageRGB8 image) -> doImage image
Right (ImageRGBA8 image) -> doImage (pixelMap dropTransparency image)
_ -> putStrLn "Expecting RGB8 or RGBA8 image"
where
doImage image = do
let (indexmap, palette) = meanCutQuant image numRegions
case encodePalettedPng palette indexmap of
Left err -> putStrLn err
Right bstring -> BS.writeFile outpath bstring
main :: IO ()
main = do
args <- getArgs
prog <- getProgName
case args of
[path, outpath] -> quantizeIO path outpath 16
_ -> putStrLn $ "Usage: " ++ prog ++ " <image-file> <out-file.png>" |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Vlang | Vlang | import rand
import strings
import time
struct Field {
mut:
s [][]bool
w int
h int
}
fn new_field(w int, h int) Field {
s := [][]bool{len: h, init: []bool{len: w}}
return Field{s, w, h}
}
fn (mut f Field) set(x int, y int, b bool) {
f.s[y][x] = b
}
fn (f Field) next(x int, y int) bool {
mut on := 0
for i := -1; i <= 1; i++ {
for j := -1; j <= 1; j++ {
if f.state(x+i, y+j) && !(j == 0 && i == 0) {
on++
}
}
}
return on == 3 || (on == 2 && f.state(x, y))
}
fn (f Field) state(xx int, yy int) bool {
mut x, mut y := xx, yy
for y < 0 {
y += f.h
}
for x < 0 {
x += f.w
}
return f.s[y%f.h][x%f.w]
}
struct Life {
mut:
w int
h int
a Field
b Field
}
fn new_life(w int, h int) Life {
mut a := new_field(w, h)
for _ in 0..(w * h / 2) {
a.set(rand.intn(w) or {0}, rand.intn(h) or {0}, true)
}
return Life{
a: a,
b: new_field(w, h),
w: w
h: h,
}
}
fn (mut l Life) step() {
for y in 0..l.h {
for x in 0.. l.w {
l.b.set(x, y, l.a.next(x, y))
}
}
l.a, l.b = l.b, l.a
}
fn (l Life) str() string {
mut buf := strings.new_builder(128)
for y in 0..l.h {
for x in 0..l.w {
mut b := ' '
if l.a.state(x, y) {
b = '*'
}
buf.write_string(b)
}
buf.write_string('\n')
}
return buf.str()
}
fn main() {
mut l := new_life(80, 15)
for i := 0; i < 300; i++ {
l.step()
//println("------------------------------------------------")
print('\x0c')
println(l)
time.sleep(time.second / 30)
}
} |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #J | J | load 'viewmat'
size=. 2{.".wd'qm' NB. J6
size=. getscreenwh_jgtk_ '' NB. J7
'rgb'viewmat (4<.@%~{:size)# ({.size) $&> 1 2 3 4#&.> <256#.255*#:i.8 |
http://rosettacode.org/wiki/Colour_pinstripe/Display | Colour pinstripe/Display | The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.
The pinstripes should either follow the system palette sequence, or a sequence that includes:
black, red, green, blue, magenta, cyan, yellow, and white:
after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
halfway down the display, switch to 3 pixel wide vertical pinstripe,
finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.
See also
display black and white
print colour
| #Java | Java | import java.awt.*;
import static java.awt.Color.*;
import javax.swing.*;
public class ColourPinstripeDisplay extends JPanel {
final static Color[] palette = {black, red, green, blue, magenta,cyan,
yellow, white};
final int bands = 4;
public ColourPinstripeDisplay() {
setPreferredSize(new Dimension(900, 600));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = getHeight();
for (int b = 1; b <= bands; b++) {
for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {
g.setColor(palette[colIndex % palette.length]);
g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("ColourPinstripeDisplay");
f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Nim | Nim | import gtk2, gdk2, gdk2pixbuf
type Color = tuple[r, g, b: byte]
gtk2.nim_init()
proc getPixelColor(x, y: int32): Color =
var p = pixbufNew(COLORSPACE_RGB, false, 8, 1, 1)
discard p.getFromDrawable(getDefaultRootWindow().Drawable,
getDefaultScreen().getSystemColormap(), x, y, 0, 0, 1, 1)
result = cast[ptr Color](p.getPixels)[]
echo getPixelColor(0, 0) |
http://rosettacode.org/wiki/Color_of_a_screen_pixel | Color of a screen pixel | Task
Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.
The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
| #Perl | Perl | use strict;
use warnings;
use GD;
my $file = '/tmp/one-pixel-screen-capture.png';
system "screencapture -R 123,456,1,1 $file";
my $image = GD::Image->newFromPng($file);
my $index = $image->getPixel(0,0);
my($red,$green,$blue) = $image->rgb($index);
print "RGB: $red, $green, $blue\n";
unlink $file; |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Processing | Processing | size(300, 300);
background(0);
float radius = min(width, height) / 2.0;
float cx = width / 2;
float cy = width / 2;
for (int x = 0; x < width; x++) {
for (int y = 0; y < width; y++) {
float rx = x - cx;
float ry = y - cy;
float s = sqrt(sq(rx) + sq(ry)) / radius;
if (s <= 1.0) {
float h = ((atan2(ry, rx) / PI) + 1.0) / 2.0;
colorMode(HSB);
color c = color(int(h * 255), int(s * 255), 255);
set(x, y, c);
}
}
} |
http://rosettacode.org/wiki/Color_wheel | Color wheel | Task
Write a function to draw a HSV color wheel completely with code.
This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.
| #Python | Python | from PIL import Image
import colorsys
import math
if __name__ == "__main__":
im = Image.new("RGB", (300,300))
radius = min(im.size)/2.0
cx, cy = im.size[0]/2, im.size[1]/2
pix = im.load()
for x in range(im.width):
for y in range(im.height):
rx = x - cx
ry = y - cy
s = (rx ** 2.0 + ry ** 2.0) ** 0.5 / radius
if s <= 1.0:
h = ((math.atan2(ry, rx) / math.pi) + 1.0) / 2.0
rgb = colorsys.hsv_to_rgb(h, s, 1.0)
pix[x,y] = tuple([int(round(c*255.0)) for c in rgb])
im.show() |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from 1 (unity) instead of 0 (zero),
the combinations can be of the integers from 1 to n.
See also
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AutoHotkey | AutoHotkey | MsgBox % Comb(1,1)
MsgBox % Comb(3,3)
MsgBox % Comb(3,2)
MsgBox % Comb(2,3)
MsgBox % Comb(5,3)
Comb(n,t) { ; Generate all n choose t combinations of 1..n, lexicographically
IfLess n,%t%, Return
Loop %t%
c%A_Index% := A_Index
i := t+1, c%i% := n+1
Loop {
Loop %t%
i := t+1-A_Index, c .= c%i% " "
c .= "`n" ; combinations in new lines
j := 1, i := 2
Loop
If (c%j%+1 = c%i%)
c%j% := j, ++j, ++i
Else Break
If (j > t)
Return c
c%j% += 1
}
} |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #MATLAB | MATLAB | if x == 1
disp 'x==1';
elseif x > 1
disp 'x>1';
else
disp 'x<1';
end |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #OxygenBasic | OxygenBasic |
' Basic line comment
; Assembly code line comment
// C line comment
/* C block comment */
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Oz | Oz | % one line comment
%% often with double "%" because then the indentation is correct in Emacs
/* multi line
comment
*/
|
http://rosettacode.org/wiki/Color_quantization | Color quantization | full color
Example: Gimp 16 color
Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.
Task: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should not use a fixed palette such as Web colors or Windows system palette. Dithering is not required.
Note: the funny color bar on top of the frog image is intentional.
| #J | J | kmcL=:4 :0
C=. /:~ 256 #.inv ,y NB. colors
G=. x (i.@] <.@* %) #C NB. groups (initial)
Q=. _ NB. quantized list of colors (initial
whilst.-. Q-:&<.&(x&*)Q0 do.
Q0=. Q
Q=. /:~C (+/ % #)/.~ G
G=. (i. <./)"1 C +/&.:*: .- |:Q
end.Q
) |
http://rosettacode.org/wiki/Color_quantization | Color quantization | full color
Example: Gimp 16 color
Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.
Task: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should not use a fixed palette such as Web colors or Windows system palette. Dithering is not required.
Note: the funny color bar on top of the frog image is intentional.
| #Julia | Julia |
const execstring =`convert Quantum_frog.png -dither None -colors 16 Quantum_frog_new.png`
run(execstring)
|
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #Wren | Wren | import "random" for Random
import "timer" for Timer
var Rand = Random.new(0) // using a constant seed to produce same output on each run
// patterns
var BLINKER = 0
var GLIDER = 1
var RANDOM = 2
class Field {
construct new(w, h) {
_w = w
_h = h
_s = List.filled(h, null)
for (i in 0...h) _s[i] = List.filled(w, false)
}
[x, y]=(b) { _s[y][x] = b }
state(x, y) {
if (!(0..._w).contains(x) || !(0..._h).contains(y)) return false
return _s[y][x]
}
next(x, y) {
var on = 0
for (i in -1..1) {
for (j in -1..1) {
if (state(x + i, y + j) && !(j == 0 && i == 0)) on = on + 1
}
}
return on == 3 || (on == 2 && state(x, y))
}
}
class Life {
construct new(pattern) {
if (pattern == BLINKER) {
_w = 3
_h = 3
_a = Field.new(_w, _h)
_b = Field.new(_w, _h)
_a[0, 1] = true
_a[1, 1] = true
_a[2, 1] = true
} else if (pattern == GLIDER) {
_w = 4
_h = 4
_a = Field.new(_w, _h)
_b = Field.new(_w, _h)
_a[1, 0] = true
_a[2, 1] = true
for (i in 0..2) _a[i, 2] = true
} else if(pattern == RANDOM) {
_w = 80
_h = 15
_a = Field.new(_w, _h)
_b = Field.new(_w, _h)
for (i in 0...(_w * _h).floor / 2) {
_a[Rand.int(_w), Rand.int(_h)] = true
}
}
}
step() {
for (y in 0..._h) {
for (x in 0..._w) _b[x, y] = _a.next(x, y)
}
var t = _a
_a = _b
_b = t
}
toString {
var sb = ""
for (y in 0..._h) {
for (x in 0..._w) {
var c = _a.state(x, y) ? "#" : "."
sb = sb + c
}
sb = sb + "\n"
}
return sb
}
}
var lives = [
[Life.new(BLINKER), 3, "BLINKER"],
[Life.new(GLIDER), 4, "GLIDER" ],
[Life.new(RANDOM), 100, "RANDOM" ]
]
for (t in lives) {
var game = t[0]
var gens = t[1]
var title = t[2]
System.print("%(title):\n")
for (i in 0..gens) {
System.print("Generation: %(i)\n%(game)")
Timer.sleep(30)
game.step()
}
System.print()
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.