task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player) | Guess the number/With feedback (player) | Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score... | #Racket | Racket | #lang racket
(define (guess low high)
(define (input-loop available)
(define input (car (string->list (symbol->string (read)))))
(if (member input available)
input
(begin
(printf "Invalid Input\n") (input-loop available))))
(define (guess-loop low high)
(define guess (floor... |
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... | #Raku | Raku | multi sub MAIN() { MAIN(0, 100) }
multi sub MAIN($min is copy where ($min >= 0), $max is copy where ($max > $min)) {
say "Think of a number between $min and $max and I'll guess it!";
while $min <= $max {
my $guess = (($max + $min)/2).floor;
given lc prompt "My guess is $guess. Is your number hig... |
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... | #FALSE | FALSE | [$10/$10*@\-$*\]m: {modulo squared and division}
[$m;![$9>][m;!@@+\]#$*+]s: {sum of squares}
[$0[1ø1>][1ø3+ø3ø=|\1-\]#\%]f: {look for duplicates}
{check happy number}
[
$1[f;!~2ø1=~&][1+\s;!@]# {loop over sequence until 1 or duplicate}
1ø1= {return value}
\[$0=~][@%1-... |
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... | #PowerShell | PowerShell |
Add-Type -AssemblyName System.Device
$BNA = New-Object System.Device.Location.GeoCoordinate 36.12, -86.67
$LAX = New-Object System.Device.Location.GeoCoordinate 33.94, -118.40
$BNA.GetDistanceTo( $LAX ) / 1000
|
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... | #Pure_Data | Pure Data | #N canvas 527 1078 450 686 10;
#X obj 28 427 atan2;
#X obj 28 406 sqrt;
#X obj 62 405 sqrt;
#X obj 28 447 * 2;
#X obj 62 384 -;
#X msg 62 362 1 \$1;
#X obj 28 339 t f f;
#X obj 28 210 sin;
#X obj 83 207 sin;
#X obj 138 206 cos;
#X obj 193 206 cos;
#X obj 28 179 / 2;
#X obj 83 182 / 2;
#X obj 28 74 unpack f f;
#X obj 28... |
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
| #Gosu | Gosu | print("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/... | #Python | Python | >>> import itertools
>>> def harshad():
for n in itertools.count(1):
if n % sum(int(ch) for ch in str(n)) == 0:
yield n
>>> list(itertools.islice(harshad(), 0, 20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42]
>>> for n in harshad():
if n > 1000:
print(n)
break
1002
>>> |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | CreateDialog["Hello 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
| #MATLAB | MATLAB | msgbox('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... | #Delphi | Delphi | program GrayCode;
{$APPTYPE CONSOLE}
uses SysUtils;
function Encode(v: Integer): Integer;
begin
Result := v xor (v shr 1);
end;
function Decode(v: Integer): Integer;
begin
Result := 0;
while v > 0 do
begin
Result := Result xor v;
v := v shr 1;
end;
end;
function IntToBin(aValue: LongInt; aDi... |
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
| #Icon_and_Unicon | Icon and Unicon | #
# piped.icn, Get system command output
#
# Dedicated to the public domain
#
procedure main()
# start with an empty list
directory := []
# ls for UNIX, dir for other, assume Windows
command := if &features == "UNIX" then "ls" else "dir"
# open command in pipe mode
p := open(command, "p") | ... |
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
| #IS-BASIC | IS-BASIC | 100 OPEN #1:"dirinfo.txt" ACCESS OUTPUT
110 SET DEFAULT CHANNEL 1
120 EXT "dir"
130 CLOSE #1
140 SET DEFAULT CHANNEL 0 |
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
| #J | J | require 'task'
<shell 'uname -imp'
┌─────────────────────┐
│x86_64 x86_64 x86_64 │
└─────────────────────┘ |
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... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Swap(BYTE POINTER ptr1,ptr2 INT size)
BYTE tmp
INT i
FOR i=0 TO size-1
DO
tmp=ptr1^ ptr1^=ptr2^ ptr2^=tmp
ptr1==+1 ptr2==+1
OD
RETURN
PROC Main()
BYTE b1=[13],b2=[56]
INT i1=[65234],i2=[534]
REAL r1,r2
CHAR ARRAY s1="abcde",s2="XYZ"
... |
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.
| #AWK | AWK | $ awk 'func max(a){for(i in a)if(a[i]>r)r=a[i];return r}BEGIN{a[0]=42;a[1]=33;a[2]=21;print max(a)}'
42 |
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-M | ALGOL-M | BEGIN
% RETURN P MOD Q %
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% RETURN GREATEST COMMON DIVISOR OF X AND Y %
INTEGER FUNCTION GCD (X, Y);
INTEGER X, Y;
BEGIN
INTEGER R;
IF X < Y THEN
BEGIN
INTEGER TEMP;
TEMP := X;
X := Y;
Y := TEMP;
END;
WHILE (R := MOD(X... |
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.
| #Haskell | Haskell | import Data.List (tails, elemIndices, isPrefixOf)
replace :: String -> String -> String -> String
replace [] _ xs = xs
replace _ [] xs = xs
replace _ _ [] = []
replace a b xs = replAll
where
-- make substrings, dropping one element each time
xtails = tails xs
-- what substrings begin wit... |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
globalrepl("Goodbye London","Hello New York","a.txt","b.txt") # variable args for files
end
procedure globalrepl(old,new,files[])
every fn := !files do
if s := reads(f := open(fn,"bu"),stat(f).size) then {
writes(seek(f,1),replace(s,old,new))
close(f)
}
else write(&errout... |
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... | #AutoHotkey | AutoHotkey | ; Submitted by MasterFocus --- http://tiny.cc/iTunis
; [1] Generate the Hailstone Seq. for a number
List := varNum := 7 ; starting number is 7, not counting elements
While ( varNum > 1 )
List .= ", " ( varNum := ( Mod(varNum,2) ? (varNum*3)+1 : varNum//2 ) )
MsgBox % List
; [2] Seq. for starting number 27 has 1... |
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... | #OCaml | OCaml | let to_grayscale ~img:(_, r_channel, g_channel, b_channel) =
let width = Bigarray.Array2.dim1 r_channel
and height = Bigarray.Array2.dim2 r_channel in
let gray_channel =
let kind = Bigarray.int8_unsigned
and layout = Bigarray.c_layout
in
(Bigarray.Array2.create kind layout width height)
in
f... |
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... | #Octave | Octave | function [grayImage] = colortograyscale(inputImage)
grayImage = rgb2gray(inputImage); |
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... | #OCaml | OCaml | #!/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 ... | #Elm | Elm | module Main exposing ( main )
import Bitwise exposing (..)
import BigInt
import Task exposing ( Task, succeed, perform, andThen )
import Html exposing (Html, div, text)
import Browser exposing ( element )
import Time exposing ( now, posixToMillis )
cLIMIT : Int
cLIMIT = 1000000
-- an infinite non-empty non-memoiz... |
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... | #J | J | require 'misc'
game=: verb define
n=: 1 + ?10
smoutput 'Guess my integer, which is bounded by 1 and 10'
whilst. -. guess -: n do.
guess=. {. 0 ". prompt 'Guess: '
if. 0 -: guess do. 'Giving up.' return. end.
smoutput (guess=n){::'no.';'Well guessed!'
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... | #Java | Java | public class Guessing {
public static void main(String[] args) throws NumberFormatException{
int n = (int)(Math.random() * 10 + 1);
System.out.print("Guess the number between 1 and 10: ");
while(Integer.parseInt(System.console().readLine()) != n){
System.out.print("Wrong! Guess a... |
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... | #Haskell | Haskell | import Data.List (inits, tails, maximumBy)
import Data.Ord (comparing)
subseqs :: [a] -> [[a]]
subseqs = concatMap inits . tails
maxsubseq :: (Ord a, Num a) => [a] -> [a]
maxsubseq = maximumBy (comparing sum) . subseqs
main = print $ maxsubseq [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] |
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... | #Elixir | Elixir | defmodule GuessingGame do
def play(lower, upper) do
play(lower, upper, Enum.random(lower .. upper))
end
defp play(lower, upper, number) do
guess = Integer.parse(IO.gets "Guess a number (#{lower}-#{upper}): ")
case guess do
{^number, _} ->
IO.puts "Well guessed!"
{n, _} when n in lo... |
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... | #Red | Red | Red[]
lower: 1
upper: 100
print ["Please think of a number between" lower "and" upper]
forever [
guess: to-integer upper + lower / 2
print ["My guess is" guess]
until [
input: ask "Is your number (l)ower, (e)qual to, or (h)igher than my guess? "
find ["l" "e" "h"] input
]
if "e" ... |
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... | #REXX | REXX | /*REXX program plays guess─the─number (with itself) with positive integers. */
parse arg low high seed . /*obtain optional arguments from the CL*/
if low=='' | low=="," then low= 1 /*Not specified? Then use the default.*/
if high=='' | high=="," then high= 1000 ... |
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... | #Fantom | Fantom | class Main
{
static Bool isHappy (Int n)
{
Int[] record := [,]
while (n != 1 && !record.contains(n))
{
record.add (n)
// find sum of squares of digits
newn := 0
while (n > 0)
{
newn += (n.mod(10) * n.mod(10))
n = n.div(10)
}
n = newn
}
... |
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... | #PureBasic | PureBasic | #DIA=2*6372.8
Procedure.d Haversine(th1.d,ph1.d,th2.d,ph2.d)
Define dx.d,
dy.d,
dz.d
ph1=Radian(ph1-ph2)
th1=Radian(th1)
th2=Radian(th2)
dz=Sin(th1)-Sin(th2)
dx=Cos(ph1)*Cos(th1)-Cos(th2)
dy=Sin(ph1)*Cos(th1)
ProcedureReturn ASin(Sqr(Pow(dx,2)+Pow(dy,2)+Pow(dz,2))/2)*#DIA
EndProc... |
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
| #Groovy | Groovy | 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/... | #Quackery | Quackery | [ number$ $ "0 " swap
witheach
[ join $ " + " join ]
quackery ] is digitsum ( n --> n )
[ dup digitsum
mod 0 = ] is isharshad ( n --> b )
say "The first 20 Harshad numbers are: "
0 1
[ dup isharshad if
[ dup echo sp dip 1+ ]
1+
over 20 = until ]
2drop
cr
cr... |
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
| #MAXScript | MAXScript | messageBox "Goodbye world" |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #mIRC_Scripting_Language | mIRC Scripting Language | alias goodbyegui {
dialog -m Goodbye Goodbye
}
dialog Goodbye {
title "Goodbye, World!"
size -1 -1 80 20
option dbu
text "Goodbye, World!", 1, 20 6 41 7
} |
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... | #DWScript | DWScript | function Encode(v : Integer) : Integer;
begin
Result := v xor (v shr 1);
end;
function Decode(v : Integer) : Integer;
begin
Result := 0;
while v>0 do begin
Result := Result xor v;
v := v shr 1;
end;
end;
PrintLn('decimal binary gray decoded');
var i : Integer;
for i:=0 to 31 do begin
... |
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
| #Java | Java | import java.io.*;
import java.util.*;
public class SystemCommand {
public static void main(String args[]) throws IOException {
String command = "cmd /c dir";
Process p = Runtime.getRuntime().exec(command);
try (Scanner sc = new Scanner(p.getInputStream())) {
System.out.... |
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
| #Jsish | Jsish | var commandOutput = exec('ls -gocart', { retAll:true });
puts(commandOutput.data); |
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
| #Julia | Julia | ls = readstring(`ls`) |
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... | #Ada | Ada | generic
type Swap_Type is private; -- Generic parameter
procedure Generic_Swap (Left, Right : in out Swap_Type);
procedure Generic_Swap (Left, Right : in out Swap_Type) is
Temp : constant Swap_Type := Left;
begin
Left := Right;
Right := Temp;
end Generic_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.
| #Axe | Axe | Lbl MAX
0→M
While {r₁}
{r₁}>M?{r₁}→M
End
M
Return |
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_W | ALGOL W | begin
% iterative Greatest Common Divisor routine %
integer procedure gcd ( integer value m, n ) ;
begin
integer a, b, newA;
a := abs( m );
b := abs( n );
if a = 0 then begin
b
end
else begin
while b no... |
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.
| #J | J | require'strings'
(1!:2~rplc&('Goodbye London!';'Hello New York!')@(1!:1))"0 files |
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.
| #Java | Java | import java.io.*;
import java.nio.file.*;
public class GloballyReplaceText {
public static void main(String[] args) throws IOException {
for (String fn : new String[]{"test1.txt", "test2.txt"}) {
String s = new String(Files.readAllBytes(Paths.get(fn)));
s = s.replace("Goodbye L... |
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... | #AutoIt | AutoIt |
$Hail = Hailstone(27)
ConsoleWrite("Sequence-Lenght: "&$Hail&@CRLF)
$Big = -1
$Sequenzlenght = -1
For $I = 1 To 100000
$Hail = Hailstone($i, False)
If Number($Hail) > $Sequenzlenght Then
$Sequenzlenght = Number($Hail)
$Big = $i
EndIf
Next
ConsoleWrite("Longest Sequence : "&$Sequenzlenght&" from number "&$Big&@CR... |
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... | #Oz | Oz | functor
import
Array2D
export
ToGraymap
FromGraymap
define
fun {ToGraymap bitmap(Arr)}
graymap({Array2D.map Arr Luminance})
end
fun {Luminance Color}
F = {Record.map Color Int.toFloat}
in
0.2126*F.1 + 0.7152*F.2 + 0.0722*F.3
end
fun {FromGraymap graymap(Arr)}
bitma... |
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... | #Perl | Perl | #! /usr/bin/perl
use strict;
use Image::Imlib2;
sub tograyscale
{
my $img = shift;
my $gimg = Image::Imlib2->new($img->width, $img->height);
for ( my $x = 0; $x < $gimg->width; $x++ ) {
for ( my $y = 0; $y < $gimg->height; $y++ ) {
my ( $r, $g, $b, $a ) = $img->query_pixel($x, $y);
my $gray =... |
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... | #Perl | Perl | #!/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 ... | #ERRE | ERRE | PROGRAM HAMMING
!$DOUBLE
DIM H[2000]
PROCEDURE HAMMING(L%->RES)
LOCAL I%,J%,K%,N%,M,X2,X3,X5
H[0]=1
X2=2 X3=3 X5=5
FOR N%=1 TO L%-1 DO
M=X2
IF M>X3 THEN M=X3 END IF
IF M>X5 THEN M=X5 END IF
H[N%]=M
IF M=X2 THEN I%+=1 X2=2*H[I%] END IF
IF ... |
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... | #JavaScript | JavaScript |
function guessNumber() {
// Get a random integer from 1 to 10 inclusive
var num = Math.ceil(Math.random() * 10);
var guess;
while (guess != num) {
guess = prompt('Guess the number between 1 and 10 inclusive');
}
alert('Congratulations!\nThe number was ' + num);
}
guessNumber(); |
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... | #jq | jq |
{prompt: "Please enter your guess:", random: (1+rand(9)) }
| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt),
"Well done!" |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
L1 := [-1,-2,3,5,6,-2,-1,4,-4,2,-1] # sample list
L := [-1,1,2,3,4,-11]|||L1 # prepend a local maximum into the mix
write(ximage(maxsubseq(L)))
end
link ximage # to show lists
procedure maxsubseq(L) #: return the subsequence of L with maximum positive sum
l... |
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... | #Emacs_Lisp | Emacs Lisp | (let* ((min 1)
(max 100)
(number (+ (random (1+ (- max min))) min))
guess done)
(message "Guess the number between %d and %d" min max)
(while (not done)
(setq guess (read-number "Please enter a number "))
(cond
((< guess number)
(message "Too low!"))
((> guess number)
... |
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... | #Ring | Ring |
min = 1
max = 100
see "think of a number between " + min + " and " + max + nl
see "i will try to guess your number." + nl
while true
guess =floor((min + max) / 2)
see "my guess is " + guess + nl
see "is it higher than, lower than or equal to your number " give answer
ans = left(answer,1)
... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player) | Guess the number/With feedback (player) | Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score... | #Ruby | Ruby | def play(low, high, turns=1)
num = (low + high) / 2
print "guessing #{num}\t"
case is_it?(num)
when 1
puts "too high"
play(low, num - 1, turns + 1)
when -1
puts "too low"
play(num + 1, high, turns + 1)
else
puts "found the number in #{turns} turns."
end
end
def is_it?(num)
num <=> ... |
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... | #FOCAL | FOCAL | 01.10 S J=0;S N=1;T %2
01.20 D 3;I (K-2)1.5
01.30 S N=N+1
01.40 I (J-8)1.2;Q
01.50 T N,!
01.60 S J=J+1
01.70 G 1.3
02.10 S A=K;S R=0
02.20 S B=FITR(A/10)
02.30 S R=R+(A-10*B)^2
02.40 S A=B
02.50 I (-A)2.2
03.10 F X=0,162;S S(X)=-1
03.20 S K=N
03.30 S S(K)=0
03.40 D 2;S K=R
03.50 I (S(K))3.3 |
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... | #Python | Python | from math import radians, sin, cos, sqrt, asin
def haversine(lat1, lon1, lat2, lon2):
R = 6372.8 # Earth radius in kilometers
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**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
| #GW-BASIC | GW-BASIC | 10 PRINT "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/... | #Racket | Racket | #lang racket
(define (digsum n)
(for/sum ([c (number->string n)]) (string->number [string c])))
(define harshads
(stream-filter (λ (n) (= (modulo n (digsum n)) 0)) (in-naturals 1)))
; First 20 harshad numbers
(displayln (for/list ([i 20]) (stream-ref harshads i)))
; First harshad greater than 1000
(displa... |
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
| #Modula-3 | Modula-3 | MODULE GUIHello EXPORTS Main;
IMPORT TextVBT, Trestle;
<*FATAL ANY*>
VAR v := TextVBT.New("Goodbye, World!");
BEGIN
Trestle.Install(v);
Trestle.AwaitDelete(v);
END GUIHello. |
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
| #N.2Ft.2Froff | N/t/roff | 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... | #Elixir | Elixir | defmodule Gray_code do
use Bitwise
def encode(n), do: bxor(n, bsr(n,1))
def decode(g), do: decode(g,0)
def decode(0,n), do: n
def decode(g,n), do: decode(bsr(g,1), bxor(g,n))
end
Enum.each(0..31, fn(n) ->
g = Gray_code.encode(n)
d = Gray_code.decode(g)
:io.fwrite("~2B : ~5.2.0B : ~5.2.0B : ~5.2.0B... |
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... | #Erlang | Erlang | -module(gray).
-export([encode/1, decode/1]).
encode(N) -> N bxor (N bsr 1).
decode(G) -> decode(G,0).
decode(0,N) -> N;
decode(G,N) -> decode(G bsr 1, G bxor N).
|
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
| #Kotlin | Kotlin | // version 1.0.6
import java.util.Scanner
fun main(args: Array<String>) {
val command = "cmd /c chcp"
val p = Runtime.getRuntime().exec(command)
val sc = Scanner(p.inputStream)
println(sc.nextLine())
sc.close()
} |
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
| #LIL | LIL | set rc [system ls -go] |
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
| #Lingo | Lingo | sx = xtra("Shell").new()
put sx.shell_cmd("cd C:\dev\lsw\lib & dir")
-- "
<snip>
31.08.2016 21:25 <DIR> .
31.08.2016 21:25 <DIR> ..
20.08.2016 04:58 <DIR> aes
23.06.2016 18:23 <DIR> audio
21.07.2016 19:19 <DIR> avmedia
23.06.2016 18:22 <DIR> ... |
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... | #Aime | Aime | void
__swap(&, &,,)
{
set(0, $3);
set(1, $2);
}
void
swap(&, &)
{
xcall(xcall, __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.
| #BASIC | BASIC | DECLARE SUB addVal (value AS INTEGER)
DECLARE FUNCTION findMax% ()
REDIM SHARED vals(0) AS INTEGER
DIM SHARED valCount AS INTEGER
DIM x AS INTEGER, y AS INTEGER
valCount = -1
'''''begin test run
RANDOMIZE TIMER
FOR x = 1 TO 10
y = INT(RND * 100)
addVal y
PRINT y; " ";
NEXT
PRINT ": "; findMax
'''''end... |
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... | #Alore | Alore | def gcd(a as Int, b as Int) as Int
while b != 0
a,b = b, a mod b
end
return Abs(a)
end |
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.
| #jq | jq | for file
do
jq -Rr 'gsub($from; $to)' --arg from 'Goodbye London!' --arg to 'Hello New York!' "$file" |
sponge "$file"
done |
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.
| #Jsish | Jsish | /* Global replace in Jsish */
if (console.args.length == 0) {
console.args.push('-');
}
/* For each file, globally replace "Goodbye London!" with "Hello New York!" */
var fn, data, changed;
for (fn of console.args) {
/* No args, or an argument of - uses "stdin" (a special Channel name) */
if (fn == 'stdin... |
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... | #AWK | AWK |
#!/usr/bin/awk -f
function hailstone(v, verbose) {
n = 1;
u = v;
while (1) {
if (verbose) printf " "u;
if (u==1) return(n);
n++;
if (u%2 > 0 )
u = 3*u+1;
else
u = u/2;
}
}
BEGIN {
i = 27;
printf("hailstone(%i) has %i elements\n",i,hailstone(i,1));
ix=0;
m=0;
for (i=1; i<100000; i++) {... |
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... | #Phix | Phix | -- demo\rosetta\Bitmap_Greyscale.exw (runnable version)
function to_grey(sequence image)
integer dimx = length(image),
dimy = length(image[1])
for x=1 to dimx do
for y=1 to dimy do
integer pixel = image[x][y] -- red,green,blue
sequence r_g_b = sq_and_bit... |
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... | #PHP | PHP | class BitmapGrayscale extends Bitmap {
public function toGrayscale(){
for ($i = 0; $i < $this->h; $i++){
for ($j = 0; $j < $this->w; $j++){
$l = ($this->data[$j][$i][0] * 0.2126)
+ ($this->data[$j][$i][1] * 0.7152)
+ ($this->data[$j][$i][2] * 0.0722);
$l = round($l);
... |
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... | #Phix | Phix |
Red [
Title: "Go Fish"
Author: "gltewalt"
]
chand: [] ;-- c and p = computer and player
cguesses: []
phand: []
cbooks: 0
pbooks: 0
gf: {
***************
* GO FISH *
***************
}
pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant
pile: [] ;-- whe... |
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... | #PicoLisp | PicoLisp |
Red [
Title: "Go Fish"
Author: "gltewalt"
]
chand: [] ;-- c and p = computer and player
cguesses: []
phand: []
cbooks: 0
pbooks: 0
gf: {
***************
* GO FISH *
***************
}
pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant
pile: [] ;-- whe... |
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... | #PowerShell | PowerShell |
Red [
Title: "Go Fish"
Author: "gltewalt"
]
chand: [] ;-- c and p = computer and player
cguesses: []
phand: []
cbooks: 0
pbooks: 0
gf: {
***************
* GO FISH *
***************
}
pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant
pile: [] ;-- whe... |
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... | #PureBasic | PureBasic |
Red [
Title: "Go Fish"
Author: "gltewalt"
]
chand: [] ;-- c and p = computer and player
cguesses: []
phand: []
cbooks: 0
pbooks: 0
gf: {
***************
* GO FISH *
***************
}
pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant
pile: [] ;-- whe... |
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... | #Python | Python |
Red [
Title: "Go Fish"
Author: "gltewalt"
]
chand: [] ;-- c and p = computer and player
cguesses: []
phand: []
cbooks: 0
pbooks: 0
gf: {
***************
* GO FISH *
***************
}
pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant
pile: [] ;-- whe... |
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 ... | #F.23 | F# | type LazyList<'a> = Cons of 'a * Lazy<LazyList<'a>> // ': fix colouring
let rec hammings() =
let rec (-|-) (Cons(x, nxf) as xs) (Cons(y, nyf) as ys) =
if x < y then Cons(x, lazy(nxf.Value -|- ys))
elif x > y then Cons(y, lazy(xs -|- nyf.Value))
else Cons(x, lazy(nxf.Value -|- nyf.Value))
let rec inf_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... | #Jsish | Jsish | function guessNumber() {
// Get a random integer from 1 to 10 inclusive
var num = Math.ceil(Math.random() * 10);
var guess;
var tries = 0;
while (guess != num) {
tries += 1;
printf('%s', 'Guess the number between 1 and 10 inclusive: ');
guess = console.input();
}
pr... |
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... | #Julia | Julia | function guess()
number = dec(rand(1:10))
print("Guess my number! ")
while readline() != number
print("Nope, try again... ")
end
println("Well guessed!")
end
guess() |
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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Subseq.bas"
110 RANDOMIZE
120 NUMERIC A(1 TO 15)
130 PRINT "Sequence:"
140 FOR I=LBOUND(A) TO UBOUND(A)
150 LET A(I)=RND(11)-6
160 PRINT A(I);
170 NEXT
180 LET MAXSUM,ST=0:LET EN=-1
190 FOR I=LBOUND(A) TO UBOUND(A)
200 LET SUM=0
210 FOR J=I TO UBOUND(A)
220 LET SUM=SUM+A(J)
230 IF SUM>MAX... |
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... | #J | J | maxss=: monad define
AS =. 0,; <:/~@i.&.> #\y
MX =. (= >./) AS +/ . * y
y #~ {. MX#AS
) |
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... | #Erlang | Erlang | % Implemented by Arjun Sunel
-module(guess_number).
-export([main/0]).
main() ->
L = 1 , % Lower Limit
U = 100, % Upper Limit
io:fwrite("Guess my number between ~p and ", [L]),
io:fwrite("and ~p until you get it right.\n", [U]),
N = random:uniform(100),
guess(N).
guess(N) ->
{ok, [K]} = io:fread("Gues... |
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... | #Rust | Rust | use std::io::stdin;
const MIN: isize = 1;
const MAX: isize = 100;
fn main() {
loop {
let mut min = MIN;
let mut max = MAX;
let mut num_guesses = 1;
println!("Please think of a number between {} and {}", min, max);
loop {
let guess = (min + max) / 2;
... |
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... | #Scala | Scala | object GuessNumber extends App {
val n = 1 + scala.util.Random.nextInt(20)
println("Guess which number I've chosen in the range 1 to 20\n")
do println("Your guess, please: ")
while (io.StdIn.readInt() match {
case `n` => println("Correct, well guessed!"); false
case guess if (n + 1 to 20).contains(gue... |
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... | #Forth | Forth | : next ( n -- n )
0 swap begin 10 /mod >r dup * + r> ?dup 0= until ;
: cycle? ( n -- ? )
here dup @ cells +
begin dup here >
while 2dup @ = if 2drop true exit then
1 cells -
repeat
1 over +! dup @ cells + ! false ;
: happy? ( n -- ? )
0 here ! begin next dup cycle? until 1 = ;
: happy-... |
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... | #QB64 | QB64 |
SCREEN _NEWIMAGE(800, 100, 32)
'*** Units: K=kilometers M=miles N=nautical miles
DIM UNIT AS STRING
DIM Distance AS STRING
DIM Result AS DOUBLE
DIM ANSWER AS DOUBLE
'*** Change the To/From Latittude/Logitudes for your run
'*** LAT/LON for Nashville International Airport (BNA)
lat1 = 36.12
Lon1 = -86.67
'***... |
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... | #R | R | dms_to_rad <- function(d, m, s) (d + m / 60 + s / 3600) * pi / 180
# Volumetric mean radius is 6371 km, see http://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
# The diameter is thus 12742 km
great_circle_distance <- function(lat1, long1, lat2, long2) {
a <- sin(0.5 * (lat2 - lat1))
b <- sin(0.5 * (... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Hack | Hack | <?hh echo '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/... | #Raku | Raku | constant @harshad = grep { $_ %% .comb.sum }, 1 .. *;
say @harshad[^20];
say @harshad.first: * > 1000; |
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
| #Neko | Neko | /*
Tectonics:
gcc -shared -fPIC -o nekoagar.ndll nekoagar.c `agar-config --cflags --libs`
*/
/* Neko primitives for libAgar http://www.libagar.org */
#include <stdio.h>
#include <neko.h>
#include <agar/core.h>
#include <agar/gui.h>
#define val_widget(v) ((AG_Widget *)val_data(v))
DEFINE_KIND(k_agar_widg... |
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... | #Euphoria | Euphoria | function gray_encode(integer n)
return xor_bits(n,floor(n/2))
end function
function gray_decode(integer n)
integer g
g = 0
while n > 0 do
g = xor_bits(g,n)
n = floor(n/2)
end while
return g
end function
function dcb(integer n)
atom d,m
d = 0
m = 1
while n do
... |
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
| #Lua | Lua | local output = io.popen("echo Hurrah!")
print(output:read("*all")) |
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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Dos "cd "+quote$(Dir$) +" & cmd /U /C dir *.txt >txt.out";
Document txt$
Repeat {
Wait 100
Try {
load.doc txt$, "txt.out"
}
} Until doc.len(txt$)<>0
Report txt$
}
Checkit
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | RunProcess["date"] |
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
| #Neko | Neko | /* Get system command output, neko */
var process_run = $loader.loadprim("std@process_run", 2);
var process_stdout_read = $loader.loadprim("std@process_stdout_read", 4);
var process_stderr_read = $loader.loadprim("std@process_stderr_read", 4);
var process_stdin_close = $loader.loadprim("std@process_stdin_close", 1);
va... |
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... | #ALGOL_68 | ALGOL 68 | MODE GENMODE = STRING;
GENMODE v1:="Francis Gary Powers", v2:="Vilyam Fisher";
PRIO =:= = 1;
OP =:= = (REF GENMODE v1, v2)VOID: (
GENMODE tmp:=v1; v1:=v2; v2:=tmp
);
v1 =:= v2;
print(("v1: ",v1, ", v2: ", v2, new line)) |
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.
| #BASIC256 | BASIC256 | l$ = "1,1234,62,234,12,34,6"
dim n$(1)
n$ = explode(l$, ",")
m$ = "" : m = 0
for i = 1 to n$[?]-1
t$ = n$[i]
if t$ > m$ then m$ = t$
if int(t$) > m then m = int(t$)
next i
print "Alphabetic order: "; m$; ", numeric order: "; m |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.