task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, 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.
|
#Run_BASIC
|
Run BASIC
|
D2R = atn(1)/45
diam = 2 * 6372.8
Lg1m2 = ((-86.67)-(-118.4)) * D2R
Lt1 = 36.12 * D2R ' degrees to rad
Lt2 = 33.94 * D2R
dz = sin(Lt1) - sin(Lt2)
dx = cos(Lg1m2) * cos(Lt1) - cos(Lt2)
dy = sin(Lg1m2) * cos(Lt1)
hDist = asn((dx^2 + dy^2 + dz^2)^0.5 /2) * diam
print "Haversine distance: ";using("####.#############",hDist);" km."
'Tips: ( 36 deg 7 min 12 sec ) = print 36+(7/60)+(12/3600). Produces: 36.12 deg.
'
' http://maps.google.com
' Search 36.12,-86.67
' Earth.
' Center the pin, zoom airport.
' Directions (destination).
' 36.12.-86.66999
' Distance is 35.37 inches.
|
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.
|
#Rust
|
Rust
|
use std::f64;
static R: f64 = 6372.8;
struct Point {
lat: f64,
lon: f64,
}
fn haversine(mut origin: Point, mut destination: Point) -> f64 {
origin.lon -= destination.lon;
origin.lon = origin.lon.to_radians();
origin.lat = origin.lat.to_radians();
destination.lat = destination.lat.to_radians();
let dz: f64 = origin.lat.sin() - destination.lat.sin();
let dx: f64 = origin.lon.cos() * origin.lat.cos() - destination.lat.cos();
let dy: f64 = origin.lon.sin() * origin.lat.cos();
((dx * dx + dy * dy + dz * dz).sqrt() / 2.0).asin() * 2.0 * R
}
fn main() {
let origin: Point = Point {
lat: 36.12,
lon:-86.67
};
let destination: Point = Point {
lat: 33.94,
lon:-118.4
};
let d: f64 = haversine(origin, destination);
println!("Distance: {} km ({} mi)", d, d / 1.609344);
}
|
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
|
#Haskell
|
Haskell
|
main = putStrLn "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
|
#Run_BASIC
|
Run BASIC
|
while count < 20
h = h + 1
if neven(h) = 0 then
count = count + 1
print count;": ";h
end if
wend
h = 1000
while 1 = 1
h = h + 1
if neven(h) = 0 then
print h
exit while
end if
wend
function neven(h)
h$ = str$(h)
for i = 1 to len(h$)
d = d + val(mid$(h$,i,1))
next i
neven = h mod d
end function
|
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
|
#NS-HUBASIC
|
NS-HUBASIC
|
10 LOCATE 6,11
20 PRINT "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
|
#Nyquist
|
Nyquist
|
;nyquist plug-in
;version 4
;type tool
;name "Goodbye World"
(print "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.
|
#Frink
|
Frink
|
for i=0 to 31
{
gray = binaryToGray[i]
back = grayToBinary[gray]
println[(i->binary) + "\t" + (gray->binary) + "\t" + (back->binary)]
}
|
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.
|
#Go
|
Go
|
package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
|
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
|
#Python
|
Python
|
>>> import subprocess
>>> returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True)
>>> type(returned_text)
<class 'str'>
>>> print(returned_text)
Volume in drive C is Windows
Volume Serial Number is 44X7-73CE
Directory of C:\Python33
04/07/2013 06:40 <DIR> .
04/07/2013 06:40 <DIR> ..
27/05/2013 07:10 <DIR> DLLs
27/05/2013 07:10 <DIR> Doc
27/05/2013 07:10 <DIR> include
27/05/2013 07:10 <DIR> Lib
27/05/2013 07:10 <DIR> libs
16/05/2013 00:15 33,326 LICENSE.txt
15/05/2013 22:49 214,554 NEWS.txt
16/05/2013 00:03 26,624 python.exe
16/05/2013 00:03 27,136 pythonw.exe
15/05/2013 22:49 6,701 README.txt
27/05/2013 07:10 <DIR> tcl
27/05/2013 07:10 <DIR> Tools
16/05/2013 00:02 43,008 w9xpopen.exe
6 File(s) 351,349 bytes
9 Dir(s) 46,326,947,840 bytes free
>>> # Ref: https://docs.python.org/3/library/subprocess.html
|
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
|
#Quackery
|
Quackery
|
/O> $ /
... import subprocess
... string_to_stack(str(subprocess.check_output('ls'),encoding='utf-8'))
... / python
... reverse echo$
...
ykq.kcudeltrut
yrdnus
yp.yrekcauq
ykq.Xsnoisnetxe
ykq.targib
fdp.yrekcauQ fo kooB ehT
fdp.tnirp rof yrekcauQ fo kooB ehT
txt.TSRIF EM DAER
fdp.ecnerefeR kciuQ yrekcauQ
|
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!
|
#Arc
|
Arc
|
(mac myswap (a b)
(w/uniq gx
`(let ,gx a
(= a b)
(= b ,gx))))
(with (a 1
b 2)
(myswap a b)
(prn "a:" a #\Newline "b:" b))
|
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.
|
#Befunge
|
Befunge
|
001pv <
>&:01g`#v_1+#^_01g.@
^p10 <
|
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.
|
#Arendelle
|
Arendelle
|
< a , b >
( r , @a )
[ @r != 0 ,
( r , @a % @b )
{ @r != 0 ,
( a , @b )
( b , @r )
}
]
( return , @b )
|
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
|
Globally replace text in several files
|
Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
|
#Pascal
|
Pascal
|
Program StringReplace;
uses
Classes, StrUtils;
const
fileName: array[1..3] of string = ('a.txt', 'b.txt', 'c.txt');
matchText = 'Goodbye London!';
replaceText = 'Hello New York!';
var
AllText: TStringlist;
i, j: integer;
begin
for j := low(fileName) to high(fileName) do
begin
AllText := TStringlist.Create;
AllText.LoadFromFile(fileName[j]);
for i := 0 to AllText.Count-1 do
AllText.Strings[i] := AnsiReplaceStr(AllText.Strings[i], matchText, replaceText);
AllText.SaveToFile(fileName[j]);
AllText.Destroy;
end;
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.
|
#Perl
|
Perl
|
perl -pi -e "s/Goodbye London\!/Hello New York\!/g;" a.txt b.txt c.txt
|
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).
|
#BQN
|
BQN
|
Collatz ← ⥊⊸{
𝕨𝕊1: 𝕨;
(𝕨⊸∾ 𝕊 ⊢) (2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩
}
Collatz1 ← ⌽∘{
1: ⟨1⟩;
𝕩∾˜𝕊(2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩
}
•Show Collatz1 5
•Show (⊑∾≠){𝕩⊑˜⊑⍒≠¨𝕩}Collatz1¨1+↕99999
|
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.
|
#Scala
|
Scala
|
object BitmapOps {
def luminosity(c:Color)=(0.2126*c.getRed + 0.7152*c.getGreen + 0.0722*c.getBlue+0.5).toInt
def grayscale(bm:RgbBitmap)={
val image=new RgbBitmap(bm.width, bm.height)
for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y)))
image.setPixel(x, y, new Color(l,l,l))
image
}
}
|
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.
|
#Sidef
|
Sidef
|
require('Image::Imlib2')
func tograyscale(img) {
var (width, height) = (img.width, img.height)
var gimg = %s'Image::Imlib2'.new(width, height)
for y,x in (^height ~X ^width) {
var (r, g, b) = img.query_pixel(x, y)
var gray = int(0.2126*r + 0.7152*g + 0.0722*b)
gimg.set_color(gray, gray, gray, 255)
gimg.draw_point(x, y)
}
return gimg
}
var (input='input.png', output='output.png') = ARGV...
var image = %s'Image::Imlib2'.load(input)
var gscale = tograyscale(image)
gscale.set_quality(80)
gscale.save(output)
|
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).
|
#FunL
|
FunL
|
native scala.collection.mutable.Queue
val hamming =
q2 = Queue()
q3 = Queue()
q5 = Queue()
def enqueue( n ) =
q2.enqueue( n*2 )
q3.enqueue( n*3 )
q5.enqueue( n*5 )
def stream =
val n = min( min(q2.head(), q3.head()), q5.head() )
if q2.head() == n then q2.dequeue()
if q3.head() == n then q3.dequeue()
if q5.head() == n then q5.dequeue()
enqueue( n )
n # stream()
for q <- [q2, q3, q5] do q.enqueue( 1 )
stream()
|
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
|
#LOLCODE
|
LOLCODE
|
HAI 1.3
VISIBLE "SEED ME, FEMUR! "!
I HAS A seed, GIMMEH seed
HOW IZ I randomizin
seed R MOD OF SUM OF 1 AN PRODUKT OF 69069 AN seed AN 10
IF U SAY SO
I IZ randomizin MKAY
I HAS A answer ITZ SUM OF seed AN 1
I HAS A guess
IM IN YR guesser
VISIBLE "WUTS MY NUMBR? "!
GIMMEH guess, guess IS NOW A NUMBR
BOTH SAEM guess AN answer, O RLY?
YA RLY, VISIBLE "U WIN!", GTFO
OIC
IM OUTTA YR guesser
KTHXBYE
|
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
|
#Lua
|
Lua
|
math.randomseed( os.time() )
n = math.random( 1, 10 )
print( "I'm thinking of a number between 1 and 10. Try to guess it: " )
repeat
x = tonumber( io.read() )
if x == n then
print "Well guessed!"
else
print "Guess again: "
end
until x == n
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Liberty_BASIC
|
Liberty BASIC
|
'Greatest_subsequential_sum
N= 20 'number of elements
randomize 0.52
for K = 1 to 5
a$ = using("##",int(rnd(1)*12)-5)
for i=2 to N
a$ = a$ +","+using("##",int(rnd(1)*12)-5)
next
call maxsumseq a$
next K
sub maxsumseq a$
sum=0
maxsum=0
sumStart=1
end1 =0
start1 =1
token$="*"
i=0
while 1
i=i+1
token$=word$(a$, i, ",")
if token$ ="" then exit while 'end of stream
x=val(token$)
sum=sum+x
if maxsum<sum then
maxsum = sum
start1 = sumStart
end1 = i
else
if sum <0 then
sum=0
sumStart = i+1
end if
end if
wend
print "sequence: ";a$
print " ";
for i=1 to start1-1: print " "; :next
for i= start1 to end1: print "---"; :next
print
if end1 >0 then
print "Maximum sum subsequense: ";start1 ;" to "; end1
else
print "Maximum sum subsequense: is empty"
end if
print "Maximum sum ";maxsum
print
end sub
|
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)
|
#FOCAL
|
FOCAL
|
01.01 S T=0
01.02 A "LOWER LIMIT",L
01.03 A "UPPER LIMIT",H
01.04 I (H-L)1.05,1.05,1.06
01.05 T "INVALID RANGE",!;G 1.02
01.06 S S=FITR(L+FRAN()*(H-L+1))
01.10 A "GUESS",G
01.11 I (H-G)1.13,1.12,1.12
01.12 I (G-L)1.13,1.14,1.14
01.13 T "OUT OF RANGE",!;G 1.1
01.14 S T=T+1
01.15 I (G-S)1.16,1.17,1.18
01.16 T "TOO LOW!",!;G 1.1
01.17 T "CORRECT! GUESSES",%4,T,!;Q
01.18 T "TOO HIGH!",!;G 1.1
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
|
Guess the number/With feedback (player)
|
Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the 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
|
#UNIX_Shell
|
UNIX Shell
|
read -p "Lower bound: " lower
read -p "Upper bound: " upper
moves=0
PS3="> "
while :; do
((moves++))
guess=$(( lower + (upper-lower)/2 ))
echo "Is it $guess?"
select ans in "too small" "too big" "got it!"; do
case $ans in
"got it!") break 2 ;;
"too big") upper=$(( upper==guess ? upper-1 : guess )); break ;;
"too small") lower=$(( lower==guess ? lower+1 : guess )); break ;;
esac
done
((lower>upper)) && echo "you must be cheating!"
done
echo "I guessed it in $moves guesses"
|
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
|
#Go
|
Go
|
package main
import "fmt"
func happy(n int) bool {
m := make(map[int]bool)
for n > 1 {
m[n] = true
var x int
for x, n = n, 0; x > 0; x /= 10 {
d := x % 10
n += d * d
}
if m[n] {
return false
}
}
return true
}
func main() {
for found, n := 0, 1; found < 8; n++ {
if happy(n) {
fmt.Print(n, " ")
found++
}
}
fmt.Println()
}
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, 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.
|
#SAS
|
SAS
|
options minoperator;
%macro haver(lat1, long1, lat2, long2, type=D, dist=K);
%if %upcase(&type) in (D DEG DEGREE DEGREES) %then %do;
%let convert = constant('PI')/180;
%end;
%else %if %upcase(&type) in (R RAD RADIAN RADIANS) %then %do;
%let convert = 1;
%end;
%else %do;
%put ERROR - Enter RADIANS or DEGREES for type.;
%goto exit;
%end;
%if %upcase(&dist) in (M MILE MILES) %then %do;
%let distrat = 1.609344;
%end;
%else %if %upcase(&dist) in (K KM KILOMETER KILOMETERS) %then %do;
%let distrat = 1;
%end;
%else %do;
%put ERROR - Enter M on KM for dist;
%goto exit;
%end;
data _null_;
convert = &convert;
lat1 = &lat1 * convert;
lat2 = &lat2 * convert;
long1 = &long1 * convert;
long2 = &long2 * convert;
diff1 = lat2 - lat1;
diff2 = long2 - long1;
part1 = sin(diff1/2)**2;
part2 = cos(lat1)*cos(lat2);
part3 = sin(diff2/2)**2;
root = sqrt(part1 + part2*part3);
dist = 2 * 6372.8 / &distrat * arsin(root);
put "Distance is " dist "%upcase(&dist)";
run;
%exit:
%mend;
%haver(36.12, -86.67, 33.94, -118.40);
|
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
|
#Haxe
|
Haxe
|
trace("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
|
#Rust
|
Rust
|
fn is_harshad (n : u32) -> bool {
let sum_digits = n.to_string()
.chars()
.map(|c| c.to_digit(10).unwrap())
.fold(0, |a, b| a+b);
n % sum_digits == 0
}
fn main() {
for i in (1u32..).filter(|num| is_harshad(*num)).take(20) {
println!("Harshad : {}", i);
}
for i in (1_001u32..).filter(|num| is_harshad(*num)).take(1) {
println!("First Harshad bigger than 1_000 : {}", i);
}
}
|
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
|
#Objeck
|
Objeck
|
use Qt;
bundle Default {
class QtExample {
function : Main(args : String[]) ~ Nil {
app := QAppliction->New();
win := QWidget->New();
win->Resize(400, 300);
win->SetWindowTitle("Goodbye, World!");
win->Show();
app->Exec();
app->Delete();
}
}
}
|
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.
|
#Groovy
|
Groovy
|
def grayEncode = { i ->
i ^ (i >>> 1)
}
def grayDecode;
grayDecode = { int code ->
if(code <= 0) return 0
def h = grayDecode(code >>> 1)
return (h << 1) + ((code ^ h) & 1)
}
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The 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.
|
#Haskell
|
Haskell
|
import Data.Bits
import Data.Char
import Numeric
import Control.Monad
import Text.Printf
grayToBin :: (Integral t, Bits t) => t -> t
grayToBin 0 = 0
grayToBin g = g `xor` (grayToBin $ g `shiftR` 1)
binToGray :: (Integral t, Bits t) => t -> t
binToGray b = b `xor` (b `shiftR` 1)
showBinary :: (Integral t, Show t) => t -> String
showBinary n = showIntAtBase 2 intToDigit n ""
showGrayCode :: (Integral t, Bits t, PrintfArg t, Show t) => t -> IO ()
showGrayCode num = do
let bin = showBinary num
let gray = showBinary (binToGray num)
printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray
main = forM_ [0..31::Int] showGrayCode
|
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
|
#R
|
R
|
system("wc -l /etc/passwd /etc/group", intern = TRUE)
|
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
|
#Racket
|
Racket
|
#lang racket/base
(require racket/system
(only-in racket/port with-output-to-string)
tests/eli-tester)
(test
;; system runs command and outputs to current output port (which is stdout unless we catch it)
(system "ls /etc/motd") => #t
;; it throws an error on non-zero exit code (so I need to catch it in this error handler)
(system "false") => #f ; nothing printed to stdout/stderr
(system "ls /etc/mosh") => #f ; error report printed to stderr
;; output can be captured by redirecting stdout/stderr (which are known as current-output-port and
;; current-error-port in racket parlance).
;; the command printed a \n, so there is a newline captured by the system command
(with-output-to-string (λ () (system "ls /etc/motd"))) => "/etc/motd\n"
;; no \n is captured when none is captured
(with-output-to-string (λ () (system "echo -n foo"))) => "foo"
;; error is still not captured (it's still printed to stderr)
(with-output-to-string (λ () (system "echo -n foo; echo bar 1>&2"))) => "foo"
;; we can capture both with:
(let* ((out-str-port (open-output-string))
(err-str-port (open-output-string))
(system-rv
(parameterize ((current-output-port out-str-port) (current-error-port err-str-port))
(system "echo -n foo; echo bar 1>&2"))))
(values system-rv (get-output-string out-str-port) (get-output-string err-str-port)))
=> (values #t "foo" "bar\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
|
#Raku
|
Raku
|
say run($command, $arg1, $arg2, :out).out.slurp;
|
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
|
#REXX
|
REXX
|
/*REXX program executes a system command and displays the results (from an array). */
parse arg xxxCmd /*obtain the (system) command from CL.*/
trace off /*suppress REXX error msgs for fails. */
@.= 0 /*assign default in case ADDRESS fails.*/
address system xxxCmd with output stem @. /*issue/execute the command and parms. */
if rc\==0 then say copies('─', 40) ' return code ' rc " from: " xxxCmd
/* [↑] display if an error occurred.*/
do #=1 for @.0 /*display the output from the command. */
say strip(@.#, 'T') /*display one line at a time──►terminal*/
end /*#*/ /* [↑] displays all the output. */
exit 0 /*stick a fork in it, we're all done. */
|
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!
|
#Arturo
|
Arturo
|
swap: function [a,b]-> @[b,a]
c: 1
d: 2
print [c d]
[c,d]: swap c d
print [c d]
|
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.
|
#BQN
|
BQN
|
Max ← ⌈´
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Arturo
|
Arturo
|
print gcd [10 15]
|
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.
|
#Phix
|
Phix
|
without js -- file i/o
procedure global_replace(string s, string r, sequence file_list)
for i=1 to length(file_list) do
string filename = file_list[i]
integer fn = open(filename,"rb")
if fn=-1 then ?9/0 end if -- message/retry?
string text = get_text(fn)
close(fn)
text = substitute(text,s,r)
fn = open(filename,"wb")
puts(fn,text)
close(fn)
end for
end procedure
sequence file_list = {"ctrace.out"}
global_replace("Goodbye London!", "Hello New York!", file_list)
|
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.
|
#PicoLisp
|
PicoLisp
|
(for File '(a.txt b.txt c.txt)
(call 'mv File (tmp File))
(out File
(in (tmp File)
(while (echo "Goodbye London!")
(prin "Hello New York!") ) ) ) )
|
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).
|
#Bracmat
|
Bracmat
|
(
( hailstone
= L len
. !arg:?L
& whl
' ( !arg:~1
& (!arg*1/2:~/|3*!arg+1):?arg
& !arg !L:?L
)
& (!L:? [?len&!len.!L)
)
& ( reverse
= L e
. :?L
& whl'(!arg:%?e ?arg&!e !L:?L)
& !L
)
& hailstone$27:(?len.?list)
& reverse$!list:?first4 [4 ? [-5 ?last4
& put$"Hailstone sequence starting with "
& put$!first4
& put$(str$(" has " !len " elements and ends with "))
& put$(!last4 \n)
& 1:?N
& 0:?max:?Nmax
& whl
' ( !N+1:<100000:?N
& hailstone$!N
: ( >!max:?max&!N:?Nmax
| ?
. ?
)
)
& out
$ ( str
$ ( "The number <100000 with the longest hailstone sequence is "
!Nmax
" with "
!max
" elements."
)
)
);
|
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.
|
#Tcl
|
Tcl
|
package require Tk
proc grayscale image {
set w [image width $image]
set h [image height $image]
for {set x 0} {$x<$w} {incr x} {
for {set y 0} {$y<$h} {incr y} {
lassign [$image get $x $y] r g b
set l [expr {int(0.2126*$r + 0.7152*$g + 0.0722*$b)}]
$image put [format "#%02x%02x%02x" $l $l $l] -to $x $y
}
}
}
|
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.
|
#Vedit_macro_language
|
Vedit macro language
|
// Convert RGB image to grayscale (8 bit/pixel)
// #10 = buffer that contains image data
// On return:
// #20 = buffer for the new grayscale image
:RGB_TO_GRAYSCALE:
File_Open("|(VEDIT_TEMP)\gray.data", OVERWRITE+NOEVENT+NOMSG)
#20 = Buf_Num
BOF
Del_Char(ALL)
Buf_Switch(#10)
Repeat(File_Size/3) {
#9 = Cur_Char() * 2126
#9 += Cur_Char(1) * 7152
#9 += Cur_Char(2) * 722
Char(3)
Buf_Switch(#20)
Ins_Char(#9 / 10000)
Buf_Switch(#10)
}
Return
|
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.C5.8Drmul.C3.A6
|
Fōrmulæ
|
package main
import (
"fmt"
"math/big"
)
func min(a, b *big.Int) *big.Int {
if a.Cmp(b) < 0 {
return a
}
return b
}
func hamming(n int) []*big.Int {
h := make([]*big.Int, n)
h[0] = big.NewInt(1)
two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5)
next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5)
i, j, k := 0, 0, 0
for m := 1; m < len(h); m++ {
h[m] = new(big.Int).Set(min(next2, min(next3, next5)))
if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) }
if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) }
if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) }
}
return h
}
func main() {
h := hamming(1e6)
fmt.Println(h[:20])
fmt.Println(h[1691-1])
fmt.Println(h[len(h)-1])
}
|
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
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module QBASIC_Based {
supervisor:
GOSUB initialize
GOSUB guessing
GOTO continue
initialize:
\\ Not need to RANDOMIZE TIMER
\\ we can use Random(1, 100) to get a number from 1 to 100
n = 0: r = INT(RND * 100 + 1): g = 0: c$ = ""
RETURN
guessing:
WHILE g <> r {
INPUT "Pick a number between 1 and 100:"; g
IF g = r THEN {
PRINT "You got it!"
n ++
PRINT "It took "; n; " tries to pick the right number."
} ELSE.IF g < r THEN {
PRINT "Try a larger number."
n ++
} ELSE {
PRINT "Try a smaller number."
n++
}
}
RETURN
continue:
WHILE c$ <> "YES" AND c$ <> "NO" {
INPUT "Do you want to continue? (YES/NO)"; c$
c$ = UCASE$(c$)
IF c$ = "YES" THEN {
GOTO supervisor
} ELSE.IF c$ = "NO" THEN {
Goto End
}
}
End:
}
QBASIC_Based
|
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
|
#Maple
|
Maple
|
GuessNumber := proc()
local number;
randomize():
printf("Guess a number between 1 and 10 until you get it right:\n:");
number := rand(1..10)();
while parse(readline()) <> number do
printf("Try again!\n:");
end do:
printf("Well guessed! The answer was %d.\n", number);
end proc:
|
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.
|
#Lua
|
Lua
|
function sumt(t, start, last) return start <= last and t[start] + sumt(t, start+1, last) or 0 end
function maxsub(ary, idx)
local idx = idx or 1
if not ary[idx] then return {} end
local maxsum, last = 0, idx
for i = idx, #ary do
if sumt(ary, idx, i) > maxsum then maxsum, last = sumt(ary, idx, i), i end
end
local v = maxsub(ary, idx + 1)
if maxsum < sumt(v, 1, #v) then return v end
local ret = {}
for i = idx, last do ret[#ret+1] = ary[i] end
return ret
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)
|
#Fortran
|
Fortran
|
program Guess_a_number
implicit none
integer, parameter :: limit = 100
integer :: guess, number
real :: rnum
write(*, "(a, i0, a)") "I have chosen a number between 1 and ", limit, &
" and you have to try to guess it."
write(*, "(a/)") "I will score your guess by indicating whether it is higher, lower or the same as that number"
call random_seed
call random_number(rnum)
number = rnum * limit + 1
do
write(*, "(a)", advance="no") "Enter quess: "
read*, guess
if(guess < number) then
write(*, "(a/)") "That is lower"
else if(guess > number) then
write(*, "(a/)") "That is higher"
else
write(*, "(a)") "That is correct"
exit
end if
end do
end program
|
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
|
#VBA
|
VBA
|
Sub GuessNumberPlayer()
Dim iGuess As Integer, iLow As Integer, iHigh As Integer, iCount As Integer
Dim vSolved As Variant
On Error GoTo ErrHandler
MsgBox "Pick a number between 1 and 100. I will guess it!", vbInformation + vbOKOnly, "Rosetta Code | Guess the Number Player"
iCount = 0
iLow = 1
iHigh = 100
Do While Not vSolved = "Y"
iGuess = Application.WorksheetFunction.RandBetween(iLow, iHigh)
iCount = iCount + 1
CheckGuess:
vSolved = InputBox("My guess: " & iGuess & vbCr & vbCr & "Y = Yes, correct guess" & vbCr & _
"H = your number is higher" & vbCr & "L = your number is lower" & vbCr & "X = exit game", "Rosetta Code | Guess the Number Player | Guess " & iCount)
Select Case vSolved
Case "Y", "y": GoTo CorrectGuess
Case "X", "x": Exit Sub
Case "H", "h": iLow = iGuess + 1
Case "L", "l": iHigh = iGuess - 1
Case Else: GoTo CheckGuess
End Select
Loop
CorrectGuess:
MsgBox "I guessed number " & iGuess & " in just " & iCount & " attempts!", vbExclamation + vbOKOnly, "Rosetta Code | Guess the Number Player"
Exit Sub
ErrHandler:
MsgBox "Not possible. Were you cheating?!", vbCritical + vbOKOnly, "Rosetta Code | Guess the Number Player | ERROR!"
End Sub
|
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
|
#Wren
|
Wren
|
import "io" for Stdin, Stdout
import "/str" for Char
var hle
var lowest = 1
var highest = 20
var guess = 10
System.print("Please choose a number between 1 and 20 but don't tell me what it is yet\n")
while (true) {
System.print("My guess is %(guess)")
while (true) {
System.write("Is this higher/lower than or equal to your chosen number h/l/e : ")
Stdout.flush()
hle = Char.lower(Stdin.readLine())
if (hle == "l" && guess == highest) {
System.print("It can't be more than %(highest), try again")
hle = "i" // signifies invalid
} else if (hle == "h" && guess == lowest) {
System.print("It can't be less than %(lowest), try again")
hle = "i"
}
if ("hle".contains(hle)) break
}
if (hle == "e") {
System.print("Good, thanks for playing the game with me!")
break
}
if (hle == "h") {
if (highest > guess - 1) highest = guess - 1
} else {
if (lowest < guess + 1) lowest = guess + 1
}
guess = ((lowest + highest)/2).floor
}
|
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
|
#Groovy
|
Groovy
|
Number.metaClass.isHappy = {
def number = delegate as Long
def cycle = new HashSet<Long>()
while (number != 1 && !cycle.contains(number)) {
cycle << number
number = (number as String).collect { d = (it as Long); d * d }.sum()
}
number == 1
}
def matches = []
for (int i = 0; matches.size() < 8; i++) {
if (i.happy) { matches << i }
}
println matches
|
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.
|
#Scala
|
Scala
|
import math._
object Haversine {
val R = 6372.8 //radius in km
def haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double)={
val dLat=(lat2 - lat1).toRadians
val dLon=(lon2 - lon1).toRadians
val a = pow(sin(dLat/2),2) + pow(sin(dLon/2),2) * cos(lat1.toRadians) * cos(lat2.toRadians)
val c = 2 * asin(sqrt(a))
R * c
}
def main(args: Array[String]): Unit = {
println(haversine(36.12, -86.67, 33.94, -118.40))
}
}
|
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
|
#hexiscript
|
hexiscript
|
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
|
#Scala
|
Scala
|
object Harshad extends App {
val harshads = Stream.from(1).filter(i => i % i.toString.map(_.asDigit).sum == 0)
println(harshads.take(20).toList)
println(harshads.filter(_ > 1000).head)
}
|
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
|
#Objective-C
|
Objective-C
|
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Goodbye, World!"];
[alert runModal];
|
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
|
#OCaml
|
OCaml
|
let delete_event evt = false
let destroy () = GMain.Main.quit ()
let main () =
let window = GWindow.window in
let _ = window#set_title "Goodbye, World" in
let _ = window#event#connect#delete ~callback:delete_event in
let _ = window#connect#destroy ~callback:destroy in
let _ = window#show () in
GMain.Main.main ()
;;
let _ = main () ;;
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
link bitint
procedure main()
every write(right(i := 0 to 10,4),":",right(int2bit(i),10)," -> ",
right(g := gEncode(i),10)," -> ",
right(b := gDecode(g),10)," -> ",
right(bit2int(b),10))
end
procedure gEncode(b)
return int2bit(ixor(b, ishift(b,-1)))
end
procedure gDecode(g)
b := g[1]
every i := 2 to *g do b ||:= if g[i] == b[i-1] then "0" else "1"
return b
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
|
#Ring
|
Ring
|
system("dir C:\Ring\doc")
|
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
|
#Ruby
|
Ruby
|
str = `ls`
arr = `ls`.lines
|
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
|
#Run_BASIC
|
Run BASIC
|
a$ = shell$("dir") ' Returns the directory info into a$
print a$ ' prints the directory
|
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
|
#Rust
|
Rust
|
use std::process::Command;
use std::io::{Write, self};
fn main() {
let output = Command::new("/bin/cat")
.arg("/etc/fstab")
.output()
.expect("failed to execute process");
io::stdout().write(&output.stdout);
}
|
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
|
#Scala
|
Scala
|
import scala.io.Source
val command = "cmd /c echo Time at %DATE% %TIME%"
val p = Runtime.getRuntime.exec(command)
val sc = Source.fromInputStream(p.getInputStream)
println(sc.mkString)
|
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!
|
#AutoHotkey
|
AutoHotkey
|
Swap(ByRef Left, ByRef Right)
{
temp := Left
Left := Right
Right := temp
}
|
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.
|
#Bracmat
|
Bracmat
|
( biggest
= max
. !arg:
| !arg:%?max ?arg
& !arg:? (%@:>!max:?max) (?&~)
| !max
)
& out$("1:" biggest$(5 100000 -5 aap 3446 NOOT mies 0))
& out$("2:" biggest$)
& out
$ ( "3:"
biggest
$ (5 100000 -5 43756243978569758/13 3365864921428443 87512487957139516/27 3446)
)
|
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.
|
#ATS
|
ATS
|
(********************************************************************)
(*
GCD of two integers, by Stein’s algorithm:
https://en.wikipedia.org/w/index.php?title=Binary_GCD_algorithm&oldid=1072393147
This is an implementation without proofs of anything.
The implementations shown here require the GCC builtin functions
for ‘count trailing zeros’. If your C compiler is GCC or another
that supports those functions, you are fine. Otherwise, one could
easily substitute other C code.
Compile with ‘patscc -o gcd gcd.dats’.
*)
#define ATS_EXTERN_PREFIX "rosettacode_gcd_"
#define ATS_DYNLOADFLAG 0 (* No initialization is needed. *)
#include "share/atspre_define.hats"
#include "share/atspre_staload.hats"
(********************************************************************)
(* *)
(* Declarations of the functions. *)
(* *)
(* g0uint_gcd_stein will be the generic template function for
unsigned integers. *)
extern fun {tk : tkind}
g0uint_gcd_stein :
(g0uint tk, g0uint tk) -<> g0uint tk
(* g0int_gcd_stein will be the generic template function for
signed integers, giving an unsigned result. *)
extern fun {tk_signed, tk_unsigned : tkind}
g0int_gcd_stein :
(g0int tk_signed, g0int tk_signed) -<> g0uint tk_unsigned
(* Let us call these functions ‘gcd_stein’ or just ‘gcd’. *)
overload gcd_stein with g0uint_gcd_stein
overload gcd_stein with g0int_gcd_stein
overload gcd with gcd_stein
(********************************************************************)
(* *)
(* The implementations. *)
(* *)
%{^
/*
We will need a ‘count trailing zeros of a positive number’ function,
but this is not provided in the ATS prelude. Here are
implementations using GCC builtin functions. For fast alternatives
in standard C, see
https://www.chessprogramming.org/index.php?title=BitScan&oldid=22495#Trailing_Zero_Count
*/
ATSinline() atstype_uint
rosettacode_gcd_g0uint_ctz_uint (atstype_uint x)
{
return __builtin_ctz (x);
}
ATSinline() atstype_ulint
rosettacode_gcd_g0uint_ctz_ulint (atstype_ulint x)
{
return __builtin_ctzl (x);
}
ATSinline() atstype_ullint
rosettacode_gcd_g0uint_ctz_ullint (atstype_ullint x)
{
return __builtin_ctzll (x);
}
%}
extern fun g0uint_ctz_uint : uint -<> int = "mac#%"
extern fun g0uint_ctz_ulint : ulint -<> int = "mac#%"
extern fun g0uint_ctz_ullint : ullint -<> int = "mac#%"
(* A generic template function for ‘count trailing zeros’ of
non-dependent unsigned integers. *)
extern fun {tk : tkind} g0uint_ctz : g0uint tk -<> int
(* Link the implementations to the template function. *)
implement g0uint_ctz<uint_kind> (x) = g0uint_ctz_uint x
implement g0uint_ctz<ulint_kind> (x) = g0uint_ctz_ulint x
implement g0uint_ctz<ullint_kind> (x) = g0uint_ctz_ullint x
(* Let one call the function simply ‘ctz’. *)
overload ctz with g0uint_ctz
(* Now the actual implementation of g0uint_gcd_stein, the template
function for the gcd of two unsigned integers. *)
implement {tk}
g0uint_gcd_stein (u, v) =
let
(* Make ‘t’ a shorthand for the unsigned integer type. *)
typedef t = g0uint tk
(* Use this macro to fake proof that an int is non-negative. *)
macdef nonneg (n) = $UNSAFE.cast{intGte 0} ,(n)
(* Looping is done by tail recursion. There is no proof
the function terminates; this fact is indicated by
‘<!ntm>’. *)
fun {tk : tkind}
main_loop (x_odd : t, y : t) :<!ntm> t =
let
(* Remove twos from y, giving an odd number.
Note gcd(x_odd,y_odd) = gcd(x_odd,y). *)
val y_odd = (y >> nonneg (ctz y))
in
if x_odd = y_odd then
x_odd
else
let
(* If y_odd < x_odd then swap x_odd and y_odd.
This operation does not affect the gcd. *)
val x_odd = min (x_odd, y_odd)
and y_odd = max (x_odd, y_odd)
in
main_loop (x_odd, y_odd - x_odd)
end
end
fn
u_and_v_both_positive (u : t, v : t) :<> t =
let
(* n = the number of common factors of two in u and v. *)
val n = ctz (u lor v)
(* Remove the common twos from u and v, giving x and y. *)
val x = (u >> nonneg n)
val y = (v >> nonneg n)
(* Remove twos from x, giving an odd number.
Note gcd(x_odd,y) = gcd(x,y). *)
val x_odd = (x >> nonneg (ctz x))
(* Run the main loop, but pretend it is proven to
terminate. Otherwise we could not write ‘<>’ above,
telling the ATS compiler that we trust the function
to terminate. *)
val z = $effmask_ntm (main_loop (x_odd, y))
in
(* Put the common factors of two back in. *)
(z << nonneg n)
end
(* If v < u then swap u and v. This operation does not
affect the gcd. *)
val u = min (u, v)
and v = max (u, v)
in
if iseqz u then
v
else
u_and_v_both_positive (u, v)
end
(* The implementation of g0int_gcd_stein, the template function for
the gcd of two signed integers, giving an unsigned result. *)
implement {signed_tk, unsigned_tk}
g0int_gcd_stein (u, v) =
let
val abs_u = $UNSAFE.cast{g0uint unsigned_tk} (abs u)
val abs_v = $UNSAFE.cast{g0uint unsigned_tk} (abs v)
in
g0uint_gcd_stein<unsigned_tk> (abs_u, abs_v)
end
(********************************************************************)
(* A demonstration program. *)
implement
main0 () =
begin
(* Unsigned integers. *)
assertloc (gcd (0U, 10U) = 10U);
assertloc (gcd (9UL, 6UL) = 3UL);
assertloc (gcd (40902ULL, 24140ULL) = 34ULL);
(* Signed integers. *)
assertloc (gcd (0, 10) = gcd (0U, 10U));
assertloc (gcd (~10, 0) = gcd (0U, 10U));
assertloc (gcd (~6L, ~9L) = 3UL);
assertloc (gcd (40902LL, 24140LL) = 34ULL);
assertloc (gcd (40902LL, ~24140LL) = 34ULL);
assertloc (gcd (~40902LL, 24140LL) = 34ULL);
assertloc (gcd (~40902LL, ~24140LL) = 34ULL);
assertloc (gcd (24140LL, 40902LL) = 34ULL);
assertloc (gcd (~24140LL, 40902LL) = 34ULL);
assertloc (gcd (24140LL, ~40902LL) = 34ULL);
assertloc (gcd (~24140LL, ~40902LL) = 34ULL)
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.
|
#PowerBASIC
|
PowerBASIC
|
$matchtext = "Goodbye London!"
$repltext = "Hello New York!"
FUNCTION PBMAIN () AS LONG
DIM L0 AS INTEGER, filespec AS STRING, linein AS STRING
L0 = 1
WHILE LEN(COMMAND$(L0))
filespec = DIR$(COMMAND$(L0))
WHILE LEN(filespec)
OPEN filespec FOR BINARY AS 1
linein = SPACE$(LOF(1))
GET #1, 1, linein
' No need to jump through FB's hoops here...
REPLACE $matchtext WITH $repltext IN linein
PUT #1, 1, linein
SETEOF #1
CLOSE
filespec = DIR$
WEND
INCR L0
WEND
END FUNCTION
|
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.
|
#PowerShell
|
PowerShell
|
$listfiles = @('file1.txt','file2.txt')
$old = 'Goodbye London!'
$new = 'Hello New York!'
foreach($file in $listfiles) {
(Get-Content $file).Replace($old,$new) | Set-Content $file
}
|
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.
|
#PureBasic
|
PureBasic
|
Procedure GRTISF(List File$(), Find$, Replace$)
Protected Line$, Out$, OutFile$, i
ForEach File$()
fsize=FileSize(File$())
If fsize<=0: Continue: EndIf
If ReadFile(0, File$())
i=0
;
; generate a temporary file in a safe way
Repeat
file$=GetTemporaryDirectory()+base$+"_"+Str(i)+".tmp"
i+1
Until FileSize(file$)=-1
i=CreateFile(FileID, file$)
If i
; Copy the infile to the outfile while replacing any needed text
While Not Eof(0)
Line$=ReadString(0)
Out$=ReplaceString(Line$,Find$,Replace$)
WriteString(1,Out$)
Wend
CloseFile(1)
EndIf
CloseFile(0)
If i
; If we made a new file, copy it back.
CopyFile(file$, File$())
DeleteFile(file$)
EndIf
EndIf
Next
EndProcedure
|
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).
|
#Brainf.2A.2A.2A
|
Brainf***
|
>>>>>>,>,>,<<
[
.[-<+>]
]
>
[
.[-<+>]
]
>
[
.[-<+>]
]
<<<<
>------------------------------------------------[<<+>>-]>
[
<<<
[<+>-]<
[>++++++++++<-]>
>>>
------------------------------------------------
[<<<+>>>-]>
[
<<<<
[<+>-]<
[>++++++++++<-]>
>>>>
------------------------------------------------
[<<<<+>>>>-]
]
<
<<<[>+<<<+>>-]>[-<+>]>>>>>>>>>++++[>+++++++++++<-]++++[>>++++++++<<-]<<<<<<<<<<
[
>>>>>>>>>>+>.>.<<<<<<<<<<<<
>>+>+<<<
[-[->]<]+
>>>[>]
<[-<]<[-]<
[>+>+<<-]>[<+>-]+
>[
<<<[->>>>+>+>+<<<<<<]>>>>>>
[-<<<<<<+>>>>>>]<[-<<<<<+>>>>>]<[-<<<<+>>>>]
<<<<+>>
-
>[-]]
<<[-]>[
<<[-<+>[-<->>>>>+>]<<<<<]>>>>[-<<<<+>>>>]<<
-]
<<[->+>+<<]>[-<+>]>
[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]
++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<[.[-]<]<
-[+>]<
]
[This program never terminates! ]
[This program isn't complete, (it only prints the hailstone ]
[sequence of a number until 1) but it may help other people ]
[to make complete versions. ]
[ ]
[This program only takes in up to 3 digit numbers as input ]
[If you want to input 1 digit integers, add a 0 before. e.g ]
[04. ]
[ ]
[Summary: ]
[This program takes 16 memory cells of space. Their data is ]
[presented below: ]
[ ]
[Cell 0: Temp cell. ]
[Cell 1: Displays the current number. This changes based on ]
[Collatz' Conjecture. ]
[Cell 14: Displays length of the hailstone sequence. ]
[Cell 15: ASCII code for ",". ]
[Cell 16: ASCII code for " " (Space). ]
[Rest of the cells: Temp cells. ]
|
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.
|
#Visual_Basic
|
Visual Basic
|
Option Explicit
Private Type BITMAP
bmType As Long
bmWidth As Long
bmHeight As Long
bmWidthBytes As Long
bmPlanes As Integer
bmBitsPixel As Integer
bmBits As Long
End Type
Private Type RGB
Red As Byte
Green As Byte
Blue As Byte
Alpha As Byte
End Type
Private Type RGBColor
Color As Long
End Type
Public Declare Function CreateCompatibleDC Lib "gdi32.dll" (ByVal hdc As Long) As Long
Public Declare Function GetObjectA Lib "gdi32.dll" (ByVal hObject As Long, ByVal nCount As Long, ByRef lpObject As Any) As Long
Public Declare Function SelectObject Lib "gdi32.dll" (ByVal hdc As Long, ByVal hObject As Long) As Long
Public Declare Function GetPixel Lib "gdi32.dll" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long) As Long
Public Declare Function SetPixel Lib "gdi32.dll" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal crColor As Long) As Long
Public Declare Function DeleteDC Lib "gdi32.dll" (ByVal hdc As Long) As Long
Sub Main()
Dim p As stdole.IPictureDisp
Dim hdc As Long
Dim bmp As BITMAP
Dim i As Long, x As Long, y As Long
Dim tRGB As RGB, cRGB As RGBColor
Set p = VB.LoadPicture("T:\TestData\Input_Colored.bmp")
GetObjectA p.Handle, Len(bmp), bmp
hdc = CreateCompatibleDC(0)
SelectObject hdc, p.Handle
For x = 0 To bmp.bmWidth - 1
For y = 0 To bmp.bmHeight - 1
cRGB.Color = GetPixel(hdc, x, y)
LSet tRGB = cRGB
i = (0.2126 * tRGB.Red + 0.7152 * tRGB.Green + 0.0722 * tRGB.Blue)
SetPixel hdc, x, y, RGB(i, i, i)
Next y
Next x
VB.SavePicture p, "T:\TestData\Output_GrayScale.bmp"
DeleteDC hdc
End Sub
|
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).
|
#Go
|
Go
|
package main
import (
"fmt"
"math/big"
)
func min(a, b *big.Int) *big.Int {
if a.Cmp(b) < 0 {
return a
}
return b
}
func hamming(n int) []*big.Int {
h := make([]*big.Int, n)
h[0] = big.NewInt(1)
two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5)
next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5)
i, j, k := 0, 0, 0
for m := 1; m < len(h); m++ {
h[m] = new(big.Int).Set(min(next2, min(next3, next5)))
if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) }
if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) }
if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) }
}
return h
}
func main() {
h := hamming(1e6)
fmt.Println(h[:20])
fmt.Println(h[1691-1])
fmt.Println(h[len(h)-1])
}
|
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
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
number = RandomInteger[{1, 10}];
While[guess =!= number, guess = Input["Guess my number"]];
Print["Well guessed!"]
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, 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
|
#MATLAB
|
MATLAB
|
number = ceil(10*rand(1));
[guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));
while (~status || guess ~= number)
[guess, status] = str2num(input('Guess again: ','s'));
end
disp('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.
|
#M4
|
M4
|
divert(-1)
define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1,
incr($2),shift(shift(shift($@))))')')
define(`asize',decr(setrange(`a',1,-1,-2,3,5,6,-2,-1,4,-4,2,-1)))
define(`get',`defn(`$1[$2]')')
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`maxsum',0)
for(`x',1,asize,
`define(`sum',0)`'for(`y',x,asize,
`define(`sum',eval(sum+get(`a',y)))`'ifelse(eval(sum>maxsum),1,
`define(`maxsum',sum)`'define(`xmax',x)`'define(`ymax',y)')')')
divert
for(`x',xmax,ymax,`get(`a',x) ')
|
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.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
Sequences[m_]:=Prepend[Flatten[Table[Partition[Range[m],n,1],{n,m}],1],{}]
MaximumSubsequence[x_List]:=Module[{sums},
sums={x[[#]],Total[x[[#]]]}&/@Sequences[Length[x]];
First[First[sums[[Ordering[sums,-1,#1[[2]]<#2[[2]]&]]]]]
]
|
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)
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Randomize
Dim n As Integer = Int(Rnd * 20) + 1
Dim guess As Integer
Print "Guess which number I've chosen in the range 1 to 20"
Print
Do
Input " Your guess : "; guess
If guess > n AndAlso guess <= 20 Then
Print "Your guess is higher than the chosen number, try again "
ElseIf guess = n Then
Print "Correct, well guessed!"
Exit Do
ElseIf guess < n AndAlso guess >= 1 Then
Print "Your guess is lower than the chosen number, try again"
Else
Print "Your guess is inappropriate, try again"
End If
Loop
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
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
int Hi, Lo, Guess;
[Text(0, "Think of a number between 1 and 100 then press a key.");
if ChIn(1) then [];
Lo:= 1; Hi:= 101;
loop [Guess:= (Lo+Hi)/2;
Text(0, "^M^JIs it "); IntOut(0, Guess);
Text(0, " (Y = yes, H = too high, L = too low)? ");
case ChIn(1) of
^L,^l: Lo:= Guess;
^H,^h: Hi:= Guess;
^Y,^y: quit
other ChOut(0, 7\bel\);
];
Text(0, "^M^JYippee!");
]
|
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
|
#zkl
|
zkl
|
println("Pick a number between 0 and 100 and remember it.");
low,high,g := 0,100, 20;
while(True){
r:=ask("I guess %d; is that high, low or =? ".fmt(g)).strip().toLower();
if(r=="="){ println("Yea!"); break; }
if(r[0]=="h") high=g-1 else low=g+1;
if(low==high){ println("Yea! the number is ",low); break; }
if(low>high){ println("I'm confused!"); break; }
g=(low + high)/2;
}
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not 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
|
#Harbour
|
Harbour
|
PROCEDURE Main()
LOCAL i := 8, nH := 0
? hb_StrFormat( "The first %d happy numbers are:", i )
?
WHILE i > 0
IF IsHappy( ++nH )
?? hb_NtoS( nH ) + " "
--i
ENDIF
END
RETURN
STATIC FUNCTION IsHappy( nNumber )
STATIC aUnhappy := {}
LOCAL nDigit, nSum := 0, cNumber := hb_NtoS( nNumber )
FOR EACH nDigit IN cNumber
nSum += Val( nDigit ) ^ 2
NEXT
IF nSum == 1
aUnhappy := {}
RETURN .T.
ELSEIF AScan( aUnhappy, nSum ) > 0
RETURN .F.
ENDIF
AAdd( aUnhappy, nSum )
RETURN IsHappy( nSum )
|
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.
|
#Scheme
|
Scheme
|
(define earth-radius 6371)
(define pi (acos -1))
(define (distance lat1 long1 lat2 long2)
(define (h a b) (expt (sin (/ (- b a) 2)) 2))
(* 2 earth-radius (asin (sqrt (+ (h lat1 lat2) (* (cos lat1) (cos lat2) (h long1 long2)))))))
(define (deg-to-rad d m s) (* (/ pi 180) (+ d (/ m 60) (/ s 3600))))
(distance (deg-to-rad 36 7.2 0) (deg-to-rad 86 40.2 0)
(deg-to-rad 33 56.4 0) (deg-to-rad 118 24.0 0))
; 2886.444442837984
|
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
|
#HicEst
|
HicEst
|
WRITE() '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
|
#Scheme
|
Scheme
|
#!/usr/local/bin/gosh
;; Show the first 20 niven numbers and the
;; first one greater than 1000.
(define (main args)
(display (iota-filtered 20 1 niven?))(newline)
(display (iota-filtered 1 1001 niven?))(newline))
;; Return a list of length n
;; for numbers starting at start
;; that satisfy the predicate fn.
(define (iota-filtered n start fn)
(let loop ((num start)(lst (list)))
(if (= (length lst) n)
lst
(loop (+ 1 num) (if (fn num) (append lst (list num)) lst)))))
;; Is a number a niven number?
(define (niven? n)
(and (> n 0) (= 0 (remainder n (sum-of-digits n)))))
;; Get the sum of the digits of a number.
(define (sum-of-digits n)
(apply + (map string->number (map string (string->list (number->string n))))))
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Ol
|
Ol
|
(import (lib winapi))
(MessageBox #f (c-string "Hello, World!") (c-string "Rosettacode") #x40)
|
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
|
#OpenEdge.2FProgress
|
OpenEdge/Progress
|
MESSAGE "Goodbye, World!" VIEW-AS ALERT-BOX.
|
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.
|
#J
|
J
|
G2B=: ~:/\&.|:
|
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.
|
#Java
|
Java
|
public class Gray {
public static long grayEncode(long n){
return n ^ (n >>> 1);
}
public static long grayDecode(long n) {
long p = n;
while ((n >>>= 1) != 0)
p ^= n;
return p;
}
public static void main(String[] args){
System.out.println("i\tBinary\tGray\tDecoded");
for(int i = -1; i < 32;i++){
System.out.print(i +"\t");
System.out.print(Integer.toBinaryString(i) + "\t");
System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
System.out.println(grayDecode(grayEncode(i)));
}
}
}
|
http://rosettacode.org/wiki/Get_system_command_output
|
Get system command output
|
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
|
#Sidef
|
Sidef
|
var output = `ls` # `output` is a string
var lines = `ls`.lines # `lines` is an array
|
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
|
#Stata
|
Stata
|
program shellout, rclass
tempfile f
tempname m
shell `0' > `f'
file open `m' using "`f'", read binary
file seek `m' eof
file seek `m' query
local n=r(loc)
if `n'>0 {
file seek `m' tof
file read `m' %`n's s
file close `m'
return local out "`s'"
}
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
|
#Swift
|
Swift
|
import Foundation
let process = Process()
process.launchPath = "/usr/bin/env"
process.arguments = ["pwd"]
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String.init(data: data, encoding: String.Encoding.utf8)
print(output!)
|
http://rosettacode.org/wiki/Get_system_command_output
|
Get system command output
|
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
|
#Standard_ML
|
Standard ML
|
val useOS = fn input =>
let
val text = String.translate (fn #"\"" => "\\\""|n=>str n ) input ;
val shellCommand = " echo " ^ text ^ "| gzip -c " ;
val fname = "/tmp/fConv" ^ (String.extract (Time.toString (Posix.ProcEnv.time()),7,NONE) );
val me = ( Posix.FileSys.mkfifo
(fname,
Posix.FileSys.S.flags [ Posix.FileSys.S.irusr,Posix.FileSys.S.iwusr ]
) ;
Posix.Process.fork ()
) ;
in
if (Option.isSome me) then
let
val fin =BinIO.openIn fname
in
( Posix.Process.sleep (Time.fromReal 0.1) ;
BinIO.inputAll fin before
(BinIO.closeIn fin ; OS.FileSys.remove fname )
)
end
else
( OS.Process.system ( shellCommand ^ " > " ^ fname ^ " 2>&1 " ) ;
Word8Vector.fromList [] before OS.Process.exit OS.Process.success
)
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
|
#Tcl
|
Tcl
|
set data [exec ls -l]
puts "read [string length $data] bytes and [llength [split $data \n]] lines"
|
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!
|
#AWK
|
AWK
|
# syntax: GAWK -f GENERIC_SWAP.AWK
BEGIN {
printf("%s version %s\n",ARGV[0],PROCINFO["version"])
foo = 1
bar = "a"
printf("\n%s %s\n",foo,bar)
rc = swap("foo","bar") # ok
printf("%s %s %s\n",foo,bar,rc?"ok":"ng")
printf("\n%s %s\n",foo,bar)
rc = swap("FOO","BAR") # ng
printf("%s %s %s\n",foo,bar,rc?"ok":"ng")
exit(0)
}
function swap(a1,a2, tmp) { # strings or numbers only; no arrays
if (a1 in SYMTAB && a2 in SYMTAB) {
if (isarray(SYMTAB[a1]) || isarray(SYMTAB[a2])) {
return(0)
}
tmp = SYMTAB[a1]
SYMTAB[a1] = SYMTAB[a2]
SYMTAB[a2] = tmp
return(1)
}
return(0)
}
|
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.
|
#Brat
|
Brat
|
max = { list |
list.reduce { n, max |
true? n > max
{ max = n }
{ max }
}
}
p max [3 4 1 2]
|
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.
|
#AutoHotkey
|
AutoHotkey
|
GCD(a,b) {
Return b=0 ? Abs(a) : Gcd(b,mod(a,b))
}
|
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
|
Globally replace text in several files
|
Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
|
#Python
|
Python
|
import fileinput
for line in fileinput.input(inplace=True):
print(line.replace('Goodbye London!', 'Hello New York!'), 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.
|
#Racket
|
Racket
|
#!/usr/bin/env racket
#lang racket
(define from-string #f)
(define to-string #f)
(command-line
#:once-each
[("-f") from "Text to remove" (set! from-string from)]
[("-t") to "Text to put instead" (set! to-string to)]
#:args files
(unless from-string (error "No `from' string specified"))
(unless to-string (error "No `to' string specified"))
(when (null? files) (error "No files given"))
(define from-rx (regexp (regexp-quote from-string)))
(for ([file files])
(printf "Editing ~a..." file) (flush-output)
(define text1 (file->string file))
(define text2 (regexp-replace* from-rx text1 to-string))
(if (equal? text1 text2)
(printf " no change\n")
(begin (display-to-file text2 file #:exists 'replace)
(printf " modified copy saved in place\n")))))
|
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
|
Globally replace text in several files
|
Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
|
#Raku
|
Raku
|
slurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_)
for <a.txt b.txt c.txt>;
|
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).
|
#Brat
|
Brat
|
hailstone = { num |
sequence = [num]
while { num != 1 }
{ true? num % 2 == 0
{ num = num / 2 }
{ num = num * 3 + 1 }
sequence << num
}
sequence
}
#Check sequence for 27
seq = hailstone 27
true? (seq[0,3] == [27 82 41 124] && seq[-1, -4] == [8 4 2 1])
{ p "Sequence for 27 is correct" }
{ p "Sequence for 27 is not correct!" }
#Find longest sequence for numbers < 100,000
longest = [number: 0 length: 0]
1.to 99999 { index |
seq = hailstone index
true? seq.length > longest[:length]
{ longest[:length] = seq.length
longest[:number] = index
p "Longest so far: #{index} @ #{longest[:length]} elements"
}
index = index + 1
}
p "Longest was starting from #{longest[:number]} and was of length #{longest[:length]}"
|
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.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Drawing.Imaging
Public Function Grayscale(ByVal Map As Bitmap) As Bitmap
Dim oData() As Integer = GetData(Map)
Dim oReturn As New Bitmap(Map.Width, Map.Height, Map.PixelFormat)
Dim a As Integer = 0
Dim r As Integer = 0
Dim g As Integer = 0
Dim b As Integer = 0
Dim l As Integer = 0
For i As Integer = 0 To oData.GetUpperBound(0)
a = (oData(i) >> 24)
r = (oData(i) >> 16) And 255
g = (oData(i) >> 8) And 255
b = oData(i) And 255
l = CInt(r * 0.2126F + g * 0.7152F + b * 0.0722F)
oData(i) = (a << 24) Or (l << 16) Or (l << 8) Or l
Next
SetData(oReturn, oData)
Return oReturn
End Function
Private Function GetData(ByVal Map As Bitmap) As Integer()
Dim oBMPData As BitmapData = Nothing
Dim oData() As Integer = Nothing
oBMPData = Map.LockBits(New Rectangle(0, 0, Map.Width, Map.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
Array.Resize(oData, Map.Width * Map.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oData, 0, oData.Length)
Map.UnlockBits(oBMPData)
Return oData
End Function
Private Sub SetData(ByVal Map As Bitmap, ByVal Data As Integer())
Dim oBMPData As BitmapData = Nothing
oBMPData = Map.LockBits(New Rectangle(0, 0, Map.Width, Map.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
Runtime.InteropServices.Marshal.Copy(Data, 0, oBMPData.Scan0, Data.Length)
Map.UnlockBits(oBMPData)
End Sub
|
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).
|
#Groovy
|
Groovy
|
class Hamming {
static final ONE = BigInteger.ONE
static final THREE = BigInteger.valueOf(3)
static final FIVE = BigInteger.valueOf(5)
static void main(args) {
print 'Hamming(1 .. 20) ='
(1..20).each {
print " ${hamming it}"
}
println "\nHamming(1691) = ${hamming 1691}"
println "Hamming(1000000) = ${hamming 1000000}"
}
static hamming(n) {
def priorityQueue = new PriorityQueue<BigInteger>()
priorityQueue.add ONE
def lowest
n.times {
lowest = priorityQueue.poll()
while (priorityQueue.peek() == lowest) {
priorityQueue.poll()
}
updateQueue(priorityQueue, lowest)
}
lowest
}
static updateQueue(priorityQueue, lowest) {
priorityQueue.add(lowest.shiftLeft 1)
priorityQueue.add(lowest.multiply THREE)
priorityQueue.add(lowest.multiply FIVE)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.