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/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
| #Julia | Julia | using Gtk, Graphics, Colors
function drawline(ctx, p1, p2, color, width)
move_to(ctx, p1.x, p1.y)
set_source(ctx, color)
line_to(ctx, p2.x, p2.y)
set_line_width(ctx, width)
stroke(ctx)
end
const can = @GtkCanvas()
const win = GtkWindow(can, "Colour pinstripe/Display", 400, 400)
const colors = [colorant"black", colorant"red", colorant"green", colorant"blue",
colorant"magenta", colorant"cyan", colorant"yellow", colorant"white"]
const numcolors = length(colors)
@guarded draw(can) do widget
ctx = getgc(can)
h = height(can)
w = width(can)
deltaw = 1.0
for (i, x) in enumerate(0:deltaw:w)
drawline(ctx, Point(x, 0.25*h), Point(x, 0), colors[i % numcolors + 1], deltaw)
end
for (i, x) in enumerate(0:deltaw*2:w)
drawline(ctx, Point(x, 0.5*h), Point(x, 0.25*h), colors[i % numcolors + 1], deltaw*2)
end
for (i, x) in enumerate(0:deltaw*3:w)
drawline(ctx, Point(x, 0.75*h), Point(x, 0.5*h), colors[i % numcolors + 1], deltaw*3)
end
for (i, x) in enumerate(0:deltaw*4:w)
drawline(ctx, Point(x, h), Point(x, 0.75*h), colors[i % numcolors + 1], deltaw*4)
end
end
show(can)
const cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
wait(cond)
|
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
| #Kotlin | Kotlin | // version 1.1.0
import java.awt.*
import java.awt.Color.*
import javax.swing.*
class ColourPinstripeDisplay : JPanel() {
private companion object {
val palette = arrayOf(black, red, green, blue, magenta, cyan, yellow, white)
}
private val bands = 4
init {
preferredSize = Dimension(900, 600)
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
for (b in 1..bands) {
var colIndex = 0
val h = height / bands
for (x in 0 until width step b) {
g.color = palette[colIndex % palette.size]
g.fillRect(x, (b - 1) * h, b, h)
colIndex++
}
}
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "ColourPinstripeDisplay"
f.add(ColourPinstripeDisplay(), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.isVisible = 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.
| #Phix | Phix | integer {r,g,b} = im_pixel(image, 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.
| #PHP | PHP | $img = imagegrabscreen();
$color = imagecolorat($im, 10, 50);
imagedestroy($im); |
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.
| #PicoLisp | PicoLisp | (in '(grabc)
(mapcar hex (cdr (line NIL 1 2 2 2))) ) |
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.
| #Racket | Racket | #lang racket
(require racket/draw
colors)
(define DIM 500)
(define target (make-bitmap DIM DIM))
(define dc (new bitmap-dc% [bitmap target]))
(define radius 200)
(define center (/ DIM 2))
(define (atan2 y x) (if (= 0 y x) 0 (atan y x)))
(for* ([x (in-range DIM)]
[y (in-range DIM)]
[rx (in-value (- x center))]
[ry (in-value (- y center))]
[s (in-value (/ (sqrt (+ (sqr rx) (sqr ry))) radius))]
#:when (<= s 1))
(define h (* 0.5 (+ 1 (/ (atan2 ry rx) pi))))
(send dc set-pen (hsv->color (hsv (if (= 1 h) 0 h) s 1)) 1 'solid)
(send dc draw-point x y))
target |
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.
| #Raku | Raku | use Image::PNG::Portable;
my ($w, $h) = 300, 300;
my $out = Image::PNG::Portable.new: :width($w), :height($h);
my $center = $w/2 + $h/2*i;
color-wheel($out);
$out.write: 'Color-wheel-perl6.png';
sub color-wheel ( $png ) {
^$w .race.map: -> $x {
for ^$h -> $y {
my $vector = $center - $x - $y*i;
my $magnitude = $vector.abs * 2 / $w;
my $direction = ( π + atan2( |$vector.reals ) ) / τ;
$png.set: $x, $y, |hsv2rgb( $direction, $magnitude, $magnitude < 1 );
}
}
}
sub hsv2rgb ( $h, $s, $v ){
my $c = $v * $s;
my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );
my $m = $v - $c;
(do given $h {
when 0..^1/6 { $c, $x, 0 }
when 1/6..^1/3 { $x, $c, 0 }
when 1/3..^1/2 { 0, $c, $x }
when 1/2..^2/3 { 0, $x, $c }
when 2/3..^5/6 { $x, 0, $c }
when 5/6..1 { $c, 0, $x }
} ).map: ((*+$m) * 255).Int
} |
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
| #AWK | AWK | BEGIN {
## Default values for r and n (Choose 3 from pool of 5). Can
## alternatively be set on the command line:-
## awk -v r=<number of items being chosen> -v n=<how many to choose from> -f <scriptname>
if (length(r) == 0) r = 3
if (length(n) == 0) n = 5
for (i=1; i <= r; i++) { ## First combination of items:
A[i] = i
if (i < r ) printf i OFS
else print i}
## While 1st item is less than its maximum permitted value...
while (A[1] < n - r + 1) {
## loop backwards through all items in the previous
## combination of items until an item is found that is
## less than its maximum permitted value:
for (i = r; i >= 1; i--) {
## If the equivalently positioned item in the
## previous combination of items is less than its
## maximum permitted value...
if (A[i] < n - r + i) {
## increment the current item by 1:
A[i]++
## Save the current position-index for use
## outside this "for" loop:
p = i
break}}
## Put consecutive numbers in the remainder of the array,
## counting up from position-index p.
for (i = p + 1; i <= r; i++) A[i] = A[i - 1] + 1
## Print the current combination of items:
for (i=1; i <= r; i++) {
if (i < r) printf A[i] OFS
else print A[i]}}
exit} |
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.
| #Maxima | Maxima | if test1 then (...) elseif test2 then (...) else (...); |
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.)
| #PARI.2FGP | PARI/GP | (* This is a comment.
It may extend across multiple lines. *)
{ Alternatively curly braces
can be used. }
(* This is a valid comment in Standard Pascal,
but not valid in [[Turbo Pascal]]. }
{ The same is true in this case *) |
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.)
| #Pascal | Pascal | (* This is a comment.
It may extend across multiple lines. *)
{ Alternatively curly braces
can be used. }
(* This is a valid comment in Standard Pascal,
but not valid in [[Turbo Pascal]]. }
{ The same is true in this case *) |
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.
| #Kotlin | Kotlin | // Version 1.2.41
import java.io.BufferedReader
import java.io.InputStreamReader
fun main(args: Array<String>) {
// convert 'frog' to an image which uses only 16 colors, no dithering
val pb = ProcessBuilder(
"convert",
"Quantum_frog.png",
"-dither",
"None",
"-colors",
"16",
"Quantum_frog_16.png"
)
pb.directory(null)
val proc = pb.start()
proc.waitFor()
// now show the colors used
val pb2 = ProcessBuilder(
"convert",
"Quantum_frog_16.png",
"-format",
"%c",
"-depth",
"8",
"histogram:info:-"
)
pb2.directory(null)
pb.redirectOutput(ProcessBuilder.Redirect.PIPE)
val proc2 = pb2.start()
val br = BufferedReader(InputStreamReader(proc2.inputStream))
var clrNum = 0
while (true) {
val line = br.readLine() ?: break
System.out.printf("%2d->%s\n", clrNum++, line)
}
br.close()
} |
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.
| #XPL0 | XPL0 | def M=3; \array size
char NowGen(M+2, M+2), \size with surrounding borders
NewGen(M+2, M+2);
int X, Y, I, J, N, Gen;
code ChOut=8, CrLf=9;
[for Y:= 0 to M+1 do \set up initial state
for X:= 0 to M+1 do
[NowGen(X,Y):= ^ ; NewGen(X,Y):= ^ ];
NowGen(1,2):= ^#; NowGen(2,2):= ^#; NowGen(3,2):= ^#;
for Gen:= 1 to 3 do
[for Y:= 1 to M do \show current generation
[for X:= 1 to M do [ChOut(0, NowGen(X,Y)); ChOut(0,^ )];
CrLf(0);
];
CrLf(0);
for Y:= 1 to M do \determine next generation
for X:= 1 to M do
[N:= 0; \count adjacent live (#) cells
for J:= Y-1 to Y+1 do
for I:= X-1 to X+1 do
if NowGen(I,J) = ^# then N:= N+1;
if NowGen(X,Y) = ^# then N:= N-1; \don't count center
NewGen(X,Y):= ^ ; \assume death
if N=2 then NewGen(X,Y):= NowGen(X,Y) \actually no change
else if N=3 then NewGen(X,Y):= ^#; \actually birth
];
I:= NowGen; NowGen:= NewGen; NewGen:= I; \swap arrays
];
] |
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
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Window 16, 14000,12000;
Module Pinstripe {
Smooth off ' use of GDI32
Dim colors(0 to 7)
Colors(0)=#000000,#FF0000, #00FF00, #0000FF, #FF00FF, #00FFFF, #FFFF00, #FFFFFF
pixelsX=scale.x/twipsX
pixelsY=scale.y/twipsY
zoneheight=scale.y/4
n=0
Refresh 5000
For i=1 to 4 {
move 0, (i-1)*zoneheight
pinw=i*twipsx
For j=1 to pixelsX/i {
Fill pinw, zoneheight, color(n)
Step 0, -zoneheight
n++:if n=8 then n=0
}
}
\\ now we make the refersh
Refresh 100
}
\\ draw to console window
\\ now we make a window and draw there
Pinstripe
Layer 32 {
Window 12, 10000,10000
Pinstripe
Show
}
Declare Pinstripe Form
Layer Pinstripe {
Window 12, 10000,10000
Pinstripe
motion 2000, 2000
}
refresh 20
Thread {
if control$="MAIN" then if mouse then player 32, mousea.x, mousea.y
} as anyvar interval 100
Method Pinstripe, "Show", 1
Threads Erase
Layer 32 {Hide}
Cls
}
Checkit
|
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
| #Maple | Maple |
colors := [yellow, black, red, green, magenta, cyan, white]:
plots:-display( [
seq( plot([1+i/10,y,y=5..6], color=colors[i mod 7 + 1],thickness=1), i = 1..500),
seq( plot([1+i/10,y,y=4..5], color=colors[i mod 7 + 1],thickness=2), i = 1..500),seq( plot([1+i/10,y,y=3..4], color=colors[i mod 7 + 1],thickness=3), i = 1..500),seq( plot([1+i/10,y,y=2..3], color=colors[i mod 7 + 1],thickness=4,size=[interface(screenwidth)*20,interface(screenheight)*32]), i = 1..500)],
axes=none);
|
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | color[y_] := {Black, Red, Green, Blue, Magenta, Cyan, Yellow,
White}[[Mod[y, 8] + 1]];
Graphics[Join[{Thickness[1/408]},
Flatten[{color[#], Line[{{# - 1/2, 408}, {# - 1/2, 307}}]} & /@
Range[408]], {Thickness[1/204]},
Flatten[{color[#], Line[{{2 # - 1, 306}, {2 # - 1, 205}}]} & /@
Range[204]], {Thickness[1/136]},
Flatten[{color[#], Line[{{3 # - 3/2, 204}, {3 # - 3/2, 103}}]} & /@
Range[136]], {Thickness[1/102]},
Flatten[{color[#], Line[{{4 # - 2, 102}, {4 # - 2, 1}}]} & /@
Range[102]]], ImageSize -> {408, 408}] |
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.
| #Processing | Processing | void draw(){
color c = get(mouseX,mouseY);
println(c, red(c), green(c), blue(c));
} |
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.
| #Python | Python | def get_pixel_colour(i_x, i_y):
import win32gui
i_desktop_window_id = win32gui.GetDesktopWindow()
i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)
long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)
i_colour = int(long_colour)
win32gui.ReleaseDC(i_desktop_window_id,i_desktop_window_dc)
return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)
print (get_pixel_colour(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.
| #Racket | Racket | use GD::Raw;
my $file = '/tmp/one-pixel-screen-capture.png';
qqx/screencapture -R 123,456,1,1 $file/;
my $fh = fopen($file, "rb") or die;
my $image = gdImageCreateFromPng($fh);
my $pixel = gdImageGetPixel($image, 0, 0);
my ($red,$green,$blue) =
gdImageRed( $image, $pixel),
gdImageGreen($image, $pixel),
gdImageBlue( $image, $pixel);
say "RGB: $red, $green, $blue";
fclose($fh);
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.
| #Ring | Ring |
#===================================================================#
# Sample: Color Wheel
# Author: Gal Zsolt, Bert Mariani, Ilir Liburn & Mahmoud Fayed
#===================================================================#
load "guilib.ring"
xWidth = 400
yHeight = 400
MyApp = new qapp
{
win1 = new qwidget()
{ setwindowtitle("ColorWheel-FastDraw")
setgeometry(500,150,xWidth,yHeight)
Canvas = new qlabel(win1)
{ ### daVinci paints the MonaLisa on the Canvas
MonaLisa = new qPixMap2( xWidth, yHeight)
color = new qcolor(){ setrgb(255,255,255,0) }
pen = new qpen() { setwidth(1) }
MonaLisa.fill(color)
daVinci = new qpainter()
{ begin(MonaLisa)
#endpaint() ### This will Stop the Painting. For Animation comment it out
}
setPixMap(MonaLisa)
}
show()
}
ColorWheel()
exec()
}
//=====================
Func colorWheel
#=====================================================================#
? "Start Processing..."
t1 = clock()
? "Clock : " + t1
#=====================================================================#
aList = []
pi = 3.14159265359
diameter = pi * 2
radius = yHeight / 2
v = 1 // value/brightness 1 to 100 1=bright 0=dark
for i = 1 to xWidth
iradius = i - radius
p = pow( iradius, 2)
for j = 1 to yHeight
h = (atan2( iradius, j-radius ) + pi ) / diameter // hue/color 1 to 360
s = sqrt( p + pow( j-radius, 2)) / radius // saturation/intensity 1 to 100
if s <= 1 and h <= 1
aList + [i,j,h,s,v,1]
ok
next
next
#=====================================================================#
? "Start drawing..."
t2 = clock()
? "Clock : " + t2
#=====================================================================#
daVinci.drawHSVFList(aList)
Canvas.setPixMap(MonaLisa)
#=====================================================================#
? "Done..."
t3 = clock()
? "Clock : " + t3
#=====================================================================#
? "Processing Time: " + ( (t2-t1)/ClocksPerSecond() ) + " seconds "
? "Drawing Time: " + ( (t3-t2)/ClocksPerSecond() ) + " seconds "
? "Total Time: " + ( (t3-t1)/ClocksPerSecond() ) + " seconds "
#=====================================================================#
return
//==================
|
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.
| #Ruby | Ruby |
def settings
size(300, 300)
end
def setup
sketch_title 'Color Wheel'
background(0)
radius = width / 2.0
center = width / 2
grid(width, height) do |x, y|
rx = x - center
ry = y - center
sat = Math.hypot(rx, ry) / radius
if sat <= 1.0
hue = ((Math.atan2(ry, rx) / PI) + 1) / 2.0
color_mode(HSB)
col = color((hue * 255).to_i, (sat * 255).to_i, 255)
set(x, y, col)
end
end
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
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
sort% = FN_sortinit(0,0)
M% = 3
N% = 5
C% = FNfact(N%)/(FNfact(M%)*FNfact(N%-M%))
DIM s$(C%)
PROCcomb(M%, N%, s$())
CALL sort%, s$(0)
FOR I% = 0 TO C%-1
PRINT s$(I%)
NEXT
END
DEF PROCcomb(C%, N%, s$())
LOCAL I%, U%
FOR U% = 0 TO 2^N%-1
IF FNbits(U%) = C% THEN
s$(I%) = FNlist(U%)
I% += 1
ENDIF
NEXT
ENDPROC
DEF FNbits(U%)
LOCAL N%
WHILE U%
N% += 1
U% = U% AND (U%-1)
ENDWHILE
= N%
DEF FNlist(U%)
LOCAL N%, s$
WHILE U%
IF U% AND 1 s$ += STR$(N%) + " "
N% += 1
U% = U% >> 1
ENDWHILE
= s$
DEF FNfact(N%)
IF N%<=1 THEN = 1 ELSE = N%*FNfact(N%-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.
| #MAXScript | MAXScript | if x == 1 then
(
print "one"
)
else if x == 2 then
(
print "two"
)
else
(
print "Neither one or two"
) |
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.)
| #PASM | PASM | # This is a comment
print "Hello\n" # This is also a comment
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.)
| #Peloton | Peloton |
<@ OMT>This is a
multiline
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ColorQuantize[Import["http://rosettacode.org/mw/images/3/3f/Quantum_frog.png"],16,Dithering->False] |
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.
| #Nim | Nim | import algorithm
import nimPNG
type
Channel {.pure.} = enum R, G, B
QItem = tuple
color: array[Channel, byte] # Color of the pixel.
index: int # Position of pixel in the sequential sequence.
#---------------------------------------------------------------------------------------------------
proc quantize(bucket: openArray[QItem]; output: var seq[byte]) =
## Apply the quantization to the pixels in the bucket.
# Compute the mean value on each channel.
var means: array[Channel, int]
for qItem in bucket:
for channel in R..B:
means[channel] += qItem.color[channel].int
for channel in R..B:
means[channel] = (means[channel] / bucket.len).toInt
# Store the new colors into the pixels.
for qItem in bucket:
for channel in R..B:
output[3 * qItem.index + ord(channel)] = means[channel].byte
#---------------------------------------------------------------------------------------------------
proc medianCut(bucket: openArray[QItem]; depth: Natural; output: var seq[byte]) =
## Apply the algorithm on the bucket.
if depth == 0:
# Terminated for this bucket. Apply the quantization.
quantize(bucket, output)
return
# Compute the range of values for each channel.
var minVal: array[Channel, int] = [1000, 1000, 1000]
var maxVal: array[Channel, int] = [-1, -1, -1]
for qItem in bucket:
for channel in R..B:
let val = qItem.color[channel].int
if val < minVal[channel]: minVal[channel] = val
if val > maxVal[channel]: maxVal[channel] = val
let valRange: array[Channel, int] = [maxVal[R] - minVal[R],
maxVal[G] - minVal[G],
maxVal[B] - minVal[B]]
# Find the channel with the greatest range.
var selchannel: Channel
if valRange[R] >= valRange[G]:
if valRange[R] >= valRange[B]:
selchannel = R
else:
selchannel = B
elif valrange[G] >= valrange[B]:
selchannel = G
else:
selchannel = B
# Sort the quantization items according to the selected channel.
let sortedBucket = case selchannel
of R: sortedByIt(bucket, it.color[R])
of G: sortedByIt(bucket, it.color[G])
of B: sortedByIt(bucket, it.color[B])
# Split the bucket into two buckets.
let medianIndex = bucket.high div 2
medianCut(sortedBucket.toOpenArray(0, medianIndex), depth - 1, output)
medianCut(sortedBucket.toOpenArray(medianIndex, bucket.high), depth - 1, output)
#———————————————————————————————————————————————————————————————————————————————————————————————————
const Input = "Quantum_frog.png"
const Output = "Quantum_frog_16.png"
let pngImage = loadPNG24(seq[byte], Input).get()
# Build the first bucket.
var bucket = newSeq[QItem](pngImage.data.len div 3)
var idx: Natural = 0
for item in bucket.mitems:
item = (color: [pngImage.data[idx], pngImage.data[idx + 1], pngImage.data[idx + 2]],
index: idx div 3)
inc idx, 3
# Create the storage for the quantized image.
var data = newSeq[byte](pngImage.data.len)
# Launch the quantization.
medianCut(bucket, 4, data)
# Save the result into a PNG file.
let status = savePNG24(Output, data, pngImage.width, pngImage.height)
if status.isOk:
echo "File ", Input, " processed. Result is available in file ", Output
else:
echo "Error: ", status.error |
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.
| #XSLT | XSLT | <xsl:template match="/table">
<table>
<xsl:apply-templates />
</table>
</xsl:template>
<xsl:template match="tr">
<tr><xsl:apply-templates /></tr>
</xsl:template>
<xsl:template match="td">
<xsl:variable name="liveNeighbours">
<xsl:apply-templates select="current()" mode="countLiveNeighbours" />
</xsl:variable>
<xsl:choose>
<xsl:when test="(current() = 'X' and $liveNeighbours = 2) or $liveNeighbours = 3">
<xsl:call-template name="live" />
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="die" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="td" mode="countLiveNeighbours">
<xsl:variable name="currentX" select="count(preceding-sibling::td) + 1" />
<xsl:variable name="precedingRow" select="parent::tr/preceding-sibling::tr[1]" />
<xsl:variable name="followingRow" select="parent::tr/following-sibling::tr[1]" />
<xsl:variable name="neighbours" select="$precedingRow/td[$currentX - 1] |
$precedingRow/td[$currentX] |
$precedingRow/td[$currentX + 1] |
preceding-sibling::td[1] |
following-sibling::td[1] |
$followingRow/td[$currentX - 1] |
$followingRow/td[$currentX] |
$followingRow/td[$currentX + 1]" />
<xsl:value-of select="count($neighbours[text() = 'X'])" />
</xsl:template>
<xsl:template name="die">
<td>_</td>
</xsl:template>
<xsl:template name="live">
<td>X</td>
</xsl:template> |
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
| #Nim | Nim | import gintro/[glib, gobject, gtk, gio, cairo]
const
Width = 420
Height = 420
const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0],
[0.0, 255.0, 0.0], [0.0, 0.0, 255.0],
[255.0, 0.0, 255.0], [0.0, 255.0, 255.0],
[255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]
#---------------------------------------------------------------------------------------------------
proc draw(area: DrawingArea; context: Context) =
## Draw the color bars.
const lineHeight = Height div 4
var y = 0.0
for lineWidth in [1.0, 2.0, 3.0, 4.0]:
context.setLineWidth(lineWidth)
var x = 0.0
var colorIndex = 0
while x < Width:
context.setSource(Colors[colorIndex])
context.moveTo(x, y)
context.lineTo(x, y + lineHeight)
context.stroke()
colorIndex = (colorIndex + 1) mod Colors.len
x += lineWidth
y += lineHeight
#---------------------------------------------------------------------------------------------------
proc onDraw(area: DrawingArea; context: Context; data: pointer): bool =
## Callback to draw/redraw the drawing area contents.
area.draw(context)
result = true
#---------------------------------------------------------------------------------------------------
proc activate(app: Application) =
## Activate the application.
let window = app.newApplicationWindow()
window.setSizeRequest(Width, Height)
window.setTitle("Color pinstripe")
# Create the drawing area.
let area = newDrawingArea()
window.add(area)
# Connect the "draw" event to the callback to draw the color bars.
discard area.connect("draw", ondraw, pointer(nil))
window.showAll()
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.ColorPinstripe")
discard app.connect("activate", activate)
discard app.run() |
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
| #OCaml | OCaml | open Graphics
let () =
open_graph "";
let width = size_x ()
and height = size_y () in
let colors = [| black; red; green; blue; magenta; cyan; yellow; white |] in
let num_colors = Array.length colors in
let h = height / 4 in
for i = 1 to 4 do
let j = 4 - i in
for x = 0 to pred width do
set_color colors.((x / i) mod num_colors);
moveto x (j * h); lineto x (j * h + h);
done
done;
ignore(read_key()) |
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.
| #Raku | Raku | use GD::Raw;
my $file = '/tmp/one-pixel-screen-capture.png';
qqx/screencapture -R 123,456,1,1 $file/;
my $fh = fopen($file, "rb") or die;
my $image = gdImageCreateFromPng($fh);
my $pixel = gdImageGetPixel($image, 0, 0);
my ($red,$green,$blue) =
gdImageRed( $image, $pixel),
gdImageGreen($image, $pixel),
gdImageBlue( $image, $pixel);
say "RGB: $red, $green, $blue";
fclose($fh);
unlink $file; |
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.
| #REXX | REXX | /*REXX program obtains the cursor position (within it's window) and displays it's color.*/
parse value cursor() with r c . /*get cursor's location in DOS screen. */
hue=scrRead(r, c, 1, 'A') /*get color of the cursor's location. */
if hue=='00'x then color= 'black' /*or dark grey, dark gray. */
if hue=='01'x then color= 'darkblue'
if hue=='02'x then color= 'darkgreen'
if hue=='03'x then color= 'darkturquoise' /*or dark cyan. */
if hue=='04'x then color= 'darkred' /*or maroon. */
if hue=='05'x then color= 'darkmagenta' /*or dark pink. */
if hue=='06'x then color= 'orange' /*or dark yellow, orage, brown. */
if hue=='07'x then color= 'gray' /*or grey, gray, dark white. */
if hue=='08'x then color= 'gray' /*or grey, gray, dark white. */
if hue=='09'x then color= 'blue' /*or bright blue. */
if hue=='0A'x then color= 'green' /*or bright green. */
if hue=='0B'x then color= 'turquoise' /*or bright turquoise, cyan, britecyan.*/
if hue=='0C'x then color= 'red' /*or bright red. */
if hue=='0D'x then color= 'magenta' /*or bright magenta, pink, brite pink. */
if hue=='0E'x then color= 'yellow' /*or bright yellow. */
if hue=='0F'x then color= 'white' /*or bright, brite white. */
say 'screen location ('r","c') color is:' color /*display color of char at row, column.*/ |
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.
| #Run_BASIC | Run BASIC | ' -----------------------------------
' color wheel
' -----------------------------------
global pi
pi = 22 / 7
steps = 1
graphic #g, 525, 525
for x =0 to 525 step steps
for y =0 to 525 step steps
angle = atan2(y - 250, x - 250) * 360 / 2 / pi ' full degrees....
sector = int(angle / 60) ' 60 degree sectors (0 to 5)
slope = (angle mod 60) /60 * 255 ' 1 degree sectors.
if sector = 0 then col$ = "255 "; str$( int( slope)); " 0"
if sector = 1 then col$ = str$(int(256 - slope)); " 255 0"
if sector = 2 then col$ = "0 255 "; str$( int( slope))
if sector = 3 then col$ = "0 "; str$( int( 256 -slope)); " 255"
if sector = 4 then col$ = str$(int(slope)); " 0 255"
if sector = 5 then col$ = "255 0 "; str$( int( 256 -slope))
red = val( word$( col$, 1))
grn = val( word$( col$, 2))
blu = val( word$( col$, 3))
p = ((x -270)^2 +(y -270)^2)^0.5 / 250
r = min(255,p * red)
g = min(255,p * grn)
b = min(255,p * blu)
if p > 1 then #g "color white" else #g color(r,g,b)
#g "set "; x; " "; y
next y
next x
render #g
end
function atan2(y,x)
if (x = 0) and (y <> 0) then
r$ = "Y"
if y > 0 then atan2 = pi /2
if y < 0 then atan2 = 3 * pi /2
end if
if y = 0 and (x <> 0) then
r$ = "Y"
if x > 0 then atan2 = 0
if x < 0 then atan2 = pi
end if
If r$ <> "Y" then
if x = 0 and y = 0 then
atan2 = 0
else
baseAngle = atn(abs(y) / abs(x))
if x > 0 then
if y > 0 then atan2 = baseAngle
If y < 0 then atan2 = 2 * pi - baseAngle
end if
if x < 0 then
If y > 0 then atan2 = pi - baseAngle
If y < 0 then atan2 = pi + baseAngle
end if
end if
end if
end function |
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.
| #Rust | Rust | // [dependencies]
// image = "0.23"
use image::error::ImageResult;
use image::{Rgb, RgbImage};
fn hsv_to_rgb(h: f64, s: f64, v: f64) -> Rgb<u8> {
let hp = h / 60.0;
let c = s * v;
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
let m = v - c;
let mut r = 0.0;
let mut g = 0.0;
let mut b = 0.0;
if hp <= 1.0 {
r = c;
g = x;
} else if hp <= 2.0 {
r = x;
g = c;
} else if hp <= 3.0 {
g = c;
b = x;
} else if hp <= 4.0 {
g = x;
b = c;
} else if hp <= 5.0 {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
Rgb([(r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8])
}
fn write_color_wheel(filename: &str, width: u32, height: u32) -> ImageResult<()> {
let mut image = RgbImage::new(width, height);
let margin = 10;
let diameter = std::cmp::min(width, height) - 2 * margin;
let xoffset = (width - diameter) / 2;
let yoffset = (height - diameter) / 2;
let radius = diameter as f64 / 2.0;
for x in 0..=diameter {
let rx = x as f64 - radius;
for y in 0..=diameter {
let ry = y as f64 - radius;
let r = ry.hypot(rx) / radius;
if r > 1.0 {
continue;
}
let a = 180.0 + ry.atan2(-rx).to_degrees();
image.put_pixel(x + xoffset, y + yoffset, hsv_to_rgb(a, r, 1.0));
}
}
image.save(filename)
}
fn main() {
match write_color_wheel("color_wheel.png", 400, 400) {
Ok(()) => {}
Err(error) => eprintln!("{}", error),
}
} |
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.
| #Sidef | Sidef | require('Imager')
var (width, height) = (300, 300)
var center = Complex(width/2 , height/2)
var img = %O<Imager>.new(xsize => width, ysize => height)
for y=(^height), x=(^width) {
var vector = (center - x - y.i)
var magnitude = (vector.abs * 2 / width)
var direction = ((Num.pi + atan2(vector.real, vector.imag)) / Num.tau)
img.setpixel(x => x, y => y,
color => Hash(hsv => [360*direction, magnitude, magnitude < 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
| #Bracmat | Bracmat | (comb=
bvar combination combinations list m n pat pvar var
. !arg:(?m.?n)
& ( pat
= ?
& !combinations (.!combination):?combinations
& ~
)
& :?list:?combination:?combinations
& whl
' ( !m+-1:~<0:?m
& chu$(utf$a+!m):?var
& glf$('(%@?.$var)):(=?pvar)
& '(? ()$pvar ()$pat):(=?pat)
& glf$('(!.$var)):(=?bvar)
& ( '$combination:(=)
& '$bvar:(=?combination)
| '($bvar ()$combination):(=?combination)
)
)
& whl
' (!n+-1:~<0:?n&!n !list:?list)
& !list:!pat
| !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.
| #MBS | MBS | INT x;
x:=0;
IF x = 1 THEN
! Do something
ELSE
! Do something else
ENDIF; |
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.)
| #Perl | Perl | # this is commented |
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.)
| #Phix | Phix | -- 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.
| #OCaml | OCaml | let rem_from rem from =
List.filter ((<>) rem) from
let float_rgb (r,g,b) = (* prevents int overflow *)
(float r, float g, float b)
let round x =
int_of_float (floor (x +. 0.5))
let int_rgb (r,g,b) =
(round r, round g, round b)
let rgb_add (r1,g1,b1) (r2,g2,b2) =
(r1 +. r2,
g1 +. g2,
b1 +. b2)
let rgb_mean px_list =
let n = float (List.length px_list) in
let r, g, b = List.fold_left rgb_add (0.0, 0.0, 0.0) px_list in
(r /. n, g /. n, b /. n)
let extrems lst =
let min_rgb = (infinity, infinity, infinity)
and max_rgb = (neg_infinity, neg_infinity, neg_infinity) in
List.fold_left (fun ((sr,sg,sb), (mr,mg,mb)) (r,g,b) ->
((min sr r), (min sg g), (min sb b)),
((max mr r), (max mg g), (max mb b))
) (min_rgb, max_rgb) lst
let volume_and_dims lst =
let (sr,sg,sb), (br,bg,bb) = extrems lst in
let dr, dg, db = (br -. sr), (bg -. sg), (bb -. sb) in
(dr *. dg *. db),
(dr, dg, db)
let make_cluster pixel_list =
let vol, dims = volume_and_dims pixel_list in
let len = float (List.length pixel_list) in
(rgb_mean pixel_list, len *. vol, dims, pixel_list)
type axis = R | G | B
let largest_axis (r,g,b) =
match compare r g, compare r b with
| 1, 1 -> R
| -1, 1 -> G
| 1, -1 -> B
| _ ->
match compare g b with
| 1 -> G
| _ -> B
let subdivide ((mr,mg,mb), n_vol_prod, vol, pixels) =
let part_func =
match largest_axis vol with
| R -> (fun (r,_,_) -> r < mr)
| G -> (fun (_,g,_) -> g < mg)
| B -> (fun (_,_,b) -> b < mb)
in
let px1, px2 = List.partition part_func pixels in
(make_cluster px1, make_cluster px2)
let color_quant img n =
let width, height = get_dims img in
let clusters =
let lst = ref [] in
for x = 0 to pred width do
for y = 0 to pred height do
let rgb = float_rgb (get_pixel_unsafe img x y) in
lst := rgb :: !lst
done;
done;
ref [make_cluster !lst]
in
while (List.length !clusters) < n do
let dumb = (0.0,0.0,0.0) in
let unused = (dumb, neg_infinity, dumb, []) in
let select ((_,v1,_,_) as c1) ((_,v2,_,_) as c2) =
if v1 > v2 then c1 else c2
in
let cl = List.fold_left (fun c1 c2 -> select c1 c2) unused !clusters in
let cl1, cl2 = subdivide cl in
clusters := cl1 :: cl2 :: (rem_from cl !clusters)
done;
let module PxMap = Map.Make
(struct type t = float * float * float let compare = compare end) in
let m =
List.fold_left (fun m (mean, _, _, pixel_list) ->
let int_mean = int_rgb mean in
List.fold_left (fun m px -> PxMap.add px int_mean m) m pixel_list
) PxMap.empty !clusters
in
let res = new_img ~width ~height in
for y = 0 to pred height do
for x = 0 to pred width do
let rgb = float_rgb (get_pixel_unsafe img x y) in
let mean_rgb = PxMap.find rgb m in
put_pixel_unsafe res mean_rgb x y;
done;
done;
(res) |
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.
| #Z80_Assembly | Z80 Assembly | ;MSX Bios calls
CHPUT equ 000A2H ;print character A
CHGET equ 0009FH ;wait for keyboard input
INITXT equ 0006CH ;init TEXT1 mode (40 x 24), based on TXTNAM,TXTCGP and LINL40
LDIRVM equ 0005CH ;write BC times MEM(HL++) to VRAM(DE++)
;MSX system variables
TXTNAM equ 0F3B3H ;pattern name table
TXTCGP equ 0F3B7H ;pattern generator table
LINL40 equ 0F3AEH ;line length
;defines
LIFE_CHAR equ 0xDB ;MSX all-pixels-on character
;variables
screen equ 0E000H ;40x24 bytes
scratch equ screen+(40*24) ;table for calculations
org 04000H
;*********************************************************************
HEADER ;first 16 bytes of the rom. (as specified by MSX standard)
;*********************************************************************
db "AB" ;id
dw Main ;init
dw 0 ;statement
dw 0 ;device
dw 0 ;text
dw 0 ;reserved
dw 0 ;reserved
dw 0 ;reserved
init_tab1 db 0x18
dc 7, 0x17
db " Conway's Game Of Life "
dc 8, 0x17
db 0x19
db 0x16
dc 38, " "
db 0x16, 0x1A
dc 38, 0x17
db 0x1B
init_tab2 dc 41, 0x80
dc 38, 0
dc 41, 0x80
INITLINES equ 10
init_tab3 db " "
db " X "
db " X X "
db " XX XX XX "
db " X X XX XX "
db " XX X X XX "
db " XX X X XX X X "
db " X X X "
db " X X "
db " XX "
Expand ld bc, 40
ldir ;copy top line
push de
ld bc, 40
ldir ;copy first middle line
ex (sp), hl
ld bc, 40*21
ldir ;repeat middle line
pop hl
ld bc, 40 ;copy bottom line
ldir
ret
InitGOL ;create empty screen
ld hl, init_tab1
ld de, screen
call Expand
;Now add intial pattern
if INITLINES
ld hl, init_tab3 ;glider gun start pattern
ld de, init_tab3 ;de=hl, so ldi does not change RAM
ld bc, 40*INITLINES
ld ix, screen+40
InitGOLl ld a, (hl)
cp 'X'
jr nz, InitGOLe
ld (ix), LIFE_CHAR
InitGOLe inc ix
ldi ;hl++ and bc-- (with flag!)
jp pe, InitGOLl
else
ld hl, screen+(4*40)+18
ld a, LIFE_CHAR ;blinker start pattern
ld (hl), a
inc hl
ld (hl), a
inc hl
ld (hl), a
endif
ret
DoGOL ld hl, init_tab2 ;initialize scratchpad (sums to zero, borders marked)
ld de, scratch
call Expand
;first loop: create sums in scratchpad
ld bc, 40*24
ld hl, screen
ld de, screen ;de=hl, so ldi does not change RAM
ld ix, scratch
DoGOLsuml ld a, (hl)
cp LIFE_CHAR ;if cell is alive increase sums of all surrounding cells
jr nz, DoGOLsume
inc (ix-41)
inc (ix-40)
inc (ix-39)
inc (ix-1)
inc (ix+1)
inc (ix+39)
inc (ix+40)
inc (ix+41)
DoGOLsume inc ix
ldi ;hl++, bc-- (with flag!)
jp pe, DoGOLsuml
;second loop: update cell based on current state and sum
ld bc, 40*24
ld hl, screen
ld de, screen ;de=hl, so ldi does not change RAM
ld ix, scratch
DoGOLupdl ld a, (ix)
cp 0x7f ;border -> keep the same
jr nc, DoGOLupde
cp 3 ;3 neighbors-> always live
jr z, DoGOLlive
cp 2
jr z, DoGOLupde ;2 -> stay the same
DoGOLdie ld (hl), 0x20 ;1,4,5,6,7,8 -> always die
jr DoGoLupde
DoGOLlive ld (hl), LIFE_CHAR
DoGOLupde inc ix
ldi ;hl++, bc-- (with flag!)
jp pe, DoGOLupdl
ret
;*********************************************************************
Main
;*********************************************************************
call INITXT
call InitGOL
Mainloop ld hl, screen
ld de, (TXTNAM)
ld bc, 40*24
call LDIRVM
;call CHGET
call DoGOL
jr Mainloop
;force 16k ROM size binary output
EndOfCode dc 0x8000 - EndOfCode, 0xFF
end |
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
| #Perl | Perl | #!/usr/bin/perl -w
use strict ;
use GD ;
my $image = new GD::Image( 320 , 240 ) ;
my %colors = ( "white" => [ 255 , 255 , 255 ] , "red" => [255 , 0 , 0 ] ,
"green" => [ 0 , 255 , 0 ] , "blue" => [ 0 , 0 , 255 ] ,
"magenta" => [ 255 , 0 , 255 ] , "yellow" => [ 255 , 255 , 0 ] ,
"cyan" => [ 0 , 255 , 255 ] , "black" => [ 0 , 0 , 0 ] ) ;
my @paintcolors ;
foreach my $color ( keys %colors ) {
my $paintcolor = $image->colorAllocate( @{$colors{ $color }} ) ;
push @paintcolors, $paintcolor ;
}
my $startx = 0 ;
my $starty = 0 ;
my $run = 0 ;
my $barheight = 240 / 4 ;
my $colorindex = 0 ;
while ( $run < 4 ) {
my $barwidth = $run + 1 ;
while ( $startx + $barwidth < 320 ) {
$image->filledRectangle( $startx , $starty , $startx + $barwidth ,
$starty + $barheight - 1 , $paintcolors[ $colorindex % 8 ] ) ;
$startx += $barwidth ;
$colorindex++ ;
}
$starty += $barheight ;
$startx = 0 ;
$colorindex = 0 ;
$run++ ;
}
open ( DISPLAY , ">" , "pinstripes.png" ) || die ;
binmode DISPLAY ;
print DISPLAY $image->png ;
close DISPLAY ; |
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.
| #Ring | Ring |
# Project : Color of a screen pixel
Load "gamelib.ring"
r = 0
g = 0
b = 0
al_init()
al_init_image_addon()
display = al_create_display(1000,800)
al_set_target_bitmap(al_get_backbuffer(display))
al_clear_to_color(al_map_rgb(255,255,255))
image = al_load_bitmap("stock.jpg")
al_draw_rotated_bitmap(image,0,0,250,250,150,0)
al_draw_scaled_bitmap(image,0,0,250,250,20,20,400,400,0)
ring_getpixel(image,300,300)
see "r = " + r + nl
see "g = " + g + nl
see "b = " + b + nl
al_flip_display()
al_rest(2)
al_destroy_bitmap(image)
al_destroy_display(display)
func ring_getpixel(image,x,y)
newcolor = al_get_pixel(image,x,y)
r=copy(" ",4) g=copy(" ",4) b=copy(" ",4)
p1 = VarPtr("r","float")
p2 = VarPtr("g","float")
p3 = VarPtr("b","float")
al_unmap_rgb_f(newcolor, p1 , p2 , p3 )
r = bytes2float(r)
g = bytes2float(g)
b = bytes2float(b)
return [r,g,b]
|
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.
| #Ruby | Ruby | module Screen
IMPORT_COMMAND = '/usr/bin/import'
# Returns an array with RGB values for the pixel at the given coords
def self.pixel(x, y)
if m = `#{IMPORT_COMMAND} -silent -window root -crop 1x1+#{x.to_i}+#{y.to_i} -depth 8 txt:-`.match(/\((\d+),(\d+),(\d+)\)/)
m[1..3].map(&:to_i)
else
false
end
end
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.
| #Scala | Scala | def getColorAt(x: Int, y: Int): Color = new Robot().getPixelColor(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.
| #Smart_BASIC | Smart BASIC | ' Runs on iOS
GET SCREEN SIZE sw,sh
xmax=0.45*3/7*(sw+sh)
x0=sw/2!y0=sh/2
twopi=2*3.1415926
GRAPHICS
GRAPHICS CLEAR
DIM triX(1000), triY(1000)
triX(0)=x0 ! triY(0)=y0
steps=INT(1^2*360)+1
dAngle=twopi/steps
dAngle2=dAngle/2
REFRESH OFF
FOR i=0 TO steps-1
pal(i/steps+TintOffset)
ANGLE=i*dAngle
FILL COLOR pal.r,pal.g,pal.b
DRAW COLOR pal.r,pal.g,pal.b
x=x0+(xmax-radius)*COS(ANGLE)
y=y0-(xmax-radius)*SIN(ANGLE)
k=0
FOR j=-dAngle2 TO dAngle2 STEP 0.02
k+=1
triX(k)=x0+xmax*COS(ANGLE+j)
triY(k)=y0-xmax*SIN(ANGLE+j)
NEXT j
k+=1
triX(k)=x0+xmax*COS(ANGLE+dAngle2)
triY(k)=y0-xmax*SIN(ANGLE+dAngle2)
DRAW POLY triX,triY COUNT k+1
FILL POLY triX,triY COUNT k+1
NEXT i
REFRESH ON
END
DEF pal(tint)
tint=tint*360
h=(tint%360)/60 ! f=FRACT(h) ! z=1-f ! ic=FLOOR(h)+1
ON ic GOTO s1,s2,s3,s4,s5,s6
s1: r=1 ! g=f ! b=0 ! GOTO done
s2: r=z ! g=1 ! b=0 ! GOTO done
s3: r=0 ! g=1 ! b=f ! GOTO done
s4: r=0 ! g=z ! b=1 ! GOTO done
s5: r=f ! g=0 ! b=1 ! GOTO done
s6: r=1 ! g=0 ! b=z ! done:
END DEF |
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.
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random
class Game {
static init() {
Window.title = "Color Wheel"
__width = 640
__height = 640
Window.resize(__width, __height)
Canvas.resize(__width, __height)
colorWheel()
}
static colorWheel() {
var cx = (__width/2).floor
var cy = (__height/2).floor
var r = (cx < cy) ? cx : cy
for (y in 0...__height) {
var dy = y - cy
for (x in 0...__width) {
var dx = x - cx
var dist = (dx*dx + dy*dy).sqrt
if (dist <= r) {
var theta = dy.atan(dx)
var h = (theta + Num.pi) / Num.pi * 180
var col = Color.hsv(h, dist/r, 1)
Canvas.pset(x, y, col)
}
}
}
}
static update() {}
static draw(alpha) {}
} |
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
| #C | C | #include <stdio.h>
/* Type marker stick: using bits to indicate what's chosen. The stick can't
* handle more than 32 items, but the idea is there; at worst, use array instead */
typedef unsigned long marker;
marker one = 1;
void comb(int pool, int need, marker chosen, int at)
{
if (pool < need + at) return; /* not enough bits left */
if (!need) {
/* got all we needed; print the thing. if other actions are
* desired, we could have passed in a callback function. */
for (at = 0; at < pool; at++)
if (chosen & (one << at)) printf("%d ", at);
printf("\n");
return;
}
/* if we choose the current item, "or" (|) the bit to mark it so. */
comb(pool, need - 1, chosen | (one << at), at + 1);
comb(pool, need, chosen, at + 1); /* or don't choose it, go to next */
}
int main()
{
comb(5, 3, 0, 0);
return 0;
} |
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.
| #MDL | MDL | <COND (<==? .X 1> <PRINC "one">)
(<==? .X 2> <PRINC "two">)
(T <PRINC "something else">)> |
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.)
| #PHP | PHP | # this is commented
// this is commented |
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.)
| #Picat | Picat |
/*
* Multi-line comment
*/
% Single-line Prolog-style 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.
| #Perl | Perl | use strict;
use warnings;
use Imager;
my $img = Imager->new;
$img->read(file => 'frog.png');
my $img16 = $img->to_paletted({ max_colors => 16});
$img16->write(file => "frog-16.png") |
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.
| #Phix | Phix | -- demo\rosetta\Color_quantization.exw
include pGUI.e
function makeCluster(sequence pixels)
sequence rs = vslice(pixels,1),
gs = vslice(pixels,2),
bs = vslice(pixels,3)
integer n = length(pixels),
rd = max(rs)-min(rs),
gd = max(gs)-min(gs),
bd = max(bs)-min(bs)
atom score = n*rd*gd*bd
-- atom score = n*(rd+gd+bd) -- (this is how/where to experiment)
sequence centroid = sq_round({sum(rs)/n,sum(gs)/n,sum(bs)/n}),
ranges = {rd,gd,bd}
return {score,centroid,ranges,pixels}
end function
function colorQuant(imImage img, integer n)
integer width = im_width(img),
height = im_width(img)
-- Extract the original pixels from the image
sequence original = {}
integer dx = 1
for y=height-1 to 0 by -1 do
for x=0 to width-1 do
original = append(original,im_pixel(img, x, y)&dx)
dx += 1
end for
end for
-- Divide pixels into clusters
sequence cs = {makeCluster(original)}, unsplittable={}, centroid, volume, pixels
while length(cs)<n do
cs = sort(cs)
-- cs = reverse(sort(cs)) -- (to deliberately show a much worse result)
{?,centroid,volume,pixels} = cs[$]
integer {vr,vg,vb} = volume
integer pdx = iff(vr>vg and vr>vb?1:iff(vg>vb?2:3)),
c = centroid[pdx] -- (ie r=1, g=2, b=3)
sequence p1 = {}, p2 = {}
for i=1 to length(pixels) do
sequence p = pixels[i]
if p[pdx]<c then p1 = append(p1,p) else p2 = append(p2,p) end if
end for
if length(p1) and length(p2) then
cs[$] = makeCluster(p1)
cs = append(cs,makeCluster(p2))
else
?"unsplittable"
unsplittable = append(unsplittable,cs[$])
cs = cs[1..$-1]
n -= 1
end if
end while
cs &= unsplittable
-- substitute all pixels with the centroid (aka cluster average)
for i=1 to length(cs) do
{?,centroid,?,pixels} = cs[i]
for p=1 to length(pixels) do
dx = pixels[p][4]
original[dx] = centroid
end for
end for
original = flatten(original) -- (needed for IupImageRGB)
Ihandle new_img = IupImageRGB(width, height, original)
return new_img
end function
IupOpen()
atom pError = allocate(machine_word())
imImage im1 = imFileImageLoadBitmap("Quantum_frog.png",0,pError)
if im1=NULL then ?"error opening Quantum_frog.png" abort(0) end if
-- stolen from simple_paint (else im_pixel crashed):
-- we are going to support only RGB images with no alpha
imImageRemoveAlpha(im1)
if im_color_space(im1)!=IM_RGB then
imImage new_image = imImageCreateBased(im1, -1, -1, IM_RGB, -1)
imConvertColorSpace(im1, new_image)
im1 = imImageDestroy(im1)
im1 = new_image
end if
Ihandln image1 = IupImageFromImImage(im1),
image2 = colorQuant(im1,16),
label1 = IupLabel(),
label2 = IupLabel()
IupSetAttributeHandle(label1, "IMAGE", image1)
IupSetAttributeHandle(label2, "IMAGE", image2)
Ihandle dlg = IupDialog(IupHbox({label1, label2}))
IupSetAttribute(dlg, "TITLE", "Color quantization")
IupShow(dlg)
IupMainLoop()
IupClose() |
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.
| #Yabasic | Yabasic | // Conway's_Game_of_Life
X = 59 : Y = 35 : H = 4
open window X*H,Y*H
backcolor 0, 0, 0
dim c(X,Y) : dim cn(X,Y) : dim cl(X,Y)
// Thunderbird methuselah
c(X/2-1,Y/3+1) = 1 : c(X/2,Y/3+1) = 1 : c(X/2+1,Y/3+1) = 1
c(X/2,Y/3+3) = 1 : c(X/2,Y/3+4) = 1 : c(X/2,Y/3+5) = 1
s = 0
repeat
clear window
alive = 0 : stable = 1
s = s + 1
for y = 0 to Y-1
for x = 0 to X-1
xm1 = mod(x-1+X, X) : xp1 = mod(x+1+X, X)
ym1 = mod(y-1+Y, Y) : yp1 = mod(y+1+Y, Y)
cn(x,y) = c(xm1,y) + c(xp1,y)
cn(x,y) = c(xm1,ym1) + c(x,ym1) + c(xp1,ym1) + cn(x,y)
cn(x,y) = c(xm1,yp1) + c(x,yp1) + c(xp1,yp1) + cn(x,y)
if c(x,y) = 1 then
if cn(x,y) < 2 or cn(x,y) > 3 then
cn(x,y) = 0
else
cn(x,y) = 1
alive = alive + 1
end if
else
if cn(x,y) = 3 then
cn(x,y) = 1
alive = alive + 1
else
cn(x,y) = 0
end if
end if
if c(x,y) then
if cn(x,y) then
if cl(x,y) color 0, 0, 255 // adult
if not cl(x,y) color 0, 255, 0 // newborn
else
if cl(x,y) color 255, 0, 0 // old
if not cl(x,y) color 255, 255, 0 // shortlived
end if
fill rect x*H,y*H,x*H+H,y*H+H
end if
next x
next y
pause 0.06
// Copy arrays
for i = 0 to X-1
for j = 0 to Y-1
if cl(i,j)<>cn(i,j) stable = 0
cl(i,j) = c(i,j)
c(i,j) = cn(i,j)
next j
next i
until(not alive or stable)
if not alive then
print "Died in ", s, " iterations"
clear window
else
print "Stabilized in ", s-2, " iterations"
end if |
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
| #Phix | Phix | --
-- demo\rosetta\Colour_pinstripe.exw
-- =================================
--
with javascript_semantics -- but not yet CD_PRINTER
include pGUI.e
constant colours = {CD_BLACK, CD_RED, CD_GREEN, CD_MAGENTA, CD_CYAN, CD_YELLOW, CD_WHITE}
--constant colours = {CD_BLACK, CD_WHITE}
procedure draw_to(cdCanvas cdcanvas)
cdCanvasActivate(cdcanvas)
integer {width, height} = cdCanvasGetSize(cdcanvas)
for y=1 to 4 do
integer x = 0, c = 1, h = floor(height/(5-y))
while x<width do
cdCanvasSetForeground(cdcanvas, colours[c])
cdCanvasBox(cdcanvas, x, x+y, height-h, height)
x += y
c = iff(c=length(colours)?1:c+1)
end while
height -= h
end for
cdCanvasFlush(cdcanvas)
end procedure
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function redraw_cb(Ihandle /*ih*/)
draw_to(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
return IUP_DEFAULT
end function
function unmap_cb(Ihandle /*ih*/)
cdKillCanvas(cddbuffer)
cdKillCanvas(cdcanvas)
return IUP_DEFAULT
end function
function print_cb(Ihandle /*ih*/)
if platform()!=JS then
cdCanvan print_canvas = cdCreateCanvas(CD_PRINTER, "pinstripe -d")
if print_canvas!=NULL then
draw_to(print_canvas)
cdKillCanvas(print_canvas)
end if
end if
return IUP_DEFAULT
end function
function exit_cb(Ihandle /*ih*/)
return IUP_CLOSE
end function
procedure main()
IupOpen()
Ihandle file_menu = IupMenu({IupMenuItem("&Print",Icallback("print_cb")),
IupMenuItem("E&xit", Icallback("exit_cb"))})
Ihandle main_menu = IupMenu({IupSubmenu("File", file_menu)})
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "600x400") -- initial size
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "UNMAP_CB", Icallback("unmap_cb"))
dlg = IupDialog(canvas)
IupSetAttribute(dlg, "TITLE", "Colour pinstripe")
IupSetAttributeHandle(dlg,"MENU",main_menu)
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
IupShowXY(dlg,IUP_CENTER,IUP_CENTER)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
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.
| #Smalltalk | Smalltalk | Display rootView colorAt:(10@10).
Display rootView colorAt:(Display pointerPosition) |
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.
| #Standard_ML | Standard ML | open XWindows ;
val disp = XOpenDisplay "" ;
val im =
let
val pos = #4 (XQueryPointer (RootWindow disp)) ;
in
XGetImage (RootWindow disp) (MakeRect pos (AddPoint(pos,XPoint{x=1,y=1})) ) AllPlanes ZPixmap
end;
XGetPixel disp im (XPoint {x=0,y=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.
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
# Farm out grabbing the screen to an external program.
# If it was just for a Tk window, we'd use the tkimg library instead
proc grabScreen {image} {
set pipe [open {|xwd -root -silent | convert xwd:- ppm:-} rb]
$image put [read $pipe]
close $pipe
}
# Get the RGB data for a particular pixel (global coords)
proc getPixelAtPoint {x y} {
set buffer [image create photo]
grabScreen $buffer
set data [$image get $x $y]
image delete $buffer
return $data
}
# Demo...
puts [format "pixel at mouse: (%d,%d,%d)" \
{*}[getPixelAtPoint {*}[winfo pointerxy .]]] |
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.
| #XPL0 | XPL0 | def Radius = 480/2;
real Hue, Sat, Dist, I, F, P, Q, T;
real XX, YY, RR, GG, BB;
int X, Y, R, G, B;
def Pi = 3.141592654;
def V = 1.; \Value
[SetVid($112); \640x480x24 graphics
for Y:= -Radius to Radius do
for X:= -Radius to Radius do
[XX:= float(X);
YY:= float(Y);
Dist:= sqrt(XX*XX + YY*YY);
if Dist <= float(Radius) then
[Sat:= Dist/float(Radius); \0 >= Sat <= 1
Hue:= ATan2(YY, XX); \-Pi >= Hue <= Pi
if Hue < 0. then Hue:= Hue + 2.*Pi;
Hue:= Hue * 180./Pi; \radians to degrees
Hue:= Hue / 60.; \0 >= Hue < 6
I:= Floor(Hue); \integer part of Hue
F:= Hue - I; \fractional part of Hue
P:= 1. - Sat;
Q:= 1. - Sat*F;
T:= 1. - Sat*(1.-F);
case fix(I) of
0: [RR:= V; GG:= T; BB:= P];
1: [RR:= Q; GG:= V; BB:= P];
2: [RR:= P; GG:= V; BB:= T];
3: [RR:= P; GG:= Q; BB:= V];
4: [RR:= T; GG:= P; BB:= V];
5: [RR:= V; GG:= P; BB:= Q]
other [exit 1];
R:= fix(RR*255.);
G:= fix(GG*255.);
B:= fix(BB*255.);
Point(X+Radius, Radius-Y, R<<16+G<<8+B);
];
];
] |
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.
| #zkl | zkl | var w=300,h=300,out=PPM(w,h);
colorWheel(out);
out.writeJPGFile("colorWheel.zkl.jpg");
fcn colorWheel(ppm){
zero,R:=ppm.w/2, zero;
foreach x,y in (w,h){
v,hue:=(x - zero).toFloat().toPolar(y - zero);
if(v<=R){ // only render in the circle
if((hue = hue.toDeg())<0) hue+=360; // (-pi..pi] to [0..2pi)
s:=v/R; // scale saturation zero at center to 1 at edge
ppm[x,y]=hsv2rgb(hue,1.0,s);
}
}
}
fcn hsv2rgb(hue,v,s){ // 0<=H<360, 0<=v(brightness)<=1, 0<=saturation<=1
// --> 24 bit RGB each R,G,B in [0..255]
to24bit:=fcn(r,g,b,m){
r,g,b=((r+m)*255).toInt(),((g+m)*255).toInt(),((b+m)*255).toInt();
r*0x10000 + g*0x100 + b
};
c:=v*s;
x:=c*(1.0 - (hue.toFloat()/60%2 - 1).abs());
m:=v - c;
if (0 <=hue< 60) return(to24bit(c, x, 0.0,m));
else if(60 <=hue<120) return(to24bit(x, c, 0.0,m));
else if(120<=hue<180) return(to24bit(0.0,c, x, m));
else if(180<=hue<240) return(to24bit(0.0,x, c, m));
else if(240<=hue<300) return(to24bit(x, 0.0,c, m));
else return(to24bit(c, 0.0,x, m));
} |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<int[]> Combinations(int m, int n)
{
int[] result = new int[m];
Stack<int> stack = new Stack<int>();
stack.Push(0);
while (stack.Count > 0)
{
int index = stack.Count - 1;
int value = stack.Pop();
while (value < n)
{
result[index++] = ++value;
stack.Push(value);
if (index == m)
{
yield return result;
break;
}
}
}
}
static void Main()
{
foreach (int[] c in Combinations(3, 5))
{
Console.WriteLine(string.Join(",", c));
Console.WriteLine();
}
}
} |
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.
| #Metafont | Metafont | if conditionA:
% do something
elseif conditionB:
% do something
% more elseif, if needed...
else:
% do this
fi; |
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.)
| #PicoLisp | PicoLisp | # The rest of the line is ignored
#{
This is a
multiline comment
}#
NIL
Immediately stop reading this file. Because all text in the input file following
a top-level 'NIL' is ignored.
This is typically used conditionally, with a read-macro expression like
`*Dbg
so that this text is only read if in debugging mode. |
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.)
| #Pike | Pike | // This is a comment.
/* This is a
multi
line
comment */
int e = 3; // end-of-statement 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.
| #PureBasic | PureBasic |
; ColorQuantization.pb
Structure bestA_ ; table for our histogram
nn.i ; 16,32,...
rc.i ; red count within (0,1,...,255)/(number of colors)
gc.i ; green count within (0,1,...,255)/(number of colors)
bc.i ; blue count within (0,1,...,255)/(number of colors)
EndStructure
; these two functions appear to be rather self-explanatory
UsePNGImageDecoder()
UsePNGImageEncoder()
Procedure.i ColorQuantization(Filename$,ncol)
Protected x,y,c
; load our original image or leave the procedure
If not LoadImage(0,Filename$) :ProcedureReturn 0:endif
; we are not going to actually draw on the original image...
; but we need to use the drawing library to load up
; the pixel information into our arrays...
; if we can't do that, what's the point of going any further?
; so then we would be wise to just leave the procedure [happy fred?]
If not StartDrawing(ImageOutput(0)):ProcedureReturn 0:endif
iw=ImageWidth(0)
ih=ImageHeight(0)
dim cA(iw,ih) ; color array to hold at a given (x,y)
dim rA(iw,ih) ; red array to hold at a given (x,y)
dim gA(iw,ih) ; green array to hold at a given (x,y)
dim bA(iw,ih) ; blue array to hold at a given (x,y)
dim tA(iw,ih) ; temp array to hold at a given (x,y)
; map each pixel from the original image to our arrays
; don't overrun the ranges ie. use {ih-1,iw-1}
for y=0 to ih-1
for x=0 to iw-1
c = Point(x,y)
cA(x,y)=c
rA(x,y)=Red(c)
gA(x,y)=Green(c)
bA(x,y)=Blue(c)
next
next
StopDrawing() ; don't forget to... StopDrawing()
N=ih*iw
; N is the total number if pixels
if not N:ProcedureReturn 0:endif ; to avoid a division by zero
; stuctured array ie. a table to hold the frequency distribution
dim bestA.bestA_(ncol)
; the "best" red,green,blue based upon frequency
dim rbestA(ncol/3)
dim gbestA(ncol/3)
dim bbestA(ncol/3)
; split the (0..255) range up
xoff=256/ncol ;256/16=16
xrng=xoff ;xrng=16
; store these values in our table: bestA(i)\nn= 16,32,...
for i=1 to ncol
xrng+xoff
bestA(i)\nn=xrng
next
; scan by row [y]
for y=0 to ih-1
; scan by col [x]
for x=0 to iw-1
; retrieve the rgb values from each pixel
r=rA(x,y)
g=gA(x,y)
b=bA(x,y)
; sum up the numbers that fall within our subdivisions of (0..255)
for i=1 to ncol
if r>=bestA(i)\nn and r<bestA(i+1)\nn:bestA(i)\rc+1:endif
if g>=bestA(i)\nn and g<bestA(i+1)\nn:bestA(i)\gc+1:endif
if b>=bestA(i)\nn and b<bestA(i+1)\nn:bestA(i)\bc+1:endif
next
next
next
; option and type to: Sort our Structured Array
opt=#PB_Sort_Descending
typ=#PB_Sort_Integer
; sort to get most frequent reds
off=OffsetOf(bestA_\rc)
SortStructuredArray(bestA(),opt, off, typ,1, ncol)
; save the best [ for number of colors =16 this is int(16/3)=5 ] reds
for i=1 to ncol/3
rbestA(i)=bestA(i)\nn
next
; sort to get most frequent greens
off=OffsetOf(bestA_\gc)
SortStructuredArray(bestA(),opt, off, typ,1, ncol)
; save the best [ for number of colors =16 this is int(16/3)=5 ] greens
for i=1 to ncol/3
gbestA(i)=bestA(i)\nn
next
; sort to get most frequent blues
off=OffsetOf(bestA_\bc)
SortStructuredArray(bestA(),opt, off, typ,1, ncol)
; save the best [ for number of colors =16 this is int(16/3)=5 ] blues
for i=1 to ncol/3
bbestA(i)=bestA(i)\nn
next
; reset the best low value to 15 and high value to 240
; this helps to ensure there is some contrast when the statistics bunch up
; ie. when a single color tends to predominate... such as perhaps green?
rbestA(1)=15:rbestA(ncol/3)=240
gbestA(1)=15:gbestA(ncol/3)=240
bbestA(1)=15:bbestA(ncol/3)=240
; make a copy of our original image or leave the procedure
If not CopyImage(0,1) :ProcedureReturn 0:endif
; draw on that copy of our original image or leave the procedure
If not StartDrawing(ImageOutput(1)):ProcedureReturn 0:endif
for y=0 to ih-1
for x=0 to iw-1
c = Point(x,y)
; get the rgb value from our arrays
rt=rA(x,y)
gt=gA(x,y)
bt=bA(x,y)
; given a particular red value say 123 at point x,y
; which of our rbestA(i's) is closest?
; then for green and blue?
; ==============================
r=255
for i=1 to ncol/3
rdiff=abs(rbestA(i)-rt)
if rdiff<=r:ri=i:r=rdiff:endif
next
g=255
for i=1 to ncol/3
gdiff=abs(gbestA(i)-gt)
if gdiff<=g:gi=i:g=gdiff:endif
next
b=255
for i=1 to ncol/3
bdiff=abs(bbestA(i)-bt)
if bdiff<=b:bi=i:b=bdiff:endif
next
; ==============================
; get the color value so we can plot it at that pixel
Color=RGB(rbestA(ri),gbestA(gi),bbestA(bi))
; plot it at that pixel
Plot(x,y,Color)
; save that info to tA(x,y) for our comparison image
tA(x,y)=Color
next
next
StopDrawing() ; don't forget to... StopDrawing()
; create a comparison image of our original vs 16-color or leave the procedure
If not CreateImage(2,iw*2,ih) :ProcedureReturn 0:endif
; draw on that image both our original image and our 16-color image or leave the procedure
If not StartDrawing(ImageOutput(2)):ProcedureReturn 0:endif
; plot original image
; 0,0 .... 511,0
; .
; .
; 511,0 .. 511,511
for y=0 to ih-1
for x=0 to iw-1
c = cA(x,y)
Plot(x,y,c)
next
next
; plot 16-color image to the right of original image
; 512,0 .... 1023,0
; .
; .
; 512,511 .. 1023,511
for y=0 to ih-1
for x=0 to iw-1
c = tA(x,y)
Plot(x+iw,y,c)
next
next
StopDrawing() ; don't forget to... StopDrawing()
; save the single 16-color image
SaveImage(1, "_single_"+str(ncol)+"_"+Filename$,#PB_ImagePlugin_PNG )
; save the comparison image
SaveImage(2, "_compare_"+str(ncol)+"_"+Filename$,#PB_ImagePlugin_PNG )
ProcedureReturn 1
EndProcedure
ColorQuantization("Quantum_frog.png",16)
|
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.
| #zkl | zkl | class Life{
fcn init(n, r1,c1, r2,c2, etc){
var N=n, cells=Data(n*n), tmp=Data(n*n),
ds=T(T(-1,-1),T(-1,0),T(-1,1), T(0,-1),T(0,1), T(1,-1),T(1,0),T(1,1));
icells:=vm.arglist[1,*];
(N*N).pump(Void,cells.append.fpM("1-",0)); // clear board
icells.pump(Void,Void.Read,fcn(row,col){ cells[row*N+col]=1 });
}
fcn get(row,col){
if((0<=row<N) and (0<=col<N)) return(cells[row*N+col]);
return(0);
}
fcn postToastie(row,col){
n:=ds.reduce('wrap(n,[(r,c)]){n+get(r+row,c+col)},0);
c:=get(row,col);
((n==2 and c==1) or n==3).toInt()
}
fcn cycle{
tmp.clear();
foreach row in (N){ foreach col in (N) {
tmp.append(postToastie(row,col)) } }
t:=cells; cells=tmp; tmp=t;
}
fcn toString{
cells.pump(0,String,fcn(c,rn){
(if(c)"*" else "-") + (if(rn.inc()%N) "" else "\n")
}.fp1(Ref(1)));
}
fcn toAnsi{
cells.pump(0,"\e[H",fcn(c,rn){
(if(c)"\e[07m \e[m" else " ") + (if(rn.inc()%N) "" else "\e[E")
}.fp1(Ref(1)));
}
fcn dance(n=300){ do(n){ toAnsi().print(); Atomic.sleep(0.2); cycle(); } }
} |
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
| #PicoLisp | PicoLisp | (de *Colors # Black Red Green Blue Magenta Cyan Yellow White
((0 0 0) (255 0 0) (0 255 0) (0 0 255)
(255 0 255) (0 255 255) (255 255 0) (255 255 255) .) )
(let Ppm # Create PPM of 384 x 288 pixels
(make
(for N 4
(let L
(make
(do (/ 384 N)
(let C (pop *Colors)
(do N (link C)) ) ) )
(do 72 (link L)) ) ) )
(out '(display) # Pipe to ImageMagick
(prinl "P6") # NetPBM format
(prinl (length (car Ppm)) " " (length Ppm))
(prinl 255)
(for Y Ppm (for X Y (apply wr X))) ) ) |
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
| #Plain_English | Plain English | To run:
Start up.
Clear the screen.
Imagine a box with the screen's left and the screen's top and the screen's right and the screen's bottom divided by 4.
Make a color pinstripe given 1 pixel and the box.
Draw the color pinstripe.
Draw the next color pinstripe given the color pinstripe.
Draw the next color pinstripe given the color pinstripe.
Draw the next color pinstripe given the color pinstripe.
Refresh the screen.
Wait for the escape key.
Shut down.
A color pinstripe has a width and a box.
To make a color pinstripe given a width and a box:
Put the width into the color pinstripe's width.
Put the box into the color pinstripe's box.
To draw a color pinstripe:
Put the color pinstripe's box into a bound box.
Put the color pinstripe's width into a width.
Imagine a box with the bound's left and the bound's top and the width and the bound's bottom.
Put the bound's right divided by the width into an amount.
Loop.
If a counter is past the amount, exit.
Draw and fill the box with the black color. Move the box right the width.
Draw and fill the box with the red color. Move the box right the width.
Draw and fill the box with the green color. Move the box right the width.
Draw and fill the box with the blue color. Move the box right the width.
Draw and fill the box with the magenta color. Move the box right the width.
Draw and fill the box with the cyan color. Move the box right the width.
Draw and fill the box with the yellow color. Move the box right the width.
Draw and fill the box with the white color.
Repeat.
To draw the next color pinstripe given a color pinstripe:
Add 1 pixel to the color pinstripe's width.
Move the color pinstripe's box down the color pinstripe's box's height.
Draw the color pinstripe. |
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
| #PureBasic | PureBasic | ;Create a Pinstripe image with a pattern of vertical stripe colors
Procedure PinstripeDisplay(width, height, Array psColors(1), numColors = 0)
Protected x, imgID, psHeight = height / 4, psWidth = 1, psTop, horzBand, curColor
If numColors < 1: numColors = ArraySize(psColors()) + 1: EndIf
imgID = CreateImage(#PB_Any, width, height)
If imgID
StartDrawing(ImageOutput(imgID))
Repeat
x = 0
curColor = 0
Repeat
Box(x, psTop, psWidth, psHeight, psColors(curColor))
curColor = (curColor + 1) % numColors
x + psWidth
Until x >= width
psWidth + 1
horzBand + 1
psTop = horzBand * height / 4 ;move to the top of next horizontal band of image
Until psTop >= height
StopDrawing()
EndIf
ProcedureReturn imgID
EndProcedure
;Open a window and display the pinstripe
If OpenWindow(0, 0, 0, 1, 1,"PureBasic Pinstripe", #PB_Window_Maximize | #PB_Window_SystemMenu)
Dim psColors(7)
psColors(0) = RGB($00, $00, $00) ;black
psColors(1) = RGB($FF, $00, $00) ;red
psColors(2) = RGB($00, $FF, $00) ;green
psColors(3) = RGB($00, $00, $FF) ;blue
psColors(4) = RGB($FF, $00, $FF) ;magenta
psColors(5) = RGB($00, $FF, $FF) ;cyan
psColors(6) = RGB($FF, $FF, $00) ;yellow
psColors(7) = RGB($FF, $FF, $FF) ;white
PicID = PinstripeDisplay(WindowWidth(0), WindowHeight(0), psColors())
ImageGadget(0, 0, 0, WindowWidth(0), WindowHeight(0), ImageID(PicID))
While WaitWindowEvent() <> #PB_Event_CloseWindow
Wend
EndIf |
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.
| #Wren | Wren | import "dome" for Window, Process
import "graphics" for Canvas, Color
import "input" for Mouse
class Game {
static init() {
Window.title = "Color of a screen pixel"
Canvas.cls(Color.orange) // {255, 163, 0} in the default palette
}
static update() {
// report location and color of pixel at mouse cursor
// when the left button is first pressed
if (Mouse.isButtonPressed("left")) {
var x = Mouse.x
var y = Mouse.y
var col = Canvas.pget(x, y)
System.print("The color of the pixel at (%(x), %(y)) is %(getRGB(col))")
Process.exit(0)
}
}
static draw(dt) {}
static getRGB(col) { "{%(col.r), %(col.g), %(col.b)}" }
} |
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.
| #XPL0 | XPL0 | code ReadPix=44;
int Color, X, Y;
Color:= ReadPix(X, Y); |
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
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <string>
void comb(int N, int K)
{
std::string bitmask(K, 1); // K leading 1's
bitmask.resize(N, 0); // N-K trailing 0's
// print integers and permute bitmask
do {
for (int i = 0; i < N; ++i) // [0..N-1] integers
{
if (bitmask[i]) std::cout << " " << i;
}
std::cout << std::endl;
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}
int main()
{
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.
| #min | min | (true) ("I'm true") ("I'm false") if ; If first quotation evaluates to true,
; evaluate second quotation.
; Otherwise, evaluate the third.
(true) ("I'm true") when ; If without the false quotation.
(true) ("I'm false") unless ; If without the true quotation.
2 ( ; For each quotation inside the case
((3 >) ("Greater than 3" puts!)) ; quotation, evaluate the second
((3 <) ("Smaller than 3" puts!)) ; quotation if the first quotation
((true) ("Exactly 3" puts!)) ; evaluates to true. Otherwise, move
) case ; on to the next one. |
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.)
| #PL.2FI | PL/I | /* 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.)
| #PL.2FSQL | PL/SQL | --this is a single 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.
| #Python | Python | from PIL import Image
if __name__=="__main__":
im = Image.open("frog.png")
im2 = im.quantize(16)
im2.show() |
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.
| #Racket | Racket |
#lang racket/base
(require racket/class
racket/draw)
;; This is an implementation of the Octree Quantization algorithm. This implementation
;; follows the sketch in:
;;
;; Dean Clark. Color Quantization using Octrees. Dr. Dobbs Portal, January 1, 1996.
;; http://www.ddj.com/184409805
;;
;; This code is adapted from the color quantizer in the implementation of Racket's
;; file/gif standard library.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; To view an example of the quantizer, run the following test submodule
;; in DrRacket:
(module+ test
(require racket/block net/url)
(define frog
(block
(define url (string->url "http://rosettacode.org/mw/images/3/3f/Quantum_frog.png"))
(define frog-ip (get-pure-port url))
(define bitmap (make-object bitmap% frog-ip))
(close-input-port frog-ip)
bitmap))
;; Display the original:
(print frog)
;; And the quantized version (16 colors):
(print (quantize-bitmap frog 16)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; quantize-bitmap: bitmap positive-number -> bitmap
;; Given a bitmap, returns a new bitmap quantized to, at most, n colors.
(define (quantize-bitmap bm n)
(let* ([width (send bm get-width)]
[height (send bm get-height)]
[len (* width height 4)]
[source-buffer (make-bytes len)]
[_ (send bm get-argb-pixels 0 0 width height source-buffer)]
[an-octree (make-octree-from-argb source-buffer n)]
[dest-buffer (make-bytes len)])
(let quantize-bitmap-loop ([i 0])
(when (< i len)
(let* ([i+1 (+ i 1)]
[i+2 (+ i 2)]
[i+3 (+ i 3)]
[a (bytes-ref source-buffer i)]
[r (bytes-ref source-buffer i+1)]
[g (bytes-ref source-buffer i+2)]
[b (bytes-ref source-buffer i+3)])
(cond
[(alpha-opaque? a)
(let-values ([(new-r new-g new-b)
(octree-lookup an-octree r g b)])
(bytes-set! dest-buffer i 255)
(bytes-set! dest-buffer i+1 new-r)
(bytes-set! dest-buffer i+2 new-g)
(bytes-set! dest-buffer i+3 new-b))]
[else
(bytes-set! dest-buffer i 0)
(bytes-set! dest-buffer i+1 0)
(bytes-set! dest-buffer i+2 0)
(bytes-set! dest-buffer i+3 0)]))
(quantize-bitmap-loop (+ i 4))))
(let* ([new-bm (make-object bitmap% width height)]
[dc (make-object bitmap-dc% new-bm)])
(send dc set-argb-pixels 0 0 width height dest-buffer)
(send dc set-bitmap #f)
new-bm)))
;; make-octree-from-argb: bytes positive-number -> octree
;; Constructs an octree ready to quantize the colors from an-argb.
(define (make-octree-from-argb an-argb n)
(unless (> n 0)
(raise-type-error 'make-octree-from-argb "positive number" n))
(let ([an-octree (new-octree)]
[len (bytes-length an-argb)])
(let make-octree-loop ([i 0])
(when (< i len)
(let ([a (bytes-ref an-argb i)]
[r (bytes-ref an-argb (+ i 1))]
[g (bytes-ref an-argb (+ i 2))]
[b (bytes-ref an-argb (+ i 3))])
(when (alpha-opaque? a)
(octree-insert-color! an-octree r g b)
(let reduction-loop ()
(when (> (octree-leaf-count an-octree) n)
(octree-reduce! an-octree)
(reduction-loop)))))
(make-octree-loop (+ i 4))))
(octree-finalize! an-octree)
an-octree))
;; alpha-opaque? byte -> boolean
;; Returns true if the alpha value is considered opaque.
(define (alpha-opaque? a)
(>= a 128))
;; The maximum level height of an octree.
(define MAX-LEVEL 7)
;; A color is a (vector byte byte byte)
;; An octree is a:
(define-struct octree (root ; node
leaf-count ; number
reduction-heads ; (vectorof (or/c node #f))
palette) ; (vectorof (or/c color #f))
#:mutable)
;; reduction-heads is used to accelerate the search for a reduction candidate.
;; A subtree node is a:
(define-struct node (leaf? ; bool
npixels ; number -- number of pixels this subtree node represents
redsum ; number
greensum ; number
bluesum ; number
children ; (vectorof (or/c #f node))
next ; (or/c #f node)
palette-index) ; (or/c #f byte?)
#:mutable)
;; node-next is used to accelerate the search for a reduction candidate.
;; new-octree: -> octree
(define (new-octree)
(let* ([root-node (make-node #f ;; not a leaf
0 ;; no pixels under us yet
0 ;; red sum
0 ;; green sum
0 ;; blue sum
(make-vector 8 #f) ;; no children so far
#f ;; next
#f ;; palette-index
)]
[an-octree
(make-octree root-node
0 ; no leaves so far
(make-vector (add1 MAX-LEVEL) #f) ; no reductions so far
(make-vector 256 #(0 0 0)))]) ; the palette
;; Although we'll almost never reduce to this level, initialize the first
;; reducible node to the root, for completeness sake.
(vector-set! (octree-reduction-heads an-octree) 0 root-node)
an-octree))
;; rgb->index: natural-number byte byte byte -> octet
;; Given a level and an (r,g,b) triplet, returns an octet that can be used
;; as an index into our octree structure.
(define (rgb->index level r g b)
(bitwise-ior (bitwise-and 4 (arithmetic-shift r (- level 5)))
(bitwise-and 2 (arithmetic-shift g (- level 6)))
(bitwise-and 1 (arithmetic-shift b (- level 7)))))
;; octree-insert-color!: octree byte byte byte -> void
;; Accumulates a new r,g,b triplet into the octree.
(define (octree-insert-color! an-octree r g b)
(node-insert-color! (octree-root an-octree) an-octree r g b 0))
;; node-insert-color!: node octree byte byte byte natural-number -> void
;; Adds a color to the node subtree. While we hit #f, we create new nodes.
;; If we hit an existing leaf, we accumulate our color into it.
(define (node-insert-color! a-node an-octree r g b level)
(let insert-color-loop ([a-node a-node]
[level level])
(cond [(node-leaf? a-node)
;; update the leaf with the new color
(set-node-npixels! a-node (add1 (node-npixels a-node)))
(set-node-redsum! a-node (+ (node-redsum a-node) r))
(set-node-greensum! a-node (+ (node-greensum a-node) g))
(set-node-bluesum! a-node (+ (node-bluesum a-node) b))]
[else
;; create the child node if necessary
(let ([index (rgb->index level r g b)])
(unless (vector-ref (node-children a-node) index)
(let ([new-node (make-node (= level MAX-LEVEL) ; leaf?
0 ; npixels
0 ; redsum
0 ; greensum
0 ; bluesum
(make-vector 8 #f) ; no children yet
#f ; and no next node yet
#f ; or palette index
)])
(vector-set! (node-children a-node) index new-node)
(cond
[(= level MAX-LEVEL)
;; If we added a leaf, mark it in the octree.
(set-octree-leaf-count! an-octree
(add1 (octree-leaf-count an-octree)))]
[else
;; Attach the node as a reducible node if it's interior.
(set-node-next!
new-node (vector-ref (octree-reduction-heads an-octree)
(add1 level)))
(vector-set! (octree-reduction-heads an-octree)
(add1 level)
new-node)])))
;; and recur on the child node.
(insert-color-loop (vector-ref (node-children a-node) index)
(add1 level)))])))
;; octree-reduce!: octree -> void
;; Reduces one of the subtrees, collapsing the children into a single node.
(define (octree-reduce! an-octree)
(node-reduce! (pop-reduction-candidate! an-octree) an-octree))
;; node-reduce!: node octree -> void
;; Reduces the interior node.
(define (node-reduce! a-node an-octree)
(for ([child (in-vector (node-children a-node))]
#:when child)
(set-node-npixels! a-node (+ (node-npixels a-node)
(node-npixels child)))
(set-node-redsum! a-node (+ (node-redsum a-node)
(node-redsum child)))
(set-node-greensum! a-node (+ (node-greensum a-node)
(node-greensum child)))
(set-node-bluesum! a-node (+ (node-bluesum a-node)
(node-bluesum child)))
(set-octree-leaf-count! an-octree (sub1 (octree-leaf-count an-octree))))
(set-node-leaf?! a-node #t)
(set-octree-leaf-count! an-octree (add1 (octree-leaf-count an-octree))))
;; find-reduction-candidate!: octree -> node
;; Returns a bottom-level interior node for reduction. Also takes the
;; candidate out of the conceptual queue of reduction candidates.
(define (pop-reduction-candidate! an-octree)
(let loop ([i MAX-LEVEL])
(cond
[(vector-ref (octree-reduction-heads an-octree) i)
=>
(lambda (candidate-node)
(when (> i 0)
(vector-set! (octree-reduction-heads an-octree) i
(node-next candidate-node)))
candidate-node)]
[else
(loop (sub1 i))])))
;; octree-finalize!: octree -> void
;; Finalization does a few things:
;; * Walks through the octree and reduces any interior nodes with just one leaf child.
;; Optimizes future lookups.
;; * Fills in the palette of the octree and the palette indexes of the leaf nodes.
;; * Note: palette index 0 is always reserved for the transparent color.
(define (octree-finalize! an-octree)
;; Collapse one-leaf interior nodes.
(let loop ([a-node (octree-root an-octree)])
(for ([child (in-vector (node-children a-node))]
#:when (and child (not (node-leaf? child))))
(loop child)
(when (interior-node-one-leaf-child? a-node)
(node-reduce! a-node an-octree))))
;; Attach palette entries.
(let ([current-palette-index 1])
(let loop ([a-node (octree-root an-octree)])
(cond [(node-leaf? a-node)
(let ([n (node-npixels a-node)])
(vector-set! (octree-palette an-octree) current-palette-index
(vector (quotient (node-redsum a-node) n)
(quotient (node-greensum a-node) n)
(quotient (node-bluesum a-node) n)))
(set-node-palette-index! a-node current-palette-index)
(set! current-palette-index (add1 current-palette-index)))]
[else
(for ([child (in-vector (node-children a-node))]
#:when child)
(loop child))]))))
;; interior-node-one-leaf-child?: node -> boolean
(define (interior-node-one-leaf-child? a-node)
(let ([child-list (filter values (vector->list (node-children a-node)))])
(and (= (length child-list) 1)
(node-leaf? (car child-list)))))
;; octree-lookup: octree byte byte byte -> (values byte byte byte)
;; Returns the palettized color.
(define (octree-lookup an-octree r g b)
(let* ([index (node-lookup-index (octree-root an-octree) an-octree r g b 0)]
[vec (vector-ref (octree-palette an-octree) index)])
(values (vector-ref vec 0)
(vector-ref vec 1)
(vector-ref vec 2))))
;; node-lookup-index: node byte byte byte natural-number -> byte
;; Returns the palettized color index.
(define (node-lookup-index a-node an-octree r g b level)
(let loop ([a-node a-node]
[level level])
(if (node-leaf? a-node)
(node-palette-index a-node)
(let ([child (vector-ref (node-children a-node) (rgb->index level r g b))])
(unless child
(error 'node-lookup-index
"color (~a, ~a, ~a) not previously inserted"
r g b))
(loop child (add1 level))))))
|
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #6502_Assembly | 6502 Assembly | lda #0
tax
tay ;clear regs
;video ram on Easy6502 is four pages ranging from $0200-$0500
loop:
sta $0200,x
sta $0220,x
sta $0240,x
sta $0260,x
sta $0280,x
sta $02A0,x
sta $02C0,x
sta $02E0,x
sta $0300,x
sta $0320,x
sta $0340,x
sta $0360,x
sta $0380,x
sta $03A0,x
sta $03C0,x
sta $03E0,x
sta $0400,x
sta $0420,x
sta $0440,x
sta $0460,x
sta $0480,x
sta $04A0,x
sta $04C0,x
sta $04E0,x
sta $0500,x
sta $0520,x
sta $0540,x
sta $0560,x
sta $0580,x
sta $05A0,x
sta $05C0,x
sta $05E0,x
inx
txa ;effectively increment A
cpx #$20 ;32 columns of video memory
beq exit
jmp loop
exit:
brk ;on easy6502 this terminates a program. |
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.
| #ZPL | ZPL | program Life;
config var
n : integer = 100;
region
BigR = [0 .. n+1, 0 .. n+1];
R = [1 .. n, 1 .. n ];
direction
nw = [-1, -1]; north = [-1, 0]; ne = [-1, 1];
west = [ 0, -1]; east = [ 0, 1];
sw = [ 1, -1]; south = [ 1, 0]; se = [ 1, 1];
var
TW : [BigR] boolean; -- The World
NN : [R] integer; -- Number of Neighbours
procedure Life();
begin
-- Initialize world
[R] repeat
NN := TW@nw + TW@north + TW@ne +
TW@west + TW@east +
TW@sw + TW@south + TW@se;
TW := (TW & NN = 2) | ( NN = 3);
until !(|<< TW);
end; |
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
| #Python | Python |
from turtle import *
colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]
# Middle of screen is 0,0
screen = getscreen()
left_edge = -screen.window_width()//2
right_edge = screen.window_width()//2
quarter_height = screen.window_height()//4
half_height = quarter_height * 2
speed("fastest")
for quarter in range(4):
pensize(quarter+1)
colornum = 0
min_y = half_height - ((quarter + 1) * quarter_height)
max_y = half_height - ((quarter) * quarter_height)
for x in range(left_edge,right_edge,quarter+1):
penup()
pencolor(colors[colornum])
colornum = (colornum + 1) % len(colors)
setposition(x,min_y)
pendown()
setposition(x,max_y)
notused = input("Hit enter to continue: ")
|
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
| #QBasic | QBasic | SCREEN 12
w = 640: h = 480
h = h / 4
y2 = h - 1
FOR i = 1 TO 4
col = 0
y = (i - 1) * h
FOR x = 1 TO w STEP i
IF col MOD 15 = 0 THEN col = 0
LINE (x, y)-(x + i, y + h), col, BF
col = col + 1
NEXT x
NEXT i |
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
| #Clojure | Clojure | (defn combinations
"If m=1, generate a nested list of numbers [0,n)
If m>1, for each x in [0,n), and for each list in the recursion on [x+1,n), cons the two"
[m n]
(letfn [(comb-aux
[m start]
(if (= 1 m)
(for [x (range start n)]
(list x))
(for [x (range start n)
xs (comb-aux (dec m) (inc x))]
(cons x xs))))]
(comb-aux m 0)))
(defn print-combinations
[m n]
(doseq [line (combinations m n)]
(doseq [n line]
(printf "%s " n))
(printf "%n"))) |
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.
| #MiniScript | MiniScript | x = 42
if x < 10 then
print "small"
else if x < 20 then
print "small-ish"
else if x > 100 then
print "large"
else
print "just right"
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.)
| #Plain_English | Plain English | \A comment like this lasts until the end of the line
Put 1 plus [there are inline comments too] 1 into a number. |
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.)
| #Plain_TeX | Plain TeX | % this is a comment
This is not. |
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.
| #Raku | Raku | use MagickWand;
use MagickWand::Enums;
my $frog = MagickWand.new;
$frog.read("./Quantum_frog.png");
$frog.quantize(16, RGBColorspace, 0, True, False);
$frog.write('./Quantum-frog-16-perl6.png'); |
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.
| #Sidef | Sidef | require('Image::Magick')
func quantize_image(n = 16, input, output='output.png') {
var im = %O<Image::Magick>.new
im.Read(input)
im.Quantize(colors => n, dither => 1) # 1 = None
im.Write(output)
}
quantize_image(input: 'Quantum_frog.png') |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Action.21 | Action! | PROC Main()
BYTE
i,
CH=$02FC, ;Internal hardware value for last key pressed
PALNTSC=$D014, ;To check if PAL or NTSC system is used
PCOLR0=$02C0,PCOLR1=$02C1,
PCOLR2=$02C2,PCOLR3=$02C3,
COLOR0=$02C4,COLOR1=$02C5,
COLOR2=$02C6,COLOR3=$02C7,
COLOR4=$02C8
Graphics(10)
PCOLR0=$04 ;gray
PCOLR1=$00 ;black
IF PALNTSC=15 THEN
PCOLR2=$42 ;red for NTSC
PCOLR3=$C6 ;green for NTSC
COLOR0=$84 ;blue for NTSC
COLOR1=$66 ;magenta for NTSC
COLOR2=$A6 ;cyan for NTSC
COLOR3=$FC ;yellow for NTSC
ELSE
PCOLR2=$22 ;red for PAL
PCOLR3=$B6 ;green for PAL
COLOR0=$74 ;blue for PAL
COLOR1=$48 ;magenta for PAL
COLOR2=$96 ;cyan for PAL
COLOR3=$EC ;yellow for PAL
FI
COLOR4=$0F ;white
FOR i=0 TO 79
DO
Color=i/10+1
Plot(i,0)
DrawTo(i,191)
OD
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #ActionScript | ActionScript |
package {
import flash.display.Sprite;
import flash.events.Event;
public class ColourBars extends Sprite {
public function ColourBars():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
var colours:Array = [ 0x000000, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF00FF, 0x00FFFF, 0xFFFF00, 0xFFFFFF ];
var w:Number = stage.stageWidth / 8, h:Number = stage.stageHeight;
var x:Number = 0, i:uint, c:uint;
for ( i = 0; i < 8; i++ ) {
c = colours[i];
graphics.beginFill(c);
graphics.drawRect(w * i, 0, w, h);
}
}
}
}
|
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM Initialize
20 LET w=32*22
30 DIM w$(w): DIM n$(w)
40 FOR n=1 TO 100
50 LET w$(RND*w+1)="O"
60 NEXT n
70 REM Loop
80 FOR i=34 TO w-34
90 LET p$="": LET d=0
100 LET p$=p$+w$(i-1)+w$(i+1)+w$(i-33)+w$(i-32)+w$(i-31)+w$(i+31)+w$(i+32)+w$(i+33)
110 LET n$(i)=w$(i)
120 FOR n=1 TO LEN p$
130 IF p$(n)="O" THEN LET d=d+1
140 NEXT n
150 IF (w$(i)=" ") AND (d=3) THEN LET n$(i)="O": GO TO 180
160 IF (w$(i)="O") AND (d<2) THEN LET n$(i)=" ": GO TO 180
170 IF (w$(i)="O") AND (d>3) THEN LET n$(i)=" "
180 NEXT i
190 PRINT AT 0,0;w$
200 LET w$=n$
210 GO TO 80 |
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
| #Racket | Racket |
#lang racket/gui
(define-values [W H] (get-display-size #t))
(define parts 4)
(define colors
'("Black" "Red" "Green" "Blue" "Magenta" "Cyan" "Yellow" "White"))
(define (paint-pinstripe canvas dc)
(send dc set-pen "black" 0 'transparent)
(send dc set-brush "black" 'solid)
(define H* (round (/ H parts)))
(for ([row parts])
(define Y (* row H*))
(for ([X (in-range 0 W (add1 row))] [c (in-cycle colors)])
(send dc set-brush c 'solid)
(send dc draw-rectangle X Y (add1 row) H*))))
(define full-frame%
(class frame%
(define/override (on-subwindow-char r e)
(when (eq? 'escape (send e get-key-code))
(send this show #f)))
(super-new
[label "Color Pinstripe"] [width W] [height H]
[style '(no-caption no-resize-border hide-menu-bar no-system-menu)])
(define c (new canvas% [parent this] [paint-callback paint-pinstripe]))
(send this show #t)))
(void (new full-frame%))
|
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
| #Raku | Raku | my ($x,$y) = 1280, 720;
my @colors = map -> $r, $g, $b { [$r, $g, $b] },
0, 0, 0,
255, 0, 0,
0, 255, 0,
0, 0, 255,
255, 0, 255,
0, 255, 255,
255, 255, 0,
255, 255, 255;
my $img = open "pinstripes.ppm", :w orelse die "Can't create pinstripes.ppm: $_";
$img.print: qq:to/EOH/;
P3
# pinstripes.ppm
$x $y
255
EOH
my $vzones = $y div 4;
for 1..4 -> $width {
my $stripes = ceiling $x / $width / +@colors;
my $row = [flat ((@colors Xxx $width) xx $stripes).map: *.values].splice(0,$x);
$img.put: $row for ^$vzones;
}
$img.close; |
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
| #CLU | CLU | % generate the size-M combinations from 0 to n-1
combinations = iter (m, n: int) yields (sequence[int])
if m<=n then
state: array[int] := array[int]$predict(1, m)
for i: int in int$from_to(0, m-1) do
array[int]$addh(state, i)
end
i: int := m
while i>0 do
yield (sequence[int]$a2s(state))
i := m
while i>0 do
state[i] := state[i] + 1
for j: int in int$from_to(i,m-1) do
state[j+1] := state[j] + 1
end
if state[i] < n-(m-i) then break end
i := i - 1
end
end
end
end combinations
% print a combination
print_comb = proc (s: stream, comb: sequence[int])
for i: int in sequence[int]$elements(comb) do
stream$puts(s, int$unparse(i) || " ")
end
end print_comb
start_up = proc ()
po: stream := stream$primary_output()
for comb: sequence[int] in combinations(3, 5) do
print_comb(po, comb)
stream$putl(po, "")
end
end start_up |
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.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | x=0 XX
x#0 XX
x>=0 XX
x<0 XX |
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.)
| #Pop11 | Pop11 | ;;; 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.)
| #PostScript | PostScript |
%This is a legal comment in PostScript
|
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.
| #Tcl | Tcl | package require Tcl 8.6
package require Tk
proc makeCluster {pixels} {
set rmin [set rmax [lindex $pixels 0 0]]
set gmin [set gmax [lindex $pixels 0 1]]
set bmin [set bmax [lindex $pixels 0 2]]
set rsum [set gsum [set bsum 0]]
foreach p $pixels {
lassign $p r g b
if {$r<$rmin} {set rmin $r} elseif {$r>$rmax} {set rmax $r}
if {$g<$gmin} {set gmin $g} elseif {$g>$gmax} {set gmax $g}
if {$b<$bmin} {set bmin $b} elseif {$b>$bmax} {set bmax $b}
incr rsum $r
incr gsum $g
incr bsum $b
}
set n [llength $pixels]
list [expr {double($n)*($rmax-$rmin)*($gmax-$gmin)*($bmax-$bmin)}] \
[list [expr {$rsum/$n}] [expr {$gsum/$n}] [expr {$bsum/$n}]] \
[list [expr {$rmax-$rmin}] [expr {$gmax-$gmin}] [expr {$bmax-$bmin}]] \
$pixels
}
proc colorQuant {img n} {
set width [image width $img]
set height [image height $img]
# Extract the pixels from the image
for {set x 0} {$x < $width} {incr x} {
for {set y 0} {$y < $height} {incr y} {
lappend pixels [$img get $x $y]
}
}
# Divide pixels into clusters
for {set cs [list [makeCluster $pixels]]} {[llength $cs] < $n} {} {
set cs [lsort -real -index 0 $cs]
lassign [lindex $cs end] score centroid volume pixels
lassign $centroid cr cg cb
lassign $volume vr vg vb
while 1 {
set p1 [set p2 {}]
if {$vr>$vg && $vr>$vb} {
foreach p $pixels {
if {[lindex $p 0]<$cr} {lappend p1 $p} {lappend p2 $p}
}
} elseif {$vg>$vb} {
foreach p $pixels {
if {[lindex $p 1]<$cg} {lappend p1 $p} {lappend p2 $p}
}
} else {
foreach p $pixels {
if {[lindex $p 2]<$cb} {lappend p1 $p} {lappend p2 $p}
}
}
if {[llength $p1] && [llength $p2]} break
# Partition failed! Perturb partition point away from the centroid and try again
set cr [expr {$cr + 20*rand() - 10}]
set cg [expr {$cg + 20*rand() - 10}]
set cb [expr {$cb + 20*rand() - 10}]
}
set cs [lreplace $cs end end [makeCluster $p1] [makeCluster $p2]]
}
# Produce map from pixel values to quantized values
foreach c $cs {
set centroid [format "#%02x%02x%02x" {*}[lindex $c 1]]
foreach p [lindex $c end] {
set map($p) $centroid
}
}
# Remap the source image
set newimg [image create photo -width $width -height $height]
for {set x 0} {$x < $width} {incr x} {
for {set y 0} {$y < $height} {incr y} {
$newimg put $map([$img get $x $y]) -to $x $y
}
}
return $newimg
} |
http://rosettacode.org/wiki/Colour_bars/Display | Colour bars/Display | Task
Display a series of vertical color bars across the width of the display.
The color bars should either use:
the system palette, or
the sequence of colors:
black
red
green
blue
magenta
cyan
yellow
white
| #Ada | Ada | with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Video.Palettes;
with SDL.Events.Events;
with SDL.Events.Keyboards;
procedure Colour_Bars_Display is
use type SDL.Events.Event_Types;
use SDL.C;
Colours : constant array (0 .. 7) of SDL.Video.Palettes.Colour :=
((0, 0, 0, 255), (255, 0, 0, 255),
(0, 255, 0, 255), (0, 0, 255, 255),
(255, 0, 255, 255), (0, 255, 255, 255),
(255, 255, 0, 255), (255, 255, 255, 255));
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
Event : SDL.Events.Events.Events;
Bar_Width : int;
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "",
Position => SDL.Natural_Coordinates'(0, 0),
Size => SDL.Positive_Sizes'(0, 0),
Flags => SDL.Video.Windows.Full_Screen_Desktop);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Bar_Width := Window.Get_Size.Width / 8;
for A in Colours'Range loop
Renderer.Set_Draw_Colour (Colour => Colours (A));
Renderer.Fill (Rectangle => (X => SDL.C.int (A) * Bar_Width, Y => 0,
Width => Bar_Width,
Height => Window.Get_Size.Height));
end loop;
Window.Update_Surface;
Wait_Loop : loop
while SDL.Events.Events.Poll (Event) loop
exit Wait_Loop when Event.Common.Event_Type = SDL.Events.Keyboards.Key_Down;
end loop;
delay 0.050;
end loop Wait_Loop;
Window.Finalize;
SDL.Finalise;
end Colour_Bars_Display; |
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
| #Ring | Ring |
# Project : Colour pinstripe/Display
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("archimedean spiral")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
w = 100
h = 100
color = list(8)
color[1] = [0 ,0, 0]
color[2] = [255, 0, 0]
color[3] = [0, 255, 0]
color[4] = [0, 0, 255]
color[5] = [255, 0, 255]
color[6] = [0, 255, 255]
color[7] = [255, 255, 0]
color[8] = [255, 255, 255]
y = h*4
for p = 1 to 4
y = y - h
for x = 0 to w step 4*p
col = random(7) + 1
color2 = new qcolor()
color2.setrgb(color[col][1],color[col][2],color[col][3],255)
mybrush = new qbrush() {setstyle(1) setcolor(color2)}
setbrush(mybrush)
paint.drawrect(x, y, 2*p, h)
next
next
endpaint()
}
label1 { setpicture(p1) show() }
|
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
| #Scala | Scala | import java.awt.Color._
import java.awt._
import javax.swing._
object ColourPinstripeDisplay extends App {
private def palette = Seq(black, red, green, blue, magenta, cyan, yellow, white)
SwingUtilities.invokeLater(() =>
new JFrame("Colour Pinstripe") {
class ColourPinstripe_Display extends JPanel {
override def paintComponent(g: Graphics): Unit = {
val bands = 4
super.paintComponent(g)
for (b <- 1 to bands) {
var colIndex = 0
for (x <- 0 until getWidth by b) {
g.setColor(ColourPinstripeDisplay.palette(colIndex % ColourPinstripeDisplay.palette.length))
g.fillRect(x, (b - 1) * (getHeight / bands), x + b, b * (getHeight / bands))
colIndex += 1
}
}
}
setPreferredSize(new Dimension(900, 600))
}
add(new ColourPinstripe_Display, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setVisible(true)
}
)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.