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/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... | #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
procedure Gcd_Test is
function Gcd (A, B : Integer) return Integer is
M : Integer := A;
N : Integer := B;
T : Integer;
begin
while N /= 0 loop
T := M;
M := N;
N := T mod N;
end loop;
return M;
end Gcd;
begin
... |
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.
| #D | D | import std.file, std.array;
void main() {
auto from = "Goodbye London!", to = "Hello, New York!";
foreach (fn; "a.txt b.txt c.txt".split()) {
write(fn, replace(cast(string)read(fn), from, to));
}
} |
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.
| #Delphi | Delphi |
program Globally_replace_text_in_several_files;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IoUtils;
procedure StringReplaceByFile(_old, _new: string; FileName: TFilename;
ReplaceFlags: TReplaceFlags = []); overload
var
Text: string;
begin
if not FileExists(FileName) then
exit;
Text := TFile... |
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... | #APL | APL |
⍝ recursive dfn:
dfnHailstone←{
c←⊃⌽⍵ ⍝ last element
1=c:1 ⍝ if it is 1, stop.
⍵,∇(1+2|c)⊃(c÷2)(1+3×c) ⍝ otherwise pick the next step, and append the result of the recursive call
}
⍝ tradfn version:
∇seq←hailstone n;next
⍝ Returns the hailstone sequence for a given number
seq←n ⍝ Ini... |
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... | #Julia | Julia |
using Color, Images, FixedPointNumbers
const M_RGB_Y = reshape(Color.M_RGB_XYZ[2,:], 3)
function rgb2gray(img::Image)
g = red(img)*M_RGB_Y[1] + green(img)*M_RGB_Y[2] + blue(img)*M_RGB_Y[3]
g = clamp(g, 0.0, 1.0)
return grayim(g)
end
function gray2rgb(img::Image)
colorspace(img) == "Gray" || retu... |
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... | #Kotlin | Kotlin | // version 1.2.10
import java.io.File
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
fun BufferedImage.toGrayScale() {
for (x in 0 until width) {
for (y in 0 until height) {
var argb = getRGB(x, y)
val alpha = (argb shr 24) and 0xFF
val red = (arg... |
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... | #Lua | Lua | #!/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 ... | #DCL | DCL | $ limit = p1
$
$ n = 0
$ h_'n = 1
$ x2 = 2
$ x3 = 3
$ x5 = 5
$ i = 0
$ j = 0
$ k = 0
$
$ n = 1
$ loop:
$ x = x2
$ if x3 .lt. x then $ x = x3
$ if x5 .lt. x then $ x = x5
$ h_'n = x
$ if x2 .eq. h_'n
$ then
$ i = i + 1
$ x2 = 2 * h_'i
$ endif
$ if x3 .eq. h_'n
$ then
$ j = j + 1
$ x3 = 3 * h_'j
$ endif... |
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... | #Gambas | Gambas | Public Sub Form_Open()
Dim byGuess, byGos As Byte
Dim byNo As Byte = Rand(1, 10)
Dim sHead As String = "Guess the number"
Repeat
Inc byGos
byGuess = InputBox("Guess the number between 1 and 10", sHead)
sHead = "Sorry, have another go"
Until byGuess = byNo
Message.Info("Well guessed! You took " & Str(byGos) & ... |
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... | #GML | GML | var n, g;
n = irandom_range(1,10);
show_message("I'm thinking of a number from 1 to 10");
g = get_integer("Please enter guess", 1);
while(g != n)
{
g = get_integer("I'm sorry "+g+" is not my number, try again. Please enter guess", 1);
}
show_message("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... | #Factor | Factor | USING: kernel locals math math.order sequences ;
:: max-with-index ( elt0 ind0 elt1 ind1 -- elt ind )
elt0 elt1 < [ elt1 ind1 ] [ elt0 ind0 ] if ;
: last-of-max ( accseq -- ind ) -1 swap -1 [ max-with-index ] reduce-index nip ;
: max-subseq ( seq -- subseq )
dup 0 [ + 0 max ] accumulate swap suffix last-of-max hea... |
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... | #Forth | Forth | 2variable best
variable best-sum
: sum ( array len -- sum )
0 -rot cells over + swap do i @ + cell +loop ;
: max-sub ( array len -- sub len )
over 0 best 2! 0 best-sum !
dup 1 do \ foreach length
2dup i - 1+ cells over + swap do \ foreach start
i j sum
dup best-sum @ > if
... |
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... | #EasyLang | EasyLang | print "Guess a number between 1 and 100!"
n = random 100 + 1
repeat
g = number input
write g
if error = 1
print "You must enter a number!"
elif g > n
print " is too high"
elif g < n
print " is too low"
.
until g = n
.
print " is correct" |
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... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int Q, N, W, B, C, Y;
[SetVid($112); \640x480x24 graphics
for Q:= 0 to 4-1 do \quarter of screen
[N:= 8<<Q; \number of bars
W:= 640/N; \width of bar (pixels)
for B:= 0 to N-1 do ... |
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... | #Yabasic | Yabasic | open window 1024, 600
w = peek("winwidth")
h = peek("winheight")
rows = 4
hd = int(h / rows)
mitad = 0
for row = 1 to rows
if not mitad then
wd = int(w / (8 * row))
mitad = wd
else
mitad = mitad / 2
end if
c = 255 / (w / mitad)
for n = 0 to (w / mitad)
color 255 - c * n, 255 - c * n, 2... |
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... | #zkl | zkl | img:=PPM(640,480);
foreach q in ([0..3]){ //quarter of screen
n:=(8).shiftLeft(q); //number of bars
w:=640/n; //width of bar (pixels)
foreach b in ([0..n-1]){ //for each bar...
c:=(255.0/(n-1).toFloat() * (if(q.isOdd) n-1-b else b)).toInt();
c:=c.shiftLeft(16) + c.shiftLeft(8) + c; //R... |
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... | #PureBasic | PureBasic | min=0
max=100
If OpenConsole()
PrintN("Think of a number between "+Str(min)+" and "+Str(max)+".")
PrintN("On every guess of mine you should state whether my guess was")
PrintN("too high, too low, or equal to your number by typing 'h', 'l', Or '='")
Repeat
If max<=min
PrintN("I think somthing is stra... |
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... | #Euphoria | Euphoria | function is_happy(integer n)
sequence seen
integer k
seen = {}
while n > 1 do
seen &= n
k = 0
while n > 0 do
k += power(remainder(n,10),2)
n = floor(n/10)
end while
n = k
if find(n,seen) then
return 0
end if
... |
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... | #Phix | Phix | function haversine(atom lat1, long1, lat2, long2)
constant MER = 6371, -- mean earth radius(km)
DEG_TO_RAD = PI/180
lat1 *= DEG_TO_RAD
lat2 *= DEG_TO_RAD
long1 *= DEG_TO_RAD
long2 *= DEG_TO_RAD
return MER*arccos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(long2-long1))
end function
... |
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
| #GML | GML | show_message("Hello world!"); // displays a pop-up message
show_debug_message("Hello world!"); // sends text to the debug log or IDE |
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/... | #PowerShell | PowerShell |
1..1000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 20
1001..2000 | Where { $_ % ( [int[]][string[]][char[]][string]$_ | Measure -Sum ).Sum -eq 0 } | Select -First 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
| #xTalk | xTalk | answer "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
| #Lobster | Lobster | gl_window("graphical hello world", 800, 600)
gl_setfontname("data/fonts/Droid_Sans/DroidSans.ttf")
gl_setfontsize(30)
while gl_frame():
gl_clear([ 0.0, 0.0, 0.0, 1.0 ])
gl_text("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... | #Visual_Basic | Visual Basic | VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 2265
ClientLeft = 60
ClientTop = 600
ClientWidth = 2175
LinkTopic = "Form1"
ScaleHeight = 2265
ScaleWidth = 2175
StartUpPosition = 3 'Windows Default
Begin VB.Comm... |
http://rosettacode.org/wiki/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... | #Web_68 | Web 68 | @1Rosetta code program.
@aPROGRAM guicomponent CONTEXT VOID USE standard
BEGIN
@<Included declarations@>
@<Modes in the outer reach@>
@<Names in the outer reach@>
@<Callback procedures@>
@<Other routines@>
@<Main logic@>
END
FINISH
@ This file contains all the macros for the Xforms library procedures.
Only macros whi... |
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... | #CoffeeScript | CoffeeScript |
gray_encode = (n) ->
n ^ (n >> 1)
gray_decode = (g) ->
n = g
n ^= g while g >>= 1
n
for i in [0..32]
console.log gray_decode gray_encode(i)
|
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... | #Common_Lisp | Common Lisp | (defun gray-encode (n)
(logxor n (ash n -1)))
(defun gray-decode (n)
(do ((p n (logxor p n)))
((zerop n) p)
(setf n (ash n -1))))
(loop for i to 31 do
(let* ((g (gray-encode i)) (b (gray-decode g)))
(format t "~2d:~6b =>~6b =>~6b :~2d~%" i i g b b))) |
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
| #F.23 | F# |
// System Command Output. Nigel Galloway: October 6th., 2020
let n=new System.Diagnostics.Process(StartInfo=System.Diagnostics.ProcessStartInfo(RedirectStandardOutput=true,RedirectStandardError=true,UseShellExecute=false,
FileName= @"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE... |
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
| #Factor | Factor | USING: io.encodings.utf8 io.launcher ;
"echo hello" utf8 [ contents ] with-process-reader . |
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
| #Forth | Forth | s" ps " system \ Output only
\ read via pipe into buffer
create buffer 266 allot
s" ps " r/o open-pipe throw
dup buffer swap 256 swap
read-file throw
swap close-pipe throw drop
buffer swap type \ output is the sa... |
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... | #8086_Assembly | 8086 Assembly | xchg ax,bx ;exchanges ax with bx
xchg ah,al ;swap the high and low bytes of ax
;XCHG a register with memory
mov dx,0FFFFh
mov word ptr [ds:userRam],dx
mov si,offset userRam
mov ax,1234h
xchg ax,[si] ;exchange ax with the value stored at userRam. Now, ax = 0FFFFh and the value stored at userRam = 1234h
... |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program rechMax.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMess... |
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... | #Aime | Aime | o_integer(gcd(33, 77));
o_byte('\n');
o_integer(gcd(49865, 69811));
o_byte('\n'); |
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.
| #Erlang | Erlang |
-module( globally_replace_text ).
-export( [in_files/3, main/1] ).
in_files( Old, New, Files ) when is_list(Old) ->
in_files( binary:list_to_bin(Old), binary:list_to_bin(New), Files );
in_files( Old, New, Files ) -> [replace_in_file(Old, New, X, file:read_file(X)) || X <- Files].
main( [Old, New | Files... |
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... | #AppleScript | AppleScript | on hailstoneSequence(n)
script o
property sequence : {n}
end script
repeat until (n = 1)
if (n mod 2 is 0) then
set n to n div 2
else
set n to 3 * n + 1
end if
set end of o's sequence to n
end repeat
return o's sequence
end hailston... |
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... | #Liberty_BASIC | Liberty BASIC |
nomainwin
WindowWidth = 400
WindowHeight = 400
open "Bitmap" for graphics_nf_nsb as #1
h=hwnd(#1)
calldll #user32, "GetDC", h as ulong, DC as ulong
#1 "trapclose [q]"
loadbmp "clr","MLcolor.bmp"
#1 "drawbmp clr 1 1;flush"
for x = 1 to 150
for y = 1 to 200
calldll #gdi32, "GetPixel", DC as ulong, x as lon... |
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... | #Lingo | Lingo | on rgbToGrayscaleImageFast (img)
res = image(img.width, img.height, 8)
res.paletteRef = #grayScale
res.copyPixels(img, img.rect, img.rect)
return res
end
on rgbToGrayscaleImageCustom (img)
res = image(img.width, img.height, 8)
res.paletteRef = #grayScale
repeat with x = 0 to img.width-1
repeat with ... |
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... | #Locomotive_Basic | Locomotive Basic | #!/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 ... | #Delphi | Delphi |
note
description : "Initial part, in order, of the sequence of Hamming numbers"
math : "[
Hamming numbers, also known as regular numbers and 5-smooth numbers, are natural integers
that have 2, 3 and 5 as their only prime factors.
]"
computer_arithmetic :
"[
... |
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... | #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Print("Guess number from 1 to 10: ")
rand.Seed(time.Now().Unix())
n := rand.Intn(10) + 1
for guess := n; ; fmt.Print("No. Try again: ") {
switch _, err := fmt.Scan(&guess); {
case err != nil:
f... |
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... | #Groovy | Groovy |
def random = new Random()
def keyboard = new Scanner(System.in)
def number = random.nextInt(10) + 1
println "Guess the number which is between 1 and 10: "
def guess = keyboard.nextInt()
while (number != guess) {
println "Guess again: "
guess = keyboard.nextInt()
}
println "Hurray! You guessed correctly!"
|
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... | #Fortran | Fortran | program MaxSubSeq
implicit none
integer, parameter :: an = 11
integer, dimension(an) :: a = (/ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 /)
integer, dimension(an,an) :: mix
integer :: i, j
integer, dimension(2) :: m
forall(i=1:an,j=1:an) mix(i,j) = sum(a(i:j))
m = maxloc(mix)
! a(m(1):m(2)) is the w... |
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... | #EchoLisp | EchoLisp |
;;(read <default-value> <prompt>) prompts the user with a default value using the browser dialog box.
;; we play sounds to make this look like an arcade game
(lib 'web) ; (play-sound) is defined in web.lib
(define (guess-feed (msg " 🔮 Enter a number in [0...100], -1 to stop.") (n (random 100)) (user 0))
(set! u... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM wind the colour down or use a black and white television to see greyscale bars
20 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces
25 BORDER 0: CLS
30 FOR r=0 TO 21: REM There are 22 rows
40 FOR c=0 TO 7: REM We use the native colour sequence here
50 PRINT PAPER c;" ";: REM fou... |
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... | #Python | Python | inclusive_range = mn, mx = (1, 10)
print('''\
Think of a number between %i and %i and wait for me to guess it.
On every guess of mine you should state whether the guess was
too high, too low, or equal to your number by typing h, l, or =
''' % inclusive_range)
i = 0
while True:
i += 1
guess = (mn+mx)//2
... |
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... | #F.23 | F# | open System.Collections.Generic
open Microsoft.FSharp.Collections
let answer =
let sqr x = x*x // Classic square definition
let rec AddDigitSquare n =
match n with
| 0 -> 0 // Sum of squares for ... |
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... | #PHP | PHP | class POI {
private $latitude;
private $longitude;
public function __construct($latitude, $longitude) {
$this->latitude = deg2rad($latitude);
$this->longitude = deg2rad($longitude);
}
public function getLatitude() {
return $this->latitude;
}
public function getL... |
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
| #Go | Go | package main
import "fmt"
func main() { fmt.Println("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/... | #Prolog | Prolog | :- use_module(library(lambda)).
niven :-
nb_setval(go, 1),
L = [1 | _],
print_niven(L, 1),
gen_niven(1, L).
print_niven([X|T], N) :-
when(ground(X),
( ( nb_getval(go, 1)
-> ( N < 20
-> writeln(X),
N1 is N+1,
print_niven(T, N1)
; ( X > 1000
-> writeln(X),
... |
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
| #Logo | Logo | LABEL [Hello, World!]
SETLABELHEIGHT 2 * last LABELSIZE
LABEL [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
| #Lua | Lua | require "iuplua"
dlg = iup.dialog{iup.label{title="Goodbye, World!"}; title="test"}
dlg:show()
if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then
iup.MainLoop()
end |
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... | #Wren | Wren | import "graphics" for Canvas, Color
import "input" for Mouse, Keyboard
import "dome" for Window
import "random" for Random
import "./polygon" for Polygon
var Rand = Random.new()
class Button {
construct new(x, y, w, h, legend, c, oc, lc) {
var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
... |
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... | #Component_Pascal | Component Pascal |
MODULE GrayCodes;
IMPORT StdLog,SYSTEM;
PROCEDURE Encode*(i: INTEGER; OUT x: INTEGER);
VAR
j: INTEGER;
s,r: SET;
BEGIN
s := BITS(i);j := MAX(SET);
WHILE (j >= 0) & ~(j IN s) DO DEC(j) END;
r := {};IF j >= 0 THEN INCL(r,j) END;
WHILE j > 0 DO
IF ((j IN s) & ~(j - 1 IN s)) OR (~(j IN s) & (j - 1 IN s)) THEN ... |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
'capture the output of the 'dir' command and print it to a text file
Open "dir_output.txt" For Output As #1
Open Pipe "dir" For Input As #2
Dim li As String
While Not Eof(2)
Line Input #2, li
Print #1, li
Wend
Close #2
Close #1
End |
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
| #FutureBasic | FutureBasic |
include "NSLog.incl"
local fn ObserverOne( ref as NotificationRef )
FileHandleRef fh = fn NotificationObject( ref )
CFDataRef dta = fn FileHandleAvailableData( fh )
if ( fn DataLength( dta ) > 0 )
CFStringRef string = fn StringWithData( dta, NSUTF8StringEncoding )
NSLog( @"%@", string )
FileHandleWaitForDataIn... |
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
| #Gambas | Gambas | Public Sub Main()
Dim sStore As String
Shell "ls" To sStore
Print sStore
End |
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... | #8th | 8th |
swap
|
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.
| #Arturo | Arturo | arr: [5 4 2 9 7 3]
print max arr |
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... | #ALGOL_60 | ALGOL 60 | begin
comment Greatest common divisor - algol 60;
integer procedure gcd(m,n);
value m,n;
integer m,n;
begin
integer a,b;
a:=abs(m);
b:=abs(n);
if a=0 then gcd:=b
else begin
integer c,i;
for i:=a while b notequal 0 do begin
c:=b;
... |
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.
| #F.23 | F# | open System.IO
[<EntryPoint>]
let main args =
let textFrom = "Goodbye London!"
let textTo = "Hello New York!"
for name in args do
let content = File.ReadAllText(name)
let newContent = content.Replace(textFrom, textTo)
if content <> newContent then
File.WriteAllText(name... |
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.
| #Factor | Factor | USING: fry io.encodings.utf8 io.files kernel qw sequences
splitting ;
: global-replace ( files old new -- )
'[
[ utf8 file-contents _ _ replace ]
[ utf8 set-file-contents ] bi
] each ;
qw{ a.txt b.txt c.txt }
"Goodbye London!" "Hello New York!" global-replace |
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.
| #Fortran | Fortran | SUBROUTINE FILEHACK(FNAME,THIS,THAT) !Attacks a file!
CHARACTER*(*) FNAME !The name of the file, presumed to contain text.
CHARACTER*(*) THIS !The text sought in each record.
CHARACTER*(*) THAT !Its replacement, should it be found.
INTEGER F,T !Mnemonics for file unit numbers.
... |
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... | #ARM_Assembly | ARM Assembly | .org 0x08000000
b ProgramStart
;cartridge header goes here
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Program Start
.equ ramarea, 0x02000000
.equ CursorX,ramarea
.equ CursorY,ramarea+1
.equ hailstoneram... |
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... | #Lua | Lua | function ConvertToGrayscaleImage( bitmap )
local size_x, size_y = #bitmap, #bitmap[1]
local gray_im = {}
for i = 1, size_x do
gray_im[i] = {}
for j = 1, size_y do
gray_im[i][j] = math.floor( 0.2126*bitmap[i][j][1] + 0.7152*bitmap[i][j][2] + 0.0722*bitmap[i][j][3] )
end... |
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... | #Maple | Maple | with(ImageTools):
#conversion forward
dimensions:=[upperbound(img)];
gray := Matrix(dimensions[1], dimensions[2]);
for i from 1 to dimensions[1] do
for j from 1 to dimensions[2] do
gray[i,j] := 0.2126 * img[i,j,1] + 0.7152*img[i,j,2] + 0.0722*img[i,j,3]:
end do:
end do:
#display the result
Embed(Create(gray)):
#con... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | #!/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 ... | #Eiffel | Eiffel |
note
description : "Initial part, in order, of the sequence of Hamming numbers"
math : "[
Hamming numbers, also known as regular numbers and 5-smooth numbers, are natural integers
that have 2, 3 and 5 as their only prime factors.
]"
computer_arithmetic :
"[
... |
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... | #GW-BASIC | GW-BASIC | 10 RANDOMIZE TIMER:N=INT(RND*10+1):G=0
20 PRINT "Guess the number between 1 and 10."
30 WHILE N<>G
40 INPUT "Your guess? ",G
50 WEND
60 PRINT "That's correct!" |
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... | #Haskell | Haskell |
import Control.Monad
import System.Random
-- Repeat the action until the predicate is true.
until_ act pred = act >>= pred >>= flip unless (until_ act pred)
answerIs ans guess
| ans == guess = putStrLn "You got it!" >> return True
| otherwise = putStrLn "Nope. Guess again." >> return False
ask = liftM ... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim As Integer seq(10) = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1}
Dim As Integer i, j, sum, maxSum, first, last
maxSum = 0
For i = LBound(seq) To UBound(seq)
sum = 0
For j = i To UBound(seq)
' only proper sub-sequences are considered
If i = LBound(seq) AndAlso j = UBound(seq... |
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... | #Ela | Ela | open string datetime random core monad io
guess () = do
putStrLn "What's the upper bound?"
ub <- readAny
main ub
where main ub
| ub < 0 = "Bound should be greater than 0."
| else = do
putStrLn $ format "Guess a number from 1 to {0}" ub
dt <- datetime.now
... |
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... | #Quackery | Quackery |
[ [ $ "lower higher equal" nest$ ]
constant ] is responses ( --> $ )
[ trim reverse
trim reverse
$ "" swap witheach
[ lower join ] ] is cleanup ( $ --> $ )
[ $ "Think of a number from 1 to"
$ " 100 and press enter." join
input drop
0... |
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... | #R | R | guessANumberPlayer <- function(low, high)
{
boundryErrorCheck(low, high)
repeat
{
guess <- floor(mean(c(low, high)))
#Invalid inputs to this switch will simply cause the repeat loop to run again, breaking nothing.
switch(guessResult(guess),
l = low <- guess + 1,
h = high <- guess... |
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... | #Factor | Factor | USING: combinators kernel make math sequences ;
: squares ( n -- s )
0 [ over 0 > ] [ [ 10 /mod sq ] dip + ] while nip ;
: (happy?) ( n1 n2 -- ? )
[ squares ] [ squares squares ] bi* {
{ [ dup 1 = ] [ 2drop t ] }
{ [ 2dup = ] [ 2drop f ] }
[ (happy?) ]
} cond ;
: happy? ( n -- ... |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, g... | #PicoLisp | PicoLisp | (scl 12)
(load "@lib/math.l")
(de haversine (Th1 Ph1 Th2 Ph2)
(setq
Ph1 (*/ (- Ph1 Ph2) pi 180.0)
Th1 (*/ Th1 pi 180.0)
Th2 (*/ Th2 pi 180.0) )
(let
(DX (- (*/ (cos Ph1) (cos Th1) 1.0) (cos Th2))
DY (*/ (sin Ph1) (cos Th1) 1.0)
DZ (- (sin Th1) (sin Th2)) )
(* `(* ... |
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... | #PL.2FI | PL/I | test: procedure options (main); /* 12 January 2014. Derived from Fortran version */
declare d float;
d = haversine(36.12, -86.67, 33.94, -118.40); /* BNA to LAX */
put edit ( 'distance: ', d, ' km') (A, F(10,3)); /* distance: 2887.2600 km */
degrees_to_radians: procedure (degree) returns (float);
de... |
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
| #Golfscript | Golfscript | "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/... | #PureBasic | PureBasic | If OpenConsole()=0 : End 1 : EndIf
Procedure.i Niven(v.i)
w=v
While v : s+v%10 : v/10 : Wend
If w%s=0 : ProcedureReturn w : EndIf
EndProcedure
Repeat
i+1
If Niven(i) : c+1 : Print(Str(i)+" ") : EndIf
If c=20 And i<1000 : Print("... ") : i=1000 : EndIf
If c=21 : Break : EndIf
ForEver
Input() |
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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Declare Simple Form
\\ we can define form before open
Layer Simple {
\\ center Window with 12pt font, 12000 twips width and 6000 twips height
\\ ; at the end command to center the form in current screen
Window 12, 12000, 6000;
\\ make ... |
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
| #Maple | Maple |
Maplets:-Display( Maplets:-Elements:-Maplet( [ "Goodbye, World!" ] ) );
|
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... | #Crystal | Crystal |
def gray_encode(bin)
bin ^ (bin >> 1)
end
def gray_decode(gray)
bin = gray
while gray > 0
gray >>= 1
bin ^= gray
end
bin
end
|
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... | #D | D | uint grayEncode(in uint n) pure nothrow @nogc {
return n ^ (n >> 1);
}
uint grayDecode(uint n) pure nothrow @nogc {
auto p = n;
while (n >>= 1)
p ^= n;
return p;
}
void main() {
import std.stdio;
" N N2 enc dec2 dec".writeln;
foreach (immutable n; 0 .. 32) {
... |
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
| #Genie | Genie | [indent=4]
/*
Get system command output, in Genie
valac getSystemCommandOutput.gs
./getSystemCommandOutput
*/
init
try
// Blocking with output capture
standard_output : string
standard_error : string
exit_status : int
Process.spawn_command_line_sync("sh -c 'ls getSy... |
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
| #Go | Go | package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
output, err := exec.Command("ls", "-l").CombinedOutput()
if err != nil {
log.Fatal(err)
}
fmt.Print(string(output))
} |
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
| #Haskell | Haskell | #!/usr/bin/env stack
-- stack --resolver lts-8.15 --install-ghc runghc --package process
import System.Process (readProcess)
main :: IO ()
main = do
-- get the output of the process as a list of lines
results <- lines <$> readProcess "hexdump" ["-C", "/etc/passwd"] ""
-- print each line in reverse
... |
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... | #ACL2 | ACL2 | (defun swap (pair)
(cons (cdr pair)
(car pair)))
(let ((p (cons 1 2)))
(cw "Before: ~x0~%After: ~x1~%" p (swap p))) |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #AutoHotkey | AutoHotkey | list = 1,5,17,-2
Loop Parse, list, `,
x := x < A_LoopField ? A_LoopField : x
MsgBox Max = %x% |
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... | #ALGOL_68 | ALGOL 68 | PROC gcd = (INT a, b) INT: (
IF a = 0 THEN
b
ELIF b = 0 THEN
a
ELIF a > b THEN
gcd(b, a MOD b)
ELSE
gcd(a, b MOD a)
FI
);
test:(
INT a = 33, b = 77;
printf(($x"The gcd of"g" and "g" is "gl$,a,b,gcd(a,b)));
INT c = 49865, d = 69811;
printf(($x"The gcd of"g" and "g" is "gl$,c,d,gcd... |
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.
| #FreeBASIC | FreeBASIC | Const matchtext = "Goodbye London!"
Const repltext = "Hello New York!"
Const matchlen = Len(matchtext)
Dim As Integer x, L0 = 1
dim as string filespec, linein
L0 = 1
While Len(Command(L0))
filespec = Dir(Command(L0))
While Len(filespec)
Open filespec For Binary As 1
linein = Space(Lof(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.
| #Go | Go | package main
import (
"bytes"
"io/ioutil"
"log"
"os"
)
func main() {
gRepNFiles("Goodbye London!", "Hello New York!", []string{
"a.txt",
"b.txt",
"c.txt",
})
}
func gRepNFiles(olds, news string, files []string) {
oldb := []byte(olds)
newb := []byte(news)
... |
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... | #Arturo | Arturo | hailstone: function [n][
ret: @[n]
while [n>1][
if? 1 = and n 1 -> n: 1+3*n
else -> n: n/2
'ret ++ n
]
ret
]
print "Hailstone sequence for 27:"
print hailstone 27
maxHailstoneLength: 0
maxHailstone: 0
loop 2..1000 'x [
l: size hailstone x
if l>maxHailstoneLength [
maxHailstoneLength: l
maxHailst... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | toGrayscale[rgb_Image] := ImageApply[#.{0.2126, 0.7152, 0.0722}&, rgb]
toFakeRGB[L_Image] := ImageApply[{#, #, #}&, L] |
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... | #MATLAB | MATLAB | function [grayImage] = colortograyscale(inputImage)
grayImage = rgb2gray(inputImage); |
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... | #Nim | Nim |
import bitmap
import lenientops
type
GrayImage* = object
w*, h*: Index
pixels*: seq[Luminance]
proc newGrayImage*(width, height: int): GrayImage =
## Create a gray image with given width and height.
new(result)
result.w = width
result.h = height
result.pixels.setLen(width * height)
iterato... |
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... | #Nim | Nim | #!/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 ... | #Elixir | Elixir | defmodule Hamming do
def generater do
queues = [{2, queue}, {3, queue}, {5, queue}]
Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end)
end
defp next(n, queues) do
queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end)
min = Enum.map(queues, fn {_, queue} -> top(queue) end)... |
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... | #HolyC | HolyC | U8 n, *g;
n = 1 + RandU16 % 10;
Print("I'm thinking of a number between 1 and 10.\n");
Print("Try to guess it:\n");
while(1) {
g = GetStr;
if (Str2I64(g) == n) {
Print("Correct!\n");
break;
}
Print("That's not my number. Try another guess:\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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
n := ?10
repeat {
writes("Pick a number from 1 through 10: ")
if n = numeric(read()) then break
}
write("Well guessed!")
end |
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... | #Go | Go | package main
import "fmt"
func gss(s []int) ([]int, int) {
var best, start, end, sum, sumStart int
for i, x := range s {
sum += x
switch {
case sum > best:
best = sum
start = sumStart
end = i + 1
case sum < 0:
sum = 0
... |
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... | #Elena | Elena | import extensions;
public program()
{
int randomNumber := randomGenerator.eval(1,10);
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
bool numberCorrect := false;
until(numberCorrect)
{
console.print("Guess: ");
int userGuess := console.readLine(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.