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 scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#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 (/ (+ low high) 2)))
(printf "My guess is ~a.\n" guess)
(define input (input-loop (list #\c #\l #\h)))
(case input
((#\c) (displayln "I knew it!\n"))
((#\l) (guess-loop low (sub1 guess)))
((#\h) (guess-loop (add1 guess) high))))
(printf "Think of a number between ~a and ~a.
Use (h)igh, (l)ow and (c)orrect to guide me.\n" low high)
(guess-loop low high))
|
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 scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#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 higher, lower or equal? " {
when /^e/ { say "I knew it!"; exit }
when /^h/ { $min = $guess + 1 }
when /^l/ { $max = $guess }
default { say "WHAT!?!?!" }
}
}
say "How can your number be both higher and lower than $max?!?!?";
}
|
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 include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#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-]#% {drop sequence and counter}
]h:
0 1
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?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, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#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, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#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 98 t f f;
#X obj 28 301 expr $f1 + ($f2 * $f3 * $f4);
#X obj 28 148 deg2rad;
#X obj 83 149 deg2rad;
#X obj 138 148 deg2rad;
#X obj 193 149 deg2rad;
#X obj 28 232 t f f;
#X obj 28 257 *;
#X obj 83 232 t f f;
#X obj 83 257 *;
#X obj 83 98 t f b;
#X obj 28 542 * 6372.8;
#X obj 193 120 f 33.94;
#X obj 28 125 - 33.94;
#X msg 28 45 36.12 -86.67;
#X obj 83 123 - -118.4;
#X floatatom 28 577 8 0 0 0 - - -, f 8;
#X connect 0 0 3 0;
#X connect 1 0 0 0;
#X connect 2 0 0 1;
#X connect 3 0 25 0;
#X connect 4 0 2 0;
#X connect 5 0 4 0;
#X connect 6 0 1 0;
#X connect 6 1 5 0;
#X connect 7 0 20 0;
#X connect 8 0 22 0;
#X connect 9 0 15 2;
#X connect 10 0 15 3;
#X connect 11 0 7 0;
#X connect 12 0 8 0;
#X connect 13 0 14 0;
#X connect 13 1 24 0;
#X connect 14 0 27 0;
#X connect 14 1 18 0;
#X connect 15 0 6 0;
#X connect 16 0 11 0;
#X connect 17 0 12 0;
#X connect 18 0 9 0;
#X connect 19 0 10 0;
#X connect 20 0 21 0;
#X connect 20 1 21 1;
#X connect 21 0 15 0;
#X connect 22 0 23 0;
#X connect 22 1 23 1;
#X connect 23 0 15 1;
#X connect 24 0 29 0;
#X connect 24 1 26 0;
#X connect 25 0 30 0;
#X connect 26 0 19 0;
#X connect 27 0 16 0;
#X connect 28 0 13 0;
#X connect 29 0 17 0;
|
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/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#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 following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#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; aDigits: Integer): string;
begin
Result := StringOfChar('0', aDigits);
while aValue > 0 do
begin
if (aValue and 1) = 1 then
Result[aDigits] := '1';
Dec(aDigits);
aValue := aValue shr 1;
end;
end;
var
i, g, d: Integer;
begin
Writeln('decimal binary gray decoded');
for i := 0 to 31 do
begin
g := Encode(i);
d := Decode(g);
Writeln(Format(' %2d %s %s %s %2d', [i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d]));
end;
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
|
#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") | stop("Cannot open pipe for ", command)
# read in results and append to list
while put(directory, read(p))
# display the fifth entry, if there is one
write(\directory[5])
close(p)
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
|
#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 the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#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"
Put(125) PutE() ;clear the screen
ValR("32.5",r1) ValR("-0.63",r2)
Print("Swap bytes: ")
PrintB(b1) Put(32) PrintB(b2) Print(" -> ")
Swap(@b1,@b2,1)
PrintB(b1) Put(32) PrintBE(b2)
Print("Swap integers: ")
PrintI(i1) Put(32) PrintI(i2) Print(" -> ")
Swap(@i1,@i2,2)
PrintI(i1) Put(32) PrintIE(i2)
Print("Swap floats: ")
PrintR(r1) Put(32) PrintR(r2) Print(" -> ")
Swap(r1,r2,6)
PrintR(r1) Put(32) PrintRE(r2)
Print("Swap strings: ")
Print(s1) Put(32) Print(s2) Print(" -> ")
Swap(@s1,@s2,2)
Print(s1) Put(32) PrintE(s2)
RETURN
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#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 task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#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, Y)) <> 0 DO
BEGIN
X := Y;
Y := R;
END;
GCD := Y;
END;
COMMENT - EXERCISE THE FUNCTION;
WRITE("THE GDC OF 21 AND 35 IS", GCD(21,35));
WRITE("THE GDC OF 23 AND 35 IS", GCD(23,35));
WRITE("THE GDC OF 1071 AND 1029 IS", GCD(1071,1029));
WRITE("THE GDC OF 3528 AND 3780 IS", GCD(3528,252));
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.
|
#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 with the string to replace?
-- get their indices
matches = elemIndices True $ map (isPrefixOf a) xtails
-- replace one occurrence
repl ys n = take n ys ++ b ++ drop (n + length b) ys
-- replace all occurrences consecutively
replAll = foldl repl xs matches
replaceInFiles a1 a2 files = do
f <- mapM readFile files
return $ map (replace a1 a2) f
|
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,"Unable to open ",fn)
end
link strings # for replace
|
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 conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#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 112 elements
Count := 1, List := varNum := 27 ; starting number is 27, counting elements
While ( varNum > 1 )
Count++ , List .= ", " ( varNum := ( Mod(varNum,2) ? (varNum*3)+1 : varNum//2 ) )
MsgBox % "Sequence:`n" List "`n`nCount: " Count
; [3] Find number<100000 with longest seq. and show both values
MaxNum := Max := 0 ; reset the Maximum variables
TimesToLoop := 100000 ; limit number here is 100000
Offset := 70000 ; offset - use 0 to process from 0 to 100000
Loop, %TimesToLoop%
{
If ( TimesToLoop < ( varNum := Index := A_Index+Offset ) )
Break
text := "Processing...`n-------------------`n"
text .= "Current starting number: " Index "`n"
text .= "Current sequence count: " Count
text .= "`n-------------------`n"
text .= "Maximum starting number: " MaxNum "`n"
text .= "Maximum sequence count: " Max " <<" ; text split to avoid long code lines
ToolTip, %text%
Count := 1 ; going to count the elements, but no "List" required
While ( varNum > 1 )
Count++ , varNum := ( Mod(varNum,2) ? (varNum*3)+1 : varNum//2 )
If ( Count > Max )
Max := Count , MaxNum := Index ; set the new maximum values, if necessary
}
ToolTip
MsgBox % "Number: " MaxNum "`nCount: " Max
|
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 use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#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
for y = 0 to pred height do
for x = 0 to pred width do
let r = r_channel.{x,y}
and g = g_channel.{x,y}
and b = b_channel.{x,y} in
let v = (2_126 * r + 7_152 * g + 722 * b) / 10_000 in
gray_channel.{x,y} <- v;
done;
done;
(gray_channel)
|
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 use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#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 the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#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, 0, 2 * 9, '';
my $mepicks = join '', $me =~ /$pat/g;
arrange($me);
$mebooks++ while $me =~ s/($pat).\1.\1.\1.//;
my $you = substr $deck, 0, 2 * 9, '';
my $youpicks = join '', $you =~ /$pat/g;
arrange($you);
$youbooks++ while $you =~ s/($pat).\1.\1.\1.//;
while( $mebooks + $youbooks < 13 )
{
play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 );
$mebooks + $youbooks == 13 and last;
play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 );
}
print "me $mebooks you $youbooks\n";
sub arrange { $_[0] = join '', sort $_[0] =~ /../g }
sub human
{
my $have = shift =~ s/($pat).\K(?!\1)/ /gr;
local $| = 1;
my $pick;
do
{
print "You have $have, enter request: ";
($pick) = lc(<STDIN>) =~ /$pat/g;
} until $pick and $have =~ /$pick/;
return $pick;
}
sub play
{
my ($me, $mb, $lastpicks, $you, $yb, $human) = @_;
my $more = 1;
while( arrange( $$me ), $more and $$mb + $$yb < 13 )
{
# use Data::Dump 'dd'; dd \@_, "deck $deck";
if( $$me =~ s/($pat).\1.\1.\1.// )
{
print "book of $&\n";
$$mb++;
}
elsif( $$me )
{
my $pick = $human ? do { human($$me) } : do
{
my %picks;
$picks{$_}++ for my @picks = $$me =~ /$pat/g;
my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks;
print "pick $pick\n";
$$lastpicks =~ s/$pick//g;
$$lastpicks .= $pick;
$pick;
};
if( $$you =~ s/(?:$pick.)+// )
{
$$me .= $&;
}
else
{
print "GO FISH !!\n";
$$me .= substr $deck, 0, 2, '';
$more = 0;
}
}
elsif( $deck )
{
$$me .= substr $deck, 0, 2, '';
}
else
{
$more = 0;
}
}
arrange( $$me );
}
|
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 particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#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-memoizing Co-Inductive Stream (CIS)...
type CIS a = CIS a (() -> CIS a)
takeCIS2List : Int -> CIS a -> List a
takeCIS2List n cis =
let loop i (CIS hd tl) lst =
if i < 1 then List.reverse lst
else loop (i - 1) (tl()) (hd :: lst)
in loop n cis []
nthCIS : Int -> CIS a -> a
nthCIS n (CIS hd tl) =
if n <= 1 then hd else nthCIS (n - 1) (tl())
type PriorityQ comparable v =
Mt
| Br comparable v (PriorityQ comparable v)
(PriorityQ comparable v)
emptyPQ : PriorityQ comparable v
emptyPQ = Mt
peekMinPQ : PriorityQ comparable v -> Maybe (comparable, v)
peekMinPQ pq = case pq of
(Br k v _ _) -> Just (k, v)
Mt -> Nothing
pushPQ : comparable -> v -> PriorityQ comparable v
-> PriorityQ comparable v
pushPQ wk wv pq =
case pq of
Mt -> Br wk wv Mt Mt
(Br vk vv pl pr) ->
if wk <= vk then Br wk wv (pushPQ vk vv pr) pl
else Br vk vv (pushPQ wk wv pr) pl
siftdown : comparable -> v -> PriorityQ comparable v
-> PriorityQ comparable v -> PriorityQ comparable v
siftdown wk wv pql pqr =
case pql of
Mt -> Br wk wv Mt Mt
(Br vkl vvl pll prl) ->
case pqr of
Mt -> if wk <= vkl then Br wk wv pql Mt
else Br vkl vvl (Br wk wv Mt Mt) Mt
(Br vkr vvr plr prr) ->
if wk <= vkl && wk <= vkr then Br wk wv pql pqr
else if vkl <= vkr then Br vkl vvl (siftdown wk wv pll prl) pqr
else Br vkr vvr pql (siftdown wk wv plr prr)
replaceMinPQ : comparable -> v -> PriorityQ comparable v
-> PriorityQ comparable v
replaceMinPQ wk wv pq = case pq of
Mt -> Mt
(Br _ _ pl pr) -> siftdown wk wv pl pr
type alias Trival = (Int, Int, Int)
showTrival : Trival -> String
showTrival tv =
let (x2, x3, x5) = tv
xpnd x m r =
if x <= 0 then r
else xpnd (shiftRightBy 1 x) (BigInt.mul m m)
(if (and 1 x) /= 0 then BigInt.mul m r else r)
in BigInt.fromInt 1 |> xpnd x2 (BigInt.fromInt 2)
|> xpnd x3 (BigInt.fromInt 3) |> xpnd x5 (BigInt.fromInt 5)
|> BigInt.toString
type alias LogRep = { lr: Float, trv: Trival }
ltLogRep : LogRep -> LogRep -> Bool
ltLogRep lra lrb = lra.lr < lrb.lr
oneLogRep : LogRep
oneLogRep = { lr = 0.0, trv = (0, 0, 0) }
lg2_2 : Float
lg2_2 = 1.0 -- log base two of two
lg2_3 : Float
lg2_3 = logBase 2.0 3.0
lg2_5 : Float
lg2_5 = logBase 2.0 5.0
multLR2 : LogRep -> LogRep
multLR2 lr = let (x2, x3, x5) = lr.trv
in LogRep (lr.lr + lg2_2) (x2 + 1, x3, x5)
multLR3 : LogRep -> LogRep
multLR3 lr = let (x2, x3, x5) = lr.trv
in LogRep (lr.lr + lg2_3) (x2, x3 + 1, x5)
multLR5 : LogRep -> LogRep
multLR5 lr = let (x2, x3, x5) = lr.trv
in LogRep (lr.lr + lg2_5) (x2, x3, x5 + 1)
hammingsLog : () -> CIS Trival
hammingsLog() =
let im235 = multLR2 oneLogRep
im35 = multLR3 oneLogRep
imrg = im35
im5 = multLR5 oneLogRep
next bpq mpq m235 mrg m35 m5 =
if ltLogRep m235 mrg then
let omin = case peekMinPQ bpq of
Just (lr, trv) -> LogRep lr trv
otherwise -> m235 -- at the beginning!
nm235 = multLR2 omin
nbpq = replaceMinPQ m235.lr m235.trv bpq
in CIS m235.trv <| \ () ->
next nbpq mpq nm235 mrg m35 m5
else
if ltLogRep mrg m5 then
let omin = case peekMinPQ mpq of
Just (lr, trv) -> LogRep lr trv
otherwise -> mrg -- at the beginning!
nm35 = multLR3 omin
nmrg = if ltLogRep nm35 m5 then nm35 else m5
nmpq = replaceMinPQ mrg.lr mrg.trv mpq
nbpq = pushPQ mrg.lr mrg.trv bpq
in CIS mrg.trv <| \ () ->
next nbpq nmpq m235 nmrg nm35 m5
else
let nm5 = multLR5 m5
nmrg = if ltLogRep m35 nm5 then m35 else nm5
nmpq = pushPQ m5.lr m5.trv mpq
nbpq = pushPQ m5.lr m5.trv bpq
in CIS m5.trv <| \ () ->
next nbpq nmpq m235 nmrg m35 nm5
in CIS (0, 0, 0) <| \ () ->
next emptyPQ emptyPQ im235 imrg im35 im5
-- following code has to do with outputting to a web page using MUV/TEA...
type alias Model = { time: Int
, str1: String, str2: String, str3: String }
type Msg = Start Int | Done ( Int, Trival )
timemillis : () -> Task Never Int -- a side effect function
timemillis() = now |> andThen (\ t -> succeed (posixToMillis t))
test : Int -> Cmd Msg -- side effect function chain (includes "perform")...
test lmt =
timemillis()
|> andThen (\ t -> succeed ( t, nthCIS lmt (hammingsLog()) ))
|> perform Done
myupdate : Msg -> Model -> (Model, Cmd Msg)
myupdate msg mdl =
case msg of
Start tm -> ( Model tm mdl.str1 mdl.str2 "Running...", test cLIMIT )
Done (stptm, answr) ->
( ( Model stptm mdl.str1 mdl.str2
<| "The " ++ String.fromInt cLIMIT ++
"th Hamming number is " ++
showTrival answr ++ " in " ++
String.fromInt (stptm - mdl.time) ++
" milliseconds." )
, Cmd.none ) -- terminates computation; allows UI update...
myview : Model -> Html msg
myview mdl =
div [] [ div [] [text mdl.str1]
, div [] [text mdl.str2]
, div [] [text mdl.str3] ]
main : Program () Model Msg
main =
element { init = \ _ -> ( Model 0
("The first 20 Hamming numbers are: " ++
(hammingsLog() |> takeCIS2List 20
|> List.map showTrival
|> String.join ", ") ++ ".")
("The 1691st Hamming number is " ++
(hammingsLog() |> nthCIS 1691
|> showTrival) ++ ".")
"", perform Start (timemillis()) )
, update = myupdate
, subscriptions = \ _ -> Sub.none
, view = myview }
|
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, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#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, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#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 again: ");
}
System.out.println("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 the empty sequence.
|
#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 the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#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 lower..upper ->
IO.puts if n > number, do: "Too high.", else: "Too low."
play(lower, upper, number)
_ ->
IO.puts "Guess not in valid range."
play(lower, upper, number)
end
end
end
GuessingGame.play(1, 100)
|
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 scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#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" = input [break]
either "l" = input [upper: guess] [lower: guess]
]
print ["I did it! Your number was" guess]
|
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 scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#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 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /*Useful seed? Then use a random seed.*/
?= random(low, high) /*generate random number from low->high*/
$= "──────── Try to guess my number (it's between " /*part of a prompt message.*/
g= /*nullify the first guess. */
do #=1; oldg= g /*save the guess for later comparison. */
if pos('high', info)\==0 then high= g /*test if the guess is too high. */
if pos('low' , info)\==0 then low = g /* " " " " " " low. */
say /*display a blank line before prompt. */
say $ low ' and ' high " inclusive):" /*issue the prompt message to terminal.*/
say /*display a blank line after prompt. */
g= (low + (high - low) / 2) / 1 /*calculate the next guess & normalize.*/
if g=oldg then g= g + 1 /*bump guess by one 'cause we're close.*/
say 'My guess is' g /*display computer's guess to the term.*/
if g=? then leave /*this guess is correct; leave & inform*/
if g>? then info= right(' Your guess is too high.', 60, "─")
else info= right(' Your guess is too low.' , 60, "─")
say info
end /*try*/
say /*stick a fork in it, we're all done. */
say 'Congratulations! You guessed the secret number in' # "tries."
|
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 include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#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
}
return (n == 1)
}
public static Void main ()
{
i := 1
count := 0
while (count < 8)
{
if (isHappy (i))
{
echo (i)
count += 1
}
i += 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, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#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
EndProcedure
OpenConsole("Haversine distance")
Print("Haversine distance: ")
Print(StrD(Haversine(36.12,-86.67,33.94,-118.4),7)+" km.")
Input()
|
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/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#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
say "The first Harshad number greater than 1000 is: "
1000 [ 1+ dup isharshad
iff echo done
again ]
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 following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#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
var g := Encode(i);
var d := Decode(g);
PrintLn(Format(' %2d %s %s %s %2d',
[i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d]));
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
|
#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.printf("Output of the command: %s %n%n", command);
while (sc.hasNext()) {
System.out.println(sc.nextLine());
}
}
}
}
|
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 the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#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 task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#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 not = 0 do begin
newA := b;
b := a rem b;
a := newA;
end;
a
end
end gcd ;
write( gcd( -21, 35 ) );
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.
|
#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 London!", "Hello New York!");
try (FileWriter fw = new FileWriter(fn)) {
fw.write(s);
}
}
}
}
|
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 conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#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&@CRLF)
Func Hailstone($int, $sequence = True)
$Counter = 0
While True
$Counter += 1
If $sequence = True Then ConsoleWrite($int & ",")
If $int = 1 Then ExitLoop
If Not Mod($int, 2) Then
$int = $int / 2
Else
$int = 3 * $int + 1
EndIf
If Not Mod($Counter, 25) AND $sequence = True Then ConsoleWrite(@CRLF)
WEnd
If $sequence = True Then ConsoleWrite(@CRLF)
Return $Counter
EndFunc ;==>Hailstone
|
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 use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#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)}
bitmap({Array2D.map Arr ToColor})
end
fun {ToColor Lum}
L = {Float.toInt Lum}
in
color(L L L)
end
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 use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#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 = int(0.2126 * $r + 0.7152 * $g + 0.0722 * $b);
# discard alpha info...
$gimg->set_color($gray, $gray, $gray, 255);
$gimg->draw_point($x, $y);
}
}
return $gimg;
}
my $animage = Image::Imlib2->load("Lenna100.jpg");
my $gscale = tograyscale($animage);
$gscale->set_quality(80);
$gscale->save("Lennagray.jpg");
exit 0;
|
http://rosettacode.org/wiki/Go_Fish
|
Go Fish
|
Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#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, 0, 2 * 9, '';
my $mepicks = join '', $me =~ /$pat/g;
arrange($me);
$mebooks++ while $me =~ s/($pat).\1.\1.\1.//;
my $you = substr $deck, 0, 2 * 9, '';
my $youpicks = join '', $you =~ /$pat/g;
arrange($you);
$youbooks++ while $you =~ s/($pat).\1.\1.\1.//;
while( $mebooks + $youbooks < 13 )
{
play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 );
$mebooks + $youbooks == 13 and last;
play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 );
}
print "me $mebooks you $youbooks\n";
sub arrange { $_[0] = join '', sort $_[0] =~ /../g }
sub human
{
my $have = shift =~ s/($pat).\K(?!\1)/ /gr;
local $| = 1;
my $pick;
do
{
print "You have $have, enter request: ";
($pick) = lc(<STDIN>) =~ /$pat/g;
} until $pick and $have =~ /$pick/;
return $pick;
}
sub play
{
my ($me, $mb, $lastpicks, $you, $yb, $human) = @_;
my $more = 1;
while( arrange( $$me ), $more and $$mb + $$yb < 13 )
{
# use Data::Dump 'dd'; dd \@_, "deck $deck";
if( $$me =~ s/($pat).\1.\1.\1.// )
{
print "book of $&\n";
$$mb++;
}
elsif( $$me )
{
my $pick = $human ? do { human($$me) } : do
{
my %picks;
$picks{$_}++ for my @picks = $$me =~ /$pat/g;
my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks;
print "pick $pick\n";
$$lastpicks =~ s/$pick//g;
$$lastpicks .= $pick;
$pick;
};
if( $$you =~ s/(?:$pick.)+// )
{
$$me .= $&;
}
else
{
print "GO FISH !!\n";
$$me .= substr $deck, 0, 2, '';
$more = 0;
}
}
elsif( $deck )
{
$$me .= substr $deck, 0, 2, '';
}
else
{
$more = 0;
}
}
arrange( $$me );
}
|
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 particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#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 M=X3 THEN J%+=1 X3=3*H[J%] END IF
IF M=X5 THEN K%+=1 X5=5*H[K%] END IF
END FOR
RES=H[L%-1]
END PROCEDURE
BEGIN
FOR H%=1 TO 20 DO
HAMMING(H%->RES)
PRINT("H(";H%;")=";RES)
END FOR
HAMMING(1691->RES)
PRINT("H(1691)=";RES)
END PROGRAM
|
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, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#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, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#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 the empty sequence.
|
#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
local i,maxglobal,maxglobalI,maxlocal,maxlocalI
maxglobal := maxlocal := 0 # global and local maxima
every i := 1 to *L do {
if (maxlocal := max(maxlocal +L[i],0)) > 0 then
if /maxlocalI then maxlocalI := [i,i] else maxlocalI[2] := i # local maxima subscripts
else maxlocalI := &null # reset subsequence
if maxglobal <:= maxlocal then # global maxima
maxglobalI := copy(maxlocalI)
}
return L[(\maxglobalI)[1]:maxglobalI[2]] | [] # return sub-sequence or empty list
end
|
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 the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#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)
(message "Too high!"))
((= guess number)
(setq done t)
(message "Well guessed!")))))
|
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 scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#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)
switch ans
on "l" min = guess + 1
on "h" max = guess - 1
on "e" exit
other see "sorry, i didn't understand your answer." + nl
off
end
see "goodbye." + nl
|
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 scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#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 <=> $number
end
low, high = 1, 100
$number = rand(low .. high)
puts "guess a number between #{low} and #{high}"
play(low, high)
|
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 include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#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, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#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
c = 2 * asin(sqrt(a))
return R * c
>>> haversine(36.12, -86.67, 33.94, -118.40)
2887.2599506071106
>>>
|
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/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#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
(displayln (for/first ([h harshads] #:when(> h 1000)) h))
|
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 following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#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 : ~2B~n", [n, n, g, d, d])
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 following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#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> base64
23.06.2016 18:21 <DIR> base9
<snip>"
|
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 the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#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 test run
SUB addVal (value AS INTEGER)
DIM tmp AS INTEGER
IF valCount > -1 THEN
'this is needed for BASICs that don't support REDIM PRESERVE
REDIM v2(valCount) AS INTEGER
FOR tmp = 0 TO valCount
v2(tmp) = vals(tmp)
NEXT
END IF
valCount = valCount + 1
REDIM vals(valCount)
IF valCount > 0 THEN
'also needed for BASICs that don't support REDIM PRESERVE
FOR tmp = 0 TO valCount - 1
vals(tmp) = v2(tmp)
NEXT
END IF
vals(valCount) = value
END SUB
FUNCTION findMax%
DIM tmp1 AS INTEGER, tmp2 AS INTEGER
FOR tmp1 = 0 TO valCount
IF vals(tmp1) > tmp2 THEN tmp2 = vals(tmp1)
NEXT
findMax = tmp2
END FUNCTION
|
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 task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#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') fn = './stdin';
if (fn == '-') fn = 'stdin';
try {
data = File.read(fn);
/* Jsi supports the m multiline regexp flag */
changed = data.replace(/Goodbye London!/gm, 'Hello New York!');
if (changed != data) {
if (fn == 'stdin') fn = 'stdout'; else fn += '.new';
var cnt = File.write(fn, changed);
puts(fn + ":" + cnt, 'updated');
}
} catch(err) { puts(err, 'processing', fn); }
}
|
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 conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#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++) {
n = hailstone(i,0);
if (m<n) {
m=n;
ix=i;
}
}
printf("longest hailstone sequence is %i and has %i elements\n",ix,m);
}
|
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 use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#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_bits(pixel,{#FF0000,#FF00,#FF})
integer {r,g,b} = sq_floor_div(r_g_b,{#010000,#0100,#01})
image[x][y] = floor(0.2126*r + 0.7152*g + 0.0722*b)*#010101
end for
end for
return image
end function
--include ppm.e -- read_ppm(), write_ppm(), to_grey() (as distributed, instead of the above)
sequence img = read_ppm("Lena.ppm")
img = to_grey(img)
write_ppm("LenaGray.ppm",img)
|
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 use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#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);
$this->data[$j][$i] = array($l,$l,$l);
}
}
}
}
$b = new BitmapGrayscale(16,16);
$b->fill(0,0,null,null, array(255,255,0));
$b->setPixel(0, 15, array(255,0,0));
$b->setPixel(0, 14, array(0,255,0));
$b->setPixel(0, 13, array(0,0,255));
$b->toGrayscale();
$b->writeP6('p6-grayscale.ppm');
|
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 the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#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: [] ;-- where discarded cards go
;---------------------
; Helper functions -
;---------------------
clear-screen: does [
"clears the console"
call/console either system/platform = 'Linux ["clear"]["cls"]
]
clear-and-show: func [duration str][
{
Poor persons animation.
Blips message to screen after a pause of duration length.
}
clear-screen
print str
wait duration
clear-screen
]
deal-cards: func [num hand][
loop num [
append hand rejoin [trim/all form take deck]
]
]
find-in: func [blk str][
"Finds a string value in a block. Series in series."
foreach i blk [if find i str [return i]]
]
go-fish: func [num hand][
either not empty? deck [
deal-cards num hand
][
append hand rejoin [trim/all form take pile] ;-- take from pile if deck is empty
]
]
guess-from: func [hand guessed][
{
Randomly picks from hand minus guessed.
Simulates a person asking for different cards on
their next turn if their previous guess resulted
in a Go Fish.
}
random/seed now/time
either any [empty? guessed empty? exclude hand guessed][
random/only hand
][
random/only exclude hand guessed
]
]
make-deck: function [] [
"make-deck and shuffle from https://rosettacode.org/wiki/Playing_cards#Red"
new-deck: make block! 52
foreach p pip [loop 4 [append/only new-deck p]]
return new-deck
]
show-cards: does [
clear-and-show 0 ""
print [newline "Player cards:" newline sort phand newline]
print ["Computer books:" cbooks]
print ["Player books:" pbooks newline]
]
shuffle: function [deck [block!]] [deck: random deck]
;------------- end of helper functions -----------------
check-for-books: func [
{
Checks for a book in a players hand.
Increments the players book score, and
discards the book from the players hand
}
hand "from or to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [
forall hand [keep find hand/1 kind]
]
remove-each i c [none = i]
if 4 = length? c [
either hand = phand [pbooks: pbooks + 1][cbooks: cbooks + 1]
remove-each i hand [if find/only c i [i]] ;-- remove book from hand
forall c [append pile c/1] ;-- append discarded book to the pile
]
]
transfer-cards: func [
"Transfers cards from player to player"
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [forall fhand [keep find fhand/1 kind]]
remove-each i c [none = i] ;-- remove none values from collected
forall c [append thand c/1] ;-- append remaining values to "to hand"
remove-each i fhand [if find/only c i [i]] ;-- remove those values from "from hand"
]
computer-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
a
][
a: ask rejoin ["Do you have any " kind " s? "]
if a = "x" [halt]
either any [a = "y" a = "yes"][
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
computer-turn fhand thand guess-from thand cguesses
][
clear-and-show 0.4 gf
go-fish 1 thand
append cguesses kind
]
]
player-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
p
][
if empty? fhand [go-fish 3 fhand]
if none? find-in thand kind [ ;-- player has to hold rank asked for
clear-and-show 1.0
"You have to have that rank in your hand to ask for it.^/Computers turn..."
exit
]
either find-in fhand kind [
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
if find-in thand kind [
p: ask "Your guess: "
either p = "x" [halt][player-turn fhand thand p]
check-for-books thand p
]
][
clear-and-show 0.4 gf
go-fish 1 thand
]
]
game-round: has [c p][
print {
-------------------
- COMPUTER TURN -
-------------------
}
if empty? chand [ ; computer has no more cards? fish 3 cards.
go-fish 3 chand
show-cards
]
computer-turn phand chand c: guess-from chand cguesses
check-for-books chand c
show-cards
print {
-------------------
- PLAYER TURN -
-------------------
}
if empty? phand [ ;-- player has no more cards? fish 3 cards.
go-fish 3 phand
show-cards
]
p: ask "Your guess: "
either p = "x" [halt][player-turn chand phand find-in phand p]
check-for-books phand p
show-cards
]
main: does [
deck: shuffle make-deck
deal-cards 9 chand
deal-cards 9 phand
show-cards
while [cbooks + pbooks < 13][
game-round
]
clear-and-show 0 ""
print "GAME OVER"
print [newline "Computer books:" cbooks newline "Player books:" pbooks]
]
main
|
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 the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#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: [] ;-- where discarded cards go
;---------------------
; Helper functions -
;---------------------
clear-screen: does [
"clears the console"
call/console either system/platform = 'Linux ["clear"]["cls"]
]
clear-and-show: func [duration str][
{
Poor persons animation.
Blips message to screen after a pause of duration length.
}
clear-screen
print str
wait duration
clear-screen
]
deal-cards: func [num hand][
loop num [
append hand rejoin [trim/all form take deck]
]
]
find-in: func [blk str][
"Finds a string value in a block. Series in series."
foreach i blk [if find i str [return i]]
]
go-fish: func [num hand][
either not empty? deck [
deal-cards num hand
][
append hand rejoin [trim/all form take pile] ;-- take from pile if deck is empty
]
]
guess-from: func [hand guessed][
{
Randomly picks from hand minus guessed.
Simulates a person asking for different cards on
their next turn if their previous guess resulted
in a Go Fish.
}
random/seed now/time
either any [empty? guessed empty? exclude hand guessed][
random/only hand
][
random/only exclude hand guessed
]
]
make-deck: function [] [
"make-deck and shuffle from https://rosettacode.org/wiki/Playing_cards#Red"
new-deck: make block! 52
foreach p pip [loop 4 [append/only new-deck p]]
return new-deck
]
show-cards: does [
clear-and-show 0 ""
print [newline "Player cards:" newline sort phand newline]
print ["Computer books:" cbooks]
print ["Player books:" pbooks newline]
]
shuffle: function [deck [block!]] [deck: random deck]
;------------- end of helper functions -----------------
check-for-books: func [
{
Checks for a book in a players hand.
Increments the players book score, and
discards the book from the players hand
}
hand "from or to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [
forall hand [keep find hand/1 kind]
]
remove-each i c [none = i]
if 4 = length? c [
either hand = phand [pbooks: pbooks + 1][cbooks: cbooks + 1]
remove-each i hand [if find/only c i [i]] ;-- remove book from hand
forall c [append pile c/1] ;-- append discarded book to the pile
]
]
transfer-cards: func [
"Transfers cards from player to player"
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [forall fhand [keep find fhand/1 kind]]
remove-each i c [none = i] ;-- remove none values from collected
forall c [append thand c/1] ;-- append remaining values to "to hand"
remove-each i fhand [if find/only c i [i]] ;-- remove those values from "from hand"
]
computer-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
a
][
a: ask rejoin ["Do you have any " kind " s? "]
if a = "x" [halt]
either any [a = "y" a = "yes"][
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
computer-turn fhand thand guess-from thand cguesses
][
clear-and-show 0.4 gf
go-fish 1 thand
append cguesses kind
]
]
player-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
p
][
if empty? fhand [go-fish 3 fhand]
if none? find-in thand kind [ ;-- player has to hold rank asked for
clear-and-show 1.0
"You have to have that rank in your hand to ask for it.^/Computers turn..."
exit
]
either find-in fhand kind [
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
if find-in thand kind [
p: ask "Your guess: "
either p = "x" [halt][player-turn fhand thand p]
check-for-books thand p
]
][
clear-and-show 0.4 gf
go-fish 1 thand
]
]
game-round: has [c p][
print {
-------------------
- COMPUTER TURN -
-------------------
}
if empty? chand [ ; computer has no more cards? fish 3 cards.
go-fish 3 chand
show-cards
]
computer-turn phand chand c: guess-from chand cguesses
check-for-books chand c
show-cards
print {
-------------------
- PLAYER TURN -
-------------------
}
if empty? phand [ ;-- player has no more cards? fish 3 cards.
go-fish 3 phand
show-cards
]
p: ask "Your guess: "
either p = "x" [halt][player-turn chand phand find-in phand p]
check-for-books phand p
show-cards
]
main: does [
deck: shuffle make-deck
deal-cards 9 chand
deal-cards 9 phand
show-cards
while [cbooks + pbooks < 13][
game-round
]
clear-and-show 0 ""
print "GAME OVER"
print [newline "Computer books:" cbooks newline "Player books:" pbooks]
]
main
|
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 the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#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: [] ;-- where discarded cards go
;---------------------
; Helper functions -
;---------------------
clear-screen: does [
"clears the console"
call/console either system/platform = 'Linux ["clear"]["cls"]
]
clear-and-show: func [duration str][
{
Poor persons animation.
Blips message to screen after a pause of duration length.
}
clear-screen
print str
wait duration
clear-screen
]
deal-cards: func [num hand][
loop num [
append hand rejoin [trim/all form take deck]
]
]
find-in: func [blk str][
"Finds a string value in a block. Series in series."
foreach i blk [if find i str [return i]]
]
go-fish: func [num hand][
either not empty? deck [
deal-cards num hand
][
append hand rejoin [trim/all form take pile] ;-- take from pile if deck is empty
]
]
guess-from: func [hand guessed][
{
Randomly picks from hand minus guessed.
Simulates a person asking for different cards on
their next turn if their previous guess resulted
in a Go Fish.
}
random/seed now/time
either any [empty? guessed empty? exclude hand guessed][
random/only hand
][
random/only exclude hand guessed
]
]
make-deck: function [] [
"make-deck and shuffle from https://rosettacode.org/wiki/Playing_cards#Red"
new-deck: make block! 52
foreach p pip [loop 4 [append/only new-deck p]]
return new-deck
]
show-cards: does [
clear-and-show 0 ""
print [newline "Player cards:" newline sort phand newline]
print ["Computer books:" cbooks]
print ["Player books:" pbooks newline]
]
shuffle: function [deck [block!]] [deck: random deck]
;------------- end of helper functions -----------------
check-for-books: func [
{
Checks for a book in a players hand.
Increments the players book score, and
discards the book from the players hand
}
hand "from or to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [
forall hand [keep find hand/1 kind]
]
remove-each i c [none = i]
if 4 = length? c [
either hand = phand [pbooks: pbooks + 1][cbooks: cbooks + 1]
remove-each i hand [if find/only c i [i]] ;-- remove book from hand
forall c [append pile c/1] ;-- append discarded book to the pile
]
]
transfer-cards: func [
"Transfers cards from player to player"
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [forall fhand [keep find fhand/1 kind]]
remove-each i c [none = i] ;-- remove none values from collected
forall c [append thand c/1] ;-- append remaining values to "to hand"
remove-each i fhand [if find/only c i [i]] ;-- remove those values from "from hand"
]
computer-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
a
][
a: ask rejoin ["Do you have any " kind " s? "]
if a = "x" [halt]
either any [a = "y" a = "yes"][
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
computer-turn fhand thand guess-from thand cguesses
][
clear-and-show 0.4 gf
go-fish 1 thand
append cguesses kind
]
]
player-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
p
][
if empty? fhand [go-fish 3 fhand]
if none? find-in thand kind [ ;-- player has to hold rank asked for
clear-and-show 1.0
"You have to have that rank in your hand to ask for it.^/Computers turn..."
exit
]
either find-in fhand kind [
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
if find-in thand kind [
p: ask "Your guess: "
either p = "x" [halt][player-turn fhand thand p]
check-for-books thand p
]
][
clear-and-show 0.4 gf
go-fish 1 thand
]
]
game-round: has [c p][
print {
-------------------
- COMPUTER TURN -
-------------------
}
if empty? chand [ ; computer has no more cards? fish 3 cards.
go-fish 3 chand
show-cards
]
computer-turn phand chand c: guess-from chand cguesses
check-for-books chand c
show-cards
print {
-------------------
- PLAYER TURN -
-------------------
}
if empty? phand [ ;-- player has no more cards? fish 3 cards.
go-fish 3 phand
show-cards
]
p: ask "Your guess: "
either p = "x" [halt][player-turn chand phand find-in phand p]
check-for-books phand p
show-cards
]
main: does [
deck: shuffle make-deck
deal-cards 9 chand
deal-cards 9 phand
show-cards
while [cbooks + pbooks < 13][
game-round
]
clear-and-show 0 ""
print "GAME OVER"
print [newline "Computer books:" cbooks newline "Player books:" pbooks]
]
main
|
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 the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#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: [] ;-- where discarded cards go
;---------------------
; Helper functions -
;---------------------
clear-screen: does [
"clears the console"
call/console either system/platform = 'Linux ["clear"]["cls"]
]
clear-and-show: func [duration str][
{
Poor persons animation.
Blips message to screen after a pause of duration length.
}
clear-screen
print str
wait duration
clear-screen
]
deal-cards: func [num hand][
loop num [
append hand rejoin [trim/all form take deck]
]
]
find-in: func [blk str][
"Finds a string value in a block. Series in series."
foreach i blk [if find i str [return i]]
]
go-fish: func [num hand][
either not empty? deck [
deal-cards num hand
][
append hand rejoin [trim/all form take pile] ;-- take from pile if deck is empty
]
]
guess-from: func [hand guessed][
{
Randomly picks from hand minus guessed.
Simulates a person asking for different cards on
their next turn if their previous guess resulted
in a Go Fish.
}
random/seed now/time
either any [empty? guessed empty? exclude hand guessed][
random/only hand
][
random/only exclude hand guessed
]
]
make-deck: function [] [
"make-deck and shuffle from https://rosettacode.org/wiki/Playing_cards#Red"
new-deck: make block! 52
foreach p pip [loop 4 [append/only new-deck p]]
return new-deck
]
show-cards: does [
clear-and-show 0 ""
print [newline "Player cards:" newline sort phand newline]
print ["Computer books:" cbooks]
print ["Player books:" pbooks newline]
]
shuffle: function [deck [block!]] [deck: random deck]
;------------- end of helper functions -----------------
check-for-books: func [
{
Checks for a book in a players hand.
Increments the players book score, and
discards the book from the players hand
}
hand "from or to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [
forall hand [keep find hand/1 kind]
]
remove-each i c [none = i]
if 4 = length? c [
either hand = phand [pbooks: pbooks + 1][cbooks: cbooks + 1]
remove-each i hand [if find/only c i [i]] ;-- remove book from hand
forall c [append pile c/1] ;-- append discarded book to the pile
]
]
transfer-cards: func [
"Transfers cards from player to player"
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [forall fhand [keep find fhand/1 kind]]
remove-each i c [none = i] ;-- remove none values from collected
forall c [append thand c/1] ;-- append remaining values to "to hand"
remove-each i fhand [if find/only c i [i]] ;-- remove those values from "from hand"
]
computer-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
a
][
a: ask rejoin ["Do you have any " kind " s? "]
if a = "x" [halt]
either any [a = "y" a = "yes"][
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
computer-turn fhand thand guess-from thand cguesses
][
clear-and-show 0.4 gf
go-fish 1 thand
append cguesses kind
]
]
player-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
p
][
if empty? fhand [go-fish 3 fhand]
if none? find-in thand kind [ ;-- player has to hold rank asked for
clear-and-show 1.0
"You have to have that rank in your hand to ask for it.^/Computers turn..."
exit
]
either find-in fhand kind [
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
if find-in thand kind [
p: ask "Your guess: "
either p = "x" [halt][player-turn fhand thand p]
check-for-books thand p
]
][
clear-and-show 0.4 gf
go-fish 1 thand
]
]
game-round: has [c p][
print {
-------------------
- COMPUTER TURN -
-------------------
}
if empty? chand [ ; computer has no more cards? fish 3 cards.
go-fish 3 chand
show-cards
]
computer-turn phand chand c: guess-from chand cguesses
check-for-books chand c
show-cards
print {
-------------------
- PLAYER TURN -
-------------------
}
if empty? phand [ ;-- player has no more cards? fish 3 cards.
go-fish 3 phand
show-cards
]
p: ask "Your guess: "
either p = "x" [halt][player-turn chand phand find-in phand p]
check-for-books phand p
show-cards
]
main: does [
deck: shuffle make-deck
deal-cards 9 chand
deal-cards 9 phand
show-cards
while [cbooks + pbooks < 13][
game-round
]
clear-and-show 0 ""
print "GAME OVER"
print [newline "Computer books:" cbooks newline "Player books:" pbooks]
]
main
|
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 the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#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: [] ;-- where discarded cards go
;---------------------
; Helper functions -
;---------------------
clear-screen: does [
"clears the console"
call/console either system/platform = 'Linux ["clear"]["cls"]
]
clear-and-show: func [duration str][
{
Poor persons animation.
Blips message to screen after a pause of duration length.
}
clear-screen
print str
wait duration
clear-screen
]
deal-cards: func [num hand][
loop num [
append hand rejoin [trim/all form take deck]
]
]
find-in: func [blk str][
"Finds a string value in a block. Series in series."
foreach i blk [if find i str [return i]]
]
go-fish: func [num hand][
either not empty? deck [
deal-cards num hand
][
append hand rejoin [trim/all form take pile] ;-- take from pile if deck is empty
]
]
guess-from: func [hand guessed][
{
Randomly picks from hand minus guessed.
Simulates a person asking for different cards on
their next turn if their previous guess resulted
in a Go Fish.
}
random/seed now/time
either any [empty? guessed empty? exclude hand guessed][
random/only hand
][
random/only exclude hand guessed
]
]
make-deck: function [] [
"make-deck and shuffle from https://rosettacode.org/wiki/Playing_cards#Red"
new-deck: make block! 52
foreach p pip [loop 4 [append/only new-deck p]]
return new-deck
]
show-cards: does [
clear-and-show 0 ""
print [newline "Player cards:" newline sort phand newline]
print ["Computer books:" cbooks]
print ["Player books:" pbooks newline]
]
shuffle: function [deck [block!]] [deck: random deck]
;------------- end of helper functions -----------------
check-for-books: func [
{
Checks for a book in a players hand.
Increments the players book score, and
discards the book from the players hand
}
hand "from or to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [
forall hand [keep find hand/1 kind]
]
remove-each i c [none = i]
if 4 = length? c [
either hand = phand [pbooks: pbooks + 1][cbooks: cbooks + 1]
remove-each i hand [if find/only c i [i]] ;-- remove book from hand
forall c [append pile c/1] ;-- append discarded book to the pile
]
]
transfer-cards: func [
"Transfers cards from player to player"
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
c "collected"
][
c: collect [forall fhand [keep find fhand/1 kind]]
remove-each i c [none = i] ;-- remove none values from collected
forall c [append thand c/1] ;-- append remaining values to "to hand"
remove-each i fhand [if find/only c i [i]] ;-- remove those values from "from hand"
]
computer-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
a
][
a: ask rejoin ["Do you have any " kind " s? "]
if a = "x" [halt]
either any [a = "y" a = "yes"][
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
computer-turn fhand thand guess-from thand cguesses
][
clear-and-show 0.4 gf
go-fish 1 thand
append cguesses kind
]
]
player-turn: func [
fhand "from hand"
thand "to hand"
kind "rank of cards"
/local
p
][
if empty? fhand [go-fish 3 fhand]
if none? find-in thand kind [ ;-- player has to hold rank asked for
clear-and-show 1.0
"You have to have that rank in your hand to ask for it.^/Computers turn..."
exit
]
either find-in fhand kind [
check-for-books thand kind
transfer-cards fhand thand kind
show-cards
if find-in thand kind [
p: ask "Your guess: "
either p = "x" [halt][player-turn fhand thand p]
check-for-books thand p
]
][
clear-and-show 0.4 gf
go-fish 1 thand
]
]
game-round: has [c p][
print {
-------------------
- COMPUTER TURN -
-------------------
}
if empty? chand [ ; computer has no more cards? fish 3 cards.
go-fish 3 chand
show-cards
]
computer-turn phand chand c: guess-from chand cguesses
check-for-books chand c
show-cards
print {
-------------------
- PLAYER TURN -
-------------------
}
if empty? phand [ ;-- player has no more cards? fish 3 cards.
go-fish 3 phand
show-cards
]
p: ask "Your guess: "
either p = "x" [halt][player-turn chand phand find-in phand p]
check-for-books phand p
show-cards
]
main: does [
deck: shuffle make-deck
deal-cards 9 chand
deal-cards 9 phand
show-cards
while [cbooks + pbooks < 13][
game-round
]
clear-and-show 0 ""
print "GAME OVER"
print [newline "Computer books:" cbooks newline "Player books:" pbooks]
]
main
|
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 particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#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_map f (Cons(x, nxf)) =
Cons(f x, lazy(inf_map f nxf.Value))
Cons(1I, lazy(let x = inf_map ((*) 2I) hamming
let y = inf_map ((*) 3I) hamming
let z = inf_map ((*) 5I) hamming
x -|- y -|- z))
// testing...
[<EntryPoint>]
let main args =
let rec iterLazyListFor f n (Cons(v, rf)) =
if n > 0 then f v; iterLazyListFor f (n - 1) rf.Value
let rec nthLazyList n ((Cons(v, rf)) as ll) =
if n <= 1 then v else nthLazyList (n - 1) rf.Value
printf "( "; iterLazyListFor (printf "%A ") 20 (hammings()); printfn ")"
printfn "%A" (hammings() |> nthLazyList 1691)
printfn "%A" (hammings() |> nthLazyList 1000000)
0
|
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, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#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();
}
printf('Congratulations!\nThe number was %d it took %d tries\n', num, tries);
}
if (Interp.conf('unitTest')) {
// Set a predictable outcome
Math.srand(0);
guessNumber();
}
/*
=!INPUTSTART!=
5
9
2
=!INPUTEND!=
*/
/*
=!EXPECTSTART!=
Guess the number between 1 and 10 inclusive: Guess the number between 1 and 10 inclusive: Guess the number between 1 and 10 inclusive: Congratulations!
The number was 2 it took 3 tries
=!EXPECTEND!=
*/
|
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, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#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 the empty sequence.
|
#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>MAXSUM THEN LET MAXSUM=SUM:LET ST=I:LET EN=J
240 NEXT
250 NEXT
260 PRINT :PRINT "SubSequence with greatest sum:"
270 IF ST>0 THEN PRINT TAB(ST*3-2);
280 FOR I=ST TO EN
290 PRINT A(I);
300 NEXT
310 PRINT :PRINT "Sum:";MAXSUM
|
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 the empty sequence.
|
#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 the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#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("Guess the number : ","~d"),
if
K=:=N ->
io:format("Well guessed!!\n");
true ->
if
K > N ->
io:format("Your guess is too high.\n");
true ->
io:format("Your guess is too low.\n")
end,
guess(N)
end.
|
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 scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#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;
println!("Is it {}?", guess);
println!("(type h if my guess is too high, l if too low, e if equal and q to quit)");
let mut line = String::new();
stdin().read_line(&mut line).unwrap();
match Some(line.chars().next().unwrap().to_uppercase().next().unwrap()) {
Some('H') => {
max = guess - 1;
num_guesses += 1;
},
Some('L')=> {
min = guess + 1;
num_guesses += 1;
},
Some('E') => {
if num_guesses == 1 {
println!("\n*** That was easy! Got it in one guess! ***\n");
} else {
println!("\n*** I knew it! Got it in only {} guesses! ***\n", num_guesses);
}
break;
},
Some('Q') => return,
_ => println!("Sorry, I didn't quite get that. Please try again.")
}
}
}
}
|
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 scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#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(guess) => println("Your guess is higher than the chosen number, try again"); true
case guess if (1 until n).contains(guess) => println("Your guess is lower than the chosen number, try again"); true
case _ => println("Your guess is inappropriate, try again"); true
})
}
|
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 include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#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-numbers ( n -- )
0 swap 0 do
begin 1+ dup happy? until dup .
loop drop ;
8 happy-numbers \ 1 7 10 13 19 23 28 31
|
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, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#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
'*** LAT/LONG for Los Angeles International Airport (LAX)
Lat2 = 33.94
Lon2 = -118.40
'*** Initialize Values
UNIT = "K"
Distance = ""
'Radius = 6378.137
Radius = 6372.8
'*** Calculate distance using Haversine Function
lat1 = (lat1 * _PI / 180)
Lon1 = (Lon1 * _PI / 180)
Lat2 = (Lat2 * _PI / 180)
Lon2 = (Lon2 * _PI / 180)
DLon = Lon1 - Lon2
ANSWER = _ACOS(SIN(lat1) * SIN(Lat2) + COS(lat1) * COS(Lat2) * COS(DLon)) * Radius
'*** Adjust Answer based on Distance Unit (kilometers, miles, nautical miles)
SELECT CASE UNIT
CASE "M"
Result = ANSWER * 0.621371192
Distance = "miles"
CASE "N"
Result = ANSWER * 0.539956803
Distance = "nautical miles"
CASE ELSE
Result = ANSWER
Distance = "kilometers"
END SELECT
'*** Change PRINT statement with your labels for FROM/TO locations
PRINT "The distance from Nashville International to Los Angeles International in "; Distance;
PRINT USING " is: ##,###.##"; Result;
PRINT "."
END
|
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, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#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 * (long2 - long1))
12742 * asin(sqrt(a * a + cos(lat1) * cos(lat2) * b * b))
}
# Coordinates are found here:
# http://www.airport-data.com/airport/BNA/
# http://www.airport-data.com/airport/LAX/
great_circle_distance(
dms_to_rad(36, 7, 28.10), dms_to_rad( 86, 40, 41.50), # Nashville International Airport (BNA)
dms_to_rad(33, 56, 32.98), dms_to_rad(118, 24, 29.05)) # Los Angeles International Airport (LAX)
# Output: 2886.327
|
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/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#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_widget);
/* Initialize Agar Core given appname and flags */
value agar_init_core(value appname, value flags) {
#ifdef DEBUG
if (!val_is_null(appname)) val_check(appname, string);
val_check(flags, int);
#endif
if (AG_InitCore(val_string(appname), val_int(flags)) == -1) return alloc_bool(0);
return alloc_bool(1);
}
DEFINE_PRIM(agar_init_core, 2);
/* Initialize Agar GUI given graphic engine driver */
value agar_init_gui(value driver) {
#ifdef DEBUG
if (!val_is_null(driver)) val_check(driver, string);
#endif
if (AG_InitGraphics(val_string(driver)) == -1) return alloc_bool(0);
AG_BindStdGlobalKeys();
return alloc_bool(1);
}
DEFINE_PRIM(agar_init_gui, 1);
/* Initialize Agar given appname, flags and GUI driver */
value agar_init(value appname, value flags, value driver) {
#ifdef DEBUG
if (!val_is_null(appname)) val_check(appname, string);
val_check(flags, int);
if (!val_is_null(driver)) val_check(driver, string);
#endif
if (!val_bool(agar_init_core(appname, flags))) return alloc_bool(0);
if (!val_bool(agar_init_gui(driver))) return alloc_bool(0);
return alloc_bool(1);
}
DEFINE_PRIM(agar_init, 3);
/* end the Agar event loop on window-close */
void rundown(AG_Event *event) {
AG_Terminate(0);
}
/* Create an Agar window, given UInt flags (which might use 32 bits...) */
value agar_window(value flags) {
#ifdef DEBUG
val_check(flags, int);
#endif
AG_Window *win;
win = AG_WindowNew(val_int(flags));
AG_SetEvent(win, "window-close", rundown, "%p", win);
if ( win == NULL) return alloc_bool(0);
return alloc_abstract(k_agar_widget, win);
}
DEFINE_PRIM(agar_window, 1);
/* Show a window */
value agar_window_show(value w) {
AG_Window *win;
#ifdef DEBUG
val_check_kind(w, k_agar_widget);
#endif
win = (AG_Window *)val_widget(w);
AG_WindowShow(win);
return alloc_bool(1);
}
DEFINE_PRIM(agar_window_show, 1);
/* New box */
value agar_box(value parent, value type, value flags) {
AG_Box *b;
#ifdef DEBUG
val_check_kind(parent, k_agar_widget);
#endif
b = AG_BoxNew(val_widget(parent), val_int(type), val_int(flags));
return alloc_abstract(k_agar_widget, b);
}
DEFINE_PRIM(agar_box, 3);
/* New label */
value agar_label(value parent, value flags, value text) {
AG_Label *lw;
#ifdef DEBUG
val_check_kind(parent, k_agar_widget);
#endif
lw = AG_LabelNewS(val_widget(parent), val_int(flags), val_string(text));
return alloc_abstract(k_agar_widget, lw);
}
DEFINE_PRIM(agar_label, 3);
/* Event Loop */
value agar_eventloop(void) {
int rc;
rc = AG_EventLoop();
return alloc_int(rc);
}
DEFINE_PRIM(agar_eventloop, 0);
|
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 following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#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
d += remainder(n,2)*m
n = floor(n/2)
m *= 10
end while
return d
end function
integer j
for i = #0 to #1F do
printf(1,"%05d => ",dcb(i))
j = gray_encode(i)
printf(1,"%05d => ",dcb(j))
j = gray_decode(j)
printf(1,"%05d\n",dcb(j))
end for
|
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);
var process_exit = $loader.loadprim("std@process_exit", 1);
var sys_exit = $loader.loadprim("std@sys_exit", 1);
/* work buffer */
var bufsize = 1024;
var buffer = $smake(bufsize);
/* default command is ls, otherwise pass command line arguments */
var argc = $asize($loader.args);
var cmd = "ls";
var args;
/* Check command line arguments */
if argc > 0 {
cmd = $loader.args[0];
}
if argc > 1 {
args = $asub($loader.args, 1, argc - 1);
}
/* spawn process, with arguments */
var proc = process_run(cmd, args);
/* Close input channel - command might be waiting for input */
process_stdin_close(proc);
/* capture and print stdout */
var not_done = true;
var len = 0;
do {
try {
len = process_stdout_read(proc, buffer, 0, bufsize);
} catch exc {
not_done = false;
}
if (not_done) $print($ssub(buffer, 0, len));
} while not_done;
/* capture and print any stderr */
not_done = true;
len = 0;
do {
try {
len = process_stderr_read(proc, buffer, 0, bufsize);
} catch exc {
not_done = false;
}
if (not_done) $print($ssub(buffer, 0, len));
} while not_done;
/* Get the exit status */
var ps = process_exit(proc);
sys_exit(ps);
|
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 the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#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.