task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Greatest_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.
|
#Liberty_BASIC
|
Liberty BASIC
|
aList$= "1 15 -5 6 39 1.5 14"
maxVal = val(word$(aList$, 1))
token$ = "?"
while token$ <> ""
index = index + 1
token$ = word$(aList$, index)
aVal = val(token$)
if aVal > maxVal then maxVal = aVal
wend
print "maxVal = ";maxVal
|
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.
|
#Groovy
|
Groovy
|
def gcdR
gcdR = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcdR(n, m%n) }
|
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).
|
#K
|
K
|
hail: (1<){:[x!2;1+3*x;_ x%2]}\
seqn: hail 27
#seqn
112
4#seqn
27 82 41 124
-4#seqn
8 4 2 1
{m,x@s?m:|/s:{#hail x}'x}{x@&x!2}!:1e5
351 77031
|
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).
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 FOR h=1 TO 20: GO SUB 1000: NEXT h
20 LET h=1691: GO SUB 1000
30 STOP
1000 REM Hamming
1010 DIM a(h)
1030 LET a(1)=1: LET x2=2: LET x3=3: LET x5=5: LET i=1: LET j=1: LET k=1
1040 FOR n=2 TO h
1050 LET m=x2
1060 IF m>x3 THEN LET m=x3
1070 IF m>x5 THEN LET m=x5
1080 LET a(n)=m
1090 IF m=x2 THEN LET i=i+1: LET x2=2*a(i)
1100 IF m=x3 THEN LET j=j+1: LET x3=3*a(j)
1110 IF m=x5 THEN LET k=k+1: LET x5=5*a(k)
1120 NEXT n
1130 PRINT "H(";h;")= ";a(h)
1140 RETURN
|
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)
|
#Ursa
|
Ursa
|
decl int high low
set low 0
set high 100
out "Guess a number between " low " and " high "." endl endl console
decl int target answer i
decl ursa.util.random random
set target (int (+ 1 (+ low (random.getint (int (- high low))))))
while (not (= answer target))
inc i
out "Your guess(" i "): " console
set answer (in int console)
if (or (< answer low) (> answer high))
out " Out of range!" endl console
continue
end if
if (= answer target)
out " Ye-Haw!!" endl console
continue
end if
if (< answer target)
out " Too low." endl console
end if
if (> answer target)
out " Too high." endl console
end if
end while
out endl "Thanks for playing." endl console
|
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)
|
#Vala
|
Vala
|
void main(){
const int from = 1;
const int to = 100;
int random = Random.int_range(from, to);
int guess = 0;
while (guess != random){
stdout.printf("Guess the target number that's between %d and %d.\n", from, to);
string? num = stdin.read_line ();
num.canon("0123456789", '!'); // replaces any character in num that's not in "0123456789" with "!"
if ("!" in num)
stdout.printf("Please enter a number!\n");
else{
guess = int.parse(num);
if (guess > random && guess <= to)
stdout.printf("Too high!\n");
if (guess < random && guess >= from)
stdout.printf("Too low!\n");
if (guess == random)
stdout.printf("You guess it! You win!\n");
if (guess < from || guess > to)
stdout.printf("%d Your guess isn't even in the right range!\n", guess);
}
}//while
} // main
|
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
|
#Rust
|
Rust
|
#![feature(core)]
fn sumsqd(mut n: i32) -> i32 {
let mut sq = 0;
while n > 0 {
let d = n % 10;
sq += d*d;
n /= 10
}
sq
}
use std::num::Int;
fn cycle<T: Int>(a: T, f: fn(T) -> T) -> T {
let mut t = a;
let mut h = f(a);
while t != h {
t = f(t);
h = f(f(h))
}
t
}
fn ishappy(n: i32) -> bool {
cycle(n, sumsqd) == 1
}
fn main() {
let happy = std::iter::count(1, 1)
.filter(|&n| ishappy(n))
.take(8)
.collect::<Vec<i32>>();
println!("{:?}", happy)
}
|
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
|
#Lily
|
Lily
|
print("Hello world!")
|
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!
|
#Joy
|
Joy
|
swap
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Lingo
|
Lingo
|
l = [1,7,5]
put max(l)
-- 7
|
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.
|
#LiveCode
|
LiveCode
|
put max(2,3,6,7,4,1)
|
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.
|
#GW-BASIC
|
GW-BASIC
|
10 INPUT A, B
20 IF A < 0 THEN A = -A
30 IF B < 0 THEN B = -B
40 GOTO 70
50 PRINT A
60 END
70 IF B = 0 THEN GOTO 50
80 TEMP = B
90 B = A MOD TEMP
100 A = TEMP
110 GOTO 70
|
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).
|
#Kotlin
|
Kotlin
|
import java.util.ArrayDeque
fun hailstone(n: Int): ArrayDeque<Int> {
val hails = when {
n == 1 -> ArrayDeque<Int>()
n % 2 == 0 -> hailstone(n / 2)
else -> hailstone(3 * n + 1)
}
hails.addFirst(n)
return hails
}
fun main(args: Array<String>) {
val hail27 = hailstone(27)
fun showSeq(s: List<Int>) = s.map { it.toString() }.reduce { a, b -> a + ", " + b }
println("Hailstone sequence for 27 is " + showSeq(hail27.take(3)) + " ... "
+ showSeq(hail27.drop(hail27.size - 3)) + " with length ${hail27.size}.")
var longestHail = hailstone(1)
for (x in 1..99999)
longestHail = arrayOf(hailstone(x), longestHail).maxBy { it.size } ?: longestHail
println("${longestHail.first} is the number less than 100000 with " +
"the longest sequence, having length ${longestHail.size}.")
}
|
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)
|
#VBA_Excel
|
VBA Excel
|
Sub GuessTheNumberWithFeedback()
Dim Nbc&, Nbp&, m&, n&, c&
Randomize Timer
m = 11
n = 100
Nbc = Int((Rnd * (n - m + 1)) + m)
Do
c = c + 1
Nbp = Application.InputBox("Choose a number between " & m & " and " & n & " : ", "Enter your guess", Type:=1)
Select Case Nbp
Case Is > Nbc: MsgBox "Higher than target!"
Case Is < Nbc: MsgBox "Less than target!"
Case Else: Exit Do
End Select
Loop
MsgBox "Well guessed!" & vbCrLf & "You find : " & Nbc & " in " & c & " guesses!"
End Sub
|
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
|
#Salmon
|
Salmon
|
variable happy_count := 0;
outer:
iterate(x; [1...+oo])
{
variable seen := <<(* --> false)>>;
variable now := x;
while (true)
{
if (seen[now])
{
if (now == 1)
{
++happy_count;
print(x, " is happy.\n");
if (happy_count == 8)
break from outer;;
};
break;
};
seen[now] := true;
variable new := 0;
while (now != 0)
{
new += (now % 10) * (now % 10);
now /::= 10;
};
now := new;
};
};
|
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
|
#Lilypond
|
Lilypond
|
\version "2.18.2"
global = {
\time 4/4
\key c \major
\tempo 4=100
}
\relative c''{ g e e( g2)
}
\addlyrics {
Hel -- lo, World!
}
|
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!
|
#jq
|
jq
|
jq -n '1 as $a | 2 as $b | $a as $tmp | $b as $a | $tmp as $b | [$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.
|
#Logo
|
Logo
|
to max :a :b
output ifelse :a > :b [:a] [:b]
end
print reduce "max [...]
|
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.
|
#Logtalk
|
Logtalk
|
max([X| Xs], Max) :-
max(Xs, X, Max).
max([], Max, Max).
max([X| Xs], Aux, Max) :-
( X @> Aux ->
max(Xs, X, Max)
; max(Xs, Aux, 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.
|
#Haskell
|
Haskell
|
gcd :: (Integral a) => a -> a -> a
gcd x y = gcd_ (abs x) (abs y)
where
gcd_ a 0 = a
gcd_ a b = gcd_ b (a `rem` b)
|
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).
|
#Lasso
|
Lasso
|
[
define_tag("hailstone", -required="n", -type="integer", -copy);
local("sequence") = array(#n);
while(#n != 1);
((#n % 2) == 0) ? #n = (#n / 2) | #n = (#n * 3 + 1);
#sequence->insert(#n);
/while;
return(#sequence);
/define_tag;
local("result");
#result = hailstone(27);
while(#result->size > 8);
#result->remove(5);
/while;
#result->insert("...",5);
"Hailstone sequence for n = 27 -> { " + #result->join(", ") + " }";
local("longest_sequence") = 0;
local("longest_index") = 0;
loop(-from=1, -to=100000);
local("length") = hailstone(loop_count)->size;
if(#length > #longest_sequence);
#longest_index = loop_count;
#longest_sequence = #length;
/if;
/loop;
"<br/>";
"Number with the longest sequence under 100,000: " #longest_index + ", with " + #longest_sequence + " elements.";
]
|
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)
|
#VBScript
|
VBScript
|
Dim max,min,secretnum,numtries,usernum
max=100
min=1
numtries=0
Randomize
secretnum = Int((max-min+1)*Rnd+min)
Do While usernum <> secretnum
usernum = Inputbox("Guess the secret number beween 1-100","Guessing Game")
If IsEmpty(usernum) Then
WScript.Quit
End If
If IsNumeric(usernum) Then
numtries = numtries + 1
usernum = Cint(usernum)
If usernum < secretnum Then
Msgbox("The secret number is higher than " + CStr(usernum))
ElseIf usernum > secretnum Then
Msgbox("The secret number is lower than " + CStr(usernum))
Else
Msgbox("Congratulations, you found the secret number in " + CStr(numtries) + " guesses!")
End If
Else
Msgbox("Please enter a valid number.")
End If
Loop
|
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
|
#Scala
|
Scala
|
scala> def isHappy(n: Int) = {
| new Iterator[Int] {
| val seen = scala.collection.mutable.Set[Int]()
| var curr = n
| def next = {
| val res = curr
| curr = res.toString.map(_.asDigit).map(n => n * n).sum
| seen += res
| res
| }
| def hasNext = !seen.contains(curr)
| }.toList.last == 1
| }
isHappy: (n: Int)Boolean
scala> Iterator from 1 filter isHappy take 8 foreach println
1
7
10
13
19
23
28
31
|
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
|
#Limbo
|
Limbo
|
implement Command;
include "sys.m";
sys: Sys;
include "draw.m";
include "sh.m";
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
sys->print("Hello world!\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!
|
#Julia
|
Julia
|
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.
|
#Lua
|
Lua
|
-- Table to store values
local values = {}
-- Read in the first number from stdin
local new_val = io.read"*n"
-- Append all numbers passed in
-- until there are no more numbers (io.read'*n' = nil)
while new_val do
values[#values+1] = new_val
new_val = io.read"*n"
end
-- Print the max
print(math.max(unpack(values)))
|
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.
|
#HicEst
|
HicEst
|
FUNCTION gcd(a, b)
IF(b == 0) THEN
gcd = ABS(a)
ELSE
aa = a
gcd = b
DO i = 1, 1E100
r = ABS(MOD(aa, gcd))
IF( r == 0 ) RETURN
aa = gcd
gcd = r
ENDDO
ENDIF
END
|
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).
|
#Limbo
|
Limbo
|
implement Hailstone;
include "sys.m"; sys: Sys;
include "draw.m";
Hailstone: module {
init: fn(ctxt: ref Draw->Context, args: list of string);
};
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
seq := hailstone(big 27);
l := len seq;
sys->print("hailstone(27): ");
for(i := 0; i < 4; i++) {
sys->print("%bd, ", hd seq);
seq = tl seq;
}
sys->print("⋯");
while(len seq > 4)
seq = tl seq;
while(seq != nil) {
sys->print(", %bd", hd seq);
seq = tl seq;
}
sys->print(" (length %d)\n", l);
max := 1;
maxn := big 1;
for(n := big 2; n < big 100000; n++) {
cur := len hailstone(n);
if(cur > max) {
max = cur;
maxn = n;
}
}
sys->print("hailstone(%bd) has length %d\n", maxn, max);
}
hailstone(i: big): list of big
{
if(i == big 1)
return big 1 :: nil;
if(i % big 2 == big 0)
return i :: hailstone(i / big 2);
return i :: hailstone((big 3 * i) + big 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)
|
#Vlang
|
Vlang
|
import rand.seed
import rand
import os
const (
lower = 1
upper = 100
)
fn main() {
rand.seed(seed.time_seed_array(2))
n := rand.intn(upper-lower+1) or {0} + lower
for {
guess := os.input("Guess integer number from $lower to $upper: ").int()
if guess < n {
println("Too low. Try again: ")
} else if guess > n {
println("Too high. Try again: ")
} else {
println("Well guessed!")
return
}
}
}
|
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)
|
#VTL-2
|
VTL-2
|
10 ?="Minimum? ";
20 L=?
30 ?="Maximum? ";
40 H=?
50 #=L<H*80
60 ?="Minimum must be lower than maximum."
70 #=10
80 S='/(H-L+1)*0+L+%
90 T=0
100 ?="Guess? ";
110 G=?
120 #=G>L*(H>G)*150
130 ?="Guess must be in between minimum and maximum."
140 #=100
150 T=T+1
160 #=G=S*220
170 #=G<S*200
180 ?="Too high."
190 #=100
200 ?="Too low."
210 #=100
220 ?="Correct!"
230 ?="Tries: ";
240 ?=T
|
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
|
#Scheme
|
Scheme
|
(define (number->list num)
(do ((num num (quotient num 10))
(lst '() (cons (remainder num 10) lst)))
((zero? num) lst)))
(define (happy? num)
(let loop ((num num) (seen '()))
(cond ((= num 1) #t)
((memv num seen) #f)
(else (loop (apply + (map (lambda (x) (* x x)) (number->list num)))
(cons num seen))))))
(display "happy numbers:")
(let loop ((n 1) (more 8))
(cond ((= more 0) (newline))
((happy? n) (display " ") (display n) (loop (+ n 1) (- more 1)))
(else (loop (+ n 1) more))))
|
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
|
#Lingo
|
Lingo
|
put "Hello world!"
|
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!
|
#Kotlin
|
Kotlin
|
// version 1.1
fun <T> swap(t1: T, t2: T) = Pair(t2, t1)
fun main(args: Array<String>) {
var a = 3
var b = 4
val c = swap(a, b) // infers that swap<Int> be used
a = c.first
b = c.second
println("a = $a")
println("b = $b")
var d = false
var e = true
val f = swap(d, e) // infers that swap<Boolean> be used
d = f.first
e = f.second
println("d = $d")
println("e = $e")
}
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module TestThis {
Print "Search a tuple type list (is an array also)"
A=(,)
For i=1 to Random(1,10)
Append A, (Random(1,100),)
Next
Print Len(A)
Print A
Print A#max()
Print "Search an array"
B=lambda->Random(1,100)
Rem Dim A(1 to Random(1,10))<<B()
Dim A(1 to Random(1,10))<<lambda->{=Random(1,100)}()
Print Len(A())
Print A()
Print A()#max()
\\ #max() skip non numeric values
Rem Print (1,"100",3)#max()=3
Print "Search an inventory list"
Inventory C
for i=1 to Random(1,10)
do
key=random(10000)
until not exist(c, key)
\\ we can put a number as string
if random(1,2)=1 then Append c, key:=B() else Append c, key:=str$(B())
Next
\\ if inventory item is string with a number work fine
Function MaxItem(a) {
k=each(a,2)
val=a(0!)
while k
\\ using stack of values
\\ over -equal to over 1 - copy value from 1 to top, means double the top value
\\ number - pop top value
\\ drop -equal to drop 1 : drop top value
Push a(k^!): Over : If Number>val then Read Val else drop
Rem If a(k^!)>Val Then Val=a(k^!)
end while
=val
}
Print Len(C)
Print C
Print MaxItem(C)
Print "Search a stack object"
\\ a stack object is the same as the stack of values
\\ which always is present
D=stack
I=0
J=Random(1,10)
\\ Stack stackobjext {}
\\ hide current stack and attach the D stack
Stack D {
Push B() : I++ : IF I>J Else Loop
}
\\ if stack item isn't numeric we get a run time error
Function MaxItemStack(a) {
Stack a {env$=envelope$()}
if replace$("N","", env$)<>"" then error "only numbers allowed"
k=each(a,2)
val=Stackitem(a,1)
while k
If Stackitem(k)>val then Val=stackitem(k)
end while
=val
}
Print Len(D)
Print D
Print MaxItemStack(D)
}
TestThis
|
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.
|
#Maple
|
Maple
|
> max( { 1, 2, Pi, exp(1) } ); # set
Pi
> max( [ 1, 2, Pi, exp(1) ] ); # list
Pi
> max( 1, 2, Pi, exp(1) ); # sequence
Pi
> max( Array( [ 1, 2, Pi, exp(1) ] ) ); # Array
Pi
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
link numbers # gcd is part of the Icon Programming Library
procedure main(args)
write(gcd(arg[1], arg[2])) | "Usage: gcd n m")
end
|
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).
|
#Lingo
|
Lingo
|
on hailstone (n, sequenceList)
len = 1
repeat while n<>1
if listP(sequenceList) then sequenceList.add(n)
if n mod 2 = 0 then
n = n / 2
else
n = 3 * n + 1
end if
len = len + 1
end repeat
if listP(sequenceList) then sequenceList.add(n)
return len
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)
|
#Wren
|
Wren
|
import "io" for Stdin, Stdout
import "random" for Random
var rand = Random.new()
var n = rand.int(1, 21) // computer number from 1..20 inclusive, say
System.print("The computer has chosen a number between 1 and 20 inclusive.")
while (true) {
System.write(" Your guess 1-20 : ")
Stdout.flush()
var g = Num.fromString(Stdin.readLine())
if (!g || g.type != Num || !g.isInteger || g < 1 || g > 20) {
System.print(" Inappropriate")
} else if (g > n) {
System.print(" Too high")
} else if (g < n) {
System.print(" Too low")
} else {
System.print(" Spot on!")
break
}
}
|
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
|
#Scratch
|
Scratch
|
$ include "seed7_05.s7i";
const type: cacheType is hash [integer] boolean;
var cacheType: cache is cacheType.value;
const func boolean: happy (in var integer: number) is func
result
var boolean: isHappy is FALSE;
local
var bitset: cycle is bitset.value;
var integer: newnumber is 0;
var integer: cycleNum is 0;
begin
while number > 1 and number not in cycle do
if number in cache then
number := ord(cache[number]);
else
incl(cycle, number);
newnumber := 0;
while number > 0 do
newnumber +:= (number rem 10) ** 2;
number := number div 10;
end while;
number := newnumber;
end if;
end while;
isHappy := number = 1;
for cycleNum range cycle do
cache @:= [cycleNum] isHappy;
end for;
end func;
const proc: main is func
local
var integer: number is 0;
begin
for number range 1 to 50 do
if happy(number) then
writeln(number);
end if;
end for;
end func;
|
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
|
#Lisaac
|
Lisaac
|
Section Header // The Header section is required.
+ name := GOODBYE; // Define the name of this object.
Section Public
- main <- ("Hello world!\n".print;);
|
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!
|
#Lambdatalk
|
Lambdatalk
|
1) using an Immediately Invoked Function Expression:
{{lambda {:x :y} :y :x} hello world}
-> world hello
2) or user defined function
{def swap {lambda {:x :y} :y :x}}
-> swap
3) applied on words (which can be numbers)
{swap hello world}
-> world hello
{swap hello brave new world}
-> brave new hello world
{swap {cons hello brave} {cons new world}}
-> (new world) (hello brave)
|
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.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
Max[1, 3, 3, 7]
Max[Pi,E+2/5,17 Cos[6]/5,Sqrt[91/10]]
Max[1,6,Infinity]
Max[]
|
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.
|
#MATLAB
|
MATLAB
|
function [maxValue] = findmax(setOfValues)
maxValue = max(setOfValues);
|
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.
|
#J
|
J
|
x+.y
|
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.
|
#Java
|
Java
|
public static long gcd(long a, long b){
long factor= Math.min(a, b);
for(long loop= factor;loop > 1;loop--){
if(a % loop == 0 && b % loop == 0){
return loop;
}
}
return 1;
}
|
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).
|
#Logo
|
Logo
|
to hail.next :n
output ifelse equal? 0 modulo :n 2 [:n/2] [3*:n + 1]
end
to hail.seq :n
if :n = 1 [output [1]]
output fput :n hail.seq hail.next :n
end
show hail.seq 27
show count hail.seq 27
to max.hail :n
localmake "max.n 0
localmake "max.length 0
repeat :n [if greater? count hail.seq repcount :max.length [
make "max.n repcount
make "max.length count hail.seq repcount
] ]
(print :max.n [has hailstone sequence length] :max.length)
end
max.hail 100000
|
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)
|
#XLISP
|
XLISP
|
(defun guessing-game (a b)
; minimum and maximum, to be supplied by the user
(defun prompt ()
(display "What is your guess? ")
(define guess (read))
(if (eq guess n) ; EQ, unlike =, won't blow up
; if GUESS isn't a number
(display "Well guessed!")
(begin
(display
(cond
((not (integer? guess)) "Come on, that isn't even an integer")
((or (< guess a) (> guess b)) "Now you k n o w it won't be that")
((< guess n) "Too low")
((> guess n) "Too high")))
(display "! Try again...")
(newline)
(prompt))))
(define n (+ (random (- (+ b 1) a)) a))
(display "I have thought of an integer between ")
(display a)
(display " and ")
(display b)
(display ". Try to guess it!")
(newline)
(prompt))
|
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
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const type: cacheType is hash [integer] boolean;
var cacheType: cache is cacheType.value;
const func boolean: happy (in var integer: number) is func
result
var boolean: isHappy is FALSE;
local
var bitset: cycle is bitset.value;
var integer: newnumber is 0;
var integer: cycleNum is 0;
begin
while number > 1 and number not in cycle do
if number in cache then
number := ord(cache[number]);
else
incl(cycle, number);
newnumber := 0;
while number > 0 do
newnumber +:= (number rem 10) ** 2;
number := number div 10;
end while;
number := newnumber;
end if;
end while;
isHappy := number = 1;
for cycleNum range cycle do
cache @:= [cycleNum] isHappy;
end for;
end func;
const proc: main is func
local
var integer: number is 0;
begin
for number range 1 to 50 do
if happy(number) then
writeln(number);
end if;
end for;
end func;
|
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
|
#Little
|
Little
|
puts("Hello world!");
|
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!
|
#Lang5
|
Lang5
|
swap # stack
reverse # array
|
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.
|
#Maxima
|
Maxima
|
u : makelist(random(1000), 50)$
/* Three solutions */
lreduce(max, u);
apply(max, u);
lmax(u);
|
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.
|
#MAXScript
|
MAXScript
|
fn MaxValue AnArray =
(
if AnArray.count != 0 then
(
local maxVal = 0
for i in AnArray do if i > maxVal then maxVal = i
maxVal
)
else undefined
)
|
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.
|
#JavaScript
|
JavaScript
|
function gcd(a,b) {
a = Math.abs(a);
b = Math.abs(b);
if (b > a) {
var temp = a;
a = b;
b = temp;
}
while (true) {
a %= b;
if (a === 0) { return b; }
b %= a;
if (b === 0) { 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).
|
#Logtalk
|
Logtalk
|
:- object(hailstone).
:- public(generate_sequence/2).
:- mode(generate_sequence(+natural, -list(natural)), zero_or_one).
:- info(generate_sequence/2, [
comment is 'Generates the Hailstone sequence that starts with its first argument. Fails if the argument is not a natural number.',
argnames is ['Start', 'Sequence']
]).
:- public(write_sequence/1).
:- mode(write_sequence(+natural), zero_or_one).
:- info(write_sequence/1, [
comment is 'Writes to the standard output the Hailstone sequence that starts with its argument. Fails if the argument is not a natural number.',
argnames is ['Start']
]).
:- public(sequence_length/2).
:- mode(sequence_length(+natural, -natural), zero_or_one).
:- info(sequence_length/2, [
comment is 'Calculates the length of the Hailstone sequence that starts with its first argument. Fails if the argument is not a natural number.',
argnames is ['Start', 'Length']
]).
:- public(longest_sequence/4).
:- mode(longest_sequence(+natural, +natural, -natural, -natural), zero_or_one).
:- info(longest_sequence/4, [
comment is 'Calculates the longest Hailstone sequence in the interval [Start, End]. Fails if the interval is not valid.',
argnames is ['Start', 'End', 'N', 'Length']
]).
generate_sequence(Start, Sequence) :-
integer(Start),
Start >= 1,
sequence(Start, Sequence).
sequence(1, [1]) :-
!.
sequence(N, [N| Sequence]) :-
( N mod 2 =:= 0 ->
M is N // 2
; M is (3 * N) + 1
),
sequence(M, Sequence).
write_sequence(Start) :-
integer(Start),
Start >= 1,
sequence(Start).
sequence(1) :-
!,
write(1), nl.
sequence(N) :-
write(N), write(' '),
( N mod 2 =:= 0 ->
M is N // 2
; M is (3 * N) + 1
),
sequence(M).
sequence_length(Start, Length) :-
integer(Start),
Start >= 1,
sequence_length(Start, 1, Length).
sequence_length(1, Length, Length) :-
!.
sequence_length(N, Length0, Length) :-
Length1 is Length0 + 1,
( N mod 2 =:= 0 ->
M is N // 2
; M is (3 * N) + 1
),
sequence_length(M, Length1, Length).
longest_sequence(Start, End, N, Length) :-
integer(Start),
integer(End),
Start >= 1,
Start =< End,
longest_sequence(Start, End, 1, N, 1, Length).
longest_sequence(Current, End, N, N, Length, Length) :-
Current > End,
!.
longest_sequence(Current, End, N0, N, Length0, Length) :-
sequence_length(Current, 1, CurrentLength),
Next is Current + 1,
( CurrentLength > Length0 ->
longest_sequence(Next, End, Current, N, CurrentLength, Length)
; longest_sequence(Next, End, N0, N, Length0, Length)
).
:- end_object.
|
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)
|
#XPL0
|
XPL0
|
include c:\cxpl\codes;
int Lo, Hi, C, Guess, Number;
[loop [Text(0, "Low limit: "); Lo:= IntIn(0);
Text(0, "High limit: "); Hi:= IntIn(0);
if Lo < Hi then quit;
Text(0, "Low limit must be lower!^M^J^G");
];
Number:= Ran(Hi-Lo+1)+Lo;
Text(0, "I'm thinking of a number between ");
IntOut(0, Lo); Text(0, " and "); IntOut(0, Hi); Text(0, ".^M^J");
repeat Text(0, "Can you guess the number? ");
loop [C:= ChIn(0);
if C>=^0 & C<=^9 then quit;
Text(0, "Please enter a number in the given range.^M^J");
OpenI(0);
];
Backup; Guess:= IntIn(0);
Text(0, if Guess = Number then "Correct!"
else if Guess > Number then "Nope, too high."
else "You're too low.");
CrLf(0);
until Guess = Number;
]
|
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)
|
#zkl
|
zkl
|
r:=(0).random(10)+1;
while(1){
n:=ask("Num between 1 & 10: ");
try{n=n.toInt()}catch{ println("Number please"); continue; }
if(n==r){ println("Well guessed!"); break; }
println((n<r) and "small" or "big");
}
|
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
|
#SequenceL
|
SequenceL
|
import <Utilities/Math.sl>;
import <Utilities/Conversion.sl>;
main(argv(2)) := findHappys(stringToInt(head(argv)));
findHappys(count) := findHappysHelper(count, 1, []);
findHappysHelper(count, n, happys(1)) :=
happys when size(happys) = count
else
findHappysHelper(count, n + 1, happys ++ [n]) when isHappy(n)
else
findHappysHelper(count, n + 1, happys);
isHappy(n) := isHappyHelper(n, []);
isHappyHelper(n, cache(1)) :=
let
digits[i] := (n / integerPower(10, i - 1)) mod 10
foreach i within 1 ... ceiling(log(10, n + 1));
newN := sum(integerPower(digits, 2));
in
false when some(n = cache)
else
true when n = 1
else
isHappyHelper(newN, cache ++ [n]);
|
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
|
#LiveCode
|
LiveCode
|
put "Hello World!"
|
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!
|
#langur
|
langur
|
var .abc = [1, 2, 3]
var .def = [5, 6, 7]
.abc[3], .def[3] = .def[3], .abc[3]
writeln .abc
writeln .def
|
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.
|
#Metafont
|
Metafont
|
show max(4,5,20,1);
show max((12,3), (10,10), (25,5));
show max("hello", "world", "Hello World");
|
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.
|
#min
|
min
|
(
'bool ;does the list have any elements?
(-inf ('> 'pop 'nip if) reduce) ;do if so
({"empty seq" :error "Cannot find the maximum element of an empty sequence" :message} raise) ;do if not
if
) :seq-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.
|
#Joy
|
Joy
|
DEFINE gcd == [0 >] [dup rollup rem] while pop.
|
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.
|
#jq
|
jq
|
def recursive_gcd(a; b):
if b == 0 then a
else recursive_gcd(b; a % b)
end ;
|
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).
|
#LOLCODE
|
LOLCODE
|
HAI 1.3
HOW IZ I hailin YR stone
I HAS A sequence ITZ A BUKKIT
sequence HAS A length ITZ 1
sequence HAS A SRS 0 ITZ stone
IM IN YR stoner
BOTH SAEM stone AN 1, O RLY?
YA RLY, FOUND YR sequence
OIC
MOD OF stone AN 2, O RLY?
YA RLY, stone R SUM OF PRODUKT OF stone AN 3 AN 1
NO WAI, stone R QUOSHUNT OF stone AN 2
OIC
sequence HAS A SRS sequence'Z length ITZ stone
sequence'Z length R SUM OF sequence'Z length AN 1
IM OUTTA YR stoner
IF U SAY SO
I HAS A hail27 ITZ I IZ hailin YR 27 MKAY
VISIBLE "hail(27) = "!
IM IN YR first4 UPPIN YR i TIL BOTH SAEM i AN 4
VISIBLE hail27'Z SRS i " "!
IM OUTTA YR first4
VISIBLE "..."!
IM IN YR last4 UPPIN YR i TIL BOTH SAEM i AN 4
VISIBLE " " hail27'Z SRS SUM OF 108 AN i!
IM OUTTA YR last4
VISIBLE ", length = " hail27'Z length
I HAS A max, I HAS A len ITZ 0
BTW, DIS IZ RLY NOT FAST SO WE ONLY CHEK N IN [75000, 80000)
IM IN YR maxer UPPIN YR n TIL BOTH SAEM n AN 5000
I HAS A n ITZ SUM OF n AN 75000
I HAS A seq ITZ I IZ hailin YR n MKAY
BOTH SAEM len AN SMALLR OF len AN seq'Z length, O RLY?
YA RLY, max R n, len R seq'Z length
OIC
IM OUTTA YR maxer
VISIBLE "len(hail(" max ")) = " len
KTHXBYE
|
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)
|
#Zoomscript
|
Zoomscript
|
var randnum
var guess
randnum & random 1 10
guess = 0
while ne randnum guess
print "I'm thinking of a number between 1 and 10. What is it? "
guess & get
if lt guess randnum
print "Too low. Try again!"
println
endif
if gt guess randnum
print "Too high. Try again!"
println
endif
endwhile
print "Correct number. You win!"
|
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)
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
ZX Spectrum Basic has no [[:Category:Conditional loops|conditional LOOP]] constructs, so we have TO emulate them here using IF AND GO TO.
1 LET n=INT (RND*10)+1
2 INPUT "Guess a number that is between 1 and 10: ",g: IF g=n THEN PRINT "That's my number!": STOP
3 IF g<n THEN PRINT "That guess is too low!": GO TO 2
4 IF g>n THEN PRINT "That guess is too high!": GO TO 2
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#SETL
|
SETL
|
proc is_happy(n);
s := [n];
while n > 1 loop
if (n := +/[val(i)**2: i in str(n)]) in s then
return false;
end if;
s with:= n;
end while;
return true;
end proc;
|
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
|
#LLVM
|
LLVM
|
; const char str[14] = "Hello World!\00"
@.str = private unnamed_addr constant [14 x i8] c"Hello, world!\00"
; declare extern `puts` method
declare i32 @puts(i8*) nounwind
define i32 @main()
{
call i32 @puts( i8* getelementptr ([14 x i8]* @str, i32 0,i32 0))
ret i32 0
}
|
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!
|
#Lasso
|
Lasso
|
define swap(a, b) => (: #b, #a)
local(a) = 'foo'
local(b) = 42
local(a,b) = swap(#a, #b)
stdoutnl(#a)
stdoutnl(#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.
|
#MiniScript
|
MiniScript
|
list.max = function()
if not self then return null
result = self[0]
for item in self
if item > result then result = item
end for
return result
end function
print [47, 11, 42, 102, 13].max
|
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.
|
#.D0.9C.D0.9A-61.2F52
|
МК-61/52
|
П0 С/П x=0 07 ИП0 x<0 00 max БП 00
|
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.
|
#Julia
|
Julia
|
julia> gcd(4,12)
4
julia> gcd(6,12)
6
julia> gcd(7,12)
1
|
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.
|
#K
|
K
|
gcd:{:[~x;y;_f[y;x!y]]}
|
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).
|
#Lua
|
Lua
|
function hailstone( n, print_numbers )
local n_iter = 1
while n ~= 1 do
if print_numbers then print( n ) end
if n % 2 == 0 then
n = n / 2
else
n = 3 * n + 1
end
n_iter = n_iter + 1
end
if print_numbers then print( n ) end
return n_iter;
end
hailstone( 27, true )
max_i, max_iter = 0, 0
for i = 1, 100000 do
num = hailstone( i, false )
if num >= max_iter then
max_i = i
max_iter = num
end
end
print( string.format( "Needed %d iterations for the number %d.\n", max_iter, max_i ) )
|
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
|
#Sidef
|
Sidef
|
func happy(n) is cached {
static seen = Hash()
return true if n.is_one
return false if seen.exists(n)
seen{n} = 1
happy(n.digits.sum { _*_ })
}
say happy.first(8)
|
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
|
#Lobster
|
Lobster
|
print "Hello world!"
|
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!
|
#Lhogho
|
Lhogho
|
to swap :s1 :s2
local "t
make "t thing :s1
make :s1 thing :s2
make :s2 :t
end
make "a 4
make "b "dog
swap "a "b ; pass the names of the variables to swap
show list :a :b ; [dog 4]
|
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.
|
#Modula-3
|
Modula-3
|
GENERIC INTERFACE Maximum(Elem);
EXCEPTION Empty;
PROCEDURE Max(READONLY a: ARRAY OF Elem.T): Elem.T RAISES {Empty};
END Maximum.
|
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.
|
#MontiLang
|
MontiLang
|
2 5 3 12 9 9 56 2 ARR
LEN VAR l .
0 VAR i .
FOR l
GET i SWAP
i 1 + VAR i .
ENDFOR .
STKLEN 1 - VAR st .
FOR st
MAX
ENDFOR PRINT
|
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.
|
#Klong
|
Klong
|
gcd::{:[~x;y:|~y;x:|x>y;.f(y;x!y);.f(x;y!x)]}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Kotlin
|
Kotlin
|
tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) kotlin.math.abs(a) else gcd(b, a % b)
|
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).
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module hailstone.Task {
hailstone=lambda (n as long)->{
=lambda n (&val) ->{
if n=1 then =false: exit
=true
if n mod 2=0 then n/=2 : val=n: exit
n*=3 : n++: val=n
}
}
Count=Lambda (n) ->{
m=lambda n ->{
if n=1 then =false: exit
=true :if n mod 2=0 then n/=2 :exit
n*=3 : n++
}
c=1
While m() {c++}
=c
}
k=Hailstone(27)
counter=1
x=0
Print 27,
While k(&x) {
counter++
Print x,
if counter=4 then exit
}
Print
Flush ' empty current stack
While k(&x) {
counter++
data x ' send to end of stack -used as FIFO
if stack.size>4 then drop
}
\\ [] return a stack object and leave empty current stack
\\ Print use automatic iterator to print all values in columns.
Print []
Print "counter:";counter
m=0
For i=2 to 99999 {
m1=max.data(count(i), m)
if m1<>m then m=m1: im=i
}
Print Format$("Number {0} has then longest hailstone sequence of length {1}", im, m)
}
hailstone.Task
|
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
|
#Smalltalk
|
Smalltalk
|
Object subclass: HappyNumber [
|cache negativeCache|
HappyNumber class >> new [ |me|
me := super new.
^ me init
]
init [ cache := Set new. negativeCache := Set new. ]
hasSad: aNum [
^ (negativeCache includes: (self recycle: aNum))
]
hasHappy: aNum [
^ (cache includes: (self recycle: aNum))
]
addHappy: aNum [
cache add: (self recycle: aNum)
]
addSad: aNum [
negativeCache add: (self recycle: aNum)
]
recycle: aNum [ |r n| r := Bag new.
n := aNum.
[ n > 0 ]
whileTrue: [ |d|
d := n rem: 10.
r add: d.
n := n // 10.
].
^r
]
isHappy: aNumber [ |cycle number newnumber|
number := aNumber.
cycle := Set new.
[ (number ~= 1) & ( (cycle includes: number) not ) ]
whileTrue: [
(self hasHappy: number)
ifTrue: [ ^true ]
ifFalse: [
(self hasSad: number) ifTrue: [ ^false ].
cycle add: number.
newnumber := 0.
[ number > 0 ]
whileTrue: [ |digit|
digit := number rem: 10.
newnumber := newnumber + (digit * digit).
number := (number - digit) // 10.
].
number := newnumber.
]
].
(number = 1)
ifTrue: [
cycle do: [ :e | self addHappy: e ].
^true
]
ifFalse: [
cycle do: [ :e | self addSad: e ].
^false
]
]
].
|
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
|
#Logo
|
Logo
|
print [Hello world!]
|
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!
|
#Lingo
|
Lingo
|
on swap (x, y)
return "tmp="&x&RETURN&x&"="&y&RETURN&y&"=tmp"
end
|
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.
|
#MUMPS
|
MUMPS
|
MV(A,U)
;A is a list of values separated by the string U
NEW MAX,T,I
FOR I=1:1 SET T=$PIECE(A,U,I) QUIT:T="" S MAX=$SELECT(($DATA(MAX)=0):T,(MAX<T):T,(MAX>=T):MAX)
QUIT MAX
|
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.
|
#Nanoquery
|
Nanoquery
|
def max(list)
if len(list) = 0
return null
end
largest = list[0]
for val in list
if val > largest
largest = val
end
end
return largest
end
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#LabVIEW
|
LabVIEW
|
{def gcd
{lambda {:a :b}
{if {= :b 0}
then :a
else {gcd :b {% :a :b}}}}}
-> gcd
{gcd 12 3}
-> 3
{gcd 123 122}
-> 1
{S.map {gcd 123} {S.serie 1 30}}
-> 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3
A simpler one if a and b are greater than zero
{def GCD
{lambda {:a :b}
{if {= :a :b}
then :a
else {if {> :a :b}
then {GCD {- :a :b} :b}
else {GCD :a {- :b :a}}}}}}
-> GCD
{S.map {GCD 123} {S.serie 1 30}}
-> 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3
|
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).
|
#Maple
|
Maple
|
hailstone := proc( N )
local n := N, HS := Array([n]);
while n > 1 do
if type(n,even) then
n := n/2;
else
n := 3*n+1;
end if;
HS(numelems(HS)+1) := n;
end do;
HS;
end proc;
|
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
|
#Swift
|
Swift
|
func isHappyNumber(var n:Int) -> Bool {
var cycle = [Int]()
while n != 1 && !cycle.contains(n) {
cycle.append(n)
var m = 0
while n > 0 {
let d = n % 10
m += d * d
n = (n - d) / 10
}
n = m
}
return n == 1
}
var found = 0
var count = 0
while found != 8 {
if isHappyNumber(count) {
print(count)
found++
}
count++
}
|
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
|
#Logtalk
|
Logtalk
|
:- object(hello_world).
% the initialization/1 directive argument is automatically executed
% when the object is loaded into memory:
:- initialization(write('Hello world!\n')).
:- end_object.
|
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!
|
#Lisaac
|
Lisaac
|
(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.
|
#Neko
|
Neko
|
/**
greatest element from a list (Neko Array)
Tectonics:
nekoc greatest-element.neko
neko greatest-element
*/
var greatest = function(list) {
var max, element;
var pos = 1;
if $asize(list) > 0 max = list[0];
while pos < $asize(list) {
element = list[pos];
if max < element max = element;
pos += 1;
}
return max;
}
$print(greatest($array(5, 1, 3, 5)), "\n");
$print(greatest($array("abc", "123", "zyx", "def")), "\n");
|
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.
|
#Lambdatalk
|
Lambdatalk
|
{def gcd
{lambda {:a :b}
{if {= :b 0}
then :a
else {gcd :b {% :a :b}}}}}
-> gcd
{gcd 12 3}
-> 3
{gcd 123 122}
-> 1
{S.map {gcd 123} {S.serie 1 30}}
-> 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3
A simpler one if a and b are greater than zero
{def GCD
{lambda {:a :b}
{if {= :a :b}
then :a
else {if {> :a :b}
then {GCD {- :a :b} :b}
else {GCD :a {- :b :a}}}}}}
-> GCD
{S.map {GCD 123} {S.serie 1 30}}
-> 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3
|
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).
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
HailstoneF[n_] := NestWhileList[If[OddQ[#], 3 # + 1, #/2] &, n, # > 1 &]
|
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
|
#Tcl
|
Tcl
|
proc is_happy n {
set seen [list]
while {$n > 1 && [lsearch -exact $seen $n] == -1} {
lappend seen $n
set n [sum_of_squares [split $n ""]]
}
return [expr {$n == 1}]
}
set happy [list]
set n -1
while {[llength $happy] < 8} {
if {[is_happy $n]} {lappend happy $n}
incr n
}
puts "the first 8 happy numbers are: [list $happy]"
|
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
|
#LOLCODE
|
LOLCODE
|
HAI
CAN HAS STDIO?
VISIBLE "Hello world!"
KTHXBYE
|
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!
|
#LiveCode
|
LiveCode
|
put "first" into a1
put "last" into b2
swap a1,b2
put a1 && b2
command swap @p1, @p2
put p2 into p3
put p1 into p2
put p3 into p1
end swap
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Nemerle
|
Nemerle
|
using System;
using Nemerle.Collections;
using System.Linq;
using System.Console;
module SeqMax
{
SeqMax[T, U] (this seq : T) : U
where T : Seq[U]
where U : IComparable
{
$[s | s in seq].Fold(seq.First(), (x, y) => {if (x.CompareTo(y) > 0) x else y})
}
Main() : void
{
def numbers = [1, 12, 3, -5, 6, 23];
def letters = ['s', 'p', 'a', 'm'];
// using SeqMax() method (as task says to "create a function")
WriteLine($"numbers.SeqMax() = $(numbers.SeqMax())");
WriteLine($"letters.SeqMax() = $(letters.SeqMax())");
// using the already available Max() method
WriteLine($"numbers.Max() = $(numbers.Max())");
WriteLine($"letters.Max() = $(letters.Max())")
}
}
|
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.
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref savelog symbols binary
rn = Random()
maxElmts = 100
dlist = double[maxElmts]
rlist = Rexx[maxElmts]
loop r_ = 0 to maxElmts - 1
nr = rn.nextGaussian * 100.0
dlist[r_] = nr
rlist[r_] = Rexx(nr)
end r_
say 'Max double:' Rexx(getMax(dlist)).format(4, 9)
say 'Max Rexx:' getMax(rlist).format(4, 9)
return
method getMax(dlist = double[]) public static binary returns double
dmax = Double.MIN_VALUE
loop n_ = 0 to dlist.length - 1
if dlist[n_] > dmax then dmax = dlist[n_]
end n_
return dmax
method getMax(dlist = Rexx[]) public static binary returns Rexx
dmax = Rexx(Double.MIN_VALUE)
loop n_ = 0 to dlist.length - 1
dmax = dlist[n_].max(dmax)
end n_
return dmax
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.