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/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... | #Oforth | Oforth | import: math
: haversine(lat1, lon1, lat2, lon2)
| lat lon |
lat2 lat1 - asRadian ->lat
lon2 lon1 - asRadian ->lon
lon 2 / sin sq lat1 asRadian cos * lat2 asRadian cos *
lat 2 / sin sq + sqrt asin 2 * 6372.8 * ;
haversine(36.12, -86.67, 33.94, -118.40) println |
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... | #ooRexx | ooRexx | /*REXX pgm calculates distance between Nashville & Los Angles airports. */
say " Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º"
say "Los Angles: north 33º 56.4', west 118º 24.0' = 33.94º, -118.40º"
say
dist=surfaceDistance(36.12, -86.67, 33.94, -118.4)
kdist=format(dist/1 ,,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
| #GLBasic | GLBasic | STDOUT "Hello world!" |
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/... | #PicoLisp | PicoLisp |
#if niven number, return it.
(de niven (N)
(if (=0 (% N (apply + (getN N)))) N) )
#function which creates a list of numbers from input
(de getN (N)
(mapcar format (chop N)) )
#This function generates niven number list
(de nivGen (R N)
(extract niven (range R N)) )
#print 1st 20 niven numbers and 1st ni... |
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
| #Just_Basic | Just Basic |
print "Goodbye, World!"
'Prints in the upper left corner of the default text window: mainwin, a window with scroll bars.
|
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
| #KonsolScript | KonsolScript | function main() {
Konsol:Message("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... | #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(200,200,100,30)
settext("Random")
... |
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... | #Ruby | Ruby | Shoes.app(title: "GUI component interaction") do
stack do
textbox = edit_line
textbox.change do
textbox.text = textbox.text.gsub(/[^\d]/, '') and alert "Input must be a number!" if textbox.text !~ /^\d*$/
end
flow do
button "Increment" do
textbox.text = textbox.text.to_i + 1
... |
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... | #Batch_File | Batch File | :: Gray Code Task from Rosetta Code
:: Batch File Implementation
@echo off
rem -------------- define batch file macros with parameters appended
rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=2518
setlocal disabledelayedexpansion % == required for macro ==%
(set \n=^^^
%== this creates escaped line f... |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #Arturo | Arturo | print split.lines execute "ls" |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #AWK | AWK |
BEGIN {
# For Windows
out = system2var("dir")
print out
# Non-Windows
out = getline2var("ls -l")
print out
}
# For a Windows environment using system() method
function system2var(command ,tempfile, cmd, out, rec, data, i) {
tempfile = "C:\\TEMP\\... |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #BaCon | BaCon | ' Get system command
result$ = EXEC$("fortune")
PRINT CHOP$(result$)
PRINT "First word: " & TOKEN$(result$, 1) |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #11l | 11l | F swap(&a, &b)
(a, b) = (b, a) |
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.
| #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
main:
lst=0
max=0
file="datos.txt"
{","} toksep
{file} statsfile
{file} load
mov (lst)
{0} reshape (lst)
{lst} array (SORT)
[end] get (lst)
mov ... |
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.
| #AntLang | AntLang | max|range[10] |
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... | #ACL2 | ACL2 | (include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)
(defun gcd$ (x y)
(declare (xargs :guard (and (natp x) (natp y))))
(cond ((or (not (natp x)) (< y 0))
nil)
((zp y) x)
(t (gcd$ y (mod x y))))) |
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <err.h>
#include <string.h>
char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)
{
ptrdiff_t i;
char *start = b... |
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... | #ALGOL_68 | ALGOL 68 | MODE LINT = # LONG ... # INT;
PROC hailstone = (INT in n, REF[]LINT array)INT:
(
INT hs := 1;
INT index := 0;
LINT n := in n;
WHILE n /= 1 DO
hs +:= 1;
IF array ISNT REF[]LINT(NIL) THEN array[index +:= 1] := n FI;
n := IF ODD n THEN 3*n+1 ELSE n OVER 2 FI
OD;
IF array... |
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... | #Go | Go | package raster
import (
"math"
"math/rand"
)
// Grmap parallels Bitmap, but with an element type of uint16
// in place of Pixel.
type Grmap struct {
Comments []string
rows, cols int
px []uint16
pxRow [][]uint16
}
// NewGrmap constructor.
func NewGrmap(x, y int) (b *Grmap) {
... |
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... | #Java | Java | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Go_Fish
use warnings;
use List::Util qw( first shuffle );
my $pat = qr/[atjqk2-9]/; # ranks
my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) }
qw( a t j q k ), 2 .. 9;
my $mebooks = my $youbooks = 0;
my $me = substr $deck,... |
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 ... | #Crystal | Crystal | require "big"
def hamming(limit)
h = Array.new(limit, 1.to_big_i) # h = Array.new(limit+1, 1.to_big_i)
x2, x3, x5 = 2.to_big_i, 3.to_big_i, 5.to_big_i
i, j, k = 0, 0, 0
(1...limit).each do |n| # (1..limit).each do |n|
h[n] = Math.min(x2, Math.min(x3, x5))
x2 = 2 * h[i += 1] if x2 == h... |
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... | #Factor | Factor |
USING: io random math math.parser kernel formatting ;
IN: guess-the-number
<PRIVATE
: gen-number ( -- n )
10 random 1 + ;
: make-guess ( n -- n ? )
dup readln string>number = ;
: play-game ( n -- n )
[ make-guess ]
[ "Guess a number between 1 and 10:" print flush ] do until ;
PRIVATE>
: guess-the-... |
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... | #Fantom | Fantom |
class Main
{
public static Void main ()
{
Str target := (1..10).random.toStr
Str guess := ""
while (guess != target)
{
echo ("Enter a guess: ")
guess = Env.cur.in.readLine
if (guess.trim == target) // 'trim' to remove any spaces/newline
{
echo ("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... | #Elixir | Elixir | defmodule Greatest do
def subseq_sum(list) do
list_i = Enum.with_index(list)
acc = {0, 0, length(list), 0, 0}
{_,max,first,last,_} = Enum.reduce(list_i, acc, fn {elm,i},{curr,max,first,last,curr_first} ->
if curr < 0 do
if elm > max, do: {elm, elm, i, i, curr_first},
... |
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... | #ERRE | ERRE |
PROGRAM MAX_SUM
DIM A%[11],B%[10],C%[4]
!$DYNAMIC
DIM P%[0]
PROCEDURE MAX_SUBSEQUENCE(P%[],N%->A$)
LOCAL A%,B%,I%,J%,M%,S%
A%=1
FOR I%=0 TO N% DO
S%=0
FOR J%=I% TO N% DO
S%+=P%[J%]
IF S%>M% THEN
M%=S%
A%=I%
B%=J%
... |
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... | #D | D | import std.stdio, std.random, std.typecons, std.conv, std.string,
std.range;
void main() {
immutable interval = tuple(1, 100);
writefln("Guess my target number that is between " ~
"%d and %d (inclusive).\n", interval[]);
immutable target = uniform!"[]"(interval[]);
foreach (immut... |
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... | #Scala | Scala | import scala.swing._
class GreyscaleBars extends Component {
override def paintComponent(g:Graphics2D)={
val barHeight=size.height>>2
for(run <- 0 to 3; colCount=8<<run){
val deltaX=size.width.toDouble/colCount
val colBase=if (run%2==0) -255 else 0
for(x <- 0 until colCount){
val c... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
const proc: main is func
local
var integer: barHeight is 0;
var integer: barNumber is 0;
var integer: colCount is 0;
var integer: deltaX is 0;
var integer: x is 0;
var integer: col is 0;
begin
screen(640, 480);
... |
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... | #Perl | Perl | #!/usr/bin/perl
my $min = 1;
my $max = 99;
my $guess = int(rand $max) + $min;
my $tries = 0;
print "=>> Think of a number between $min and $max and I'll guess it!\n
Press <ENTER> when are you ready... ";
<STDIN>;
{
do {
$tries++;
print "\n=>> My guess is: $guess Is your number higher, 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... | #Elena | Elena | import extensions;
import system'collections;
import system'routines;
isHappy(int n)
{
auto cache := new List<int>(5);
int sum := 0;
int num := n;
while (num != 1)
{
if (cache.indexOfElement:num != -1)
{
^ false
};
cache.append(num);
while (num !... |
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... | #PARI.2FGP | PARI/GP | dist(th1, th2, ph)={
my(v=[cos(ph)*cos(th1)-cos(th2),sin(ph)*cos(th1),sin(th1)-sin(th2)]);
asin(sqrt(norml2(v))/2)
};
distEarth(th1, ph1, th2, ph2)={
my(d=12742, deg=Pi/180); \\ Authalic diameter of the Earth
d*dist(th1*deg, th2*deg, (ph1-ph2)*deg)
};
distEarth(36.12, -86.67, 33.94, -118.4) |
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
| #Glee | Glee | "Hello world!" |
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/... | #PILOT | PILOT | C :n=0
:i=0
*first20
U :*harshad
C :i=i+1
T :#i: #n
J (i<20):*first20
C :n=1000
U :*harshad
T :First Harshad number greater than 1000: #n
E :
*harshad
C :n=n+1
:r=n
:s=0
*digit
C :a=r/10
:s=s+(r-a*10)
:r=a
J (r):*digit
J (n<>s*(n/s)):*harshad
E : |
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
| #Kotlin | Kotlin | import java.awt.*
import javax.swing.*
fun main(args: Array<String>) {
JOptionPane.showMessageDialog(null, "Goodbye, World!") // in alert box
with(JFrame("Goodbye, World!")) { // on title bar
layout = FlowLayout()
add(JButton("Goodbye, World!")) // on bu... |
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... | #Run_BASIC | Run BASIC | dim dd$(5) ' drop down box
for i = 1 to 5
dd$(i) = "Drop ";i
next i
value$ = "1234"
notes$ = "Rosetta Code
is good"
bf$ = "<SPAN STYLE='font-family:arial; font-weight:700; font-size:12pt'>"
[screen]
cls
html bf$;"<center><TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 bgcolor=wheat>"
html "<TR align=ce... |
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... | #Scala | Scala | import scala.swing._
import scala.swing.Swing._
import scala.swing.event._
object Interact extends SimpleSwingApplication {
def top = new MainFrame {
title = "Rosetta Code >>> Task: component interaction | Language: Scala"
val numberField = new TextField {
text = "0" // start at 0
horizontalAl... |
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... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"STRINGLIB"
PRINT " Decimal Binary Gray Decoded"
FOR number% = 0 TO 31
gray% = FNgrayencode(number%)
PRINT number% " " FN_tobase(number%, 2, 5) ;
PRINT " " FN_tobase(gray%, 2, 5) FNgraydecode(gray%)
NEXT
END
DEF FNgrayenco... |
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... | #bc | bc | scale = 0 /* to use integer division */
/* encode Gray code */
define e(i) {
auto h, r
if (i <= 0) return 0
h = i / 2
r = e(h) * 2 /* recurse */
if (h % 2 != i % 2) r += 1 /* xor low bits of h, i */
return r
}
/* decode Gray code */
define d(i) {
auto h, r
if (i <= 0) return 0
h = d(i ... |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
:: Without storing the output of the command, it can be viewed by inputting the command
dir
:: Storing the output of 'dir' as "line[]" containing the respective lines of output (starting at line[1])
:: Note: This method removes any empty lines from the output
set tempcoun... |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #Bracmat | Bracmat | (system=
.sys$(str$(!arg " > temp"))&get$(temp,STR)
); |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) return 1;
FILE *fd;
fd = popen(argv[1], "r");
if (!fd) return 1;
char buffer[256];
size_t chread;
/* String to store entire command contents in */
size_t comalloc = 256;
... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #360_Assembly | 360 Assembly |
SWAP CSECT , control section start
BAKR 14,0 stack caller's registers
LR 12,15 entry point address to reg.12
USING SWAP,12 use as base
MVC A,=C'5678____' init field A
MVC B,=C'____1234' i... |
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.
| #APL | APL | LIST←2 4 6 3 8
⌈/LIST |
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... | #Action.21 | Action! | CARD FUNC Gcd(CARD a,b)
CARD tmp
IF a<b THEN
tmp=a a=b b=tmp
FI
WHILE b#0
DO
tmp=a MOD b
a=b
b=tmp
OD
RETURN(a)
PROC Test(CARD a,b)
CARD res
res=Gcd(a,b)
PrintF("GCD of %I and %I is %I%E",a,b,res)
RETURN
PROC Main()
Test(48,18)
Test(9360,12240)
Test(17,19)
Test(123,1... |
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.
| #C.23 | C# |
using System.Collections.Generic;
using System.IO;
class Program {
static void Main() {
var files = new List<string> {
"test1.txt",
"test2.txt"
};
foreach (string file in files) {
File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!"... |
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.
| #C.2B.2B | C++ | #include <fstream>
#include <iterator>
#include <boost/regex.hpp>
#include <string>
#include <iostream>
int main( int argc , char *argv[ ] ) {
boost::regex to_be_replaced( "Goodbye London\\s*!" ) ;
std::string replacement( "Hello New York!" ) ;
for ( int i = 1 ; i < argc ; i++ ) {
std::ifstream infile ... |
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... | #ALGOL-M | ALGOL-M |
BEGIN
INTEGER N, LEN, YES, NO, LIMIT, LONGEST, NLONG;
% RETURN P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% COMPUTE AND OPTIONALLY DISPLAY HAILSTONE SEQUENCE FOR N. %
% RETURN LENGTH OF SEQUENCE OR ZERO ON OVERFLOW. %
INTEGER FUNCTION HAILSTONE(N, DISPLAY);
INTEGER ... |
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... | #Haskell | Haskell | module Bitmap.Gray(module Bitmap.Gray) where
import Bitmap
import Control.Monad.ST
newtype Gray = Gray Int deriving (Eq, Ord)
instance Color Gray where
luminance (Gray x) = x
black = Gray 0
white = Gray 255
toNetpbm = map $ toEnum . luminance
fromNetpbm = map $ Gray . fromEnum
netpbmMagicN... |
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... | #J | J | NB. converts the image to grayscale according to formula
NB. L = 0.2126*R + 0.7152*G + 0.0722*B
toGray=: [: <. +/ .*"1&0.2126 0.7152 0.0722
NB. converts grayscale image to the color image, with all channels equal
toColor=: 3 & $"0 |
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... | #Julia | Julia | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Go_Fish
use warnings;
use List::Util qw( first shuffle );
my $pat = qr/[atjqk2-9]/; # ranks
my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) }
qw( a t j q k ), 2 .. 9;
my $mebooks = my $youbooks = 0;
my $me = substr $deck,... |
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 ... | #D | D | import std.stdio, std.bigint, std.algorithm, std.range, core.memory;
auto hamming(in uint n) pure nothrow /*@safe*/ {
immutable BigInt two = 2, three = 3, five = 5;
auto h = new BigInt[n];
h[0] = 1;
BigInt x2 = 2, x3 = 3, x5 = 5;
size_t i, j, k;
foreach (ref el; h.dropOne) {
el = min... |
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... | #Forth | Forth |
\ tested with GForth 0.7.0
: RND ( -- n) TIME&DATE 2DROP 2DROP DROP 10 MOD ; \ crude random number
: ASK ( -- ) CR ." Guess a number between 1 and 10? " ;
: GUESS ( -- n) PAD DUP 4 ACCEPT EVALUATE ;
: REPLY ( n n' -- n) 2DUP <> IF CR ." No, it's not " DUP . THEN ;
: GAME ( -- )
RND
... |
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... | #Fortran | Fortran | program guess_the_number
implicit none
integer :: guess
real :: r
integer :: i, clock, count, n
integer,dimension(:),allocatable :: seed
real,parameter :: rmax = 10
!initialize random number generator:
call random_seed(size=n)
... |
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... | #Euler_Math_Toolbox | Euler Math Toolbox |
>function %maxsubs (v,n) ...
$if n==1 then
$ if (v[1]<0) then return {zeros(1,0),zeros(1,0)}
$ else return {v,v};
$ endif;
$endif;
${v1,v2}=%maxsubs(v[1:n-1],n-1);
$m1=sum(v1); m2=sum(v2); m3=m2+v[n];
$if m3>0 then v3=v2|v[n]; else v3=zeros(1,0); endif;
$if m3>m1 then return {v2|v[n],v3};
$else return {v1,v3};
... |
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... | #Euphoria | Euphoria | function maxSubseq(sequence s)
integer sum, maxsum, first, last
maxsum = 0
first = 1
last = 0
for i = 1 to length(s) do
sum = 0
for j = i to length(s) do
sum += s[j]
if sum > maxsum then
maxsum = sum
first = i
la... |
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... | #DCL | DCL | $ rnd = f$extract( 21, 2, f$time() )
$ count = 0
$ loop:
$ inquire guess "guess what number between 0 and 99 inclusive I am thinking of"
$ guess = f$integer( guess )
$ if guess .lt. 0 .or. guess .gt. 99
$ then
$ write sys$output "out of range"
$ goto loop
$ endif
$ count = count + 1
$ if guess .lt. rnd then $ write s... |
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... | #Tcl | Tcl | package require Tcl 8.5
package require Tk 8.5
wm attributes . -fullscreen 1
pack [canvas .c -highlightthick 0] -fill both -expand 1
# Add more values into this to do more greyscale bar variations
set splits {8 16 32 64}
set dy [expr {[winfo screenheight .c] / [llength $splits]}]
set y 0
foreach s $splits {
set... |
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... | #Phix | Phix | --
-- demo\rosetta\Guess_the_number2.exw
--
with javascript_semantics -- (spacing not (yet) great...)
include pGUI.e
Ihandle lbl, guess, toohigh, too_low, correct, newgame, dlg
integer Min=0, Max=100, Guess
constant LTHINK = sprintf("Think of a number between %d and %d.",{Min,Max})
procedure set_active(bool bActive)
... |
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... | #Elixir | Elixir | defmodule Happy do
def task(num) do
Process.put({:happy, 1}, true)
Stream.iterate(1, &(&1+1))
|> Stream.filter(fn n -> happy?(n) end)
|> Enum.take(num)
end
defp happy?(n) do
sum = square_sum(n, 0)
val = Process.get({:happy, sum})
if val == nil do
Process.put({:happy, sum}, fals... |
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... | #Pascal | Pascal | Program HaversineDemo(output);
uses
Math;
function haversineDist(th1, ph1, th2, ph2: double): double;
const
diameter = 2 * 6372.8;
var
dx, dy, dz: double;
begin
ph1 := degtorad(ph1 - ph2);
th1 := degtorad(th1);
th2 := degtorad(th2);
dz := sin(th1) - sin(th2);
dx := cos(ph1) * co... |
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
| #Global_Script | Global Script | λ _. print qq{Hello world!\n} |
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/... | #PL.2FI | PL/I | *process source or(!) xref attributes;
niven: Proc Options(main);
/*********************************************************************
* 08-06.2013 Walter Pachl translated from Rexx
* with a slight improvement: Do j=y+1 By 1;
**************************************************************... |
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
| #LabVIEW | LabVIEW | sys_process('/usr/bin/osascript', (: '-e', 'display dialog "Goodbye, World!"'))->wait |
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
| #Lasso | Lasso | sys_process('/usr/bin/osascript', (: '-e', 'display dialog "Goodbye, World!"'))->wait |
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... | #Smalltalk | Smalltalk | |top input vh incButton rndButton|
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/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... | #Tcl | Tcl | package require Tk
###--- Our data Model! ---###
# A single variable will do just fine
set field 0
###--- Lay out the GUI components in our View ---###
# We use the Ttk widget set here; it looks much better on Windows and OSX
# First, a quick hack to make things look even nicer
place [ttk::frame .bg] -relwidth 1 ... |
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... | #C | C | int gray_encode(int n) {
return n ^ (n >> 1);
}
int gray_decode(int n) {
int p = n;
while (n >>= 1) p ^= n;
return p;
} |
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... | #C.23 | C# | using System;
public class Gray {
public static ulong grayEncode(ulong n) {
return n^(n>>1);
}
public static ulong grayDecode(ulong n) {
ulong i=1<<8*64-2; //long is 64-bit
ulong p, b=p=n&i;
while((i>>=1)>0)
b|=p=n&i^p>>1;
return b;
}
publi... |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #C.23 | C# | using System;
namespace GetSystemCommandOutput {
class Program {
static void Main(string[] args) {
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo... |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #C.2B.2B | C++ | #include <fstream>
#include <iostream>
std::string execute(const std::string& command) {
system((command + " > temp.txt").c_str());
std::ifstream ifs("temp.txt");
std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };
ifs.close(); // must close the inout stream so ... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #6502_Assembly | 6502 Assembly | ;swap X with Y
pha ;push accumulator
txa
pha ;push x
tya
pha ;push y
pla
tax ;pop y into x
pla
tay ;pop x into y
pla ;pop accumulator |
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.
| #AppleScript | AppleScript |
max({1, 2, 3, 4, 20, 6, 11, 3, 9, 7})
on max(aList)
set _curMax to first item of aList
repeat with i in (rest of aList)
if i > _curMax then set _curMax to contents of i
end repeat
return _curMax
end max
|
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... | #ActionScript | ActionScript | //Euclidean algorithm
function gcd(a:int,b:int):int
{
var tmp:int;
//Swap the numbers so a >= b
if(a < b)
{
tmp = a;
a = b;
b = tmp;
}
//Find the gcd
while(b != 0)
{
tmp = a % b;
a = b;
b = tmp;
}
return a;
} |
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.
| #Clojure | Clojure | (defn hello-goodbye [& more]
(doseq [file more]
(spit file (.replace (slurp file) "Goodbye London!" "Hello New York!")))) |
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.
| #Common_Lisp | Common Lisp |
(defun hello-goodbye (files)
(labels ((replace-from-file (file)
(with-open-file (in file)
(loop for line = (read-line in nil)
while line do
(loop for index = (search "Goodbye London!" line)
while index do
... |
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... | #ALGOL_W | ALGOL W | begin
% show some Hailstone Sequence related information %
% calculates the length of the sequence generated by n, %
% if showFirstAndLast is true, the first and last 4 elements of the %
% sequence are stored in first and last ... |
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... | #Java | Java | void convertToGrayscale(final BufferedImage image){
for(int i=0; i<image.getWidth(); i++){
for(int j=0; j<image.getHeight(); j++){
int color = image.getRGB(i,j);
int alpha = (color >> 24) & 255;
int red = (color >> 16) & 255;
int green = (color >> 8) & 255;
... |
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... | #JavaScript | JavaScript |
function toGray(img) {
let cnv = document.getElementById("canvas");
let ctx = cnv.getContext('2d');
let imgW = img.width;
let imgH = img.height;
cnv.width = imgW;
cnv.height = imgH;
ctx.drawImage(img, 0, 0);
let pixels = ctx.getImageData(0, 0, imgW, imgH);
for (let y = 0; y < pixels.height; 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... | #Kotlin | Kotlin | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Go_Fish
use warnings;
use List::Util qw( first shuffle );
my $pat = qr/[atjqk2-9]/; # ranks
my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) }
qw( a t j q k ), 2 .. 9;
my $mebooks = my $youbooks = 0;
my $me = substr $deck,... |
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 ... | #Dart | Dart | import 'dart:math';
final lb2of2 = 1.0;
final lb2of3 = log(3.0) / log(2.0);
final lb2of5 = log(5.0) / log(2.0);
class Trival {
final double log2;
final int twos;
final int threes;
final int fives;
Trival mul2() {
return Trival(this.log2 + lb2of2, this.twos + 1, this.threes, this.fives);
}
Trival m... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Randomize
Dim n As Integer = Int(Rnd * 10) + 1
Dim guess As Integer
Print "Guess which number I've chosen in the range 1 to 10"
Print
Do
Input " Your guess : "; guess
If n = guess Then
Print "Well guessed!"
End
End If
Loop |
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... | #Frink | Frink | // Guess a Number
target = random[1,10] // Min and max are both inclusive for the random function
guess = 0
println["Welcome to guess a number! I've picked a number between 1 and 10. Try to guess it!"]
while guess != target
{
guessStr = input["What is your guess?"]
guess = parseInt[guessStr]
if guess == undef
... |
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... | #F.23 | F# | let maxsubseq s =
let (_, _, maxsum, maxseq) =
List.fold (fun (sum, seq, maxsum, maxseq) x ->
let (sum, seq) = (sum + x, x :: seq)
if sum < 0 then (0, [], maxsum, maxseq)
else if sum > maxsum then (sum, seq, sum, seq)
else (sum, seq, maxsum, maxseq))
... |
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... | #Delphi | Delphi | program GuessTheNumber;
{$APPTYPE CONSOLE}
uses
SysUtils,
Math;
const
// Set min/max limits
min: Integer = 1;
max: Integer = 10;
var
last,
val,
inp: Integer;
s: string;
// Initialise new game
procedure NewGame;
begin
// Make sure this number isn't the same as the last one
rep... |
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... | #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math
class GreyBars {
construct new(width, height) {
Window.title = "Grey bars example"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
}
init() {
... |
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... | #PicoLisp | PicoLisp | (de guessTheNumber (Min Max)
(prinl "Think of a number between " Min " and " Max ".")
(prinl "On every guess of mine you should state whether my guess was")
(prinl "too high, too low, or equal to your number by typing 'h', 'l', Or '='")
(use Guess
(loop
(NIL (> Max Min)
(prinl "I ... |
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... | #Prolog | Prolog | min(1). max(10).
pick_number(Min, Max) :-
min(Min), max(Max),
format('Pick a number between ~d and ~d, and I will guess it...~nReady? (Enter anything when ready):', [Min, Max]),
read(_).
guess_number(Min, Max) :-
Guess is (Min + Max) // 2,
format('I guess ~d...~nAm I correct (c), too low (l), or... |
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... | #Erlang | Erlang | -module(tasks).
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).
is_happy(X, XS) ->
if
X == 1 ->
true;
X < 1 ->
false;
true ->
case member(X, XS) of
true -> false;
false ->
is_happy(sum(map(fun(Z) -> Z*Z end,
[Y - 48 || Y <- integer_to_list(X)])),
... |
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... | #Perl | Perl | use ntheory qw/Pi/;
sub asin { my $x = shift; atan2($x, sqrt(1-$x*$x)); }
sub surfacedist {
my($lat1, $lon1, $lat2, $lon2) = @_;
my $radius = 6372.8;
my $radians = Pi() / 180;;
my $dlat = ($lat2 - $lat1) * $radians;
my $dlon = ($lon2 - $lon1) * $radians;
$lat1 *= $radians;
$lat2 *= $radians;
my $a =... |
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
| #GlovePIE | GlovePIE | debug="Hello world!" |
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/... | #PL.2FM | PL/M | 100H:
/* FIND THE SUM OF THE DIGITS OF A 16-BIT NUMBER */
DIGIT$SUM: PROCEDURE(N) BYTE;
DECLARE N ADDRESS, SUM BYTE;
SUM = 0;
DO WHILE N > 0;
SUM = SUM + (N MOD 10);
N = N / 10;
END;
RETURN SUM;
END DIGIT$SUM;
/* FIND THE NEXT HARSHAD NUMBER ABOVE N */
NEXT$HARSHAD: PROCEDURE(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
| #Liberty_BASIC | Liberty BASIC | NOTICE "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
| #Lingo | Lingo | _player.alert("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... | #Vala | Vala | bool validate_input(Gtk.Window window, string str){
int64 val;
bool ret = int64.try_parse(str,out val);;
if(!ret){
var dialog = new Gtk.MessageDialog(window,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR,
... |
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... | #C.2B.2B | C++ |
#include <bitset>
#include <iostream>
#include <string>
#include <assert.h>
uint32_t gray_encode(uint32_t b)
{
return b ^ (b >> 1);
}
uint32_t gray_decode(uint32_t g)
{
for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
{
if (g & bit) g ^= bit >> 1;
}
return g;
}
std::string to_binary... |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #Clojure | Clojure | (use '[clojure.java.shell :only [sh]])
(sh "echo" "Hello") |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #Common_Lisp | Common Lisp | (trivial-shell:shell-command "uname -imp") |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #D | D | import std.process;
import std.stdio;
void main() {
auto cmd = executeShell("echo hello");
if (cmd.status == 0) {
writeln("Output: ", cmd.output);
} else {
writeln("Failed to execute command, status=", cmd.status);
}
} |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #68000_Assembly | 68000 Assembly | EXG D0,D1 ;swap the contents of D0 and D1
EXG A0,A1 ;swap the contents of A0 and A1 |
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.
| #Applesoft_BASIC | Applesoft BASIC | 100 REMMAX
110 R$ = "":E$ = ""
120 L = LEN (L$)
130 IF L = 0 THEN RETURN
140 FOR I = 1 TO L
150 C$ = MID$ (L$,I,1)
160 SP = C$ = " "
170 IF SP THEN GOSUB 200
180 E$ = E$ + C$
190 NEXT I
200 C$ = ""
210 IF E$ = "" THEN RETURN
220 V = VAL (E$):V$ = R$
230 E$ = "":E = V$ = ""
240 IF E ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.