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/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
|
#HQ9.2B
|
HQ9+
|
H
|
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
|
#Tcl
|
Tcl
|
# Determine if the given number is a member of the class of Harshad numbers
proc isHarshad {n} {
if {$n < 1} {return false}
set sum [tcl::mathop::+ {*}[split $n ""]]
return [expr {$n%$sum == 0}]
}
# Get the first 20 numbers that satisfy the condition
for {set n 1; set harshads {}} {[llength $harshads] < 20} {incr n} {
if {[isHarshad $n]} {
lappend harshads $n
}
}
puts [format "First twenty Harshads: %s" [join $harshads ", "]]
# Get the first value greater than 1000 that satisfies the condition
for {set n 1000} {![isHarshad [incr n]]} {} {}
puts "First Harshad > 1000 = $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
|
#PHP
|
PHP
|
if (!class_exists('gtk'))
{
die("Please load the php-gtk2 module in your php.ini\r\n");
}
$wnd = new GtkWindow();
$wnd->set_title('Goodbye world');
$wnd->connect_simple('destroy', array('gtk', 'main_quit'));
$lblHello = new GtkLabel("Goodbye, World!");
$wnd->add($lblHello);
$wnd->show_all();
Gtk::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.
|
#Logo
|
Logo
|
to gray_encode :number
output bitxor :number lshift :number -1
end
to gray_decode :code
local "value
make "value 0
while [:code > 0] [
make "value bitxor :code :value
make "code lshift :code -1
]
output :value
end
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Lua
|
Lua
|
local _M = {}
local bit = require('bit')
local math = require('math')
_M.encode = function(number)
return bit.bxor(number, bit.rshift(number, 1));
end
_M.decode = function(gray_code)
local value = 0
while gray_code > 0 do
gray_code, value = bit.rshift(gray_code, 1), bit.bxor(gray_code, value)
end
return value
end
return _M
|
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!
|
#BASIC256
|
BASIC256
|
global a, b
a = "one"
b = "two"
print a, b
call swap(a, b)
print a, b
end
subroutine swap(a, b)
temp = a : a = b : b = temp
end subroutine
|
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.
|
#CFEngine
|
CFEngine
|
bundle agent __main__
{
vars:
"number_of_list_elements"
int => randomint( "0", 100 ),
unless => isvariable( "$(this.promiser)" );
"idx"
slist => expandrange( "[0-$(number_of_list_elements)]", 1 ),
unless => isvariable( "$(this.promiser)" );
"number[$(idx)]"
int => randomint( "0", "100" ),
unless => isvariable( "$(this.promiser)" );
"numbers" slist => sort( getvalues( number ), int );
methods:
"Get the greatest value"
usebundle => greatest_value( @(numbers) ),
useresult => "returned";
reports:
"'$(returned[max])' is the largest number in $(with)"
with => join( ",", numbers );
}
bundle agent greatest_value(list_of_values)
{
reports:
"$(with)"
with => max( list_of_values, int ),
bundle_return_value_index => "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.
|
#BASIC256
|
BASIC256
|
function gcdI(x, y)
while y
t = y
y = x mod y
x = t
end while
return x
end function
# ------ test ------
a = 111111111111111
b = 11111
print : print "GCD(";a;", ";b;") = "; gcdI(a, b)
print : print "GCD(";a;", 111) = "; gcdI(a, 111)
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.
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
files="a.txt'b.txt'c.txt"
BUILD S_TABLE search = ":Goodbye London!:"
LOOP file=files
ERROR/STOP OPEN (file,WRITE,-std-)
ERROR/STOP CREATE ("scratch",FDF-o,-std-)
ACCESS q: READ/STREAM/RECORDS/UTF8 $file s,aken+text/search+eken
ACCESS s: WRITE/ERASE/STREAM/UTF8 "scratch" s,aken+text+eken
LOOP
READ/EXIT q
IF (text.ct.search) SET text="Hello New York!"
WRITE/ADJUST s
ENDLOOP
ENDACCESS/PRINT q
ENDACCESS/PRINT s
ERROR/STOP COPY ("scratch",file)
ERROR/STOP CLOSE (file)
ENDLOOP
ERROR/STOP DELETE ("scratch")
|
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.
|
#TXR
|
TXR
|
@(next :args)
@(repeat)
@file
@(next `@file`)
@(freeform)
@(coll :gap 0)@notmatch@{match /Goodbye, London!/}@(end)@*tail@/\n/
@(output `@file.tmp`)
@(rep)@{notmatch}Hello, New York!@(end)@tail
@(end)
@(do @(rename-path `@file.tmp` file))
@(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.
|
#UNIX_Shell
|
UNIX Shell
|
replace() {
local search=$1 replace=$2
local file lines line
shift 2
for file in "$@"; do
lines=()
while IFS= read -r line; do
lines+=( "${line//$search/$replace}" )
done < "$file"
printf "%s\n" "${lines[@]}" > "$file"
done
}
replace "Goodbye London!" "Hello New York!" 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).
|
#Ceylon
|
Ceylon
|
shared void run() {
{Integer*} hailstone(variable Integer n) {
variable [Integer*] stones = [n];
while(n != 1) {
n = if(n.even) then n / 2 else 3 * n + 1;
stones = stones.append([n]);
}
return stones;
}
value hs27 = hailstone(27);
print("hailstone sequence for 27 is ``hs27.take(3)``...``hs27.skip(hs27.size - 3).take(3)`` with length ``hs27.size``");
variable value longest = hailstone(1);
for(i in 2..100k - 1) {
value current = hailstone(i);
if(current.size > longest.size) {
longest = current;
}
}
print("the longest sequence under 100,000 starts with ``longest.first else "what?"`` and has length ``longest.size``");
}
|
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).
|
#JavaScript
|
JavaScript
|
function hamming() {
var queues = {2: [], 3: [], 5: []};
var base;
var next_ham = 1;
while (true) {
yield next_ham;
for (base in queues) {queues[base].push(next_ham * base)}
next_ham = [ queue[0] for each (queue in queues) ].reduce(function(min, val) {
return Math.min(min,val)
});
for (base in queues) {if (queues[base][0] == next_ham) queues[base].shift()}
}
}
var ham = hamming();
var first20=[], i=1;
for (; i <= 20; i++)
first20.push(ham.next());
print(first20.join(', '));
print('...');
for (; i <= 1690; i++)
ham.next();
print(i + " => " + ham.next());
|
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
|
#Nim
|
Nim
|
import strutils, random
randomize()
var chosen = rand(1..10)
echo "I have thought of a number. Try to guess it!"
var guess = parseInt(readLine(stdin))
while guess != chosen:
echo "Your guess was wrong. Try again!"
guess = parseInt(readLine(stdin))
echo "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
|
#NS-HUBASIC
|
NS-HUBASIC
|
10 NUMBER=RND(10)+1
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
30 IF GUESS<>NUMBER THEN PRINT "INCORRECT GUESS. TRY AGAIN.": GOTO 20
40 PRINT "CORRECT NUMBER."
|
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.
|
#Pascal
|
Pascal
|
Program GreatestSubsequentialSum(output);
var
a: array[1..11] of integer = (-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1);
i, j: integer;
seqStart, seqEnd: integer;
maxSum, seqSum: integer;
begin
maxSum := 0;
seqStart := 0;
seqEnd := -1;
for i := low(a) to high(a) do
begin
seqSum := 0;
for j := i to high(a) do
begin
seqSum := seqSum + a[j];
if seqSum > maxSum then
begin
maxSum := seqSum;
seqStart := i;
seqEnd := j;
end;
end;
end;
writeln ('Sequence: ');
for i := low(a) to high(a) do
write (a[i]:3);
writeln;
writeln ('Subsequence with greatest sum: ');
for i := low(a) to seqStart - 1 do
write (' ':3);
for i := seqStart to seqEnd do
write (a[i]:3);
writeln;
writeln ('Sum:');
writeln (maxSum);
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)
|
#HolyC
|
HolyC
|
U8 n, *g;
U8 min = 1, max = 100;
n = min + RandU16 % max;
Print("Guess the number between %d and %d: ", min, max);
while(1) {
g = GetStr;
if (Str2I64(g) == n) {
Print("You guessed correctly!\n");
break;
}
if (Str2I64(g) < n)
Print("Your guess was too low.\nTry again: ");
if (Str2I64(g) > n)
Print("Your guess was too high.\nTry again: ");
}
|
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
|
#jq
|
jq
|
def is_happy_number:
def next: tostring | explode | map( (. - 48) | .*.) | add;
def last(g): reduce g as $i (null; $i);
# state: either 1 or [i, o]
# where o is an an object with the previously encountered numbers as keys
def loop:
recurse( if . == 1 then empty # all done
elif .[0] == 1 then 1 # emit 1
else (.[0]| next) as $n
| if $n == 1 then 1
elif .[1]|has($n|tostring) then empty
else [$n, (.[1] + {($n|tostring):true}) ]
end
end );
1 == last( [.,{}] | loop );
|
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.
|
#TechBASIC
|
TechBASIC
|
{{trans|BASIC}}
FUNCTION HAVERSINE
!---------------------------------------------------------------
!*** Haversine Formula - Calculate distances by LAT/LONG
!
!*** LAT/LON of the two locations and Unit of measure are GLOBAL
!*** as they are defined in the main logic of the program, so they
!*** available for use in the Function.
!*** Usage: X=HAVERSINE
Radius=6378.137
Lat1=(Lat1*MATH.PI/180)
Lon1=(Lon1*MATH.PI/180)
Lat2=(Lat2*MATH.PI/180)
Lon2=(Lon2*MATH.PI/180)
DLon=Lon1-Lon2
ANSWER=ACOS(SIN(Lat1)*SIN(Lat2)+COS(Lat1)*COS(Lat2)*COS(DLon))*Radius
DISTANCE="kilometers"
SELECT CASE UNIT
CASE "M"
HAVERSINE=ANSWER*0.621371192
Distance="miles"
CASE "N"
HAVERSINE=ANSWER*0.539956803
Distance="nautical miles"
END SELECT
END FUNCTION
|
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.
|
#Teradata_Stored_Procedure
|
Teradata Stored Procedure
|
# syntax: CALL SP_HAVERSINE(36.12,33.94,-86.67,-118.40,x);
CREATE PROCEDURE SP_HAVERSINE
(
IN lat1 FLOAT,
IN lat2 FLOAT,
IN lon1 FLOAT,
IN lon2 FLOAT,
OUT distance FLOAT)
BEGIN
DECLARE dLat FLOAT;
DECLARE dLon FLOAT;
DECLARE c FLOAT;
DECLARE a FLOAT;
DECLARE km FLOAT;
SET dLat = RADIANS(lat2-lat1);
SET dLon = RADIANS(lon2-lon1);
SET a = SIN(dLat / 2) * SIN(dLat / 2) + SIN(dLon / 2) * SIN(dLon / 2) * COS(RADIANS(lat1)) * COS(RADIANS(lat2));
SET c = 2 * ASIN(SQRT(a));
SET km = 6372.8 * c;
SELECT km INTO distance;
END;
|
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
|
#Huginn
|
Huginn
|
#! /bin/sh
exec huginn --no-argv -E "${0}" "${@}"
#! huginn
main() {
print( "Hello World!\n" );
return ( 0 );
}
|
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
|
#uBasic.2F4tH
|
uBasic/4tH
|
C=0
For I = 1 Step 1 Until C = 20 ' First 20 Harshad numbers
If FUNC(_FNHarshad(I)) Then Print I;" "; : C = C + 1
Next
For I = 1001 Step 1 ' First Harshad greater than 1000
If FUNC(_FNHarshad(I)) Then Print I;" " : Break
Next
End
_FNHarshad Param(1)
Local(2)
c@ = a@
b@ = 0
Do While (c@ > 0)
b@ = b@ + (c@ % 10)
c@ = c@ / 10
Loop
Return ((a@ % b@) = 0)
|
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
|
#PicoLisp
|
PicoLisp
|
(call 'dialog "--msgbox" "Goodbye, World!" 5 20)
|
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
|
#Plain_English
|
Plain English
|
To run:
Start up.
Clear the screen.
Write "Goodbye, World!".
Refresh the screen.
Wait for the escape key.
Shut down.
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module Code32 (&code(), &decode()){
Const d$="{0::-2} {1:-6} {2:-6} {3:-6} {4::-2}"
For i=0 to 32
g=code(i)
b=decode(g)
Print format$(d$, i, @bin$(i), @bin$(g), @bin$(b), b)
Next
// static function
Function bin$(a)
a$=""
Do n= a mod 2 : a$=if$(n=1->"1", "0")+a$ : a|div 2 : Until a==0
=a$
End Function
}
Module GrayCode {
Module doit (&a(), &b()) { }
Function GrayEncode(a) {
=binary.xor(a, binary.shift(a,-1))
}
Function GrayDecode(a) {
b=0
Do b=binary.xor(a, b) : a=binary.shift(a,-1) : Until a==0
=b
}
// pass 2 functions to Code32
doit &GrayEncode(), &GrayDecode()
}
// pass Code32 to GrayCode in place of doit
GrayCode ; doit as Code32
|
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.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
graycode[n_]:=BitXor[n,BitShiftRight[n]]
graydecode[n_]:=Fold[BitXor,0,FixedPointList[BitShiftRight,n]]
|
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!
|
#BBC_BASIC
|
BBC BASIC
|
a = 1.23 : b = 4.56
SWAP a,b
PRINT a,b
a$ = "Hello " : b$ = "world!"
SWAP a$,b$
PRINT a$,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.
|
#Clojure
|
Clojure
|
(max 1 2 3 4) ; evaluates to 4
;; If the values are already in a collection, use apply:
(apply max [1 2 3 4]) ; evaluates to 4
|
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.
|
#Batch_File
|
Batch File
|
:: gcd.cmd
@echo off
:gcd
if "%2" equ "" goto :instructions
if "%1" equ "" goto :instructions
if %2 equ 0 (
set final=%1
goto :done
)
set /a res = %1 %% %2
call :gcd %2 %res%
goto :eof
:done
echo gcd=%final%
goto :eof
:instructions
echo Syntax:
echo GCD {a} {b}
echo.
|
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.
|
#VBScript
|
VBScript
|
Const ForReading = 1
Const ForWriting = 2
strFiles = Array("test1.txt", "test2.txt", "test3.txt")
With CreateObject("Scripting.FileSystemObject")
For i = 0 To UBound(strFiles)
strText = .OpenTextFile(strFiles(i), ForReading).ReadAll()
With .OpenTextFile(strFiles(i), ForWriting)
.Write Replace(strText, "Goodbye London!", "Hello New York!")
.Close
End With
Next
End With
|
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.
|
#Vedit_macro_language
|
Vedit macro language
|
File_Open("files.lst") // list of files to process
#20 = Reg_Free // text register for filename
While(!At_EOF) {
Reg_Copy_Block(#20, Cur_Pos, EOL_Pos)
File_Open(@(#20))
Replace("Goodbye London!", "Hello New York!", BEGIN+ALL+NOERR)
Buf_Close(NOMSG)
Line(1, ERRBREAK)
}
Reg_Empty(#20) // Cleanup
Buf_Quit(OK)
|
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.
|
#Wren
|
Wren
|
import "io" for File
var files = ["file1.txt", "file2.txt"]
for (file in files) {
var text = File.read(file)
System.print("%(file) contains: %(text)")
text = text.replace("Goodbye London!", "Hello New York!")
File.create(file) { |f| // overwrites existing file
f.writeBytes(text)
}
System.print("%(file) now contains: %(File.read(file))")
}
|
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).
|
#CLIPS
|
CLIPS
|
(deftemplate longest
(slot bound) ; upper bound for the range of values to check
(slot next (default 2)) ; next value that needs to be checked
(slot start (default 1)) ; starting value of longest sequence
(slot len (default 1)) ; length of longest sequence
)
(deffacts startup
(query 27)
(longest (bound 100000))
)
(deffunction hailstone-next
(?n)
(if (evenp ?n)
then (div ?n 2)
else (+ (* 3 ?n) 1)
)
)
(defrule extend-sequence
?hail <- (hailstone $?sequence ?tail&:(> ?tail 1))
=>
(retract ?hail)
(assert (hailstone ?sequence ?tail (hailstone-next ?tail)))
)
(defrule start-query
(query ?num)
=>
(assert (hailstone ?num))
)
(defrule result-query
(query ?num)
(hailstone ?num $?sequence 1)
=>
(bind ?sequence (create$ ?num ?sequence 1))
(printout t "Hailstone sequence starting with " ?num ":" crlf)
(bind ?len (length ?sequence))
(printout t " Length: " ?len crlf)
(printout t " First four: " (implode$ (subseq$ ?sequence 1 4)) crlf)
(printout t " Last four: " (implode$ (subseq$ ?sequence (- ?len 3) ?len)) crlf)
(printout t crlf)
)
(defrule longest-create-next-hailstone
(longest (bound ?bound) (next ?next))
(test (<= ?next ?bound))
(not (hailstone ?next $?))
=>
(assert (hailstone ?next))
)
(defrule longest-check-next-hailstone
?longest <- (longest (bound ?bound) (next ?next) (start ?start) (len ?len))
(test (<= ?next ?bound))
?hailstone <- (hailstone ?next $?sequence 1)
=>
(retract ?hailstone)
(bind ?thislen (+ 2 (length ?sequence)))
(if (> ?thislen ?len) then
(modify ?longest (start ?next) (len ?thislen) (next (+ ?next 1)))
else
(modify ?longest (next (+ ?next 1)))
)
)
(defrule longest-finished
(longest (bound ?bound) (next ?next) (start ?start) (len ?len))
(test (> ?next ?bound))
=>
(printout t "The number less than " ?bound " that has the largest hailstone" crlf)
(printout t "sequence is " ?start " with a length of " ?len "." crlf)
(printout t crlf)
)
|
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).
|
#jq
|
jq
|
# Return the index in the input array of the min_by(f) value
def index_min_by(f):
. as $in
| if length == 0 then null
else .[0] as $first
| reduce range(0; length) as $i
([0, $first, ($first|f)]; # state: [ix; min; f|min]
($in[$i]|f) as $v
| if $v < .[2] then [ $i, $in[$i], $v ] else . end)
| .[0]
end;
# Emit n Hamming numbers if n>0; the nth if n<0
def hamming(n):
# input: [twos, threes, fives] of which at least one is assumed to be non-empty
# output: the index of the array holding the min of the firsts
def next: map( .[0] ) | index_min_by(.);
# input: [value, [twos, threes, fives] ....]
# ix is the index in [twos, threes, fives] of the array to be popped
# output: [popped, updated_arrays ...]
def pop(ix):
.[1] as $triple
| setpath([0]; $triple[ix][0])
| setpath([1,ix]; $triple[ix][1:]);
# input: [x, [twos, threes, fives], count]
# push value*2 to twos, value*3 to threes, value*5 to fives and increment count
def push(v):
[.[0], [.[1][0] + [2*v], .[1][1] + [3*v], .[1][2] + [5*v]], .[2] + 1];
# _hamming is the workhorse
# input: [previous, [twos, threes, fives], count]
def _hamming:
.[0] as $previous
| if (n > 0 and .[2] == n) or (n<0 and .[2] == -n) then $previous
else (.[1]|next) as $ix # $ix cannot be null
| pop($ix)
| .[0] as $next
| (if $next == $previous then empty elif n>=0 then $previous else empty end),
(if $next == $previous then . else push($next) end | _hamming)
end;
[1, [[2],[3],[5]], 1] | _hamming;
. as $n | hamming($n)
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, 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
|
#Oberon-2
|
Oberon-2
|
MODULE GuessTheNumber;
IMPORT
RandomNumbers,
In,
Out;
PROCEDURE Do;
VAR
n,guess: LONGINT;
BEGIN
n := RandomNumbers.RND(10);
Out.String("Guess a number between 1 and 10: ");Out.Flush();
LOOP
In.LongInt(guess);
IF guess = n THEN
Out.String("You guessed!!"); Out.Ln; EXIT
END;
Out.String(" Sorry, try again: ");Out.Flush()
END
END Do;
BEGIN
Do;
END GuessTheNumber.
|
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
|
#Objeck
|
Objeck
|
use IO;
bundle Default {
class GuessNumber {
function : Main(args : String[]) ~ Nil {
done := false;
"Guess the number which is between 1 and 10 or 'q' to quite: "->PrintLine();
rand_num := (Float->Random() * 10.0)->As(Int) + 1;
while(done = false) {
guess := Console->ReadString();
number := guess->ToInt();
if(number <> 0) {
if(number <> rand_num) {
"Guess again: "->PrintLine();
}
else {
"Hurray! You guessed correctly!"->PrintLine();
done := true;
};
}
else {
if(guess->StartsWith("q") | guess->StartsWith("Q")) {
done := true;
};
};
};
}
}
}
|
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.
|
#Perl
|
Perl
|
use strict;
sub max_sub(\@) {
my ($a, $maxs, $maxe, $s, $sum, $maxsum) = shift;
foreach (0 .. $#$a) {
my $t = $sum + $a->[$_];
($s, $sum) = $t > 0 ? ($s, $t) : ($_ + 1, 0);
if ($maxsum < $sum) {
$maxsum = $sum;
($maxs, $maxe) = ($s, $_ + 1)
}
}
@$a[$maxs .. $maxe - 1]
}
my @a = map { int(rand(20) - 10) } 1 .. 10;
my @b = (-1) x 10;
print "seq: @a\nmax: [ @{[max_sub @a]} ]\n";
print "seq: @b\nmax: [ @{[max_sub @b]} ]\n";
|
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)
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
smallest := 5
highest := 25
n := smallest-1 + ?(1+highest-smallest)
repeat {
writes("Pick a number from ", smallest, " through ", highest, ": ")
guess := read ()
if n = numeric(guess)
then {
write ("Well guessed!")
exit ()
}
else if n < numeric(guess)
then write ("Your guess is too high")
else if n > numeric(guess)
then write ("Your guess is too low")
else write ("Did you enter a number?")
}
end
|
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
|
#Julia
|
Julia
|
function happy(x)
happy_ints = ref(Int)
int_try = 1
while length(happy_ints) < x
n = int_try
past = ref(Int)
while n != 1
n = sum([y^2 for y in digits(n)])
contains(past,n) ? break : push!(past,n)
end
n == 1 && push!(happy_ints,int_try)
int_try += 1
end
return happy_ints
end
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#Transact-SQL
|
Transact-SQL
|
CREATE FUNCTION [dbo].[Haversine](@Lat1 AS DECIMAL(9,7), @Lon1 AS DECIMAL(10,7), @Lat2 AS DECIMAL(9,7), @Lon2 AS DECIMAL(10,7))
RETURNS DECIMAL(12,7)
AS
BEGIN
DECLARE @R DECIMAL(11,7);
DECLARE @dLat DECIMAL(9,7);
DECLARE @dLon DECIMAL(10,7);
DECLARE @a DECIMAL(10,7);
DECLARE @c DECIMAL(10,7);
SET @R = 6372.8;
SET @dLat = RADIANS(@Lat2 - @Lat1);
SET @dLon = RADIANS(@Lon2 - @Lon1);
SET @Lat1 = RADIANS(@Lat1);
SET @Lat2 = RADIANS(@Lat2);
SET @a = SIN(@dLat / 2) * SIN(@dLat / 2) + SIN(@dLon / 2) * SIN(@dLon / 2) * COS(@Lat1) * COS(@Lat2);
SET @c = 2 * ASIN(SQRT(@a));
RETURN @R * @c;
END
GO
SELECT dbo.Haversine(36.12,-86.67,33.94,-118.4)
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#HTML5
|
HTML5
|
<!DOCTYPE html>
<html>
<body>
<h1>Hello world!</h1>
</body>
</html>
|
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
|
#VBA
|
VBA
|
Option Explicit
Sub Main()
Dim i As Long, out As String, Count As Integer
Do
i = i + 1
If IsHarshad(i) Then out = out & i & ", ": Count = Count + 1
Loop While Count < 20
Debug.Print "First twenty Harshad numbers are : " & vbCrLf & out & "..."
i = 1000
Do
i = i + 1
Loop While Not IsHarshad(i)
Debug.Print "The first harshad number after 1000 is : " & i
End Sub
Function IsHarshad(sNumber As Long) As Boolean
Dim Summ As Long, i As Long, temp
temp = Split(StrConv(sNumber, vbUnicode), Chr(0))
For i = LBound(temp) To UBound(temp) - 1
Summ = Summ + temp(i)
Next i
IsHarshad = sNumber Mod Summ = 0
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
|
#Portugol
|
Portugol
|
programa {
// includes graphics library and use an alias
inclua biblioteca Graficos --> g
// define WIDTH and HEIGHT integer constants
const inteiro WIDTH = 200
const inteiro HEIGHT = 100
// main entry
funcao inicio() {
// begin graphical mode (verdadeiro = true)
g.iniciar_modo_grafico(verdadeiro)
// define window title
g.definir_titulo_janela("Hello")
// define window dimesions
g.definir_dimensoes_janela(WIDTH, HEIGHT)
// while loop
enquanto (verdadeiro) {
// define color to black(preto) and clear window
g.definir_cor(g.COR_PRETO)
g.limpar()
// define color to white(branco)
g.definir_cor(g.COR_BRANCO)
// set text font size
g.definir_tamanho_texto(32.0)
// draws text
g.desenhar_texto(0, HEIGHT / 3, "Hello, world!")
// calls render function
g.renderizar()
}
// end graphical mode
g.encerrar_modo_grafico()
}
}
|
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
|
#PostScript
|
PostScript
|
%!PS
% render in Helvetica, 12pt:
/Helvetica findfont 12 scalefont setfont
% somewhere in the lower left-hand corner:
50 dup moveto
% render text
(Goodbye, World!) show
% wrap up page display:
showpage
|
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.
|
#MATLAB
|
MATLAB
|
%% Gray Code Generator
% this script generates gray codes of n bits
% total 2^n -1 continuous gray codes will be generated.
% this code follows a recursive approach. therefore,
% it can be slow for large n
clear all;
clc;
bits = input('Enter the number of bits: ');
if (bits<1)
disp('Sorry, number of bits should be positive');
elseif (mod(bits,1)~=0)
disp('Sorry, number of bits can only be positive integers');
else
initial_container = [0;1];
if bits == 1
result = initial_container;
else
previous_container = initial_container;
for i=2:bits
new_gray_container = zeros(2^i,i);
new_gray_container(1:(2^i)/2,1) = 0;
new_gray_container(((2^i)/2)+1:end,1) = 1;
for j = 1:(2^i)/2
new_gray_container(j,2:end) = previous_container(j,:);
end
for j = ((2^i)/2)+1:2^i
new_gray_container(j,2:end) = previous_container((2^i)+1-j,:);
end
previous_container = new_gray_container;
end
result = previous_container;
end
fprintf('Gray code of %d bits',bits);
disp(' ');
disp(result);
end
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in 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!
|
#Beads
|
Beads
|
beads 1 program 'Generic swap'
var
a = [1 2 "Beads" 3 4]
b = [1 2 "Language" 4 5]
calc main_init
swap a[4] <=> b[3]
|
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.
|
#CLU
|
CLU
|
% This "maximum" procedure is fully general, as long as
% the container type has an elements iterator and the
% data type is comparable.
% It raises an exception ("empty") if there are no elements.
maximum = proc [T,U: type] (a: T) returns (U)
signals (empty)
where T has elements: itertype (T) yields (U),
U has gt: proctype (U,U) returns (bool)
max: U
seen: bool := false
for item: U in T$elements(a) do
if ~seen cor item > max then
max := item
seen := true
end
end
if (~seen) then
signal empty
else
return(max)
end
end maximum
start_up = proc ()
po: stream := stream$primary_output()
% try it on an array of ints
ints: array[int] := array[int]$[1,5,17,2,53,99,61,3]
imax: int := maximum[array[int], int](ints)
stream$putl(po, "maximum int: " || int$unparse(imax))
% try it on a sequence of reals
reals: sequence[real] := sequence[real]$[-0.5, 2.6, 3.14, 2.72]
rmax: real := maximum[sequence[real], real](reals)
stream$putl(po, "maximum real: " || real$unparse(rmax))
end start_up
|
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.
|
#BBC_BASIC
|
BBC BASIC
|
DEF FN_GCD_Iterative_Euclid(A%, B%)
LOCAL C%
WHILE B%
C% = A%
A% = B%
B% = C% MOD B%
ENDWHILE
= ABS(A%)
|
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
|
Globally replace text in several files
|
Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
func StrLen(A); \Return number of characters in an ASCIIZ string
char A;
int I;
for I:= 0 to -1>>1-1 do
if A(I) = 0 then return I;
func StrFind(A, B); \Search for ASCIIZ string A in string B
\Returns address of first occurrence of string A in B, or zero if A is not found
char A, B; \strings to be compared
int LA, LB, I, J;
[LA:= StrLen(A);
LB:= StrLen(B);
for I:= 0 to LB-LA do
[for J:= 0 to LA-1 do
if A(J) # B(J+I) then J:= LA+1;
if J = LA then return B+I; \found
];
return 0;
];
proc ReplaceText(FileName); \replace text in specified file
char FileName;
char Str(1_000_000), Hello, Bye, Pointer;
int Handle, I, C;
[Handle:= FOpen(FileName, 0); \get handle for input file
FSet(Handle, ^I); \set device 3 input to file handle
OpenI(3); \initialize buffer pointers
I:= 0;
repeat C:= ChIn(3); \read file into memory
Str(I):= C;
I:= I+1;
until C = $1A; \EOF
FClose(Handle); \release handle
Hello:= "Hello New York!"; \replacement text
Bye:= "Goodbye London!";
Pointer:= StrFind(Bye, Str);
if Pointer \#0\ then \overwrite (both strings are same length)
for I:= 0 to 15-1 do Pointer(I):= Hello(I);
Handle:= FOpen(FileName, 1); \get handle for output file
FSet(Handle, ^O); \set device 3 output to file handle
OpenO(3);
I:= 0;
repeat C:= Str(I); \write file from memory
I:= I+1;
ChOut(3, C);
until C = $1A; \EOF
Close(3); \flush output buffer
FClose(Handle); \release handle
];
int File, I;
[File:= ["Alpha.txt", "Beta.txt", "Gamma.txt", "Delta.txt"];
for I:= 0 to 4-1 do ReplaceText(File(I));
]
|
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.
|
#zkl
|
zkl
|
fcn sed(data,src,dst){
srcSz:=src.len(); dstSz:=dst.len(); md5:=Utils.MD5.calc(data);
n:=0; while(Void!=(n:=data.find(src,n)))
{ data.del(n,srcSz); data.insert(n,dst); n+= dstSz; }
return(md5!=Utils.MD5.calc(data)); // changed?
}
fcn sedFile(fname,src,dst){
f:=File(fname,"r"); data:=f.read(); f.close();
if(sed(data,"Goodbye London!", "Hello New York!"))
{ f:=File(fname,"w"); f.write(data); f.close(); }
}
|
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).
|
#Clojure
|
Clojure
|
(defn hailstone-seq [n]
{:pre [(pos? n)]}
(lazy-seq
(cond (= n 1) '(1)
(even? n) (cons n (hailstone-seq (/ n 2)))
:else (cons n (hailstone-seq (+ (* n 3) 1))))))
(let [hseq (hailstone-seq 27)]
(-> hseq count (= 112) assert)
(->> hseq (take 4) (= [27 82 41 124]) assert)
(->> hseq (drop 108) (= [8 4 2 1]) assert))
(let [{max-i :num, max-len :len}
(reduce #(max-key :len %1 %2)
(for [i (range 1 100000)]
{:num i, :len (count (hailstone-seq i))}))]
(println "Maximum length" max-len "was found for hailstone(" max-i ")."))
|
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).
|
#Julia
|
Julia
|
function hammingsequence(N)
if N < 1
throw("Hamming sequence exponent must be a positive integer")
end
ham = N > 4000 ? Vector{BigInt}([1]) : Vector{Int}([1])
base2, base3, base5 = (1, 1, 1)
for i in 1:N-1
x = min(2ham[base2], 3ham[base3], 5ham[base5])
push!(ham, x)
if 2ham[base2] <= x
base2 += 1
end
if 3ham[base3] <= x
base3 += 1
end
if 5ham[base5] <= x
base5 += 1
end
end
ham
end
println(hammingsequence(20))
println(hammingsequence(1691)[end])
println(hammingsequence(1000000)[end])
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Objective-C
|
Objective-C
|
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"I'm thinking of a number between 1 - 10. Can you guess what it is?\n");
int rndNumber = arc4random_uniform(10) + 1;
// Debug (Show rndNumber in console)
//NSLog(@"Random number is %i", rndNumber);
int userInput;
do {
NSLog(@"Input the number below\n");
scanf("%i", &userInput);
if (userInput > 10) {
NSLog(@"Please enter a number less than 10\n");
}
if (userInput > 10 || userInput != rndNumber) {
NSLog(@"Your guess %i is incorrect, please try again", userInput);
} else {
NSLog(@"Your guess %i is correct!", userInput);
}
} while (userInput > 10 || userInput != rndNumber);
}
return 0;
}
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#OCaml
|
OCaml
|
#!/usr/bin/env ocaml
let () =
Random.self_init();
let n =
if Random.bool () then
let n = 2 + Random.int 8 in
print_endline "Please guess a number between 1 and 10 excluded";
(n)
else
let n = 1 + Random.int 10 in
print_endline "Please guess a number between 1 and 10 included";
(n)
in
while read_int () <> n do
print_endline "The guess was wrong! Please try again!"
done;
print_endline "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.
|
#Phix
|
Phix
|
with javascript_semantics
function maxSubseq(sequence s)
integer maxsum = 0, first = 1, last = 0
for i=1 to length(s) do
integer sumsij = 0
for j=i to length(s) do
sumsij += s[j]
if sumsij>maxsum then
{maxsum,first,last} = {sumsij,i,j}
end if
end for
end for
return s[first..last]
end function
? maxSubseq({-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1})
? maxSubseq({})
? maxSubseq({-1, -5, -3})
|
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)
|
#J
|
J
|
require 'misc'
game=: verb define
assert. y -: 1 >. <.{.y
n=: 1 + ?y
smoutput 'Guess my integer, which is bounded by 1 and ',":y
whilst. -. x -: n do.
x=. {. 0 ". prompt 'Guess: '
if. 0 -: x do. 'Giving up.' return. end.
smoutput (*x-n){::'You win.';'Too high.';'Too low.'
end.
)
|
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
|
#K
|
K
|
hpy: {x@&1={~|/x=1 4}{_+/_sqr 0$'$x}//:x}
hpy 1+!100
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100
8#hpy 1+!100
1 7 10 13 19 23 28 31
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#True_BASIC
|
True BASIC
|
DEF Haversine (lat1, long1, lat2, long2)
OPTION ANGLE RADIANS
LET R = 6372.8 !radio terrestre en km.
LET dLat = RAD(lat2-lat1)
LET dLong = RAD(long2-long1)
LET lat1 = RAD(lat1)
LET lat2 = RAD(lat2)
LET Haversine = R *2 * ASIN(SQR(SIN(dLat/2)^2 + SIN(dLong/2)^2 *COS(lat1) * COS(lat2)))
END DEF
PRINT
PRINT "Distancia de Haversine:"; Haversine(36.12, -86.67, 33.94, -118.4); "km"
END
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#TypeScript
|
TypeScript
|
let radians = function (degree: number) {
// degrees to radians
let rad: number = degree * Math.PI / 180;
return rad;
}
export const haversine = (lat1: number, lon1: number, lat2: number, lon2: number) => {
// var dlat: number, dlon: number, a: number, c: number, R: number;
let dlat, dlon, a, c, R: number;
R = 6372.8; // km
dlat = radians(lat2 - lat1);
dlon = radians(lon2 - lon1);
lat1 = radians(lat1);
lat2 = radians(lat2);
a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.sin(dlon / 2) * Math.sin(dlon / 2) * Math.cos(lat1) * Math.cos(lat2)
c = 2 * Math.asin(Math.sqrt(a));
return R * c;
}
console.log("Distance:" + 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
|
#Hy
|
Hy
|
(print "Hello world!")
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#VBScript
|
VBScript
|
n = 0
m = 1
first20 = ""
after1k = ""
Do
If IsHarshad(m) And n <= 20 Then
first20 = first20 & m & ", "
n = n + 1
m = m + 1
ElseIf IsHarshad(m) And m > 1000 Then
after1k = m
Exit Do
Else
m = m + 1
End If
Loop
WScript.StdOut.Write "First twenty Harshad numbers are: "
WScript.StdOut.WriteLine
WScript.StdOut.Write first20
WScript.StdOut.WriteLine
WScript.StdOut.Write "The first Harshad number after 1000 is: "
WScript.StdOut.WriteLine
WScript.StdOut.Write after1k
Function IsHarshad(s)
IsHarshad = False
sum = 0
For i = 1 To Len(s)
sum = sum + CInt(Mid(s,i,1))
Next
If s Mod sum = 0 Then
IsHarshad = True
End If
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
|
#PowerBASIC
|
PowerBASIC
|
FUNCTION PBMAIN() AS LONG
MSGBOX "Goodbye, World!"
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
|
#PowerShell
|
PowerShell
|
New-Label "Goodbye, World!" -FontSize 24 -Show
|
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.
|
#Mercury
|
Mercury
|
:- module gray.
:- interface.
:- import_module int.
:- type gray.
% VALUE conversion functions
:- func gray.from_int(int) = gray.
:- func gray.to_int(gray) = int.
% REPRESENTATION conversion predicate
:- pred gray.coerce(gray, int).
:- mode gray.coerce(in, out) is det.
:- mode gray.coerce(out, in) is det.
:- implementation.
:- import_module list.
:- type gray
---> gray(int).
gray.from_int(X) = gray(X `xor` (X >> 1)).
gray.to_int(gray(G)) = (G > 0 -> G `xor` gray.to_int(gray(G >> 1))
; G).
gray.coerce(gray(I), I).
:- end_module gray.
|
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.
|
#Nim
|
Nim
|
proc grayEncode(n: int): int =
n xor (n shr 1)
proc grayDecode(n: int): int =
result = n
var t = n
while t > 0:
t = t shr 1
result = result xor t
|
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!
|
#BQN
|
BQN
|
a‿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.
|
#CMake
|
CMake
|
# max(var [value1 value2...]) sets var to the maximum of a list of
# integers. If list is empty, sets var to NO.
function(max var)
set(first YES)
set(choice NO)
foreach(item ${ARGN})
if(first)
set(choice ${item})
set(first NO)
elseif(choice LESS ${item})
set(choice ${item})
endif()
endforeach(item)
set(${var} ${choice} PARENT_SCOPE)
endfunction(max)
set(list 33 11 44 22 66 55)
max(maximum ${list})
message(STATUS "maximum of ${list} => ${maximum}")
|
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.
|
#Bc
|
Bc
|
define even(a)
{
if ( a % 2 == 0 ) {
return(1);
} else {
return(0);
}
}
define abs(a)
{
if (a<0) {
return(-a);
} else {
return(a);
}
}
|
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).
|
#CLU
|
CLU
|
% Generate the hailstone sequence for a number
hailstone = iter (n: int) yields (int)
while true do
yield(n)
if n=1 then break end
if n//2 = 0 then
n := n/2
else
n := 3*n + 1
end
end
end hailstone
% Make an array from an iterator
iter_array = proc [T,U: type] (i: itertype (U) yields (T), s: U) returns (array[T])
arr: array[T] := array[T]$[]
for item: T in i(s) do array[T]$addh(arr, item) end
return(arr)
end iter_array
start_up = proc ()
po: stream := stream$primary_output()
% Generate the hailstone sequence for 27
h27: array[int] := iter_array[int,int](hailstone, 27)
lo27: int := array[int]$low(h27)
hi27: int := array[int]$high(h27)
stream$putl(po, "The hailstone sequence for 27 has "
|| int$unparse(array[int]$size(h27)) || " elements.")
stream$puts(po, "The first 4 elements are:")
for i: int in int$from_to(lo27, lo27+3) do
stream$puts(po, " " || int$unparse(h27[i]))
end
stream$puts(po, ", and the last 4 elements are:")
for i: int in int$from_to(hi27-3, hi27) do
stream$puts(po, " " || int$unparse(h27[i]))
end
stream$putl(po, "")
% Find whichever sequence < 100 000 has the longest sequence
maxnum: int := 0
maxlen: int := 0
for i: int in int$from_to(1, 99999) do
len: int := array[int]$size(iter_array[int,int](hailstone, i))
if len > maxlen then
maxnum, maxlen := i, len
end
end
stream$putl(po, int$unparse(maxnum)
|| " has the longest hailstone sequence < 100000: "
|| int$unparse(maxlen))
end start_up
|
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).
|
#Kotlin
|
Kotlin
|
import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
}
|
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
|
#Oforth
|
Oforth
|
import: console
: guess
10 rand doWhile: [ "Guess :" . System.Console askln asInteger over <> ]
drop "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
|
#Ol
|
Ol
|
(import (otus random!))
(define number (+ 1 (rand! 10)))
(let loop ()
(display "Pick a number from 1 through 10: ")
(if (eq? (read) number)
(print "Well guessed!")
(loop)))
|
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.
|
#PHP
|
PHP
|
<?php
function max_sum_seq($sequence) {
// This runs in linear time.
$sum_start = 0;
$sum = 0;
$max_sum = 0;
$max_start = 0;
$max_len = 0;
for ($i = 0; $i < count($sequence); $i += 1) {
$n = $sequence[$i];
$sum += $n;
if ($sum > $max_sum) {
$max_sum = $sum;
$max_start = $sum_start;
$max_len = $i + 1 - $max_start;
}
if ($sum < 0) { # start new sequence
$sum = 0;
$sum_start = $i + 1;
}
}
return array_slice($sequence, $max_start, $max_len);
}
function print_array($arr) {
if (count($arr) > 0) {
echo join(" ", $arr);
} else {
echo "(empty)";
}
echo '<br>';
}
// tests
print_array(max_sum_seq(array(-1, 0, 15, 3, -9, 12, -4)));
print_array(max_sum_seq(array(-1)));
print_array(max_sum_seq(array(4, -10, 3)));
?>
|
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)
|
#Java
|
Java
|
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random random = new Random();
long from = 1;
long to = 100;
int randomNumber = random.nextInt(to - from + 1) + from;
int guessedNumber = 0;
System.out.printf("The number is between %d and %d.\n", from, to);
do
{
System.out.print("Guess what the number is: ");
guessedNumber = scan.nextInt();
if (guessedNumber > randomNumber)
System.out.println("Your guess is too high!");
else if (guessedNumber < randomNumber)
System.out.println("Your guess is too low!");
else
System.out.println("You got it!");
} while (guessedNumber != randomNumber);
}
}
|
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
|
#Kotlin
|
Kotlin
|
// version 1.0.5-2
fun isHappy(n: Int): Boolean {
val cache = mutableListOf<Int>()
var sum = 0
var nn = n
var digit: Int
while (nn != 1) {
if (nn in cache) return false
cache.add(nn)
while (nn != 0) {
digit = nn % 10
sum += digit * digit
nn /= 10
}
nn = sum
sum = 0
}
return true
}
fun main(args: Array<String>) {
var num = 1
val happyNums = mutableListOf<Int>()
while (happyNums.size < 8) {
if (isHappy(num)) happyNums.add(num)
num++
}
println("First 8 happy numbers : " + happyNums.joinToString(", "))
}
|
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.
|
#UBASIC
|
UBASIC
|
10 Point 7 'Sets decimal display to 32 places (0+.1^56)
20 Rf=#pi/180 'Degree -> Radian Conversion
100 ?Using(,7),.DxH(36+7.2/60,-(86+40.2/60),33+56.4/60,-(118+24/60));" km"
999 End
1000 '*** Haversine Distance Function ***
1010 .DxH(Lat_s,Long_s,Lat_f,Long_f)
1020 L_s=Lat_s*rf:L_f=Lat_f*rf:LD=L_f-L_s:MD=(Long_f-Long_s)*rf
1030 Return(12745.6*asin( (sin(.5*LD)^2+cos(L_s)*cos(L_f)*sin(.5*MD)^2)^.5))
'' ''
Run
2887.2599506 km
OK
|
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.
|
#VBA
|
VBA
|
Const MER = 6371 '-- mean earth radius(km)
Public DEG_TO_RAD As Double
Function haversine(lat1 As Double, long1 As Double, lat2 As Double, long2 As Double) As Double
lat1 = lat1 * DEG_TO_RAD
lat2 = lat2 * DEG_TO_RAD
long1 = long1 * DEG_TO_RAD
long2 = long2 * DEG_TO_RAD
haversine = MER * WorksheetFunction.Acos(Sin(lat1) * Sin(lat2) + Cos(lat1) * Cos(lat2) * Cos(long2 - long1))
End Function
Public Sub main()
DEG_TO_RAD = WorksheetFunction.Pi / 180
d = haversine(36.12, -86.67, 33.94, -118.4)
Debug.Print "Distance is "; Format(d, "#.######"); " km ("; Format(d / 1.609344, "#.######"); " miles)."
End Sub
|
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
|
#i
|
i
|
software {
print("Hello world!")
}
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#Visual_FoxPro
|
Visual FoxPro
|
LOCAL lnCount As Integer, k As Integer
CLEAR
lnCount = 0
k = 0
*!* First 20 numbers
? "First 20 numbers:"
DO WHILE lnCount < 20
k = k + 1
IF Harshad(k)
lnCount = lnCount + 1
? lnCount, k
ENDIF
ENDDO
*!* First such number > 1000
k = 1001
DO WHILE NOT Harshad(k)
k = k + 1
ENDDO
? "First such number > 1000", k
FUNCTION Harshad(n As Integer) As Boolean
LOCAL cn As String, d As Integer, i As Integer
cn = TRANSFORM(n)
d = 0
FOR i = 1 TO LEN(cn)
d = d + VAL(SUBSTR(cn, i, 1))
ENDFOR
RETURN n % d = 0
ENDFUNC
|
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
|
#Processing
|
Processing
|
fill(0, 0, 0);
text("Goodbye, World!",0,height/2);
|
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
|
#Prolog
|
Prolog
|
send(@display, inform, '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.
|
#NOWUT
|
NOWUT
|
; link with PIOxxx.OBJ
sectiondata
output: db " : "
inbinary: db "00000 => "
graybinary: db "00000 => "
outbinary: db "00000"
db 13,10,0 ; carriage return and null terminator
sectioncode
start!
gosub initplatform
beginfunc
localvar i.d,g.d,b.d
i=0
whileless i,32
callex g,gray_encode,i
callex b,gray_decode,g
callex ,bin2string,i,inbinary,5 ; 5 = number of binary digits
callex ,bin2string,g,graybinary,5
callex ,bin2string,b,outbinary,5
callex ,printhex8,i ; display hex value
; because there is no PIO routine for decimals...
callex ,printnt,output.a
i=_+1
wend
endfunc
end
gray_encode:
beginfunc n.d
n=_ xor (n shr 1)
endfunc n
returnex 4 ; clean off 1 parameter from the stack
gray_decode:
beginfunc n.d
localvar p.d
p=n
whilegreater n,1
n=_ shr 1 > p=_ xor n
wend
endfunc p
returnex 4 ; clean off 1 parameter from the stack
bin2string:
beginfunc digits.d,straddr.d,value.d
whilegreater digits,0
digits=_-1
[straddr].b=value shr digits and 1+$30 ; write an ASCII '0' or '1'
straddr=_+1 ; increment the pointer
wend
endfunc
returnex $0C ; clean off 3 parameters from the stack
|
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.
|
#OCaml
|
OCaml
|
let gray_encode b =
b lxor (b lsr 1)
let gray_decode n =
let rec aux p n =
if n = 0 then p
else aux (p lxor n) (n lsr 1)
in
aux n (n lsr 1)
let bool_string len n =
let s = Bytes.make len '0' in
let rec aux i n =
if n land 1 = 1 then Bytes.set s i '1';
if i <= 0 then (Bytes.to_string s)
else aux (pred i) (n lsr 1)
in
aux (pred len) n
let () =
let s = bool_string 5 in
for i = 0 to pred 32 do
let g = gray_encode i in
let b = gray_decode g in
Printf.printf "%2d : %s => %s => %s : %2d\n" i (s i) (s g) (s b) b
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!
|
#Bracmat
|
Bracmat
|
(!a.!b):(?b.?a)
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#COBOL
|
COBOL
|
DISPLAY FUNCTION MAX(nums (ALL))
|
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.
|
#BCPL
|
BCPL
|
get "libhdr"
let gcd(m,n) = n=0 -> m, gcd(n, m rem n)
let show(m,n) be
writef("gcd(%N, %N) = %N*N", m, n, gcd(m, n))
let start() be
$( show(18,12)
show(1071,1029)
show(3528,3780)
$)
|
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).
|
#COBOL
|
COBOL
|
identification division.
program-id. hailstones.
remarks. cobc -x hailstones.cob.
data division.
working-storage section.
01 most constant as 1000000.
01 coverage constant as 100000.
01 stones usage binary-long.
01 n usage binary-long.
01 storm usage binary-long.
01 show-arg pic 9(6).
01 show-default pic 99 value 27.
01 show-sequence usage binary-long.
01 longest usage binary-long occurs 2 times.
01 filler.
05 hail usage binary-long
occurs 0 to most depending on stones.
01 show pic z(10).
01 low-range usage binary-long.
01 high-range usage binary-long.
01 range usage binary-long.
01 remain usage binary-long.
01 unused usage binary-long.
procedure division.
accept show-arg from command-line
if show-arg less than 1 or greater than coverage then
move show-default to show-arg
end-if
move show-arg to show-sequence
move 1 to longest(1)
perform hailstone varying storm
from 1 by 1 until storm > coverage
display "Longest at: " longest(2) " with " longest(1) " elements"
goback.
*> **************************************************************
hailstone.
move 0 to stones
move storm to n
perform until n equal 1
if stones > most then
display "too many hailstones" upon syserr
stop run
end-if
add 1 to stones
move n to hail(stones)
divide n by 2 giving unused remainder remain
if remain equal 0 then
divide 2 into n
else
compute n = 3 * n + 1
end-if
end-perform
add 1 to stones
move n to hail(stones)
if stones > longest(1) then
move stones to longest(1)
move storm to longest(2)
end-if
if storm equal show-sequence then
display show-sequence ": " with no advancing
perform varying range from 1 by 1 until range > stones
move 5 to low-range
compute high-range = stones - 4
if range < low-range or range > high-range then
move hail(range) to show
display function trim(show) with no advancing
if range < stones then
display ", " with no advancing
end-if
end-if
if range = low-range and stones > 8 then
display "..., " with no advancing
end-if
end-perform
display ": " stones " elements"
end-if
.
end program hailstones.
|
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).
|
#Liberty_BASIC
|
Liberty BASIC
|
dim h( 1000000)
for i =1 to 20
print hamming( i); " ";
next i
print
print "H( 1691)", hamming( 1691)
print "H( 1000000)", hamming( 1000000)
end
function hamming( limit)
h( 0) =1
x2 =2: x3 =3: x5 =5
i =0: j =0: k =0
for n =1 to limit
h( n) = min( x2, min( x3, x5))
if x2 = h( n) then i = i +1: x2 =2 *h( i)
if x3 = h( n) then j = j +1: x3 =3 *h( j)
if x5 = h( n) then k = k +1: x5 =5 *h( k)
next n
hamming =h( limit -1)
end function
|
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
|
#PARI.2FGP
|
PARI/GP
|
guess()=my(r=random(10)+1);while(input()!=r,); "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
|
#Pascal
|
Pascal
|
Program GuessTheNumber(input, output);
var
number, guess: integer;
begin
randomize;
number := random(10) + 1;
writeln ('I''m thinking of a number between 1 and 10, which you should guess.');
write ('Enter your guess: ');
readln (guess);
while guess <> number do
begin
writeln ('Sorry, but your guess is wrong. Please try again.');
write ('Enter your new guess: ');
readln (guess);
end;
writeln ('You made an excellent guess. Thank you and have a nice day.');
end.
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Picat
|
Picat
|
greatest_subsequential_sum_it([]) = [] => true.
greatest_subsequential_sum_it(A) = Seq =>
P = allcomb(A),
Total = max([Tot : Tot=_T in P]),
Seq1 = [],
if Total > 0 then
[B,E] = P.get(Total),
Seq1 := [A[I] : I in B..E]
else
Seq1 := []
end,
Seq = Seq1.
allcomb(A) = Comb =>
Len = A.length,
Comb = new_map([(sum([A[I]:I in B..E])=([B,E])) : B in 1..Len, E in B..Len]).
|
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.
|
#PicoLisp
|
PicoLisp
|
(maxi '((L) (apply + L))
(mapcon '((L) (maplist reverse (reverse L)))
(-1 -2 3 5 6 -2 -1 4 -4 2 -1) ) )
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#JavaScript
|
JavaScript
|
<p>Pick a number between 1 and 100.</p>
<form id="guessNumber">
<input type="text" name="guess">
<input type="submit" value="Submit Guess">
</form>
<p id="output"></p>
<script type="text/javascript">
|
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
|
#Lasso
|
Lasso
|
#!/usr/bin/lasso9
define isHappy(n::integer) => {
local(past = set)
while(#n != 1) => {
#n = with i in string(#n)->values sum math_pow(integer(#i), 2)
#past->contains(#n) ? return false | #past->insert(#n)
}
return true
}
with x in generateSeries(1, 500)
where isHappy(#x)
take 8
select #x
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, 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.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Math
Module Module1
Const deg2rad As Double = PI / 180
Structure AP_Loc
Public IATA_Code As String, Lat As Double, Lon As Double
Public Sub New(ByVal iata_code As String, ByVal lat As Double, ByVal lon As Double)
Me.IATA_Code = iata_code : Me.Lat = lat * deg2rad : Me.Lon = lon * deg2rad
End Sub
Public Overrides Function ToString() As String
Return String.Format("{0}: ({1}, {2})", IATA_Code, Lat / deg2rad, Lon / deg2rad)
End Function
End Structure
Function Sin2(ByVal x As Double) As Double
Return Pow(Sin(x / 2), 2)
End Function
Function calculate(ByVal one As AP_Loc, ByVal two As AP_Loc) As Double
Dim R As Double = 6371, ' In kilometers, (as recommended by the International Union of Geodesy and Geophysics)
a As Double = Sin2(two.Lat - one.Lat) + Sin2(two.Lon - one.Lon) * Cos(one.Lat) * Cos(two.Lat)
Return R * 2 * Asin(Sqrt(a))
End Function
Sub ShowOne(pntA As AP_Loc, pntB as AP_Loc)
Dim adst As Double = calculate(pntA, pntB), sfx As String = "km"
If adst < 1000 Then adst *= 1000 : sfx = "m"
Console.WriteLine("The approximate distance between airports {0} and {1} is {2:n2} {3}.", pntA, pntB, adst, sfx)
Console.WriteLine("The uncertainty is under 0.5%, or {0:n1} {1}." & vbLf, adst / 200, sfx)
End Sub
' Airport coordinate data excerpted from the data base at http://www.partow.net/miscellaneous/airportdatabase/
' The four additional airports are the furthest and closest pairs, according to the "Fun Facts..." section.
' KBNA, BNA, NASHVILLE INTERNATIONAL, NASHVILLE, USA, 036, 007, 028, N, 086, 040, 041, W, 00183, 36.124, -86.678
' KLAX, LAX, LOS ANGELES INTERNATIONAL, LOS ANGELES, USA, 033, 056, 033, N, 118, 024, 029, W, 00039, 33.942, -118.408
' SKNV, NVA, BENITO SALAS, NEIVA, COLOMBIA, 002, 057, 000, N, 075, 017, 038, W, 00439, 2.950, -75.294
' WIPP, PLM, SULTAN MAHMUD BADARUDDIN II, PALEMBANG, INDONESIA, 002, 053, 052, S, 104, 042, 004, E, 00012, -2.898, 104.701
' LOWL, LNZ, HORSCHING INTERNATIONAL AIRPORT (AUS - AFB), LINZ, AUSTRIA, 048, 014, 000, N, 014, 011, 000, E, 00096, 48.233, 14.183
' LOXL, N/A, LINZ, LINZ, AUSTRIA, 048, 013, 059, N, 014, 011, 015, E, 00299, 48.233, 14.188
Sub Main()
ShowOne(New AP_Loc("BNA", 36.124, -86.678), New AP_Loc("LAX", 33.942, -118.408))
ShowOne(New AP_Loc("NVA", 2.95, -75.294), New AP_Loc("PLM", -2.898, 104.701))
ShowOne(New AP_Loc("LNZ", 48.233, 14.183), New AP_Loc("N/A", 48.233, 14.188))
End Sub
End Module
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
write( "Hello world!" )
end
|
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
|
#VTL-2
|
VTL-2
|
10 ?="First 20: ";
20 N=0
30 I=0
40 #=200
50 ?=N
60 $=32
70 I=I+1
80 #=I<20*40
90 ?=""
100 ?="First above 1000: ";
110 N=1000
120 #=200
130 ?=N
140 #=999
200 ;=!
210 N=N+1
220 K=N
230 S=0
240 K=K/10
250 S=S+%
260 #=0<K*240
270 #=N/S*0+0<%*210
280 #=;
|
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
|
#Pure_Data
|
Pure Data
|
#N canvas 321 432 450 300 10;
#X obj 100 52 loadbang;
#X msg 100 74 Goodbye\, World!;
#X obj 100 96 print -n;
#X connect 0 0 1 0;
#X connect 1 0 2 0;
|
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
|
#PureBasic
|
PureBasic
|
MessageRequester("Hello","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.
|
#PARI.2FGP
|
PARI/GP
|
toGray(n)=bitxor(n,n>>1);
fromGray(n)=my(k=1,m=n);while(m>>k,n=bitxor(n,n>>k);k+=k);n;
bin(n)=concat(apply(k->Str(k),binary(n)))
for(n=0,31,print(n"\t"bin(n)"\t"bin(g=toGray(n))"\t"fromGray(g)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.