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/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... | #J | J | require 'misc'
guess=:3 :0
'lo hi'=.y
while.lo < hi do.
smoutput 'guessing a number between ',(":lo),' and ',":hi
guess=.lo+?hi-lo
select.{.deb tolower prompt 'is it ',(":guess),'? '
case.'y'do. smoutput 'Win!' return.
case.'l'do. lo=.guess+1
case.'h'do. hi=.guess-1
case.'q'do. s... |
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... | #Crystal | Crystal | def happy?(n)
past = [] of Int32 | Int64
until n == 1
sum = 0; while n > 0; sum += (n % 10) ** 2; n //= 10 end
return false if past.includes? (n = sum)
past << n
end
true
end
i = count = 0
until count == 8; (puts i; count += 1) if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i|... |
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... | #Julia | Julia | haversine(lat1, lon1, lat2, lon2) =
2 * 6372.8 * asin(sqrt(sind((lat2 - lat1) / 2) ^ 2 +
cosd(lat1) * cosd(lat2) * sind((lon2 - lon1) / 2) ^ 2))
@show haversine(36.12, -86.67, 33.94, -118.4) |
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... | #Kotlin | Kotlin | import java.lang.Math.*
const val R = 6372.8 // in kilometers
fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
val λ1 = toRadians(lat1)
val λ2 = toRadians(lat2)
val Δλ = toRadians(lat2 - lat1)
val Δφ = toRadians(lon2 - lon1)
return 2 * R * asin(sqrt(pow(sin(Δλ / 2)... |
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
| #Furor | Furor | ."Hello, World!\n" |
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
| #Swift | Swift | let keys = ["a","b","c"]
let vals = [1,2,3]
var hash = [String: Int]()
for (key, val) in zip(keys, vals) {
hash[key] = val
} |
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
| #Tcl | Tcl | set keys [list fred bob joe]
set values [list barber plumber tailor]
array set arr {}
foreach a $keys b $values { set arr($a) $b }
parray arr |
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/... | #min | min | (
:n () =list
(n 0 >) (
n 10 mod list prepend #list
n 10 div @n
) while
list
) :digits
(dup digits sum mod 0 ==) :harshad?
(
succ :n
(n harshad? not) (
n succ @n
) while
n
) :next-harshad
0 (next-harshad print " " print!) 20 times newline
1000 next-harshad print! |
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
| #GUISS | GUISS | Start,Programs,Accessories,Notepad,Type:Goodbye[comma][space]World[pling] |
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
| #Harbour | Harbour | PROCEDURE Main()
RETURN wapi_MessageBox(,"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... | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Declare form1 form
Declare textbox1 textbox form form1
Declare buttonInc Button form form1
Declare buttonRND Button form form1
Method textbox1, "move", 2000,2000,4000,600
Method buttonInc, "move", 2000,3000,2000,600
Method buttonRND, "move", 4000,3000,2000,60... |
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... | #Maple | Maple |
Increase();
|
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... | #Action.21 | Action! | INCLUDE "H6:RGB2GRAY.ACT" ;from task Grayscale image
PROC PrintB3(BYTE x)
IF x<10 THEN
Print(" ")
ELSEIF x<100 THEN
Print(" ")
FI
PrintB(x)
RETURN
PROC PrintRgbImage(RgbImage POINTER img)
BYTE x,y
RGB c
FOR y=0 TO img.h-1
DO
FOR x=0 TO img.w-1
DO
GetRgbPixel(img,x,y,c)
... |
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... | #Ada | Ada | type Grayscale_Image is array (Positive range <>, Positive range <>) of Luminance; |
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... | #BASIC256 | BASIC256 | w = 143
h = 188
name$ = "Mona_Lisa.jpg"
graphsize w,h
imgload w/2, h/2, name$
fastgraphics
for x = 0 to w-1
for y = 0 to h-1
p = pixel(x,y)
b = p % 256
p = p \256
g = p % 256
p = p \ 256
r = p % 256
l = 0.2126*r + 0.7152*g + 0.0722*b
color rgb(l,l,l)
plot x,y
... |
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... | #Aime | Aime |
' 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 ... | #BASIC256 | BASIC256 | print "The first 20 Hamming numbers are :"
for i = 1 to 20
print Hamming(i);" ";
next i
print
print "H( 1691) = "; Hamming(1691)
end
function min(a, b)
if a < b then return a else return b
end function
function Hamming(limit)
dim h(1000000)
h[0] = 1
x2 = 2 : x3 = 3 : x5 = 5
i = 0 : j =... |
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... | #Brat | Brat | number = random 10
p "Guess a number between 1 and 10."
until {
true? ask("Guess: ").to_i == number
{ p "Well guessed!"; true }
{ p "Guess again!" }
} |
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... | #C | C | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(void)
{
int n;
int g;
char c;
srand(time(NULL));
n = 1 + (rand() % 10);
puts("I'm thinking of a number between 1 and 10.");
puts("Try to guess it:");
while (1) {
if (scanf("%d", &g) != 1) {
/* ignore one ... |
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... | #C | C | #include "stdio.h"
typedef struct Range {
int start, end, sum;
} Range;
Range maxSubseq(const int sequence[], const int len) {
int maxSum = 0, thisSum = 0, i = 0;
int start = 0, end = -1, j;
for (j = 0; j < len; j++) {
thisSum += sequence[j];
if (thisSum < 0) {
i = j + ... |
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... | #Ring | Ring |
Load "guilib.ring"
MyApp = New qApp {
num = 0
win1 = new qWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
btn1 = new qpushbutton(win1) {
setGeometry(50,200,100,30)
settext("Increment")
... |
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... | #Brat | Brat | number = random 10
p "Guess a number between 1 and 10."
until {
guess = ask("Guess: ").to_i
true? (guess.null? || { guess > 10 || guess < 1 })
{ p "Please guess a number between 1 and 10."}
{ true? guess == number
{ p "Correct!"; true }
{ true? guess < number
{ p "Too low!" }
... |
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... | #JavaScript | JavaScript | <html><body>
<script type="text/javascript">
var width = 640; var height = 400;
var c = document.createElement("canvas");
c.setAttribute('id', 'myCanvas');
c.setAttribute('style', 'border:1px solid black;');
c.setAttribute('width', width);
c.setAttribute('height', height);
document.body.appendChild(c);
var ctx =... |
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... | #Java | Java | import java.util.AbstractList;
import java.util.Collections;
import java.util.Scanner;
public class GuessNumber {
public static final int LOWER = 0, UPPER = 100;
public static void main(String[] args) {
System.out.printf("Instructions:\n" +
"Think of integer number from %d (inclusive) to %d (exclusive) ... |
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... | #D | D | bool isHappy(int n) pure nothrow {
int[int] past;
while (true) {
int total = 0;
while (n > 0) {
total += (n % 10) ^^ 2;
n /= 10;
}
if (total == 1)
return true;
if (total in past)
return false;
n = total;
pa... |
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... | #Liberty_BASIC | Liberty BASIC | print "Haversine distance: "; using( "####.###########", havDist( 36.12, -86.67, 33.94, -118.4)); " km."
end
function havDist( th1, ph1, th2, ph2)
degtorad = acs(-1)/180
diameter = 2 * 6372.8
LgD = degtorad * (ph1 - ph2)
th1 = degtorad * th1
th2 = degtorad * th2
dz = 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
| #FutureBasic | FutureBasic | window 1
print @"Hello world!"
HandleEvents |
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
| #TXR | TXR | $ txr -p '^#H(() ,*[zip #(a b c) #(1 2 3)])))'
#H(() (c 3) (b 2) (a 1)) |
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
| #UNIX_Shell | UNIX Shell | keys=( foo bar baz )
values=( 123 456 789 )
declare -A hash
for (( i = 0; i < ${#keys[@]}; i++ )); do
hash["${keys[i]}"]=${values[i]}
done
for key in "${!hash[@]}"; do
printf "%s => %s\n" "$key" "${hash[$key]}"
done |
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/... | #MLite | MLite | fun sumdigits
(0, n) = n
| (m, n) = sumdigits (m div 10, m rem 10) + n
| n = sumdigits (n div 10, n rem 10)
fun is_harshad n = (n rem (sumdigits n) = 0)
fun next_harshad_after
(n, ~1) = if is_harshad n then
n
else
next_harshad_after (n + 1, ~1)
| 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
| #Haskell | Haskell | import Graphics.UI.Gtk
import Control.Monad
messDialog = do
initGUI
dialog <- messageDialogNew Nothing [] MessageInfo ButtonsOk "Goodbye, World!"
rs <- dialogRun dialog
when (rs == ResponseOk || rs == ResponseDeleteEvent) $ widgetDestroy dialog
dialog `onDestroy` mainQuit
mainGUI |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Manipulate[Null, {{value, 0}, InputField[Dynamic[value], Number] &},
Row@{Button["increment", value++],
Button["random",
If[DialogInput[
Column@{"Are you sure?",
Row@{Button["Yes", DialogReturn[True]],
Button["No", DialogReturn[False]]}}],
value = RandomInteger@10000], Method ... |
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... | #Nim | Nim | import
gtk2, glib2, strutils, random
var valu: int = 0
proc thisDestroy(widget: PWidget, data: Pgpointer) {.cdecl.} =
main_quit()
randomize()
nim_init()
var win = window_new(gtk2.WINDOW_TOPLEVEL)
var content = vbox_new(true,10)
var hbox1 = hbox_new(true,10)
var hbox2 = hbox_new(false,1)
var lbl = label_new("V... |
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.
| #11l | 11l | max(values) |
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... | #11l | 11l | F first_avail_int(data)
‘return lowest int 0... not in data’
V d = Set(data)
L(i) 0..
I i !C d
R i
F greedy_colour(name, connections)
DefaultDict[Int, [Int]] graph
L(connection) connections.split(‘ ’)
I ‘-’ C connection
V (n1, n2) = connection.split(‘-’).map(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),... | #ALGOL_68 | ALGOL 68 | BEGIN # calculate values of the Goldbach function G where G(n) is the number #
# of prime pairs that sum to n, n even and > 2 #
# generates an ASCII scatter plot of G(n) up to G(2000) #
# (Goldbach's Comet) #
... |
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... | #BBC_BASIC | BBC BASIC | Width% = 200
Height% = 200
VDU 23,22,Width%;Height%;8,16,16,128
*display c:\lena
FOR y% = 0 TO Height%-1
FOR x% = 0 TO Width%-1
rgb% = FNgetpixel(x%,y%)
r% = rgb% >> 16
g% = (rgb% >> 8) AND &FF
b% = rgb% AND &FF
l% = INT(0.3*r% ... |
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... | #C | C | typedef unsigned char luminance;
typedef luminance pixel1[1];
typedef struct {
unsigned int width;
unsigned int height;
luminance *buf;
} grayimage_t;
typedef grayimage_t *grayimage;
grayimage alloc_grayimg(unsigned int, unsigned int);
grayimage tograyscale(image);
image tocolor(grayimage); |
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... | #AutoHotkey | AutoHotkey |
' 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 ... | #BBC_BASIC | BBC BASIC | @% = &1010
FOR h% = 1 TO 20
PRINT "H("; h% ") = "; FNhamming(h%)
NEXT
PRINT "H(1691) = "; FNhamming(1691)
END
DEF FNhamming(l%)
LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%()
DIM h%(l%) : h%(0) = 1
x2 = 2 : x3 = 3 : x5 = 5
FOR n% = 1 TO l%-1
m = x... |
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... | #C.23 | C# | using System;
class GuessTheNumberGame
{
static void Main()
{
int randomNumber = new Random().Next(1, 11);
Console.WriteLine("I'm thinking of a number between 1 and 10. Can you guess it?");
while(true)
{
Console.Write("Guess: ");
if (int.Parse(Console.... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
srand(time(0));
int n = 1 + (rand() % 10);
int g;
std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! ";
while(true)
{
std::cin >> g;
if (g == n)
break;
else
... |
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... | #C.23 | C# | using System;
namespace Tests_With_Framework_4
{
class Program
{
static void Main(string[] args)
{
int[] integers = { -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 }; int length = integers.Length;
int maxsum, beginmax, endmax, sum; maxsum = beginmax = sum = 0; endmax = -1;
... |
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... | #Ruby | Ruby | Shoes.app do
@number = edit_line
@number.change {update_controls}
@incr = button('Increment') {update_controls(@number.text.to_i + 1)}
@decr = button('Decrement') {update_controls(@number.text.to_i - 1)}
def update_controls(value = @number.text.to_i)
@number.text = value
@incr.state = value.to_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... | #C | C | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define lower_limit 0
#define upper_limit 100
int main(){
int number, guess;
srand( time( 0 ) );
number = lower_limit + rand() % (upper_limit - lower_limit + 1);
printf( "Guess the number between %d and %d: ", lower_limit, upper_limit );
while... |
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... | #Julia | Julia | using Gtk, Cairo, ColorTypes
function generategrays(n, screenwidth)
verts = Vector{RGB}()
hwidth = Int(ceil(screenwidth/n))
for x in 00:Int(floor(0xff/(n-1))):0xff
rgbgray = RGB(x/255, x/255, x/255)
for i in 1:hwidth
push!(verts, rgbgray)
end
end
verts
end
fun... |
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... | #Kotlin | Kotlin | // version 1.1
import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame
class GreyBars : JFrame("grey bars example!") {
private val w: Int
private val h: Int
init {
w = 640
h = 320
setSize(w, h)
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
isVisi... |
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... | #JavaScript | JavaScript | #!/usr/bin/env js
var DONE = RIGHT = 0, HIGH = 1, LOW = -1;
function main() {
showInstructions();
while (guess(1, 100) !== DONE);
}
function guess(low, high) {
if (low > high) {
print("I can't guess it. Perhaps you changed your number.");
return DONE;
}
var g = Math.floor((lo... |
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... | #Dart | Dart | main() {
HashMap<int,bool> happy=new HashMap<int,bool>();
happy[1]=true;
int count=0;
int i=0;
while(count<8) {
if(happy[i]==null) {
int j=i;
Set<int> sequence=new Set<int>();
while(happy[j]==null && !sequence.contains(j)) {
sequence.add(j);
int sum=0;
int val... |
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... | #LiveCode | LiveCode | function radians n
return n * (3.1415926 / 180)
end radians
function haversine lat1, lng1, lat2, lng2
local radiusEarth
local lat3, lng3
local lat1Rad, lat2Rad, lat3Rad
local lngRad1, lngRad2, lngRad3
local haver
put 6372.8 into radiusEarth
put (lat2 - lat1) into lat3
put (lng2 - ... |
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... | #Lua | Lua | local function haversine(x1, y1, x2, y2)
r=0.017453292519943295769236907684886127;
x1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1;
a = math.pow(math.sin(dx/2),2) + math.cos(x1) * math.cos(x2) * math.pow(math.sin(dy/2),2); c = 2 * math.asin(math.sqrt(a)); d = 6372.8 * c;
return d;
end |
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
| #FUZE_BASIC | FUZE BASIC | 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
| #UnixPipes | UnixPipes | cat <<VAL >p.values
apple
boy
cow
dog
elephant
VAL
cat <<KEYS >p.keys
a
b
c
d
e
KEYS
paste -d\ <(cat p.values | sort) <(cat p.keys | sort) |
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
| #Ursala | Ursala | keys = <'foo','bar','baz'>
values = <12354,145430,76748>
hash_function = keys-$values |
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/... | #NetRexx | NetRexx | /* NetRexx ------------------------------------------------------------
* 21.01.2014 Walter Pachl translated from ooRexx (from REXX version 1)
*--------------------------------------------------------------------*/
options replace format comments java crossref symbols nobinary
Parse Arg x y . /... |
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
| #HicEst | HicEst | WRITE(Messagebox='!') '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
| #HolyC | HolyC | PopUpOk("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... | #Oz | Oz | declare
[QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
proc {Main}
MaxValue = 1000
NumberWidget
GUI = lr(
numberentry(init:1 min:0 max:MaxValue handle:NumberWidget)
button(text:"Increase"
action:proc {$}
OldVal = {N... |
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.
| #8th | 8th |
[ 1.0, 2.3, 1.1, 5.0, 3, 2.8, 2.01, 3.14159 ] ' n:max 0 a:reduce . cr
|
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... | #Go | Go | package main
import (
"fmt"
"sort"
)
type graph struct {
nn int // number of nodes
st int // node numbering starts from
nbr [][]int // neighbor list for each node
}
type nodeval struct {
n int // number of node
v int // valence of node i.e. number of neighbors
}
func contai... |
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),... | #Arturo | Arturo | G: function [n][
size select 2..n/2 'x ->
and? [prime? x][prime? n-x]
]
print "The first 100 G values:"
loop split.every: 10 map select 4..202 => even? => G 'row [
print map to [:string] row 'item -> pad item 3
]
print ["\nG(1000000) =" G 1000000]
csv: join.with:",\n" map select 4..2000 => even? '... |
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),... | #AWK | AWK |
# syntax: GAWK -f GOLDBACHS_COMET.AWK
BEGIN {
print("The first 100 G numbers:")
for (n=4; n<=202; n+=2) {
printf("%4d%1s",g(n),++count%10?"":"\n")
}
n = 1000000
printf("\nG(%d): %d\n",n,g(n))
n = 4
printf("G(%d): %d\n",n,g(n))
n = 22
printf("G(%d): %d\n",n,g(n))
exit(0)
}... |
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... | #C.23 | C# |
Bitmap tImage = new Bitmap("spectrum.bmp");
for (int x = 0; x < tImage.Width; x++)
{
for (int y = 0; y < tImage.Height; y++)
{
Color tCol = tImage.GetPixel(x, y);
// L = 0.2126·R + 0.7152·G + 0.0722·B
double L = 0.2126 * tCol.R + 0.7152 * tCol.G + 0.0722 * tCol.B;
tImage.SetPixel(x, y, Color.FromArgb(C... |
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... | #Clojure | Clojure |
(import '[java.io File]
'[javax.imageio ImageIO]
'[java.awt Color]
'[java.awt.image BufferedImage]))
(defn rgb-to-gray [color-image]
(let [width (.getWidth color-image)]
(partition width
(for [x (range width)
y (range (.getHeight color-image))]
... |
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... | #C | C |
' 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 ... | #Bc | Bc | cat hamming_numbers.bc
define min(x,y) {
if (x < y) {
return x
} else {
return y
}
}
define hamming(limit) {
i = 0
j = 0
k = 0
h[0] = 1
x2 = 2
x3 = 3
x5 = 5
for (n=1; n<=limit; n++) {
h[n] = min(x2,min(x3,x5))
if (h[n] == x2) { x2 = 2 * h[++i] }
if (h[n] == x3) { x3 = 3 * h[++j] }
if (h[n] == x5) {... |
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... | #Clojure | Clojure |
(def target (inc (rand-int 10))
(loop [n 0]
(println "Guess a number between 1 and 10 until you get it right:")
(let [guess (read)]
(if (= guess target)
(printf "Correct on the %d guess.\n" n)
(do
(println "Try again")
(recur (inc n))))))
|
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Guess-The-Number.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Random-Num PIC 99.
01 Guess PIC 99.
PROCEDURE DIVISION.
COMPUTE Random-Num = 1 + (FUNCTION RANDOM * 10)
DISPLAY "Guess a number between 1 an... |
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... | #C.2B.2B | C++ | #include <utility> // for std::pair
#include <iterator> // for std::iterator_traits
#include <iostream> // for std::cout
#include <ostream> // for output operator and std::endl
#include <algorithm> // for std::copy
#include <iterator> // for std::output_iterator
// Function template max_subseq
//
// Given a se... |
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... | #Scala | Scala | import swing.{ BoxPanel, Button, GridPanel, Orientation, Swing, TextField }
import swing.event.{ ButtonClicked, Key, KeyPressed, KeyTyped }
object Enabling extends swing.SimpleSwingApplication {
def top = new swing.MainFrame {
title = "Rosetta Code >>> Task: GUI enabling/disabling of controls | Language: Scala"... |
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... | #C.23 | C# | using System;
class Program
{
static void Main(string[] args)
{
const int from = 1;
const int to = 10;
int randomNumber = new Random().Next(from, to);
int guessedNumber;
Console.Write("The number is between {0} and {1}. ", from, to);
while (true)
{
... |
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... | #Liberty_BASIC | Liberty BASIC |
nomainwin
WindowWidth =DisplayWidth
WindowHeight =DisplayHeight
open "Grey bars" for graphics_fs_nsb as #w
#w "trapclose [quit]"
#w "down"
bars =4 ' alter for more, finer bars.
for group =0 to bars -1
for i = 0 to 2^( 3 +group) -1
#w "place "; WindowWidth *i /( 2^( 3 +group)); " "... |
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... | #Julia | Julia | print("Enter an upper bound: ")
lower = 0
input = readline()
upper = parse(Int, input)
if upper < 1
throw(DomainError)
end
attempts = 1
print("Think of a number, ", lower, "--", upper, ", then press ENTER.")
readline()
const maxattempts = round(Int, ceil(-log(1 / (upper - lower)) / log(2)))
println("I will need... |
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... | #Kotlin | Kotlin | // version 1.0.5-2
fun main(args: Array<String>) {
var hle: Char
var lowest = 1
var highest = 20
var guess = 10
println("Please choose a number between 1 and 20 but don't tell me what it is yet\n")
while (true) {
println("My guess is $guess")
do {
print("Is ... |
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... | #dc | dc | [lcI~rscd*+lc0<H]sH
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx |
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... | #Maple | Maple | distance := (theta1, phi1, theta2, phi2)->2*6378.14*arcsin( sqrt((1-cos(theta2-theta1))/2 + cos(theta1)*cos(theta2)*(1-cos(phi2-phi1))/2) ); |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
distance[{theta1_, phi1_}, {theta2_, phi2_}] :=
2*6378.14 ArcSin@
Sqrt[Haversine[(theta2 - theta1) Degree] +
Cos[theta1*Degree] Cos[theta2*Degree] Haversine[(phi2 - phi1) Degree]]
|
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
| #Gambas | Gambas | Public Sub Main()
PRINT "Hello world!"
End |
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
| #Vala | Vala |
using Gee;
void main(){
// mostly copied from C# example
var hashmap = new HashMap<string, string>();
string[] arg_keys = {"foo", "bar", "val"};
string[] arg_values = {"little", "miss", "muffet"};
if (arg_keys.length == arg_values.length ){
for (i... |
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
| #VBScript | VBScript | Set dict = CreateObject("Scripting.Dictionary")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
dict.Add os(n), owner(n)
Next
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows") |
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/... | #Nim | Nim | proc slice[T](iter: iterator(): T {.closure.}; sl: Slice[T]): seq[T] =
var i = 0
for n in iter():
if i > sl.b: break
if i >= sl.a: result.add(n)
inc i
iterator harshad(): int {.closure.} =
for n in 1 ..< int.high:
var sum = 0
for ch in $n:
sum += ord(ch) - ord('0')
if n mod sum ==... |
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
| #Icon_and_Unicon | Icon and Unicon | link graphics
procedure main()
WOpen("size=100,20") | stop("No window")
WWrites("Goodbye, World!")
WDone()
end |
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
| #HPPPL | HPPPL | MSGBOX("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... | #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;
my $value = 0;
my $mw = MainWindow->new;
$mw->title( 'GUI component interaction' );
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
$lf->Entry( -width => 10, -textvariable => \$value,
-validate => '... |
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... | #11l | 11l | F gray_encode(n)
R n (+) n >> 1
F gray_decode(=n)
V m = n >> 1
L m != 0
n (+)= m
m >>= 1
R n
print(‘DEC, BIN => GRAY => DEC’)
L(i) 32
V gray = gray_encode(i)
V dec = gray_decode(gray)
print(‘ #2, #. => #. => #2’.format(i, bin(i).zfill(5), bin(gray).zfill(5), dec)) |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program rechMax64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM6... |
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... | #Haskell | Haskell | import Data.Maybe
import Data.List
import Control.Monad.State
import qualified Data.Map as M
import Text.Printf
------------------------------------------------------------
-- Primitive graph representation
type Node = Int
type Color = Int
type Graph = M.Map Node [Node]
nodes :: Graph -> [Node]
nodes = M.keys
a... |
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),... | #FreeBASIC | FreeBASIC | Function isPrime(Byval ValorEval As Uinteger) As Boolean
If ValorEval <= 1 Then Return False
For i As Integer = 2 To Int(Sqr(ValorEval))
If ValorEval Mod i = 0 Then Return False
Next i
Return True
End Function
Function g(n As Uinteger) As Uinteger
Dim As Uinteger i, count = 0
If (n Mod... |
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),... | #J | J | 10 10$#/.~4,/:~ 0-.~,(<:/~ * +/~) p:1+i.p:inv 202
1 1 1 2 1 2 2 2 2 3
3 3 2 3 2 4 4 2 3 4
3 4 5 4 3 5 3 4 6 3
5 6 2 5 6 5 5 7 4 5
8 5 4 9 4 5 7 3 6 8
5 6 8 6 7 10 6 6 12 4
5 10 3 7 9 6 5 8 7 8
11 6 5 12 4 8 11 5 8 10
5 6 13 9 6 11 7 7 14 ... |
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... | #Common_Lisp | Common Lisp |
(in-package #:rgb-pixel-buffer)
(defun rgb-to-gray-image (rgb-image)
(flet ((rgb-to-gray (rgb-value)
(round (+ (* 0.2126 (rgb-pixel-red rgb-value))
(* 0.7152 (rgb-pixel-green rgb-value))
(* 0.0722 (rgb-pixel-blue rgb-value))))))
(let ((gray-image (make-array (array-dimensions rgb-image) :ele... |
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... | #C.2B.2B | C++ |
' 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 ... | #Bracmat | Bracmat | ( ( hamming
= x2 x3 x5 n i j k min
. tbl$(h,!arg) { This creates an array. Arrays are always global in Bracmat. }
& 1:?(0$h)
& 2:?x2
& 3:?x3
& 5:?x5
& 0:?n:?i:?j:?k
& whl
' ( !n+1:<!arg:?n
& !x2:?min
& (!x3:<!min:?min|)
& (!x5:... |
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... | #CoffeeScript | CoffeeScript | num = Math.ceil(Math.random() * 10)
guess = prompt "Guess the number. (1-10)"
while parseInt(guess) isnt num
guess = prompt "YOU LOSE! Guess again. (1-10)"
alert "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... | #Common_Lisp | Common Lisp | (defun guess-the-number (max)
(format t "Try to guess a number from 1 to ~a!~%Guess? " max)
(loop with num = (1+ (random max))
for guess = (read)
as num-guesses from 1
until (and (numberp guess) (= guess num))
do (format t "Your guess was wrong. Try again.~%Guess? ")
(for... |
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... | #Clojure | Clojure | (defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll)) ; tails
(mapcat #(reductions conj [] %)) ; inits
(apply max-key #(reduce + %)))) ; max 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... | #Smalltalk | Smalltalk | |top input vh incButton decButton|
vh := ValueHolder with:0.
top := StandardSystemView label:'Rosetta GUI interaction'.
top extent:300@100.
top add:((Label label:'Value:') origin: 0 @ 10 corner: 100 @ 40).
top add:(input := EditField origin: 102 @ 10 corner: 1.0 @ 40).
input model:(TypeConverter onNumberValue:vh).
... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::srand(std::time(0));
int lower, upper, guess;
std::cout << "Enter lower limit: ";
std::cin >> lower;
std::cout << "Enter upper limit: ";
std::cin >> upper;
int random_number = lower + std::rand() % ((upper + 1) - low... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | CreateDocument[ Graphics[ Flatten@Table[
{ If[EvenQ[#3], GrayLevel[ 1. - j/#1 ], GrayLevel[ j/#1 ]],
Rectangle[{j #2, 7*#3}, {#2 (j + 1), (#3 + 1) 7}]}, {j, 0, #1}] & @@@
{{7, 8, 3}, {15, 4, 2}, {31, 2, 1}, {63, 1, 0} }
,ImageSize -> Full], WindowFrame -> "Frameless", WindowSize -> Full] |
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... | #MAXScript | MAXScript |
fn drawBarRow _bmp _row _width _number _inverse=
(
local dir = if _inverse then 1 else -1
if not _inverse then
(
setpixels _bmp [0,_row] (for i in 1 to (_width/_number) collect (black))
for i = (_width/_number) to _width by (_width/_number) do
(
local loopPosition = i/(_width-(_width/_number)) as fl... |
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... | #Liberty_BASIC | Liberty BASIC | mini=0
maxi=100
print "Think of a number between ";mini;" and ";maxi
print "Each time I guess a number you must state whether my"
print "guess was too high, too low, or equal to your number."
print
while response$<>"="
if not(mini<=maxi) then
print "Error"
exit while
end if
guess=int((maxi-mini)/2)+mini
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.