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/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #DCL | DCL | $ happy_1 = 1
$ found = 0
$ i = 1
$ loop1:
$ n = i
$ seen_list = ","
$ loop2:
$ if f$type( happy_'n ) .nes. "" then $ goto happy
$ if f$type( unhappy_'n ) .nes. "" then $ goto unhappy
$ if f$locate( "," + n + ",", seen_list ) .eq. f$length( seen_list )
$ then
$ seen_list = seen_list + f$string( n ) + ","
... |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, g... | #MATLAB_.2F_Octave | MATLAB / Octave | function rad = radians(degree)
% degrees to radians
rad = degree .* pi / 180;
end;
function [a,c,dlat,dlon]=haversine(lat1,lon1,lat2,lon2)
% HAVERSINE_FORMULA.AWK - converted from AWK
dlat = radians(lat2-lat1);
dlon = radians(lon2-lon1);
lat1 = radians(lat1);
lat2 = radians(lat2);
a = (sin(... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #GAP | GAP | # Several ways to do it
"Hello world!";
Print("Hello world!\n"); # No EOL appended
Display("Hello world!");
f := OutputTextUser();
WriteLine(f, "Hello world!\n");
CloseStream(f); |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #Visual_Basic | Visual Basic | Dim dict As New Collection
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
dict.Add owner(n), os(n)
Next
Debug.Print dict.Item("Linux")
Debug.Print dict.Item("MacOS")
Debug.Print dict.Item("Windows") |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #WDTE | WDTE | let a => import 'arrays';
let s => import 'stream';
let toScope keys vals =>
s.zip (a.stream keys) (a.stream vals)
->
s.reduce (collect (true)) (@ r scope kv =>
let [k v] => kv;
set scope k v;
)
; |
http://rosettacode.org/wiki/Harshad_or_Niven_series | Harshad or Niven series | The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/... | #Objeck | Objeck |
class Harshad {
function : Main(args : String[]) ~ Nil {
count := 0;
for(i := 1; count < 20; i += 1;) {
if(i % SumDigits(i) = 0){
"{$i} "->Print();
count += 1;
};
};
for(i := 1001; true; i += 1;) {
if(i % SumDigits(i) = 0){
"... {$i}"->PrintLine();
... |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #i | i | graphics {
display("Goodbye, World!")
} |
http://rosettacode.org/wiki/GUI_component_interaction | GUI component interaction |
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dial... | #Phix | Phix | include pGUI.e
Ihandle txt, increment, random, hbx, vbx, dlg
function action_cb(Ihandle /*ih*/, integer ch)
if not find(ch,"0123456789-") then return IUP_IGNORE end if
return IUP_CONTINUE
end function
function increment_cb(Ihandle /*ih*/)
integer v = IupGetInt(txt,"VALUE")+1
IupSetInt(txt,"VALUE",... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #8080_Assembly | 8080 Assembly | org 100h
xra a ; set A=0
loop: push psw ; print number as decimal
call decout
call padding ; print padding
pop psw
push psw
call binout ; print number as binary
call padding
pop psw
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov b,a ; gray encode
ana a ; clear carry
rar ; shift right
x... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Action.21 | Action! | PROC ToBinaryStr(BYTE n CHAR ARRAY s)
BYTE i
s(0)=8 i=8
SetBlock(s+1,8,'0)
WHILE n
DO
s(i)=(n&1)+'0
n==RSH 1
i==-1
OD
RETURN
PROC PrintB2(BYTE n)
IF n<10 THEN Put(32) FI
PrintB(n)
RETURN
PROC PrintBin5(BYTE n)
CHAR ARRAY s(9),sub(6)
ToBinaryStr(n,s)
SCopyS(sub,s,4,s(0))
Print... |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #ACL2 | ACL2 | (defun maximum (xs)
(if (endp (rest xs))
(first xs)
(max (first xs)
(maximum (rest xs))))) |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #11l | 11l | F hailstone(=n)
V seq = [n]
L n > 1
n = I n % 2 != 0 {3 * n + 1} E n I/ 2
seq.append(n)
R seq
V h = hailstone(27)
assert(h.len == 112 & h[0.<4] == [27, 82, 41, 124] & h[(len)-4 ..] == [8, 4, 2, 1])
V m = max((1..99999).map(i -> (hailstone(i).len, i)))
print(‘Maximum length #. was found for hail... |
http://rosettacode.org/wiki/Graph_colouring | Graph colouring |
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected... | #J | J | parse=: {{
ref=: 2$L:1(;:each cut y) -.L:1 ;:'-'
labels=: /:~~.;ref
sparse=. (*:#labels) > 20*#ref
graph=: (+.|:) 1 (labels i.L:1 ref)} $.^:sparse 0$~2##labels
}}
greedy=: {{
colors=. (#y)#a:
for_node.y do.
color=. <{.(-.~ [:i.1+#) ~.;node#colors
colors=. color node_index} colors
end.
;colors
... |
http://rosettacode.org/wiki/Graph_colouring | Graph colouring |
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected... | #Julia | Julia | using Random
"""Useful constants for the colors to be selected for nodes of the graph"""
const colors4 = ["blue", "red", "green", "yellow"]
const badcolor = "black"
@assert(!(badcolor in colors4))
"""
struct graph
undirected simple graph
constructed from its name and a string listing of point to point connect... |
http://rosettacode.org/wiki/Graph_colouring | Graph colouring |
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[ColorGroups]
ColorGroups[g_Graph] := Module[{h, cols, indset, diffcols},
h = g;
cols = {};
While[! EmptyGraphQ[h], maxd = RandomChoice[VertexList[h]];
indset = Flatten[FindIndependentVertexSet[{h, maxd}]];
AppendTo[cols, indset];
h = VertexDelete[h, indset];
];
AppendTo[cols, VertexList[h]]... |
http://rosettacode.org/wiki/Goldbach%27s_comet | Goldbach's comet |
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E),... | #Julia | Julia | using Combinatorics
using Plots
using Primes
g(n) = iseven(n) ? count(p -> all(isprime, p), partitions(n, 2)) : error("n must be even")
println("The first 100 G numbers are: ")
foreach(p -> print(lpad(p[2], 4), p[1] % 10 == 0 ? "\n" : ""), map(g, 4:2:202) |> enumerate)
println("\nThe value of G(1000000) is ", g... |
http://rosettacode.org/wiki/Goldbach%27s_comet | Goldbach's comet |
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E),... | #Lua | Lua | function T(t) return setmetatable(t, {__index=table}) end
table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end
table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end
table.batch = function(t,n,f) for i=1,#t,n do local s=T{} for j=1,n do s[j]=t[i+j-1] end f(s) end retur... |
http://rosettacode.org/wiki/Grayscale_image | Grayscale image | Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color u... | #Crystal | Crystal | class RGBColour
def to_grayscale
luminosity = (0.2126*@red + 0.7152*@green + 0.0722*@blue).to_i
self.class.new(luminosity, luminosity, luminosity)
end
end
class Pixmap
def to_grayscale
gray = self.class.new(@width, @height)
@width.times do |x|
@height.times do |y|
gray[x,y] = self[... |
http://rosettacode.org/wiki/Grayscale_image | Grayscale image | Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color u... | #D | D | module grayscale_image;
import core.stdc.stdio, std.array, std.algorithm, std.string, std.ascii;
public import bitmap;
struct Gray {
ubyte c;
enum black = typeof(this)(0);
enum white = typeof(this)(255);
alias c this;
}
Image!Color loadPGM(Color)(Image!Color img, in string fileName) {
static... |
http://rosettacode.org/wiki/Go_Fish | Go Fish | Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
If t... | #D | D |
' Go Fish ~ ¡Pesca!
Const cartas = "A234567890JQK"
Declare Sub Reparto_Cartas
Declare Sub Pescar_Carta_Jug
Declare Sub Pescar_Carta_CPU
Declare Sub Comprobar_Libro_Jug
Declare Sub Comprobar_Libro_CPU
Declare Sub Comprobar_Fin_Partida
Declare Sub Intro
Dim Shared As Integer play(13), compu(13), deck(13), guess(1... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ham;
size_t alloc = 0, n = 1;
ham *q = 0;
void qpush(ham h)
{
int i, j;
if (alloc <= n) {
alloc = alloc ? alloc * 2 : 16;
q = realloc(q, sizeof(ham) * alloc);
}
for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j);
q[i] = h;
}
ham ... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Crystal | Crystal | n = rand(1..10)
puts "Guess the number: 1..10"
until gets.to_s.to_i == n; puts "Wrong! Guess again: " end
puts "Well guessed!" |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #D | D |
void main() {
immutable num = uniform(1, 10).text;
do write("What's next guess (1 - 9)? ");
while (readln.strip != num);
writeln("Yep, you guessed my ", num);
} |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #CoffeeScript | CoffeeScript |
max_sum_seq = (sequence) ->
# This runs in linear time.
[sum_start, sum, max_sum, max_start, max_end] = [0, 0, 0, 0, 0]
for n, i in sequence
sum += n
if sum > max_sum
max_sum = sum
max_start = sum_start
max_end = i + 1
if sum < 0 # start new sequence
sum = 0
sum_start =... |
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls | GUI enabling/disabling of controls | In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI component interaction, write a progr... | #Tcl | Tcl | package require Tk
# Model
set field 0
# View
place [ttk::frame .bg] -relwidth 1 -relheight 1; # Hack to make things look nice
pack [ttk::labelframe .val -text "Value"]
pack [ttk::entry .val.ue -textvariable field \
-validate key -invalidcommand bell \
-validatecommand {string is integer %P}]
pack [ttk::button .i... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | GUESSNUM
; get a random number between 1 and 100
set target = ($random(100) + 1) ; $r(100) gives 0-99
; loop until correct
set tries = 0
for {
write !,"Guess the integer between 1 and 100: "
read "",guess ; gets input following write
; validate input
if (gue... |
http://rosettacode.org/wiki/Greyscale_bars/Display | Greyscale bars/Display | The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha... | #Nim | Nim | import gintro/[glib, gobject, gtk, gio, cairo]
const
Width = 640
Height = 480
#---------------------------------------------------------------------------------------------------
proc draw(area: DrawingArea; context: Context) =
## Draw the greyscale bars.
const
Black = 0.0
White = 1.0
var y ... |
http://rosettacode.org/wiki/Greyscale_bars/Display | Greyscale bars/Display | The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha... | #OCaml | OCaml | open Graphics
let round x = truncate (floor (x +. 0.5))
let () =
open_graph "";
let width = size_x ()
and height = size_y () in
let bars = [| 8; 16; 32; 64 |] in
let n = Array.length bars in
Array.iteri (fun i bar ->
let part = float width /. float bar in
let y = (height / n) * (n - i - 1) in
... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player) | Guess the number/With feedback (player) | Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score... | #Lua | Lua | function wait(waittime)--wait function is used so that app will not quit immediately
local timer = os.time()
repeat until os.time() == timer + waittime
end
upperBound = 100
lowerBound = 0
print("Think of an integer between 1 to 100.")
print("I will try to guess it.")
while true do
upper1 = upperBound+1
upper2... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player) | Guess the number/With feedback (player) | Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | guessnumber[min0_, max0_] :=
DynamicModule[{min = min0, max = max0, guess, correct = False},
guess[] := Round@Mean@{min, max};
Dynamic@If[correct, Row@{"Your number is ", guess[], "."},
Column@{Row@{"I guess ", guess[], "."},
Row@{Button["too high", max = guess[]],
Button["too low", m... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #Delphi | Delphi |
program Happy_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Int;
type
TIntegerDynArray = TArray<Integer>;
TIntHelper = record helper for Integer
function IsHappy: Boolean;
procedure Next;
end;
{ TIntHelper }
function TIntHelper.IsHappy: Boolean;
var
cache: TIntegerDynArray;
... |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, g... | #Maxima | Maxima | dms(d, m, s) := (d + m/60 + s/3600)*%pi/180$
great_circle_distance(lat1, long1, lat2, long2) :=
12742*asin(sqrt(sin((lat2 - lat1)/2)^2 + cos(lat1)*cos(lat2)*sin((long2 - long1)/2)^2))$
/* Coordinates are found here:
http://www.airport-data.com/airport/BNA/
http://www.airport-data.com/airport/LAX/ *... |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, g... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П3 -> П2 -> П1 -> П0
пи 1 8 0 / П4
ИП1 МГ ИП3 МГ - ИП4 * П1 ИП0 МГ ИП4 * П0 ИП2 МГ ИП4 * П2
ИП0 sin ИП2 sin - П8
ИП1 cos ИП0 cos * ИП2 cos - П6
ИП1 sin ИП0 cos * П7
ИП6 x^2 ИП7 x^2 ИП8 x^2 + + КвКор 2 / arcsin 2 * ИП5 * С/П |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #GB_BASIC | GB BASIC | 10 print "Hello world!" |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #Vlang | Vlang | fn main() {
keys := ["a", "b", "c"]
vals := [1, 2, 3]
mut hash := map[string]int{}
for i, key in keys {
hash[key] = vals[i]
}
println(hash)
} |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #Wortel | Wortel | @hash ["a" "b" "c"] [1 2 3] ; returns {a 1 b 2 c 3} |
http://rosettacode.org/wiki/Harshad_or_Niven_series | Harshad or Niven series | The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/... | #Oforth | Oforth | : sumDigits(n) 0 while(n) [ n 10 /mod ->n + ] ;
: isHarshad dup sumDigits mod 0 == ;
1100 seq filter(#isHarshad) dup left(20) println dup filter(#[ 1000 > ]) first println |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Integer_BASIC | Integer BASIC |
10 REM FONT DERIVED FROM 04B-09 BY YUJI OSHIMOTO
20 GR
30 COLOR = 12
40 REM G
50 HLIN 0,5 AT 0 : HLIN 0,5 AT 1
60 VLIN 2,9 AT 0 : VLIN 2,9 AT 1
70 HLIN 2,5 AT 9 : HLIN 2,5 AT 8
80 VLIN 4,7 AT 5 : VLIN 4,7 AT 4
90 VLIN 4,5 AT 3
100 REM O
110 HLIN 7,12 AT 2 : HLIN 7,12 AT 3
120 HLIN 7,12 AT 8 : HLIN 7,12 AT 9
130 VLIN ... |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Ioke | Ioke | import(
:javax:swing, :JOptionPane, :JFrame, :JTextArea, :JButton
)
import java:awt:FlowLayout
JOptionPane showMessageDialog(nil, "Goodbye, World!")
button = JButton new("Goodbye, World!")
text = JTextArea new("Goodbye, World!")
window = JFrame new("Goodbye, World!") do(
layout = FlowLayout new
add(button)
ad... |
http://rosettacode.org/wiki/GUI_component_interaction | GUI component interaction |
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dial... | #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")
(de start ()
(and (app) (zero *Number))
(action
(html 0 "Increment" "@lib.css" NIL
(form NIL
(gui '(+Var +NumField) '*Number 20 "Value")
(gui '(+JS +Button) "increment"... |
http://rosettacode.org/wiki/GUI_component_interaction | GUI component interaction |
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dial... | #PowerShell | PowerShell | [xml]$XML = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Rosetta Code" WindowStartupLocation = "CenterScreen" Height="100" Width="210" ResizeMode="NoResize">
<Grid Background="#FFC1C3CB">
<Label Name="Label_Value" Content="Value" HorizontalAlignment="Left" Ma... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Ada | Ada | with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;
procedure Gray is
Bits : constant := 5; -- Change only this line for 6 or 7-bit encodings
subtype Values is Unsigned_8 range 0 .. 2 ** Bits - 1;
package Values_Io is new Ada.Text_IO.Modular_IO (Values);
function Encode (Binary : Values) return... |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Action.21 | Action! | BYTE FUNC Max(BYTE ARRAY tab BYTE size)
BYTE i,res
res=tab(0)
FOR i=1 TO size-1
DO
IF res<tab(i) THEN
res=tab(i)
FI
OD
RETURN (res)
PROC Main()
BYTE i,m,size=[20]
BYTE ARRAY tab(size)
FOR i=0 TO size-1
DO
tab(i)=Rand(0)
OD
Print("Array:")
FOR i=0 TO size-1
DO
Pr... |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #360_Assembly | 360 Assembly | * Hailstone sequence 16/08/2015
HAILSTON CSECT
USING HAILSTON,R12
LR R12,R15
ST R14,SAVER14
BEGIN L R11,=F'100000' nmax
LA R8,27 n=27
LR R1,R8
MVI FTAB,X'01' ftab=true
BAL R14,COLLATZ
... |
http://rosettacode.org/wiki/Graph_colouring | Graph colouring |
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected... | #Nim | Nim | import algorithm, sequtils, strscans, strutils, tables
const NoColor = 0
type
Color = range[0..63]
Node = ref object
num: Natural # Node number.
color: Color # Node color.
degree: Natural # Node degree.
dsat: Natural # Node Dsaturation.
neighbors: seq[Node... |
http://rosettacode.org/wiki/Graph_colouring | Graph colouring |
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected... | #Perl | Perl | use strict;
use warnings;
no warnings 'uninitialized';
use feature 'say';
use constant True => 1;
use List::Util qw(head uniq);
sub GraphNodeColor {
my(%OneMany, %NodeColor, %NodePool, @ColorPool);
my(@data) = @_;
for (@data) {
my($a,$b) = @$_;
push @{$OneMany{$a}}, $b;
push @{$O... |
http://rosettacode.org/wiki/Goldbach%27s_comet | Goldbach's comet |
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E),... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[GoldbachFuncion]
GoldbachFuncion[e_Integer] := Module[{ps},
ps = Prime[Range[PrimePi[e/2]]];
Total[Boole[PrimeQ[e - ps]]]
]
Grid[Partition[GoldbachFuncion /@ Range[4, 220, 2], 10]]
GoldbachFuncion[10^6]
DiscretePlot[GoldbachFuncion[e], {e, 4, 2000}, Filling -> None] |
http://rosettacode.org/wiki/Goldbach%27s_comet | Goldbach's comet |
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E),... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::Util 'max';
use GD::Graph::bars;
use ntheory 'is_prime';
sub table { my $t = shift() * (my $c = 1 + max map {length} @_); ( sprintf( ('%'.$c.'s')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub G {
my($n) = @_;
scalar grep { is_prime($_) and is_prime($n - $_) } ... |
http://rosettacode.org/wiki/Grayscale_image | Grayscale image | Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color u... | #Delphi | Delphi | -module(ros_bitmap).
-export([new/2, fill/2, set_pixel/3, get_pixel/2, convert/2]).
-record(bitmap, {
mode = rgb,
pixels = nil,
shape = {0, 0}
}).
tuple_to_bytes({rgb, R, G, B}) ->
<<R:8, G:8, B:8>>;
tuple_to_bytes({gray, L}) ->
<<L:8>>.
bytes_to_tuple(rgb, Bytes) ->
<<R:8, G:8, B:8>> = Byte... |
http://rosettacode.org/wiki/Go_Fish | Go Fish | Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
If t... | #Erlang | Erlang |
' Go Fish ~ ¡Pesca!
Const cartas = "A234567890JQK"
Declare Sub Reparto_Cartas
Declare Sub Pescar_Carta_Jug
Declare Sub Pescar_Carta_CPU
Declare Sub Comprobar_Libro_Jug
Declare Sub Comprobar_Libro_CPU
Declare Sub Comprobar_Fin_Partida
Declare Sub Intro
Dim Shared As Integer play(13), compu(13), deck(13), guess(1... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #C.23 | C# | using System;
using System.Numerics;
using System.Linq;
namespace Hamming {
class MainClass {
public static BigInteger Hamming(int n) {
BigInteger two = 2, three = 3, five = 5;
var h = new BigInteger[n];
h[0] = 1;
BigInteger x2 = 2, x3 = 3, x5 = 5;
... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Dart | Dart | import 'dart:math';
import 'dart:io';
main() {
final n = (1 + new Random().nextInt(10)).toString();
print("Guess which number I've chosen in the range 1 to 10");
do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
print("\nWell guessed!");
} |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #DCL | DCL | $ time = f$time()
$ number = f$extract( f$length( time ) - 1, 1, time ) + 1
$ loop:
$ inquire guess "enter a guess (integer 1-10) "
$ if guess .nes. number then $ goto loop
$ write sys$output "Well guessed!" |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Common_Lisp | Common Lisp | (defun max-subseq (list)
(let ((best-sum 0) (current-sum 0) (end 0))
;; determine the best sum, and the end of the max subsequence
(do ((list list (rest list))
(i 0 (1+ i)))
((endp list))
(setf current-sum (max 0 (+ current-sum (first list))))
(when (> current-sum best-sum)
... |
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls | GUI enabling/disabling of controls | In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI component interaction, write a progr... | #Vala | Vala | bool validate_input(Gtk.Window window, string str){
int64 val;
bool ret = int64.try_parse(str,out val);;
if(!ret || str == ""){
var dialog = new Gtk.MessageDialog(window,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.ER... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Ceylon | Ceylon | import ceylon.random {
DefaultRandom
}
shared void run() {
value random = DefaultRandom();
value range = 1..10;
while(true) {
value chosen = random.nextElement(range);
print("I have chosen a number between ``range.first`` and ``range.last``.
What is your guess?");
... |
http://rosettacode.org/wiki/Greyscale_bars/Display | Greyscale bars/Display | The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha... | #Perl | Perl | sub partition {
my($all, $div) = @_;
my @marks = 0;
push @marks, $_/$div * $all for 1..$div;
my @copy = @marks;
$marks[$_] -= $copy[$_-1] for 1..$#marks;
@marks[1..$#marks];
}
sub bars {
my($h,$w,$p,$rev) = @_;
my (@nums,@vals,$line,$d);
$d = 2**$p;
push @nums, int $_/($d-1)... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player) | Guess the number/With feedback (player) | Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score... | #MATLAB | MATLAB | function GuessNumberFeedbackPlayer
lowVal = input('Lower limit: ');
highVal = input('Upper limit: ');
fprintf('Think of your number. Press Enter when ready.\n')
pause
nGuesses = 1;
done = false;
while ~done
guess = floor(0.5*(lowVal+highVal));
score = input(sprintf( ...
... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #Draco | Draco | proc nonrec dsumsq(byte n) byte:
byte r, d;
r := 0;
while n~=0 do
d := n % 10;
n := n / 10;
r := r + d * d
od;
r
corp
proc nonrec happy(byte n) bool:
[256] bool seen;
byte i;
for i from 0 upto 255 do seen[i] := false od;
while not seen[n] do
seen[n] ... |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, g... | #MySQL | MySQL | DELIMITER $$
CREATE FUNCTION haversine (
lat1 FLOAT, lon1 FLOAT,
lat2 FLOAT, lon2 FLOAT
) RETURNS FLOAT
NO SQL DETERMINISTIC
BEGIN
DECLARE r FLOAT unsigned DEFAULT 6372.8;
DECLARE dLat FLOAT unsigned;
DECLARE dLon FLOAT unsigned;
DECLARE a FLOAT unsigned;
DECLARE c FLOAT unsigned;
SET dLat = ABS(RADIANS... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #gecho | gecho | 'Hello, <> 'World! print |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #Wren | Wren | var keys = [1, 2, 3, 4, 5]
var values = ["first", "second", "third", "fourth","fifth"]
var hash = {}
(0..4).each { |i| hash[keys[i]] = values[i] }
System.print(hash) |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #zkl | zkl | keys:=T("a","b","c","d"); vals:=T(1,2,3,4);
d:=keys.zip(vals).toDictionary();
d.println();
d["b"].println(); |
http://rosettacode.org/wiki/Harshad_or_Niven_series | Harshad or Niven series | The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/... | #ooRexx | ooRexx | /* REXX ---------------------------------------------------------------
* 21.01.2014 Walter Pachl modi-(simpli-)fied from REXX version 1
*--------------------------------------------------------------------*/
Parse Arg x y . /* get optional arguments: X Y */
If x='' Then x=20 /* ... |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #IWBASIC | IWBASIC |
DEF Win:WINDOW
DEF Close:CHAR
DEF ScreenSizeX,ScreenSizeY:UINT
GETSCREENSIZE(ScreenSizeX,ScreenSizeY)
OPENWINDOW Win,0,0,ScreenSizeX,ScreenSizeY,NULL,NULL,"Goodbye program",&MainHandler
PRINT Win,"Goodbye, World!"
'Prints in upper left corner of the window (position 0,0).
WAITUNTIL Close=1
CLOSEWINDOW Win
... |
http://rosettacode.org/wiki/GUI_component_interaction | GUI component interaction |
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dial... | #Prolog | Prolog | dialog('GUI_Interaction',
[ object :=
GUI_Interaction,
parts :=
[ GUI_Interaction :=
dialog('Rosetta Code'),
Input_field :=
text_item(input_field),
Increment :=
button(increment),
Random :=
button(random)
],
modif... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Aime | Aime | integer
gray_encode(integer n)
{
n ^ (n >> 1);
}
integer
gray_decode(integer n)
{
integer p;
p = n;
while (n >>= 1) {
p ^= n;
}
p;
} |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #ActionScript | ActionScript | function max(... args):Number
{
var curMax:Number = -Infinity;
for(var i:uint = 0; i < args.length; i++)
curMax = Math.max(curMax, args[i]);
return curMax;
} |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #ABAP | ABAP |
CLASS lcl_hailstone DEFINITION.
PUBLIC SECTION.
TYPES: tty_sequence TYPE STANDARD TABLE OF i
WITH NON-UNIQUE EMPTY KEY,
BEGIN OF ty_seq_len,
start TYPE i,
len TYPE i,
END OF ty_seq_len,
tty_seq_len TYPE HASHED TABLE OF ty_... |
http://rosettacode.org/wiki/Graph_colouring | Graph colouring |
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected... | #Phix | Phix | -- demo\rosetta\Graph_colouring.exw
with javascript_semantics
constant tests = split("""
0-1 1-2 2-0 3
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
""","\n",true)
function colour(sequence nodes, links, colours, soln, int... |
http://rosettacode.org/wiki/Goldbach%27s_comet | Goldbach's comet |
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E),... | #Phix | Phix | --
-- demo\rosetta\Goldbachs_comet.exw
-- ================================
--
-- Note: this plots n/2 vs G(n) for n=6 to 4000 by 2, matching wp and
-- Algol 68, Python, and Raku. However, while not wrong, Arturo
-- and Wren apparently plot n vs G(n) for n=6 to 2000 by 2, so
-- should you spot any (ve... |
http://rosettacode.org/wiki/Grayscale_image | Grayscale image | Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color u... | #Erlang | Erlang | -module(ros_bitmap).
-export([new/2, fill/2, set_pixel/3, get_pixel/2, convert/2]).
-record(bitmap, {
mode = rgb,
pixels = nil,
shape = {0, 0}
}).
tuple_to_bytes({rgb, R, G, B}) ->
<<R:8, G:8, B:8>>;
tuple_to_bytes({gray, L}) ->
<<L:8>>.
bytes_to_tuple(rgb, Bytes) ->
<<R:8, G:8, B:8>> = Byte... |
http://rosettacode.org/wiki/Go_Fish | Go Fish | Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
If t... | #FreeBASIC | FreeBASIC |
' Go Fish ~ ¡Pesca!
Const cartas = "A234567890JQK"
Declare Sub Reparto_Cartas
Declare Sub Pescar_Carta_Jug
Declare Sub Pescar_Carta_CPU
Declare Sub Comprobar_Libro_Jug
Declare Sub Comprobar_Libro_CPU
Declare Sub Comprobar_Fin_Partida
Declare Sub Intro
Dim Shared As Integer play(13), compu(13), deck(13), guess(1... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #C.2B.2B | C++ |
#include <iostream>
#include <vector>
// Hamming like sequences Generator
//
// Nigel Galloway. August 13th., 2012
//
class Ham {
private:
std::vector<unsigned int> _H, _hp, _hv, _x;
public:
bool operator!=(const Ham& other) const {return true;}
Ham begin() const {return *this;}
Ham end() const {return *th... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Delphi | Delphi | program GuessTheNumber;
{$APPTYPE CONSOLE}
uses SysUtils;
var
theDigit : String ;
theAnswer : String ;
begin
Randomize ;
theDigit := IntToStr(Random(9)+1) ;
while ( theAnswer <> theDigit ) do Begin
Writeln('Please enter a digit between 1 and 10' ) ;
Readln(theAnswer);
End ;
Writeln('Congra... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :number random-range 1 11
while true:
if = number to-num !prompt "Guess my number: ":
!print "Congratulations, you've guessed it!"
return
else:
!print "Nope, try again." |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Component_Pascal | Component Pascal |
MODULE OvctGreatestSubsequentialSum;
IMPORT StdLog, Strings, Args;
PROCEDURE Gss(iseq: ARRAY OF INTEGER;OUT start, end, maxsum: INTEGER);
VAR
i,j,sum: INTEGER;
BEGIN
i := 0; maxsum := 0; start := 0; end := -1;
WHILE i < LEN(iseq) - 1 DO
sum := 0; j := i;
WHILE j < LEN(iseq) -1 DO
INC(sum ,iseq[j]);
IF ... |
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls | GUI enabling/disabling of controls | In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI component interaction, write a progr... | #Visual_Basic | Visual Basic | VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 2265
ClientLeft = 60
ClientTop = 600
ClientWidth = 2175
LinkTopic = "Form1"
ScaleHeight = 2265
ScaleWidth = 2175
StartUpPosition = 3 'Windows Default
Begin VB.Comm... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Clojure | Clojure | (defn guess-run []
(let [start 1
end 100
target (+ start (rand-int (inc (- end start))))]
(printf "Guess a number between %d and %d" start end)
(loop [i 1]
(printf "Your guess %d:\n" i)
(let [ans (read)]
(if (cond
(not (number? ans)) (println "Invalid format")
(or (< ans start) (> a... |
http://rosettacode.org/wiki/Greyscale_bars/Display | Greyscale bars/Display | The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha... | #Phix | Phix | --
-- demo\rosetta\Greyscale_bars.exw
-- ===============================
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
integer quit = 1
bool refire = false
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
cdCanvasActivate(cddbuffer)
integer {width,... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player) | Guess the number/With feedback (player) | Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score... | #MAXScript | MAXScript | inclusiveRange = [1,100]
lowRange = inclusiveRange.x
maxRange = inclusiveRange.y
guesses = 1
inf = "Think of a number between % and % and I will try to guess it.\n" +\
"Type -1 if the guess is less than your number,\n"+\
"0 if the guess is correct, " +\
"or 1 if it's too high.\nPress esc to exit.\n"
clearListene... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player) | Guess the number/With feedback (player) | Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score... | #Modula-2 | Modula-2 | MODULE raden;
IMPORT InOut;
VAR done, ok : BOOLEAN;
guess, upp, low : CARDINAL;
res : CHAR;
BEGIN
InOut.WriteString ("Choose a number between 0 and 1000.");
InOut.WriteLn;
InOut.WriteLn;
upp := 1000;
low := 0;
REPEAT
ok := FALSE;
... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #DWScript | DWScript | function IsHappy(n : Integer) : Boolean;
var
cache : array of Integer;
sum : Integer;
begin
while True do begin
sum := 0;
while n>0 do begin
sum += Sqr(n mod 10);
n := n div 10;
end;
if sum = 1 then
Exit(True);
if sum in cache then
Exit(False);
... |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, g... | #Nim | Nim | import math
proc radians(x): float = x * Pi / 180
proc haversine(lat1, lon1, lat2, lon2): float =
const r = 6372.8 # Earth radius in kilometers
let
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat/2)*sin(dLat/2) + cos(lat1)*cos(... |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, g... | #Oberon-2 | Oberon-2 |
MODULE Haversines;
IMPORT
LRealMath,
Out;
PROCEDURE Distance(lat1,lon1,lat2,lon2: LONGREAL): LONGREAL;
CONST
r = 6372.8D0; (* Earth radius as LONGREAL *)
to_radians = LRealMath.pi / 180.0D0;
VAR
d,ph1,th1,th2: LONGREAL;
dz,dx,dy: LONGREAL;
BEGIN
d := lon1 - lon2;
ph1 := d * to_r... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Gema | Gema | *= ! ignore off content of input
\B=Hello world!\! ! Start output with this text. |
http://rosettacode.org/wiki/Harshad_or_Niven_series | Harshad or Niven series | The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/... | #PARI.2FGP | PARI/GP | isHarshad(n)=n%sumdigits(n)==0
n=0;k=20;while(k,if(isHarshad(n++),k--;print1(n", ")));
n=1000;while(!isHarshad(n++),);print("\n"n) |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #J | J | wdinfo 'Goodbye, World!' |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Java | Java | import javax.swing.*;
import java.awt.*;
public class OutputSwing {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JOptionPane.showMessageDialog (null, "Goodbye, World!"); // in alert box
JFrame frame ... |
http://rosettacode.org/wiki/GUI_component_interaction | GUI component interaction |
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dial... | #PureBasic | PureBasic | Enumeration
#StringGadget
#Increment
#Random
EndEnumeration
If OpenWindow(0,#PB_Ignore,#PB_Ignore,180,50,"PB-GUI",#PB_Window_SystemMenu)
StringGadget(#StringGadget,5,5,170,20,"",#PB_String_Numeric)
ButtonGadget(#Increment,5,25,80,20, "Increment")
ButtonGadget(#Random, 90,25,80,20, "Random")
Repeat
... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #ALGOL_68 | ALGOL 68 | BEGIN
OP GRAY = (BITS b) BITS : b XOR (b SHR 1); CO Convert to Gray code CO
OP YARG = (BITS g) BITS : CO Convert from Gray code CO
BEGIN
BITS b := g, mask := g SHR 1;
WHILE mask /= 2r0 DO b := b XOR mask; mask := mask SHR 1 OD;
b
END;
FOR i FROM 0 TO 31 DO
printf (($zd, ": ", 2(... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Amazing_Hopper | Amazing Hopper |
#proto GrayEncode(_X_)
#synon _GrayEncode *getGrayEncode
#proto GrayDecode(_X_)
#synon _GrayDecode *getGrayDecode
#include <hbasic.h>
Begin
Gray=0
SizeBin(4) // size 5 bits: 0->4
Take (" # BINARY GRAY DECODE\n")
Take ("------------------------------\n"), and Print It
For Up( i := 0... |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Ada | Ada | with Ada.Text_Io;
procedure Max_Test isco
-- substitute any array type with a scalar element
type Flt_Array is array (Natural range <>) of Float;
-- Create an exception for the case of an empty array
Empty_Array : Exception;
function Max(Item : Flt_Array) return Float is
Max_Element : Float :... |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #11l | 11l | F gcd(=u, =v)
L v != 0
(u, v) = (v, u % v)
R abs(u)
print(gcd(0, 0))
print(gcd(0, 10))
print(gcd(0, -10))
print(gcd(9, 6))
print(gcd(6, 9))
print(gcd(-6, 9))
print(gcd(8, 45))
print(gcd(40902, 24140)) |
http://rosettacode.org/wiki/Globally_replace_text_in_several_files | Globally replace text in several files | Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
| #11l | 11l | L(fname) fs:list_dir(‘.’)
I fname.ends_with(‘.txt’)
V fcontents = File(fname).read()
File(fname, ‘w’).write(fcontents.replace(‘Goodbye London!’, ‘Hello, New York!’))
|
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #ACL2 | ACL2 | (defun hailstone (len)
(loop for x = len
then (if (evenp x)
(/ x 2)
(+ 1 (* 3 x)))
collect x until (= x 1)))
;; Must be tail recursive
(defun max-hailstone-start (limit mx curr)
(declare (xargs :mode :program))
(if (zp limit)
... |
http://rosettacode.org/wiki/Graph_colouring | Graph colouring |
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected... | #Python | Python | import re
from collections import defaultdict
from itertools import count
connection_re = r"""
(?: (?P<N1>\d+) - (?P<N2>\d+) | (?P<N>\d+) (?!\s*-))
"""
class Graph:
def __init__(self, name, connections):
self.name = name
self.connections = connections
g = self.graph = default... |
http://rosettacode.org/wiki/Goldbach%27s_comet | Goldbach's comet |
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E),... | #Picat | Picat | main =>
println("First 100 G numbers:"),
foreach({G,I} in zip(take([G: T in 1..300, G=g(T),G>0],100),1..100))
printf("%2d %s",G,cond(I mod 10 == 0,"\n",""))
end,
nl,
printf("G(1_000_000): %d\n", g(1_000_000)).
g(N) = cond((N > 2, N mod 2 == 0),
{1 : I in 1..N // 2,
prime(I... |
http://rosettacode.org/wiki/Goldbach%27s_comet | Goldbach's comet |
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E),... | #Python | Python | from matplotlib.pyplot import scatter, show
from sympy import isprime
def g(n):
assert n > 2 and n % 2 == 0, 'n in goldbach function g(n) must be even'
count = 0
for i in range(1, n//2 + 1):
if isprime(i) and isprime(n - i):
count += 1
return count
print('The first 100 ... |
http://rosettacode.org/wiki/Goldbach%27s_comet | Goldbach's comet |
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E),... | #Raku | Raku | sub G (Int $n) { +(2..$n/2).grep: { .is-prime && ($n - $_).is-prime } }
# Task
put "The first 100 G values:\n", (^100).map({ G 2 × $_ + 4 }).batch(10)».fmt("%2d").join: "\n";
put "\nG 1_000_000 = ", G 1_000_000;
# Stretch
use SVG;
use SVG::Plot;
my @x = map 2 × * + 4, ^2000;
my @y = @x.map: &G;
'Goldbachs-Com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.