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/Nautical_bell | Nautical bell |
Task
Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.
The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.
It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type.
Related task
Sleep
| #Wren | Wren | import "os" for Process
import "timer" for Timer
import "/date" for Date
import "/fmt" for Fmt
var watches = ["First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First"]
var args = Process.arguments
if (args.count == 0) {
System.print("Please enter current time in the format (24 hour clock): hh:mm:ss.")
return
}
var now = Date.parse(args[0], Date.isoTime)
while (true) {
var h = now.hour
var m = now.minute
var s = now.second
if ((m == 0 || m == 30) && s == 0) {
var bell = (m == 30) ? 1 : 0
var bells = (h*2 + bell) % 8
var watch = (h/4).floor + 1
if (bells == 0) {
bells = 8
watch = watch - 1
}
var sound = "\a" * bells
var pl = (bells != 1) ? "s" : ""
var w = watches[watch] + " watch"
if (watch == 5) {
if (bells < 5) {
w = "First " + w
} else {
w = "Last " + w
}
}
Fmt.lprint("$s$02d:$02d = $d bell$s : $s", [sound, h, m, bells, pl, w])
}
Timer.sleep(1000)
now = now.addSeconds(1)
} |
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence.
Note: Subsequences are defined structurally, not by their contents.
So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
Task: Find all non-continuous subsequences for a given sequence.
Example
For the sequence 1,2,3,4, there are five non-continuous subsequences, namely:
1,3
1,4
2,4
1,3,4
1,2,4
Goal
There are different ways to calculate those subsequences.
Demonstrate algorithm(s) that are natural for the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Raku | Raku | sub non_continuous_subsequences ( *@list ) {
@list.combinations.grep: { 1 != all( .[ 0 ^.. .end] Z- .[0 ..^ .end] ) }
}
say non_continuous_subsequences( 1..3 )».gist;
say non_continuous_subsequences( 1..4 )».gist;
say non_continuous_subsequences( ^4 ).map: {[<a b c d>[.list]].gist}; |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #HicEst | HicEst | CHARACTER txt*80
num = 36^7 -1 ! 7836416410
CALL DecToBase(num, txt, 36)
WRITE(ClipBoard, Name) num, txt, BaseToDec(36, txt)
END
FUNCTION BaseToDec(base, string)
CHARACTER string
BaseToDec = 0
length = LEN_TRIM(string)
DO i = 1, length
n = INDEX("0123456789abcdefghijklmnopqrstuvwxyz", string(i)) - 1
BaseToDec = BaseToDec + n * base^(length-i)
ENDDO
END
SUBROUTINE DectoBase(decimal, string, base)
CHARACTER string
string = '0'
temp = decimal
length = CEILING( LOG(decimal+1, base) )
DO i = length, 1, -1
n = MOD( temp, base )
string(i) = "0123456789abcdefghijklmnopqrstuvwxyz"(n+1)
temp = INT(temp / base)
ENDDO
END |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary (expect 21102)
Encode the decimal number 15 as negadecimal (expect 195)
In each of the above cases, convert the encoded number back to decimal.
extra credit
supply an integer, that when encoded to base -62 (or something "higher"), expresses the
name of the language being used (with correct capitalization). If the computer language has
non-alphanumeric characters, try to encode them into the negatory numerals, or use other
characters instead.
| #Ring | Ring |
# Project : Negative base numbers
negs = [[146,-3],[21102,-3],[10,-2],[11110,-2],[15,-10],[195,-10]]
for n = 1 to len(negs) step 2
enc = encodeNegBase(negs[n][1],negs[n][2])
encstr = showarray(enc)
dec = decodeNegBase(negs[n+1][1],negs[n+1][2])
see "" + negs[n][1] + " encoded in base " + negs[n][2] + " = " + encstr + nl
see "" + negs[n+1][1] + " decoded in base " + negs[n+1][2] + " = " + dec + nl
next
func encodeNegBase(n,b)
out = []
while n != 0
rem = (n%b)
if rem < 0
rem = rem - b
ok
n = ceil(n/b)
rem = fabs(rem)
add(out,rem)
end
out = reverse(out)
return out
func decodeNegBase(n,b)
out = 0
n = string(n)
for nr = len(n) to 1 step -1
out = out + n[nr]*pow(b,len(n)-nr)
next
return out
func showarray(vect)
svect = ""
for n = 1 to len(vect)
svect = svect + vect[n]
next
return svect
|
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary (expect 21102)
Encode the decimal number 15 as negadecimal (expect 195)
In each of the above cases, convert the encoded number back to decimal.
extra credit
supply an integer, that when encoded to base -62 (or something "higher"), expresses the
name of the language being used (with correct capitalization). If the computer language has
non-alphanumeric characters, try to encode them into the negatory numerals, or use other
characters instead.
| #Ruby | Ruby | DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
# convert a base 10 integer into a negative base value (as a string)
def negative_base_encode(n, b)
raise 'base out of range' if (b < -62) || (b > -2)
return '0' if n == 0
revdigs = []
while n != 0 do
n, r = n.divmod(b)
if r < 0
n += 1
r -= b
end
revdigs << r
end
return revdigs.reduce('') { |digstr, digit| DIGITS[digit] + digstr }
end
# convert a negative base value (as a string) into a base 10 integer
def negative_base_decode(n, b)
raise 'base out of range' if (b < -62) || (b > -2)
value = 0
n.reverse.each_char.with_index do |ch, inx|
value += DIGITS.index(ch) * b**inx
end
return value
end
# do the task
[ [10, -2], [146, -3], [15, -10], [0, -31], [-6221826, -62] ].each do |pair|
decimal, base = pair
encoded = negative_base_encode(decimal, base)
decoded = negative_base_decode(encoded, base)
puts("Enc: %8i base %-3i = %5s base %-3i Dec: %5s base %-3i = %8i base %-3i" %
[decimal, 10, encoded, base, encoded, base, decoded, 10])
end |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Rust | Rust |
fn main() {
let mut tokens = 12;
println!("Nim game");
println!("Starting with {} tokens.", tokens);
println!("");
loop {
tokens = p_turn(&tokens);
print_remaining(&tokens);
tokens = c_turn(&tokens);
print_remaining(&tokens);
if tokens == 0 {
println!("Computer wins!");
break;
}
}
}
fn p_turn(tokens: &i32) -> i32 {
loop { //try until we get a good number
println!("How many tokens would you like to take?");
let mut take = String::new();
io::stdin().read_line(&mut take)
.expect("Sorry, I didn't understand that.");
let take: i32 = match take.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid input");
println!("");
continue;
}
};
if take > 3 || take < 1 {
println!("Take must be between 1 and 3.");
println!("");
continue;
}
return tokens - take;
}
}
fn c_turn(tokens: &i32) -> i32 {
let take = tokens % 4;
println!("Computer takes {} tokens.", take);
return tokens - take;
}
fn print_remaining(tokens: &i32) {
println!("{} tokens remaining.", tokens);
println!("");
}
|
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #S-Basic | S-Basic |
$constant maxtokens = 12
$constant machine = 0
$constant human = 1
$constant false = 0
$constant true = 0FFFFH
procedure welcome
print "Welcome to the Game of Nim."
print "We begin with";maxtokens;" tokens. On each turn, a player"
print "may take between 1 and 3 tokens. The player who takes the"
print "last token wins."
print
end
procedure show(n = integer)
var i = integer
print "Available tokens:";n;" ";
rem - provide a visual display
for i = 1 to n
print "o ";
next i
print
end
function getnum(lowlim, toplim = integer) = integer
var ok, n = integer
repeat
begin
input "You take:";n
if n < lowlim or n > toplim then
begin
print "Must take between";lowlim;" and";toplim
print "Try again."
ok = false
end
else
ok = true
end
until ok
end = n
function play(player, tokens, taken = integer) = integer
if player = human then
taken = getnum(1,3)
else
taken = 4 - taken
end = taken
procedure report(player = integer)
if player = human then
print "You took the last one. You win. Congratulations!"
else
print "I took the last one, so I win. Sorry about that."
end
var player, tokens, taken = integer
welcome
tokens = maxtokens
taken = 0
player = human
print "You go first."
repeat
begin
show tokens
taken = play(player, tokens, taken)
tokens = tokens - taken
if player = machine then print "I took:";taken
if tokens > 0 then player = 1 - player
end
until tokens = 0
report player
print "Thanks for playing!"
end |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Scala | Scala |
var tokens = 12
def playerTurn(curTokens: Int): Unit =
{
val take = readLine("How many tokens would you like to take? ").toInt
if (take < 1 || take > 3) {
println("Number must be between 1 and 3.")
playerTurn(curTokens)
}
else {
tokens = curTokens - take
println(s"You take $take tokens. $tokens tokens remaining.\n")
}
}
def compTurn(curTokens: Int): Unit =
{
val take = curTokens % 4
tokens = curTokens - take
println(s"Computer takes $take tokens. $tokens remaining.\n")
}
def main(args: Array[String]): Unit =
{
while (tokens > 0)
{
playerTurn(tokens)
compTurn(tokens)
}
println("Computer wins!")
}
|
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #AWK | AWK |
# syntax: GAWK -f NARCISSISTIC_DECIMAL_NUMBER.AWK
BEGIN {
for (n=0;;n++) {
leng = length(n)
sum = 0
for (i=1; i<=leng; i++) {
c = substr(n,i,1)
sum += c ^ leng
}
if (n == sum) {
printf("%d ",n)
if (++count == 25) { break }
}
}
exit(0)
}
|
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Ada | Ada | with Cairo; use Cairo;
with Cairo.Png; use Cairo.Png;
with Cairo.Image_Surface; use Cairo.Image_Surface;
procedure XorPattern is
type xorable is mod 256;
Surface : Cairo_Surface;
Data : RGB24_Array_Access;
Status : Cairo_Status;
Num : Byte;
begin
Data := new RGB24_Array(0..256*256-1);
for x in Natural range 0..255 loop
for y in Natural range 0..255 loop
Num := Byte(xorable(x) xor xorable(y));
Data(x+256*y) := RGB24_Data'(Num,0,Num);
end loop;
end loop;
Surface := Create_For_Data_RGB24(Data, 256, 256);
Status := Write_To_Png (Surface, "AdaXorPattern.png");
pragma Assert (Status = Cairo_Status_Success);
end XorPattern; |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Applesoft_BASIC | Applesoft BASIC | 100 DATA 0,2, 6,10,5, 6, 7,15
110 DATA 0,1, 3,10,5, 3,11,15
120 DATA 0,8, 9,10,5, 9,13,15
130 DATA 0,4,12,10,5,12,14,15
140 LET C = 7
150 POKE 768,169: REM LDA #
160 POKE 770,073: REM EOR #
170 POKE 772,133: REM STA
180 POKE 773,235: REM $EB
190 POKE 774,096: REM RTS
200 GR
210 FOR H = 0 TO 1
220 FOR W = 0 TO 1
230 FOR S = 0 TO C
240 READ C(S)
250 NEXT S
260 FOR Y = 0 TO C
270 POKE 769,Y
280 LET Y1 = H * S * 2 + Y * 2
290 FOR X = 0 TO C
300 POKE 771,X
310 CALL 768
320 COLOR= C( PEEK (235))
330 VLIN Y1,Y1 + 1 AT W * S + X
340 NEXT X,Y,W,H |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #8080_Assembly | 8080 Assembly | org 100h
jmp test
;;; Implementation of F(A).
F: ana a ; Zero?
jz one ; Then set A=1
mov b,a ; Otherwise, set B=A,
push b ; And put it on the stack
dcr a ; Set A=A-1
call F ; Set A=F(A-1)
call M ; Set A=M(F(A-1))
pop b ; Retrieve input value
cma ; (-A)+B is actually one cycle faster
inr a ; than C=A;A=B;A-=B, and equivalent
add b
ret
one: mvi a,1 ; Set A to 1,
ret ; and return.
;;; Implementation of M(A).
M: ana a ; Zero?
rz ; Then keep it that way and return.
mov b,a
push b ; Otherwise, same deal as in F,
dcr a ; but M and F are called in opposite
call M ; order.
call F
pop b
cma
inr a
add b
ret
;;; Demonstration code.
test: lhld 6 ; Set stack pointer to highest usable
sphl ; memory.
;;; Print F([0..15])
lxi d,fpfx ; Print "F: "
mvi c,9
call 5
xra a ; Start with N=0
floop: push psw ; Keep N
call F ; Get value for F(N)
call pdgt ; Print it
pop psw ; Restore N
inr a ; Next N
cpi 16 ; Done yet?
jnz floop
;;; Print M([0..15])
lxi d,mpfx ; Print "\r\nM: "
mvi c,9
call 5
xra a ; Start with N=0
mloop: push psw ; same deal as above
call M
call pdgt
pop psw ; Restore N
inr a
cpi 16
jnz mloop
rst 0 ; Explicit exit, we got rid of system stack
;;; Print digit and space
pdgt: adi '0' ; ASCII
mov e,a
mvi c,2
call 5
mvi e,' ' ; Space
mvi c,2
jmp 5 ; Tail call optimization
fpfx: db 'F: $'
mpfx: db 13,10,'M: $' |
http://rosettacode.org/wiki/Musical_scale | Musical scale | Task
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| #Action.21 | Action! | DEFINE PTR="CARD"
PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
BYTE AUDCTL=$D208,AUDF1=$D200,AUDC1=$D201,AUDF2=$D202,AUDC2=$D203
PTR ARRAY notes(8)
BYTE ARRAY pitch8=[60 53 47 45 40 35 31 30]
CARD ARRAY pitch16=[1703 1517 1350 1274 1134 1010 899 848]
BYTE i
CARD p
notes(0)="Do" notes(1)="Re" notes(2)="Mi" notes(3)="Fa"
notes(4)="Sol" notes(5)="La" notes(6)="Si" notes(7)="Do"
PrintE("8-bit precision pitch values:")
FOR i=0 TO 7
DO
PrintF("%S-%B ",notes(i),pitch8(i))
Sound(0,pitch8(i),10,10)
Wait(20)
OD
SndRst()
Wait(20)
PutE() PutE()
AUDCTL=$50 ;join channel 1 and 2 to get 16-bit
AUDC1=$A0 ;turn off channel 1
AUDC2=$AA ;turn on channel 2
PrintE("16-bit precision pitch values:")
FOR i=0 TO 7
DO
PrintF("%S-%U ",notes(i),pitch16(i))
p=pitch16(i)
AUDF2=p RSH 8
AUDF1=p&$FF
Wait(20)
OD
SndRst()
AUDCTL=$00 ;restore default configuration
Wait(20)
RETURN |
http://rosettacode.org/wiki/N-smooth_numbers | N-smooth numbers | n-smooth numbers are positive integers which have no prime factors > n.
The n (when using it in the expression) n-smooth is always prime,
there are no 9-smooth numbers.
1 (unity) is always included in n-smooth numbers.
2-smooth numbers are non-negative powers of two.
5-smooth numbers are also called Hamming numbers.
7-smooth numbers are also called humble numbers.
A way to express 11-smooth numbers is:
11-smooth = 2i × 3j × 5k × 7m × 11p
where i, j, k, m, p ≥ 0
Task
calculate and show the first 25 n-smooth numbers for n=2 ───► n=29
calculate and show three numbers starting with 3,000 n-smooth numbers for n=3 ───► n=29
calculate and show twenty numbers starting with 30,000 n-smooth numbers for n=503 ───► n=521 (optional)
All ranges (for n) are to be inclusive, and only prime numbers are to be used.
The (optional) n-smooth numbers for the third range are: 503, 509, and 521.
Show all n-smooth numbers for any particular n in a horizontal list.
Show all output here on this page.
Related tasks
Hamming numbers
humble numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A000079 2-smooth numbers or non-negative powers of two
OEIS entry: A003586 3-smooth numbers
OEIS entry: A051037 5-smooth numbers or Hamming numbers
OEIS entry: A002473 7-smooth numbers or humble numbers
OEIS entry: A051038 11-smooth numbers
OEIS entry: A080197 13-smooth numbers
OEIS entry: A080681 17-smooth numbers
OEIS entry: A080682 19-smooth numbers
OEIS entry: A080683 23-smooth numbers
| #D | D | import std.algorithm;
import std.bigint;
import std.exception;
import std.range;
import std.stdio;
BigInt[] primes;
int[] smallPrimes;
bool isPrime(BigInt value) {
if (value < 2) return false;
if (value % 2 == 0) return value == 2;
if (value % 3 == 0) return value == 3;
if (value % 5 == 0) return value == 5;
if (value % 7 == 0) return value == 7;
if (value % 11 == 0) return value == 11;
if (value % 13 == 0) return value == 13;
if (value % 17 == 0) return value == 17;
if (value % 19 == 0) return value == 19;
if (value % 23 == 0) return value == 23;
BigInt t = 29;
while (t * t < value) {
if (value % t == 0) return false;
value += 2;
if (value % t == 0) return false;
value += 4;
}
return true;
}
// cache all primes up to 521
void init() {
primes ~= BigInt(2);
smallPrimes ~= 2;
BigInt i = 3;
while (i <= 521) {
if (isPrime(i)) {
primes ~= i;
if (i <= 29) {
smallPrimes ~= i.toInt;
}
}
i += 2;
}
}
BigInt[] nSmooth(int n, int size)
in {
enforce(n >= 2 && n <= 521, "n must be between 2 and 521");
enforce(size > 1, "size must be at least 1");
}
do {
BigInt bn = n;
bool ok = false;
foreach (prime; primes) {
if (bn == prime) {
ok = true;
break;
}
}
enforce(ok, "n must be a prime number");
BigInt[] ns;
ns.length = size;
ns[] = BigInt(0);
ns[0] = 1;
BigInt[] next;
foreach(prime; primes) {
if (prime > bn) {
break;
}
next ~= prime;
}
int[] indicies;
indicies.length = next.length;
indicies[] = 0;
foreach (m; 1 .. size) {
ns[m] = next.reduce!min;
foreach (i,v; indicies) {
if (ns[m] == next[i]) {
indicies[i]++;
next[i] = primes[i] * ns[indicies[i]];
}
}
}
return ns;
}
void main() {
init();
foreach (i; smallPrimes) {
writeln("The first ", i, "-smooth numbers are:");
writeln(nSmooth(i, 25));
writeln;
}
foreach (i; smallPrimes.drop(1)) {
writeln("The 3,000th to 3,202 ", i, "-smooth numbers are:");
writeln(nSmooth(i, 3_002).drop(2_999));
writeln;
}
foreach (i; [503, 509, 521]) {
writeln("The 30,000th to 30,019 ", i, "-smooth numbers are:");
writeln(nSmooth(i, 30_019).drop(29_999));
writeln;
}
} |
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before.
Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL.
See also:
Varargs
Optional parameters
Wikipedia: Named parameter
| #Dyalect | Dyalect | func fun(x, y = 0, z = 12.2, dsc = "Useless text") {
print("x=\(x), y=\(y), z=\(z), dsc=\(dsc)")
}
fun(12, z: 24.4, dsc: "Foo", y: 3)
fun(y: 42, x: 12) |
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before.
Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL.
See also:
Varargs
Optional parameters
Wikipedia: Named parameter
| #E | E | def printName([=> first := null, => last := null]) {
if (last == null) {
print("?")
} else {
print(last)
}
if (first != null) {
print(", ")
print(first)
}
} |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #E | E | def nthroot(n, x) {
require(n > 1 && x > 0)
def np := n - 1
def iter(g) { return (np*g + x/g**np) / n }
var g1 := x
var g2 := iter(g1)
while (!(g1 <=> g2)) {
g1 := iter(g1)
g2 := iter(iter(g2))
}
return g1
} |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Applesoft_BASIC | Applesoft BASIC | 0 OP = 1
10 FOR N = 0 TO 25 : GOSUB 100 : NEXT
20 FOR N = 250 TO 265 : GOSUB 100 : NEXT
30 FOR N = 1000 TO 1025 : GOSUB 100 : NEXT
40 END
100 GOSUB 200"NTH
110 PRINT NTH$ " ";
120 RETURN
200 M1 = N - INT(N / 10) * 10
210 M2 = N - INT(N / 100) * 100
220 NTH$ = "TH"
230 IF M1 = 1 AND M2 <> 11 THEN NTH$ = "ST"
240 IF M1 = 2 AND M2 <> 12 THEN NTH$ = "ND"
250 IF M1 = 3 AND M2 <> 13 THEN NTH$ = "RD"
260 IF NOT OP THEN NTH$ = "'" + NTH$
270 NTH$ = STR$(N) + NTH$
280 RETURN |
http://rosettacode.org/wiki/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n:
μ(1) is defined to be 1.
μ(n) = 1 if n is a square-free positive integer with an even number of prime factors.
μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
μ(n) = 0 if n has a squared prime factor.
Task
Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
See also
Wikipedia: Möbius function
Related Tasks
Mertens function
| #FreeBASIC | FreeBASIC | function mobius( n as uinteger ) as integer
if n = 1 then return 1
for d as uinteger = 2 to int(sqr(n))
if n mod d = 0 then
if n mod (d*d) = 0 then return 0
return -mobius(n/d)
end if
next d
return -1
end function
dim as string outstr = " . "
for i as uinteger = 1 to 200
if mobius(i)>=0 then outstr += " "
outstr += str(mobius(i))+" "
if i mod 10 = 9 then
print outstr
outstr = ""
end if
next i |
http://rosettacode.org/wiki/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n:
μ(1) is defined to be 1.
μ(n) = 1 if n is a square-free positive integer with an even number of prime factors.
μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
μ(n) = 0 if n has a squared prime factor.
Task
Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
See also
Wikipedia: Möbius function
Related Tasks
Mertens function
| #FutureBasic | FutureBasic | local fn IsPrime( n as long ) as BOOL
BOOL result = YES
long i
if ( n < 2 ) then result = NO : exit fn
for i = 2 to n + 1
if ( i * i <= n ) and ( n mod i == 0 )
result = NO : exit fn
end if
next
end fn = result
local fn Mobius( n as long ) as long
long i, p = 0, result = 0
if ( n == 1 ) then result = 1 : exit fn
for i = 1 to n + 1
if ( n mod i == 0 ) and ( fn IsPrime( i ) == YES )
if ( n mod ( i * i ) == 0 )
result = 0 : exit fn
else
p++
end if
end if
next
if( p mod 2 != 0 )
result = -1
else
result = 1
end if
end fn = result
window 1, @"Möbius function", (0,0,600,300)
printf @"First 100 terms of Mobius sequence:"
long i
for i = 1 to 100
printf @"%2ld\t", fn Mobius(i)
if ( i mod 20 == 0 ) then print
next
HandleEvents |
http://rosettacode.org/wiki/Natural_sorting | Natural sorting |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Natural sorting is the sorting of text that does more than rely on the
order of individual characters codes to make the finding of
individual strings easier for a human reader.
There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include:
1. Ignore leading, trailing and multiple adjacent spaces
2. Make all whitespace characters equivalent.
3. Sorting without regard to case.
4. Sorting numeric portions of strings in numeric order.
That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers.
foo9.txt before foo10.txt
As well as ... x9y99 before x9y100, before x10y0
... (for any number of groups of integers in a string).
5. Title sorts: without regard to a leading, very common, word such
as 'The' in "The thirty-nine steps".
6. Sort letters without regard to accents.
7. Sort ligatures as separate letters.
8. Replacements:
Sort German eszett or scharfes S (ß) as ss
Sort ſ, LATIN SMALL LETTER LONG S as s
Sort ʒ, LATIN SMALL LETTER EZH as s
∙∙∙
Task Description
Implement the first four of the eight given features in a natural sorting routine/function/method...
Test each feature implemented separately with an ordered list of test strings from the Sample inputs section below, and make sure your naturally sorted output is in the same order as other language outputs such as Python.
Print and display your output.
For extra credit implement more than the first four.
Note: it is not necessary to have individual control of which features are active in the natural sorting routine at any time.
Sample input
• Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2',
'ignore leading spaces: 2-1',
'ignore leading spaces: 2+0',
'ignore leading spaces: 2+1']
• Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2',
'ignore MAS spaces: 2-1',
'ignore MAS spaces: 2+0',
'ignore MAS spaces: 2+1']
• Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3',
'Equiv. \rspaces: 3-2',
'Equiv. \x0cspaces: 3-1',
'Equiv. \x0bspaces: 3+0',
'Equiv. \nspaces: 3+1',
'Equiv. \tspaces: 3+2']
• Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2',
'caSE INDEPENDENT: 3-1',
'casE INDEPENDENT: 3+0',
'case INDEPENDENT: 3+1']
• Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt',
'foo100bar10baz0.txt',
'foo1000bar99baz10.txt',
'foo1000bar99baz9.txt']
• Title sorts. Text strings: ['The Wind in the Willows',
'The 40th step more',
'The 39 steps',
'Wanda']
• Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2',
u'Equiv. \xdd accents: 2-1',
u'Equiv. y accents: 2+0',
u'Equiv. Y accents: 2+1']
• Separated ligatures. Text strings: [u'\u0132 ligatured ij',
'no ligature']
• Character replacements. Text strings: [u'Start with an \u0292: 2-2',
u'Start with an \u017f: 2-1',
u'Start with an \xdf: 2+0',
u'Start with an s: 2+1']
| #Kotlin | Kotlin | // version 1.1.4-3
val r2 = Regex("""[ ]{2,}""")
val r3 = Regex("""\s""") // \s represents any whitespace character
val r5 = Regex("""\d+""")
/** Only covers ISO-8859-1 accented characters plus (for consistency) Ÿ */
val ucAccented = arrayOf("ÀÁÂÃÄÅ", "Ç", "ÈÉÊË", "ÌÍÎÏ", "Ñ", "ÒÓÔÕÖØ", "ÙÚÛÜ", "ÝŸ")
val lcAccented = arrayOf("àáâãäå", "ç", "èéêë", "ìíîï", "ñ", "òóôõöø", "ùúûü", "ýÿ")
val ucNormal = "ACEINOUY"
val lcNormal = "aceinouy"
/** Only the commoner ligatures */
val ucLigatures = "ÆIJŒ"
val lcLigatures = "æijœ"
val ucSeparated = arrayOf("AE", "IJ", "OE")
val lcSeparated = arrayOf("ae", "ij", "oe")
/** Miscellaneous replacements */
val miscLetters = "ßſʒ"
val miscReplacements = arrayOf("ss", "s", "s")
/** Displays strings including whitespace as if the latter were literal characters */
fun String.toDisplayString(): String {
val whitespace = arrayOf("\t", "\n", "\u000b", "\u000c", "\r")
val whitespace2 = arrayOf("\\t", "\\n", "\\u000b", "\\u000c", "\\r")
var s = this
for (i in 0..4) s = s.replace(whitespace[i], whitespace2[i])
return s
}
/** Ignoring leading space(s) */
fun selector1(s: String) = s.trimStart(' ')
/** Ignoring multiple adjacent spaces i.e. condensing to a single space */
fun selector2(s: String) = s.replace(r2, " ")
/** Equivalent whitespace characters (equivalent to a space say) */
fun selector3(s: String) = s.replace(r3, " ")
/** Case independent sort */
fun selector4(s: String) = s.toLowerCase()
/** Numeric fields as numerics (deals with up to 20 digits) */
fun selector5(s: String) = r5.replace(s) { it.value.padStart(20, '0') }
/** Title sort */
fun selector6(s: String): String {
if (s.startsWith("the ", true)) return s.drop(4)
if (s.startsWith("an ", true)) return s.drop(3)
if (s.startsWith("a ", true)) return s.drop(2)
return s
}
/** Equivalent accented characters (and case) */
fun selector7(s: String): String {
val sb = StringBuilder()
outer@ for (c in s) {
for ((i, ucs) in ucAccented.withIndex()) {
if (c in ucs) {
sb.append(ucNormal[i])
continue@outer
}
}
for ((i, lcs) in lcAccented.withIndex()) {
if (c in lcs) {
sb.append(lcNormal[i])
continue@outer
}
}
sb.append(c)
}
return sb.toString().toLowerCase()
}
/** Separated ligatures */
fun selector8(s: String): String {
var ss = s
for ((i, c) in ucLigatures.withIndex()) ss = ss.replace(c.toString(), ucSeparated[i])
for ((i, c) in lcLigatures.withIndex()) ss = ss.replace(c.toString(), lcSeparated[i])
return ss
}
/** Character replacements */
fun selector9(s: String): String {
var ss = s
for ((i, c) in miscLetters.withIndex()) ss = ss.replace(c.toString(), miscReplacements[i])
return ss
}
fun main(args: Array<String>) {
println("The 9 string lists, sorted 'naturally':\n")
val s1 = arrayOf(
"ignore leading spaces: 2-2",
" ignore leading spaces: 2-1",
" ignore leading spaces: 2+0",
" ignore leading spaces: 2+1"
)
s1.sortBy(::selector1)
println(s1.map { "'$it'" }.joinToString("\n"))
val s2 = arrayOf(
"ignore m.a.s spaces: 2-2",
"ignore m.a.s spaces: 2-1",
"ignore m.a.s spaces: 2+0",
"ignore m.a.s spaces: 2+1"
)
println()
s2.sortBy(::selector2)
println(s2.map { "'$it'" }.joinToString("\n"))
val s3 = arrayOf(
"Equiv. spaces: 3-3",
"Equiv.\rspaces: 3-2",
"Equiv.\u000cspaces: 3-1",
"Equiv.\u000bspaces: 3+0",
"Equiv.\nspaces: 3+1",
"Equiv.\tspaces: 3+2"
)
println()
s3.sortBy(::selector3)
println(s3.map { "'$it'".toDisplayString() }.joinToString("\n"))
val s4 = arrayOf(
"cASE INDEPENENT: 3-2",
"caSE INDEPENENT: 3-1",
"casE INDEPENENT: 3+0",
"case INDEPENENT: 3+1"
)
println()
s4.sortBy(::selector4)
println(s4.map { "'$it'" }.joinToString("\n"))
val s5 = arrayOf(
"foo100bar99baz0.txt",
"foo100bar10baz0.txt",
"foo1000bar99baz10.txt",
"foo1000bar99baz9.txt"
)
println()
s5.sortBy(::selector5)
println(s5.map { "'$it'" }.joinToString("\n"))
val s6 = arrayOf(
"The Wind in the Willows",
"The 40th step more",
"The 39 steps",
"Wanda"
)
println()
s6.sortBy(::selector6)
println(s6.map { "'$it'" }.joinToString("\n"))
val s7 = arrayOf(
"Equiv. ý accents: 2-2",
"Equiv. Ý accents: 2-1",
"Equiv. y accents: 2+0",
"Equiv. Y accents: 2+1"
)
println()
s7.sortBy(::selector7)
println(s7.map { "'$it'" }.joinToString("\n"))
val s8 = arrayOf(
"IJ ligatured ij",
"no ligature"
)
println()
s8.sortBy(::selector8)
println(s8.map { "'$it'" }.joinToString("\n"))
val s9 = arrayOf(
"Start with an ʒ: 2-2",
"Start with an ſ: 2-1",
"Start with an ß: 2+0",
"Start with an s: 2+1"
)
println()
s9.sortBy(::selector9)
println(s9.map { "'$it'" }.joinToString("\n"))
} |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Python | Python | #lang racket
render-game-state
send-message-to-client
traverse-forest |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Quackery | Quackery | #lang racket
render-game-state
send-message-to-client
traverse-forest |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Racket | Racket | #lang racket
render-game-state
send-message-to-client
traverse-forest |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Raku | Raku | {blanks} {-│+} {blanks} {digits} {.} {digits} { {e│E} {-│+} exponent } {blanks}
|
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #REXX | REXX | {blanks} {-│+} {blanks} {digits} {.} {digits} { {e│E} {-│+} exponent } {blanks}
|
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #Standard_ML | Standard ML | fun make_list separator =
let
val counter = ref 1;
fun make_item item =
let
val result = Int.toString (!counter) ^ separator ^ item ^ "\n"
in
counter := !counter + 1;
result
end
in
make_item "first" ^ make_item "second" ^ make_item "third"
end;
print (make_list ". ") |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #SuperCollider | SuperCollider | (
f = { |separator|
var count = 0;
var counting = { |name|
count = count + 1;
count.asString ++ separator + name ++ "\n"
};
counting.("first") + counting.("second") + counting.("third")
};
)
f.(".")
|
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #Swift | Swift | func makeList(_ separator: String) -> String {
var counter = 1
func makeItem(_ item: String) -> String {
let result = String(counter) + separator + item + "\n"
counter += 1
return result
}
return makeItem("first") + makeItem("second") + makeItem("third")
}
print(makeList(". ")) |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #Tcl | Tcl | #!/usr/bin/env tclsh
proc MakeList separator {
set counter 1
proc MakeItem string {
upvar 1 separator separator counter counter
set res $counter$separator$string\n
incr counter
return $res
}
set res [MakeItem first][MakeItem second][MakeItem third]
rename MakeItem {}
return $res
}
puts [MakeList ". "]
|
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence.
Note: Subsequences are defined structurally, not by their contents.
So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
Task: Find all non-continuous subsequences for a given sequence.
Example
For the sequence 1,2,3,4, there are five non-continuous subsequences, namely:
1,3
1,4
2,4
1,3,4
1,2,4
Goal
There are different ways to calculate those subsequences.
Demonstrate algorithm(s) that are natural for the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #REXX | REXX | /*REXX program lists all the non─continuous subsequences (NCS), given a sequence. */
parse arg list /*obtain optional argument from the CL.*/
if list='' | list=="," then list= 1 2 3 4 5 /*Not specified? Then use the default.*/
say 'list=' space(list); say /*display the list to the terminal. */
w= words(list) /*W: is the number of items in list. */
nums= strip( left(123456789, w) ) /*build a string of decimal digits. */
tail= right(nums, max(0, w-2) ) /*construct a fast tail for comparisons*/
#= 0 /*#: number of non─continuous subseq. */
do j=13 to left(nums,1) || tail /*step through list (using smart start)*/
if verify(j, nums) \== 0 then iterate /*Not one of the chosen (sequences) ? */
f= left(j, 1) /*use the fist decimal digit of J. */
NCS= 0 /*so far, no non─continuous subsequence*/
do k=2 for length(j)-1 /*search for " " " */
x= substr(j, k, 1) /*extract a single decimal digit of J.*/
if x <= f then iterate j /*if next digit ≤, then skip this digit*/
if x \== f+1 then NCS= 1 /*it's OK as of now (that is, so far).*/
f= x /*now have a new next decimal digit. */
end /*k*/
$=
if \NCS then iterate /*not OK? Then skip this number (item)*/
#= # + 1 /*Eureka! We found a number (or item).*/
do m=1 for length(j) /*build a sequence string to display. */
$= $ word(list, substr(j, m, 1) ) /*obtain a number (or item) to display.*/
end /*m*/
say 'a non─continuous subsequence: ' $ /*show the non─continuous subsequence. */
end /*j*/
say /*help ensure visual fidelity in output*/
if #==0 then #= 'no' /*make it look more gooder Angleshy. */
say # "non─continuous subsequence"s(#) 'were found.' /*handle plurals.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return ''; return word( arg(2) 's', 1) /*simple pluralizer.*/ |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every ( ns := "16r5a" | "-12r1a" ) &
( b := 8 | 12 | 16 ) do {
ns2 := convert(n := numeric(ns),b)
printf("ns=%s -> n=%d -> %s\n",ns,n,ns2)
}
end
link printf
procedure convert(i,b) #: convert i to base b radix representation
static digits
initial digits := &digits || &lcase
i := integer(i) | runerr(101, i) # arg/error checking
/b := 10 | ( 2 < (b := integer(b)) <= *digits ) | runerr(205,b)
if b = 10 then return i
else {
p := (s := "", (i := -(0 > i),"-")|"") || b || "r" # prefix/setup
until i = 0 & *s > 0 do
s ||:= digits[1 + 1( i % b, i /:= b)]
return p || reverse(s)
}
end |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary (expect 21102)
Encode the decimal number 15 as negadecimal (expect 195)
In each of the above cases, convert the encoded number back to decimal.
extra credit
supply an integer, that when encoded to base -62 (or something "higher"), expresses the
name of the language being used (with correct capitalization). If the computer language has
non-alphanumeric characters, try to encode them into the negatory numerals, or use other
characters instead.
| #Rust | Rust | const DIGITS: [char;62] = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
fn main() {
let nums_and_bases: [(i64,i64);5] = [(10,-2),(146,-3),(15,-10),(-6222885,-62),(1488588316238,-62)];
for (n,b) in nums_and_bases.iter() {
let ns = encode_neg_base(*n, *b);
println!("{} encoded in base {} = {}", *n, *b, &ns);
let nn = decode_neg_base(&ns, *b);
println!("{} decoded in base {} = {}\n", &ns, *b, nn);
}
}
fn decode_neg_base(ns: &str, b: i64) -> i64 {
if b < -62 || b > -1 {
panic!("base must be between -62 and -1 inclusive")
}
if ns == "0" {
return 0
}
let mut total: i64 = 0;
let mut bb: i64 = 1;
for c in ns.chars().rev() {
total += (DIGITS.iter().position(|&d| d==c).unwrap() as i64) * bb;
bb *= b;
}
return total;
}
fn encode_neg_base(mut n: i64, b: i64) -> String {
if b < -62 || b > -1 {
panic!("base must be between -62 and -1 inclusive");
}
if n == 0 {
return "0".to_string();
}
let mut out = String::new();
while n != 0 {
let mut rem = n % b;
n /= b;
if rem < 0 {
n+=1;
rem -= b;
}
out.push(DIGITS[rem as usize]);
}
return out.chars().rev().collect();
} |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary (expect 21102)
Encode the decimal number 15 as negadecimal (expect 195)
In each of the above cases, convert the encoded number back to decimal.
extra credit
supply an integer, that when encoded to base -62 (or something "higher"), expresses the
name of the language being used (with correct capitalization). If the computer language has
non-alphanumeric characters, try to encode them into the negatory numerals, or use other
characters instead.
| #Scala | Scala | object NegativeBase {
val digits = ('0' to '9') ++ ('a' to 'z') ++ ('A' to 'Z')
def intToStr(n: Int, b: Int): String = {
def _fromInt(n: Int): List[Int] = {
if (n == 0) {
Nil
} else {
val r = n % b
val rp = if (r < 0) r + b else r
val m = -(n - rp)/b
rp :: _fromInt(m)
}
}
_fromInt(n).map(digits).reverse.mkString
}
def strToInt(s: String, b: Int): Int = {
s.map(digits.indexOf).foldRight((0, 1)){ case (x, (sum, pow)) =>
(sum + x * pow, pow * -b)
}._1
}
} |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Smalltalk | Smalltalk |
Object subclass: Nim [
| tokens |
<comment: 'I am a game of nim'>
Nim class >> new [
<category: 'instance creation'>
^(super new) init: 12
]
init: t [
<category: 'instance creation'>
tokens := t.
^self
]
pTurn [
| take |
<category: 'gameplay'>
Transcript nextPutAll: 'How many tokens will you take?: '.
take := (stdin nextLine) asNumber.
((take < 1) | (take > 3))
ifTrue: [Transcript nextPutAll: 'Invalid input';nl;nl. self pTurn]
ifFalse: [tokens := tokens - take]
]
cTurn [
| take |
<category: 'gameplay'>
take := tokens - (4 * (tokens // 4)). "tokens % 4"
Transcript nextPutAll: 'Computer takes '.
take printOn: Transcript.
Transcript nextPutAll: ' tokens';nl.
tokens := tokens - take
]
mainLoop [
<category: 'main loop'>
Transcript nextPutAll: 'Nim game';nl.
Transcript nextPutAll: 'Starting with '.
tokens printOn: Transcript.
Transcript nextPutAll: ' tokens';nl;nl.
1 to: 3 do: [ :n | "The computer always wins on the 3rd turn"
self pTurn.
self printRemaining.
self cTurn.
self printRemaining.
(tokens = 0)
ifTrue:[Transcript nextPutAll: 'Computer wins!';nl. ^0]
]
]
printRemaining [
<category: 'information'>
tokens printOn: Transcript.
Transcript nextPutAll: ' tokens remaining';nl;nl
]
]
g := Nim new.
g mainLoop.
|
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #Befunge | Befunge | p55*\>:>:>:55+%\55+/00gvv_@
>1>+>^v\_^#!:<p01p00:+1<>\>
>#-_>\>20p110g>\20g*\v>1-v|
^!p00:-1g00+$_^#!:<-1<^\.:< |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #AWK | AWK |
BEGIN {
# square size
s = 256
# the PPM image header needs 3 lines:
# P3
# width height
# max colors number (per channel)
print("P3\n", s, s, "\n", s - 1)
# and now we generate pixels as a RGB pair in a relaxed
# form "R G B\n"
for (x = 0; x < s; x++) {
for (y = 0; y < s; y++) {
p = xor(x, y)
print(0, p, p)
}
}
}
|
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #BBC_BASIC | BBC BASIC | size% = 256
VDU 23,22,size%;size%;8,8,16,0
OFF
DIM coltab%(size%-1)
FOR I% = 0 TO size%-1
coltab%(I%) = ((I% AND &FF) * &010101) EOR &FF0000
NEXT
GCOL 1
FOR I% = 0 TO size%-1
FOR J% = 0 TO size%-1
C% = coltab%(I% EOR J%)
COLOUR 1, C%, C%>>8, C%>>16
PLOT I%*2, J%*2
NEXT
NEXT I%
REPEAT WAIT 1 : UNTIL FALSE
|
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #ABAP | ABAP |
report z_mutual_recursion.
class hoffstadter_sequences definition.
public section.
class-methods:
f
importing
n type int4
returning
value(result) type int4,
m
importing
n type int4
returning
value(result) type int4.
endclass.
class hoffstadter_sequences implementation.
method f.
result = cond int4(
when n eq 0
then 1
else n - m( f( n - 1 ) ) ).
endmethod.
method m.
result = cond int4(
when n eq 0
then 0
else n - f( m( n - 1 ) ) ).
endmethod.
endclass.
start-of-selection.
write: |{ reduce string(
init results = |f(0 - 19): { hoffstadter_sequences=>f( 0 ) }|
for i = 1 while i < 20
next results = |{ results }, { hoffstadter_sequences=>f( i ) }| ) }|, /.
write: |{ reduce string(
init results = |m(0 - 19): { hoffstadter_sequences=>m( 0 ) }|
for i = 1 while i < 20
next results = |{ results }, { hoffstadter_sequences=>m( i ) }| ) }|, /.
|
http://rosettacode.org/wiki/Musical_scale | Musical scale | Task
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| #AmigaBASIC | AmigaBASIC | FOR i=1 to 8
READ f
SOUND f,10
NEXT
DATA 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25 |
http://rosettacode.org/wiki/Musical_scale | Musical scale | Task
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| #AutoHotkey | AutoHotkey | for key, val in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]
SoundBeep, % val, 500 |
http://rosettacode.org/wiki/N-smooth_numbers | N-smooth numbers | n-smooth numbers are positive integers which have no prime factors > n.
The n (when using it in the expression) n-smooth is always prime,
there are no 9-smooth numbers.
1 (unity) is always included in n-smooth numbers.
2-smooth numbers are non-negative powers of two.
5-smooth numbers are also called Hamming numbers.
7-smooth numbers are also called humble numbers.
A way to express 11-smooth numbers is:
11-smooth = 2i × 3j × 5k × 7m × 11p
where i, j, k, m, p ≥ 0
Task
calculate and show the first 25 n-smooth numbers for n=2 ───► n=29
calculate and show three numbers starting with 3,000 n-smooth numbers for n=3 ───► n=29
calculate and show twenty numbers starting with 30,000 n-smooth numbers for n=503 ───► n=521 (optional)
All ranges (for n) are to be inclusive, and only prime numbers are to be used.
The (optional) n-smooth numbers for the third range are: 503, 509, and 521.
Show all n-smooth numbers for any particular n in a horizontal list.
Show all output here on this page.
Related tasks
Hamming numbers
humble numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A000079 2-smooth numbers or non-negative powers of two
OEIS entry: A003586 3-smooth numbers
OEIS entry: A051037 5-smooth numbers or Hamming numbers
OEIS entry: A002473 7-smooth numbers or humble numbers
OEIS entry: A051038 11-smooth numbers
OEIS entry: A080197 13-smooth numbers
OEIS entry: A080681 17-smooth numbers
OEIS entry: A080682 19-smooth numbers
OEIS entry: A080683 23-smooth numbers
| #Delphi | Delphi |
program N_smooth_numbers;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Generics.Collections,
Velthuis.BigIntegers;
var
primes: TList<BigInteger>;
smallPrimes: TList<Integer>;
function IsPrime(value: BigInteger): Boolean;
var
v: BigInteger;
begin
if value < 2 then
exit(False);
for v in [2, 3, 5, 7, 11, 13, 17, 19, 23] do
begin
if (value mod v) = 0 then
exit(value = v);
end;
v := 29;
while v * v < value do
begin
if (value mod v) = 0 then
exit(False);
inc(value, 2);
if (value mod v) = 0 then
exit(False);
inc(v, 4);
end;
Result := True;
end;
function Min(values: TList<BigInteger>): BigInteger;
var
value: BigInteger;
begin
if values.Count = 0 then
exit(0);
Result := values[0];
for value in values do
begin
if value < Result then
result := value;
end;
end;
function NSmooth(n, size: Integer): TList<BigInteger>;
var
bn, p: BigInteger;
ok: Boolean;
i: Integer;
next: TList<BigInteger>;
indices: TList<Integer>;
m: Integer;
begin
Result := TList<BigInteger>.Create;
if (n < 2) or (n > 521) then
raise Exception.Create('Argument out of range: "n"');
if (size < 1) then
raise Exception.Create('Argument out of range: "size"');
bn := n;
ok := false;
for p in primes do
begin
ok := bn = p;
if ok then
break;
end;
if not ok then
raise Exception.Create('"n" must be a prime number');
Result.Add(1);
for i := 1 to size - 1 do
Result.Add(0);
next := TList<BigInteger>.Create;
for p in primes do
begin
if p > bn then
Break;
next.Add(p);
end;
indices := TList<Integer>.Create;
for i := 0 to next.Count - 1 do
indices.Add(0);
for m := 1 to size - 1 do
begin
Result[m] := Min(next);
for i := 0 to indices.Count - 1 do
if Result[m] = next[i] then
begin
indices[i] := indices[i] + 1;
next[i] := primes[i] * Result[indices[i]];
end;
end;
indices.Free;
next.Free;
end;
procedure Init();
var
i: BigInteger;
begin
primes := TList<BigInteger>.Create;
smallPrimes := TList<Integer>.Create;
primes.Add(2);
smallPrimes.Add(2);
i := 3;
while i <= 521 do
begin
if IsPrime(i) then
begin
primes.Add(i);
if i <= 29 then
smallPrimes.Add(Integer(i));
end;
inc(i, 2);
end;
end;
procedure Println(values: TList<BigInteger>; CanFree: Boolean = False);
var
value: BigInteger;
begin
Write('[');
for value in values do
Write(value.ToString, ', ');
Writeln(']'#10);
if CanFree then
values.Free;
end;
procedure Finish();
begin
primes.Free;
smallPrimes.Free;
end;
var
p: Integer;
ns: TList<BigInteger>;
const
RANGE_3: array[0..2] of integer = (503, 509, 521);
begin
Init;
for p in smallPrimes do
begin
Writeln('The first ', p, '-smooth numbers are:');
Println(NSmooth(p, 25), True);
end;
smallPrimes.Delete(0);
for p in smallPrimes do
begin
Writeln('The 3,000 to 3,202 ', p, '-smooth numbers are:');
ns := nSmooth(p, 3002);
ns.DeleteRange(0, 2999);
println(ns, True);
end;
for p in RANGE_3 do
begin
Writeln('The 3,000 to 3,019 ', p, '-smooth numbers are:');
ns := nSmooth(p, 30019);
ns.DeleteRange(0, 29999);
println(ns, True);
end;
Finish;
Readln;
end.
|
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before.
Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL.
See also:
Varargs
Optional parameters
Wikipedia: Named parameter
| #Elixir | Elixir |
def fun(bar: bar, baz: baz), do: IO.puts "#{bar}, #{baz}."
fun(bar: "bar", baz: "baz")
|
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before.
Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL.
See also:
Varargs
Optional parameters
Wikipedia: Named parameter
| #Erlang | Erlang |
Fun = fun( Proplists ) ->
Argument1 = proplists:get_value( argument1, Proplists, 1 ),
Kalle = proplists:get_value( kalle, Proplists, "hobbe" ),
io:fwrite( "~p ~s~n", [Argument1, Kalle] )
end.
|
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #EasyLang | EasyLang | func power x n . r .
r = 1
for i range n
r *= x
.
.
func nth_root x n . r .
r = 2
repeat
call power r n - 1 p
d = (x / p - r) / n
r += d
until abs d < 0.0001
.
.
call power 3.1416 10 x
call nth_root x 10 r
numfmt 0 4
print r |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Arturo | Arturo | suffixes: ["th" "st" "nd" "rd" "th" "th" "th" "th" "th" "th"]
nth: function [n][
if? or? 100 >= n%100
20 < n%100
-> (to :string n) ++ "'" ++ suffixes\[n%10]
else -> (to :string n) ++ "'th"
]
loop range.step:250 0 1000 'j [
loop j..j+24 'i ->
prints (nth i)++" "
print ""
] |
http://rosettacode.org/wiki/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n:
μ(1) is defined to be 1.
μ(n) = 1 if n is a square-free positive integer with an even number of prime factors.
μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
μ(n) = 0 if n has a squared prime factor.
Task
Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
See also
Wikipedia: Möbius function
Related Tasks
Mertens function
| #Go | Go | package main
import "fmt"
func möbius(to int) []int {
if to < 1 {
to = 1
}
mobs := make([]int, to+1) // all zero by default
primes := []int{2}
for i := 1; i <= to; i++ {
j := i
cp := 0 // counts prime factors
spf := false // true if there is a square prime factor
for _, p := range primes {
if p > j {
break
}
if j%p == 0 {
j /= p
cp++
}
if j%p == 0 {
spf = true
break
}
}
if cp == 0 && i > 2 {
cp = 1
primes = append(primes, i)
}
if !spf {
if cp%2 == 0 {
mobs[i] = 1
} else {
mobs[i] = -1
}
}
}
return mobs
}
func main() {
mobs := möbius(199)
fmt.Println("Möbius sequence - First 199 terms:")
for i := 0; i < 200; i++ {
if i == 0 {
fmt.Print(" ")
continue
}
if i%20 == 0 {
fmt.Println()
}
fmt.Printf(" % d", mobs[i])
}
} |
http://rosettacode.org/wiki/Natural_sorting | Natural sorting |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Natural sorting is the sorting of text that does more than rely on the
order of individual characters codes to make the finding of
individual strings easier for a human reader.
There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include:
1. Ignore leading, trailing and multiple adjacent spaces
2. Make all whitespace characters equivalent.
3. Sorting without regard to case.
4. Sorting numeric portions of strings in numeric order.
That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers.
foo9.txt before foo10.txt
As well as ... x9y99 before x9y100, before x10y0
... (for any number of groups of integers in a string).
5. Title sorts: without regard to a leading, very common, word such
as 'The' in "The thirty-nine steps".
6. Sort letters without regard to accents.
7. Sort ligatures as separate letters.
8. Replacements:
Sort German eszett or scharfes S (ß) as ss
Sort ſ, LATIN SMALL LETTER LONG S as s
Sort ʒ, LATIN SMALL LETTER EZH as s
∙∙∙
Task Description
Implement the first four of the eight given features in a natural sorting routine/function/method...
Test each feature implemented separately with an ordered list of test strings from the Sample inputs section below, and make sure your naturally sorted output is in the same order as other language outputs such as Python.
Print and display your output.
For extra credit implement more than the first four.
Note: it is not necessary to have individual control of which features are active in the natural sorting routine at any time.
Sample input
• Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2',
'ignore leading spaces: 2-1',
'ignore leading spaces: 2+0',
'ignore leading spaces: 2+1']
• Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2',
'ignore MAS spaces: 2-1',
'ignore MAS spaces: 2+0',
'ignore MAS spaces: 2+1']
• Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3',
'Equiv. \rspaces: 3-2',
'Equiv. \x0cspaces: 3-1',
'Equiv. \x0bspaces: 3+0',
'Equiv. \nspaces: 3+1',
'Equiv. \tspaces: 3+2']
• Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2',
'caSE INDEPENDENT: 3-1',
'casE INDEPENDENT: 3+0',
'case INDEPENDENT: 3+1']
• Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt',
'foo100bar10baz0.txt',
'foo1000bar99baz10.txt',
'foo1000bar99baz9.txt']
• Title sorts. Text strings: ['The Wind in the Willows',
'The 40th step more',
'The 39 steps',
'Wanda']
• Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2',
u'Equiv. \xdd accents: 2-1',
u'Equiv. y accents: 2+0',
u'Equiv. Y accents: 2+1']
• Separated ligatures. Text strings: [u'\u0132 ligatured ij',
'no ligature']
• Character replacements. Text strings: [u'Start with an \u0292: 2-2',
u'Start with an \u017f: 2-1',
u'Start with an \xdf: 2+0',
u'Start with an s: 2+1']
| #Nim | Nim | import algorithm, parseutils, pegs, strutils, unidecode
type
Kind = enum fString, fNumber
KeyItem= object
case kind: Kind
of fString: str: string
of fNumber: num: Natural
Key = seq[KeyItem]
func cmp(a, b: Key): int =
## Compare two keys.
for i in 0..<min(a.len, b.len):
let ai = a[i]
let bi = b[i]
if ai.kind == bi.kind:
result = if ai.kind == fString: cmp(ai.str, bi.str) else: cmp(ai.num, bi.num)
if result != 0: return
else:
return if ai.kind == fString: 1 else: -1
result = if a.len < b.len: -1 else: (if a.len == b.len: 0 else: 1)
proc natOrderKey(s: string): Key =
## Return the natural order key for a string.
# Process 'ʒ' separately as "unidecode" converts it to 'z'.
var s = s.replace("ʒ", "s")
# Transform UTF-8 text into ASCII text.
s = s.unidecode()
# Remove leading and trailing white spaces.
s = s.strip()
# Make all whitespace characters equivalent and remove adjacent spaces.
s = s.replace(peg"\s+", " ")
# Switch to lower case.
s = s.toLowerAscii()
# Remove leading "the ".
if s.startsWith("the ") and s.len > 4: s = s[4..^1]
# Split into fields.
var idx = 0
var val: int
while idx < s.len:
var n = s.skipUntil(Digits, start = idx)
if n != 0:
result.add KeyItem(kind: fString, str: s[idx..<(idx + n)])
inc idx, n
n = s.parseInt(val, start = idx)
if n != 0:
result.add KeyItem(kind: fNumber, num: val)
inc idx, n
proc naturalCmp(a, b: string): int =
## Natural order comparison function.
cmp(a.natOrderKey, b.natOrderKey)
when isMainModule:
proc test(title: string; list: openArray[string]) =
echo title
echo sorted(list, naturalCmp)
echo ""
test("Ignoring leading spaces.",
["ignore leading spaces: 2-2",
"ignore leading spaces: 2-1",
"ignore leading spaces: 2+0",
"ignore leading spaces: 2+1"])
test("Ignoring multiple adjacent spaces (MAS).",
["ignore MAS spaces: 2-2",
"ignore MAS spaces: 2-1",
"ignore MAS spaces: 2+0",
"ignore MAS spaces: 2+1"])
test("Equivalent whitespace characters.",
["Equiv. spaces: 3-3",
"Equiv. \rspaces: 3-2",
"Equiv. \x0cspaces: 3-1",
"Equiv. \x0bspaces: 3+0",
"Equiv. \nspaces: 3+1",
"Equiv. \tspaces: 3+2"])
test("Case Independent sort.",
["cASE INDEPENDENT: 3-2",
"caSE INDEPENDENT: 3-1",
"casE INDEPENDENT: 3+0",
"case INDEPENDENT: 3+1"])
test("Numeric fields as numerics.",
["foo100bar99baz0.txt",
"foo100bar10baz0.txt",
"foo1000bar99baz10.txt",
"foo1000bar99baz9.txt"])
test("Title sorts.",
["The Wind in the Willows",
"The 40th step more",
"The 39 steps",
"Wanda"])
test("Equivalent accented characters (and case).",
["Equiv. ý accents: 2-2",
"Equiv. Ý accents: 2-1",
"Equiv. y accents: 2+0",
"Equiv. Y accents: 2+1"])
test("Separated ligatures.",
["IJ ligatured ij",
"no ligature"])
test("Character replacements.",
["Start with an ʒ: 2-2",
"Start with an ſ: 2-1",
"Start with an ß: 2+0",
"Start with an s: 2+1"]) |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Ruby | Ruby |
test_variable = [1, 9, 8, 3]
test_variable.sort # => [1, 3, 8, 9]
test_variable # => [1, 9, 8, 3]
test_variable.sort! # => [1, 3, 8, 9]
test_variable # => [1, 3, 8, 9]
|
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Rust | Rust | Dim dblDistance as Double |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Scala | Scala | Dim dblDistance as Double |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Tcl | Tcl | Dim dblDistance as Double |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #VBA | VBA | Option Explicit
Private Const Sep As String = ". "
Private Counter As Integer
Sub Main()
Dim L As Variant
Counter = 0
L = MakeList(Array("first", "second", "third"))
Debug.Print L
End Sub
Function MakeList(Datas) As Variant
Dim i As Integer
For i = LBound(Datas) To UBound(Datas)
MakeList = MakeList & MakeItem(Datas(i))
Next i
End Function
Function MakeItem(Item As Variant) As Variant
Counter = Counter + 1
MakeItem = Counter & Sep & Item & vbCrLf
End Function |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #Wren | Wren | var makeList = Fn.new { |sep|
var counter = 0
var makeItem = Fn.new { |name|
counter = counter + 1
return "%(counter)%(sep)%(name)"
}
var items = []
for (name in ["first", "second", "third"]) {
items.add(makeItem.call(name))
}
System.print(items.join("\n"))
}
makeList.call(". ") |
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence.
Note: Subsequences are defined structurally, not by their contents.
So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
Task: Find all non-continuous subsequences for a given sequence.
Example
For the sequence 1,2,3,4, there are five non-continuous subsequences, namely:
1,3
1,4
2,4
1,3,4
1,2,4
Goal
There are different ways to calculate those subsequences.
Demonstrate algorithm(s) that are natural for the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ring | Ring |
# Project : Non-continuous subsequences
load "stdlib.ring"
list = [1,2,3,4]
items = newlist(pow(2,len(list))-1,len(list))
see "For [1, 2, 3, 4] non-continuous subsequences are:" + nl
powerset(list,4)
showarray(items,4)
see nl
list = [1,2,3,4,5]
items = newlist(pow(2,len(list))-1,len(list))
see "For [1, 2, 3, 4, 5] non-continuous subsequences are:" + nl
powerset(list,5)
showarray(items,5)
func showarray(items,ind)
for n = 1 to len(items)
flag = 0
for m = 1 to ind - 1
if items[n][m] = 0 or items[n][m+1] = 0
exit
ok
if (items[n][m] + 1) != items[n][m+1]
flag = 1
exit
ok
next
if flag = 1
see "["
str = ""
for x = 1 to len(items[n])
if items[n][x] != 0
str = str + items[n][x] + " "
ok
next
str = left(str, len(str) - 1)
see str + "]" + nl
ok
next
func powerset(list,ind)
num = 0
num2 = 0
items = newlist(pow(2,len(list))-1,ind)
for i = 2 to (2 << len(list)) - 1 step 2
num2 = 0
num = num + 1
for j = 1 to len(list)
if i & (1 << j)
num2 = num2 + 1
if list[j] != 0
items[num][num2] = list[j]
ok
ok
next
next
return items
|
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence.
Note: Subsequences are defined structurally, not by their contents.
So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
Task: Find all non-continuous subsequences for a given sequence.
Example
For the sequence 1,2,3,4, there are five non-continuous subsequences, namely:
1,3
1,4
2,4
1,3,4
1,2,4
Goal
There are different ways to calculate those subsequences.
Demonstrate algorithm(s) that are natural for the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ruby | Ruby | class Array
def func_power_set
inject([[]]) { |ps,item| # for each item in the Array
ps + # take the powerset up to now and add
ps.map { |e| e + [item] } # it again, with the item appended to each element
}
end
def non_continuous_subsequences
func_power_set.reject {|seq| continuous?(seq)}
end
def continuous?(seq)
seq.each_cons(2) {|a, b| return false if a.succ != b}
true
end
end
p (1..3).to_a.non_continuous_subsequences
p (1..4).to_a.non_continuous_subsequences
p (1..5).to_a.non_continuous_subsequences
p ("a".."d").to_a.non_continuous_subsequences |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #J | J | 2b100 8b100 10b_100 16b100 36b100 36bzy
4 64 _100 256 1296 1294 |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Java | Java | public static long backToTen(String num, int oldBase){
return Long.parseLong(num, oldBase); //takes both uppercase and lowercase letters
}
public static String tenToBase(long num, int newBase){
return Long.toString(num, newBase);//add .toUpperCase() for capital letters
} |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary (expect 21102)
Encode the decimal number 15 as negadecimal (expect 195)
In each of the above cases, convert the encoded number back to decimal.
extra credit
supply an integer, that when encoded to base -62 (or something "higher"), expresses the
name of the language being used (with correct capitalization). If the computer language has
non-alphanumeric characters, try to encode them into the negatory numerals, or use other
characters instead.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const string: DIGITS is "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const func string: encodeNegativeBase (in var integer: number, in integer: base) is func
result
var string: encoded is "";
local
var integer: remainder is 0;
begin
if base < -62 or base > -1 then
raise RANGE_ERROR;
elsif number = 0 then
encoded := "0";
else
while number <> 0 do
remainder := number rem base;
number := number div base;
if remainder < 0 then
incr(number);
remainder -:= base;
end if;
encoded &:= DIGITS[succ(remainder)];
end while;
encoded := reverse(encoded);
end if;
end func;
const func integer: decodeNegativeBase (in string: encoded, in integer: base) is func
result
var integer: decoded is 0;
local
var integer: factor is 1;
var integer: index is 0;
var integer: digit is 0;
begin
if base < -62 or base > -1 then
raise RANGE_ERROR;
elsif encoded = "0" then
decoded := 0;
else
for index range length(encoded) downto 1 do
digit := pred(pos(DIGITS, encoded[index]));
if digit = -1 then
raise RANGE_ERROR;
else
decoded +:= digit * factor;
factor *:= base;
end if;
end for;
end if;
end func;
const proc: doCheck (in integer: number, in integer: base) is func
local
var string: encoded is "";
var integer: decoded is 0;
begin
encoded := encodeNegativeBase(number, base);
writeln(number lpad 10 <& " encoded in base " <& base lpad 3 <& " = " <& encoded);
decoded := decodeNegativeBase(encoded, base);
writeln(encoded lpad 10 <& " decoded in base " <& base lpad 3 <& " = " <& decoded);
end func;
const proc: main is func
begin
doCheck(10, -2);
doCheck(146, -3);
doCheck(15, -10);
doCheck(404355637, -62);
end func; |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary (expect 21102)
Encode the decimal number 15 as negadecimal (expect 195)
In each of the above cases, convert the encoded number back to decimal.
extra credit
supply an integer, that when encoded to base -62 (or something "higher"), expresses the
name of the language being used (with correct capitalization). If the computer language has
non-alphanumeric characters, try to encode them into the negatory numerals, or use other
characters instead.
| #Sidef | Sidef | func EncodeNegBase(Num n, Num b { .~~ (-36 .. -2) }) {
var out = []
var r = 0
while (n) {
(n, r) = divmod(n, b)
if (r < 0) {
n += 1
r -= b
}
out << r.base(-b)
}
return (out.join.flip || "0")
}
func DecodeNegBase(Str s, Num b { .~~ (-36 .. -2) }) {
var total = 0
for i,c in (s.flip.chars.kv) {
total += (Num(c, -b) * b**i)
}
return total
}
say (" 10 in base -2: ", EncodeNegBase(10, -2))
say ("146 in base -3: ", EncodeNegBase(146, -3))
say (" 15 in base -10: ", EncodeNegBase(15, -10))
say '-'*25
say ("11110 from base -2: ", DecodeNegBase("11110", -2))
say ("21102 from base -3: ", DecodeNegBase("21102", -3))
say (" 195 from base -10: ", DecodeNegBase("195", -10))
say '-'*25
# Extra
say ("25334424 in base -31: ", EncodeNegBase(25334424, -31))
say ("sidef from base -31: ", DecodeNegBase("sidef", -31)) |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #SNOBOL4 | SNOBOL4 | &TRIM = 1
&DUMP = 1
OUTPUT(.prompt, 9, 'T', '-')
********************************************************************************
* GETCOUNT() - Get the count of tokens to take.
********************************************************************************
define('GETCOUNT()I')
:(GETCOUNT.END)
GETCOUNT OUTPUT = 'Enter a number between 1 and 3, blank line to exit.'
****************************************
* Data input and integrity check loop.
****************************************
GETCOUNT.LOOP PROMPT = '> '
i = trim(INPUT)
* Abort on nil entry.
eq(size(i), 0) :S(EXIT)
* Check range.
integer(i) :F(GETCOUNT.INVALID)
lt(i, 4) :F(GETCOUNT.INVALID)
gt(i, 0) :F(GETCOUNT.INVALID)
* It all checked out.
GETCOUNT = i :(RETURN)
****************************************
* An invalid entry was caught.
****************************************
GETCOUNT.INVALID OUTPUT = 'Invalid number.' :(GETCOUNT.LOOP)
GETCOUNT.END
********************************************************************************
* MAINLINE CODE
********************************************************************************
MAIN OUTPUT =
OUTPUT = 'The mysterious game of Nim!'
OUTPUT = 'Whoever takes the last token of twelve wins.'
tokens = 12
****************************************
* MAIN LOOP
****************************************
MAIN.LOOP OUTPUT =
OUTPUT = 'There are ' tokens ' tokens remaining. How many do you want to take?'
********************
* Player turn.
********************
MAIN.P ptake = getcount()
tokens = tokens - ptake
OUTPUT = 'You selected ' ptake ' tokens leaving ' tokens '.'
lt(tokens, 0) :S(ERROR)
gt(tokens, 12) :S(ERROR)
eq(tokens, 0) :S(MAIN.PWIN)
********************
* Computer turn.
********************
MAIN.C ctake = 4 - ptake
tokens = tokens - ctake
OUTPUT = 'Computer selects ' ctake ' tokens leaving ' tokens '.'
lt(tokens, 0) :S(ERROR)
gt(tokens, 12) :S(ERROR)
eq(tokens, 0) :S(MAIN.CWIN)
:(MAIN.LOOP)
****************************************
* Player win is impossible. Joke code.
****************************************
MAIN.PWIN OUTPUT = 'Player wins. This is impossible. You must have cheated.'
OUTPUT = 'Formatting hard drive...' :(ERROR)
****************************************
* Computer win is inevitable.
****************************************
MAIN.CWIN OUTPUT = 'Computer wins.' :(EXIT)
********************************************************************************
* On a routine exit we turn off the variable dump.
* If we exit through an error (like branching to a non-existent label 'ERROR')
* then this code doesn't happen and variables get dumped and the line of the
* failed check getting printed.
********************************************************************************
EXIT OUTPUT = 'Bye!'
&DUMP = 0
END |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Swift | Swift | var tokens = 12
while tokens != 0 {
print("Tokens remaining: \(tokens)\nPlease enter a number between 1 and 3: ", terminator: "")
guard let input = readLine(), let n = Int(input), n >= 1 && n <= 3 else {
fatalError("Invalid input")
}
tokens -= n
if tokens == 0 {
print("You win!")
break
}
print("I'll remove \(4 - n) tokens.")
tokens -= 4 - n
if tokens == 0 {
print("I win!")
}
print()
} |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Tiny_BASIC | Tiny BASIC | 10 LET H = 12
20 PRINT "There are"
30 PRINT H
40 PRINT "tokens remaining. How many would you like to take?"
50 INPUT T
60 IF T > 3 THEN GOTO 170
70 IF T < 1 THEN GOTO 170
80 LET H = H - T
90 IF H = 0 THEN GOTO 190
100 LET T = 4 - T
110 PRINT "I will take"
120 PRINT T
130 PRINT "tokens."
140 LET H = H - T
150 IF H = 0 THEN GOTO 210
160 GOTO 20
170 PRINT "You must take 1, 2, or 3 tokens."
180 GOTO 50
190 PRINT "Congratulations. You got the last token."
200 END
210 PRINT "I got the last token. I win. Better luck next time."
220 END |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #BQN | BQN | B10 ← 10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
IsNarc ← {𝕩=+´⋆⟜≠B10 𝕩}
/IsNarc¨ ↕1e7 |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #C | C | #include <stdio.h>
#include <gmp.h>
#define MAX_LEN 81
mpz_t power[10];
mpz_t dsum[MAX_LEN + 1];
int cnt[10], len;
void check_perm(void)
{
char s[MAX_LEN + 1];
int i, c, out[10] = { 0 };
mpz_get_str(s, 10, dsum[0]);
for (i = 0; s[i]; i++) {
c = s[i]-'0';
if (++out[c] > cnt[c]) return;
}
if (i == len)
gmp_printf(" %Zd", dsum[0]);
}
void narc_(int pos, int d)
{
if (!pos) {
check_perm();
return;
}
do {
mpz_add(dsum[pos-1], dsum[pos], power[d]);
++cnt[d];
narc_(pos - 1, d);
--cnt[d];
} while (d--);
}
void narc(int n)
{
int i;
len = n;
for (i = 0; i < 10; i++)
mpz_ui_pow_ui(power[i], i, n);
mpz_init_set_ui(dsum[n], 0);
printf("length %d:", n);
narc_(n, 9);
putchar('\n');
}
int main(void)
{
int i;
for (i = 0; i <= 10; i++)
mpz_init(power[i]);
for (i = 1; i <= MAX_LEN; i++) narc(i);
return 0;
} |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Befunge | Befunge | 55+::"3P",,,28*:*::..\,:.\,:v
>2%*28*:**-2/\1-:v<:8:-1<_@ v
^\-1*2%2/*:*82::\_$0.0..:^:*< |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Burlesque | Burlesque |
blsq ) 0 25r@{0 25r@\/{$$Sh2' P[}\/+]m[}m[sp
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14 17 16 19 18 21 20 23 22 25 24
2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13 18 19 16 17 22 23 20 21 26 27
3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12 19 18 17 16 23 22 21 20 27 26
4 5 6 7 0 1 2 3 12 13 14 15 8 9 10 11 20 21 22 23 16 17 18 19 28 29
5 4 7 6 1 0 3 2 13 12 15 14 9 8 11 10 21 20 23 22 17 16 19 18 29 28
6 7 4 5 2 3 0 1 14 15 12 13 10 11 8 9 22 23 20 21 18 19 16 17 30 31
7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8 23 22 21 20 19 18 17 16 31 30
8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 24 25 26 27 28 29 30 31 16 17
9 8 11 10 13 12 15 14 1 0 3 2 5 4 7 6 25 24 27 26 29 28 31 30 17 16
10 11 8 9 14 15 12 13 2 3 0 1 6 7 4 5 26 27 24 25 30 31 28 29 18 19
11 10 9 8 15 14 13 12 3 2 1 0 7 6 5 4 27 26 25 24 31 30 29 28 19 18
12 13 14 15 8 9 10 11 4 5 6 7 0 1 2 3 28 29 30 31 24 25 26 27 20 21
13 12 15 14 9 8 11 10 5 4 7 6 1 0 3 2 29 28 31 30 25 24 27 26 21 20
14 15 12 13 10 11 8 9 6 7 4 5 2 3 0 1 30 31 28 29 26 27 24 25 22 23
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24 23 22
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6 7 8 9
17 16 19 18 21 20 23 22 25 24 27 26 29 28 31 30 1 0 3 2 5 4 7 6 9 8
18 19 16 17 22 23 20 21 26 27 24 25 30 31 28 29 2 3 0 1 6 7 4 5 10 11
19 18 17 16 23 22 21 20 27 26 25 24 31 30 29 28 3 2 1 0 7 6 5 4 11 10
20 21 22 23 16 17 18 19 28 29 30 31 24 25 26 27 4 5 6 7 0 1 2 3 12 13
21 20 23 22 17 16 19 18 29 28 31 30 25 24 27 26 5 4 7 6 1 0 3 2 13 12
22 23 20 21 18 19 16 17 30 31 28 29 26 27 24 25 6 7 4 5 2 3 0 1 14 15
23 22 21 20 19 18 17 16 31 30 29 28 27 26 25 24 7 6 5 4 3 2 1 0 15 14
24 25 26 27 28 29 30 31 16 17 18 19 20 21 22 23 8 9 10 11 12 13 14 15 0 1
25 24 27 26 29 28 31 30 17 16 19 18 21 20 23 22 9 8 11 10 13 12 15 14 1 0
|
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #11l | 11l | L(i) 5000
I i == sum(String(i).map(x -> Int(x) ^ Int(x)))
print(i) |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #ACL2 | ACL2 | (mutual-recursion
(defun f (n)
(declare (xargs :mode :program))
(if (zp n)
1
(- n (m (f (1- n))))))
(defun m (n)
(declare (xargs :mode :program))
(if (zp n)
0
(- n (f (m (1- n))))))) |
http://rosettacode.org/wiki/Musical_scale | Musical scale | Task
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| #BASIC256 | BASIC256 | sound {261.63, 500, 293.66, 500, 329.63, 500, 349.23, 500, 392, 500, 440, 500, 493.88, 500, 523.25, 500} |
http://rosettacode.org/wiki/Musical_scale | Musical scale | Task
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| #Befunge | Befunge | > "HGECA@><"8: v
v0*73"MThd"0006010101"MTrk"000<
>>#1-#,:#\_$8*74++,0,28*"'"039v
v,:,\,*2,1"Hd":\<,,,,,,*3"U"*9<
>"@1",2*,\,,1-:#^_"/3d",5*,,, @ |
http://rosettacode.org/wiki/Musical_scale | Musical scale | Task
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| #C | C |
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf("\t%s",sequence[i].str);
sound(261.63*pow(2,sequence[i].key/12.0));
delay(sequence[i].key%12==0?500:1000);
i = (i+1)%8;
i==0?printf("\n"):printf("");
}
nosound();
return 0;
} |
http://rosettacode.org/wiki/N-smooth_numbers | N-smooth numbers | n-smooth numbers are positive integers which have no prime factors > n.
The n (when using it in the expression) n-smooth is always prime,
there are no 9-smooth numbers.
1 (unity) is always included in n-smooth numbers.
2-smooth numbers are non-negative powers of two.
5-smooth numbers are also called Hamming numbers.
7-smooth numbers are also called humble numbers.
A way to express 11-smooth numbers is:
11-smooth = 2i × 3j × 5k × 7m × 11p
where i, j, k, m, p ≥ 0
Task
calculate and show the first 25 n-smooth numbers for n=2 ───► n=29
calculate and show three numbers starting with 3,000 n-smooth numbers for n=3 ───► n=29
calculate and show twenty numbers starting with 30,000 n-smooth numbers for n=503 ───► n=521 (optional)
All ranges (for n) are to be inclusive, and only prime numbers are to be used.
The (optional) n-smooth numbers for the third range are: 503, 509, and 521.
Show all n-smooth numbers for any particular n in a horizontal list.
Show all output here on this page.
Related tasks
Hamming numbers
humble numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A000079 2-smooth numbers or non-negative powers of two
OEIS entry: A003586 3-smooth numbers
OEIS entry: A051037 5-smooth numbers or Hamming numbers
OEIS entry: A002473 7-smooth numbers or humble numbers
OEIS entry: A051038 11-smooth numbers
OEIS entry: A080197 13-smooth numbers
OEIS entry: A080681 17-smooth numbers
OEIS entry: A080682 19-smooth numbers
OEIS entry: A080683 23-smooth numbers
| #Factor | Factor | USING: deques dlists formatting fry io kernel locals make math
math.order math.primes math.text.english namespaces prettyprint
sequences tools.memory.private ;
IN: rosetta-code.n-smooth-numbers
SYMBOL: primes
: ns ( n -- seq )
primes-upto [ primes set ] [ length [ 1 1dlist ] replicate ]
bi ;
: enqueue ( n seq -- )
[ primes get ] 2dip [ '[ _ * ] map ] dip [ push-back ] 2each
;
: next ( seq -- n )
dup [ peek-front ] map infimum
[ '[ dup peek-front _ = [ pop-front* ] [ drop ] if ] each ]
[ swap enqueue ] [ nip ] 2tri ;
: next-n ( seq n -- seq )
swap '[ _ [ _ next , ] times ] { } make ;
:: n-smooth ( n from to -- seq )
n ns to next-n to from - 1 + tail* ;
:: show-smooth ( plo phi lo hi -- )
plo phi primes-between [
:> p lo commas lo ordinal-suffix hi commas hi
ordinal-suffix p "%s%s through %s%s %d-smooth numbers: "
printf p lo hi n-smooth [ pprint bl ] each nl
] each ;
: smooth-numbers-demo ( -- )
2 29 1 25 show-smooth nl
3 29 3000 3002 show-smooth nl
503 521 30,000 30,019 show-smooth ;
MAIN: smooth-numbers-demo |
http://rosettacode.org/wiki/N-smooth_numbers | N-smooth numbers | n-smooth numbers are positive integers which have no prime factors > n.
The n (when using it in the expression) n-smooth is always prime,
there are no 9-smooth numbers.
1 (unity) is always included in n-smooth numbers.
2-smooth numbers are non-negative powers of two.
5-smooth numbers are also called Hamming numbers.
7-smooth numbers are also called humble numbers.
A way to express 11-smooth numbers is:
11-smooth = 2i × 3j × 5k × 7m × 11p
where i, j, k, m, p ≥ 0
Task
calculate and show the first 25 n-smooth numbers for n=2 ───► n=29
calculate and show three numbers starting with 3,000 n-smooth numbers for n=3 ───► n=29
calculate and show twenty numbers starting with 30,000 n-smooth numbers for n=503 ───► n=521 (optional)
All ranges (for n) are to be inclusive, and only prime numbers are to be used.
The (optional) n-smooth numbers for the third range are: 503, 509, and 521.
Show all n-smooth numbers for any particular n in a horizontal list.
Show all output here on this page.
Related tasks
Hamming numbers
humble numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A000079 2-smooth numbers or non-negative powers of two
OEIS entry: A003586 3-smooth numbers
OEIS entry: A051037 5-smooth numbers or Hamming numbers
OEIS entry: A002473 7-smooth numbers or humble numbers
OEIS entry: A051038 11-smooth numbers
OEIS entry: A080197 13-smooth numbers
OEIS entry: A080681 17-smooth numbers
OEIS entry: A080682 19-smooth numbers
OEIS entry: A080683 23-smooth numbers
| #Go | Go | package main
import (
"fmt"
"log"
"math/big"
)
var (
primes []*big.Int
smallPrimes []int
)
// cache all primes up to 521
func init() {
two := big.NewInt(2)
three := big.NewInt(3)
p521 := big.NewInt(521)
p29 := big.NewInt(29)
primes = append(primes, two)
smallPrimes = append(smallPrimes, 2)
for i := three; i.Cmp(p521) <= 0; i.Add(i, two) {
if i.ProbablyPrime(0) {
primes = append(primes, new(big.Int).Set(i))
if i.Cmp(p29) <= 0 {
smallPrimes = append(smallPrimes, int(i.Int64()))
}
}
}
}
func min(bs []*big.Int) *big.Int {
if len(bs) == 0 {
log.Fatal("slice must have at least one element")
}
res := bs[0]
for _, i := range bs[1:] {
if i.Cmp(res) < 0 {
res = i
}
}
return res
}
func nSmooth(n, size int) []*big.Int {
if n < 2 || n > 521 {
log.Fatal("n must be between 2 and 521")
}
if size < 1 {
log.Fatal("size must be at least 1")
}
bn := big.NewInt(int64(n))
ok := false
for _, prime := range primes {
if bn.Cmp(prime) == 0 {
ok = true
break
}
}
if !ok {
log.Fatal("n must be a prime number")
}
ns := make([]*big.Int, size)
ns[0] = big.NewInt(1)
var next []*big.Int
for i := 0; i < len(primes); i++ {
if primes[i].Cmp(bn) > 0 {
break
}
next = append(next, new(big.Int).Set(primes[i]))
}
indices := make([]int, len(next))
for m := 1; m < size; m++ {
ns[m] = new(big.Int).Set(min(next))
for i := 0; i < len(indices); i++ {
if ns[m].Cmp(next[i]) == 0 {
indices[i]++
next[i].Mul(primes[i], ns[indices[i]])
}
}
}
return ns
}
func main() {
for _, i := range smallPrimes {
fmt.Printf("The first 25 %d-smooth numbers are:\n", i)
fmt.Println(nSmooth(i, 25), "\n")
}
for _, i := range smallPrimes[1:] {
fmt.Printf("The 3,000th to 3,202nd %d-smooth numbers are:\n", i)
fmt.Println(nSmooth(i, 3002)[2999:], "\n")
}
for _, i := range []int{503, 509, 521} {
fmt.Printf("The 30,000th to 30,019th %d-smooth numbers are:\n", i)
fmt.Println(nSmooth(i, 30019)[29999:], "\n")
}
} |
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before.
Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL.
See also:
Varargs
Optional parameters
Wikipedia: Named parameter
| #Factor | Factor |
:: my-named-params ( a b -- c ) a b * ;
|
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before.
Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL.
See also:
Varargs
Optional parameters
Wikipedia: Named parameter
| #Forth | Forth | 256 buffer: first-name
256 buffer: last-name
: is ( a "name" -- ) parse-name rot place ;
: greet ( -- )
cr ." Hello, " first-name count type space last-name count type ." !" ;
first-name is Bob last-name is Hall greet
require mini-oof2.fs
require string.fs
object class
field: given-name
field: surname
end-class Person
: hiya ( -- )
cr ." Hiya, " given-name $. space surname $. ." !" ;
Person new >o s" Bob" given-name $! s" Hall" surname $! hiya o> |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Elixir | Elixir | defmodule RC do
def nth_root(n, x, precision \\ 1.0e-5) do
f = fn(prev) -> ((n - 1) * prev + x / :math.pow(prev, (n-1))) / n end
fixed_point(f, x, precision, f.(x))
end
defp fixed_point(_, guess, tolerance, next) when abs(guess - next) < tolerance, do: next
defp fixed_point(f, _, tolerance, next), do: fixed_point(f, next, tolerance, f.(next))
end
Enum.each([{2, 2}, {4, 81}, {10, 1024}, {1/2, 7}], fn {n, x} ->
IO.puts "#{n} root of #{x} is #{RC.nth_root(n, x)}"
end) |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #AutoHotkey | AutoHotkey | for k, v in [[0, 25], [250, 265], [1000, 1025]] {
while v[1] <= v[2] {
Out .= Ordinal(v[1]) " "
v[1]++
}
Out .= "`n"
}
MsgBox, % Out
Ordinal(n) {
s2 := Mod(n, 100)
if (s2 > 10 && s2 < 14)
return n "th"
s1 := Mod(n, 10)
return n (s1 = 1 ? "st" : s1 = 2 ? "nd" : s1 = 3 ? "rd" : "th")
} |
http://rosettacode.org/wiki/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n:
μ(1) is defined to be 1.
μ(n) = 1 if n is a square-free positive integer with an even number of prime factors.
μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
μ(n) = 0 if n has a squared prime factor.
Task
Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
See also
Wikipedia: Möbius function
Related Tasks
Mertens function
| #GW-BASIC | GW-BASIC | 10 FOR T = 0 TO 9
20 FOR U = 1 TO 10
30 N = 10*T + U
40 GOSUB 100
50 PRINT USING "## ";M;
60 NEXT U
70 PRINT
80 NEXT T
90 END
100 IF N = 1 THEN M = 1 : RETURN
110 M = 1 : F = 2
120 IF N MOD (F*F) = 0 THEN M = 0 : RETURN
130 IF N MOD F = 0 THEN GOSUB 170
140 F = F + 1
150 IF F <= N THEN GOTO 120
160 RETURN
170 M = -M
180 N = N/F
190 RETURN |
http://rosettacode.org/wiki/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n:
μ(1) is defined to be 1.
μ(n) = 1 if n is a square-free positive integer with an even number of prime factors.
μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
μ(n) = 0 if n has a squared prime factor.
Task
Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
See also
Wikipedia: Möbius function
Related Tasks
Mertens function
| #Haskell | Haskell | import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Data.Vector.Unboxed (toList)
import Math.NumberTheory.ArithmeticFunctions.Moebius (Moebius(..),
sieveBlockMoebius)
import System.Environment (getArgs, getProgName)
import System.IO (hPutStrLn, stderr)
import Text.Read (readMaybe)
-- Calculate the Möbius function, μ(n), for a sequence of values starting at 1.
moebiusBlock :: Word -> [Moebius]
moebiusBlock = toList . sieveBlockMoebius 1
showMoebiusBlock :: Word -> [Moebius] -> String
showMoebiusBlock cols = intercalate "\n" . map (concatMap showMoebius) .
chunksOf (fromIntegral cols)
where showMoebius MoebiusN = " -1"
showMoebius MoebiusZ = " 0"
showMoebius MoebiusP = " 1"
main :: IO ()
main = do
prog <- getProgName
args <- map readMaybe <$> getArgs
case args of
[Just cols, Just n] ->
putStrLn ("μ(n) for 1 ≤ n ≤ " ++ show n ++ ":\n") >>
putStrLn (showMoebiusBlock cols $ moebiusBlock n)
_ -> hPutStrLn stderr $ "Usage: " ++ prog ++ " num-columns maximum-number" |
http://rosettacode.org/wiki/Natural_sorting | Natural sorting |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Natural sorting is the sorting of text that does more than rely on the
order of individual characters codes to make the finding of
individual strings easier for a human reader.
There is no "one true way" to do this, but for the purpose of this task 'natural' orderings might include:
1. Ignore leading, trailing and multiple adjacent spaces
2. Make all whitespace characters equivalent.
3. Sorting without regard to case.
4. Sorting numeric portions of strings in numeric order.
That is split the string into fields on numeric boundaries, then sort on each field, with the rightmost fields being the most significant, and numeric fields of integers treated as numbers.
foo9.txt before foo10.txt
As well as ... x9y99 before x9y100, before x10y0
... (for any number of groups of integers in a string).
5. Title sorts: without regard to a leading, very common, word such
as 'The' in "The thirty-nine steps".
6. Sort letters without regard to accents.
7. Sort ligatures as separate letters.
8. Replacements:
Sort German eszett or scharfes S (ß) as ss
Sort ſ, LATIN SMALL LETTER LONG S as s
Sort ʒ, LATIN SMALL LETTER EZH as s
∙∙∙
Task Description
Implement the first four of the eight given features in a natural sorting routine/function/method...
Test each feature implemented separately with an ordered list of test strings from the Sample inputs section below, and make sure your naturally sorted output is in the same order as other language outputs such as Python.
Print and display your output.
For extra credit implement more than the first four.
Note: it is not necessary to have individual control of which features are active in the natural sorting routine at any time.
Sample input
• Ignoring leading spaces. Text strings: ['ignore leading spaces: 2-2',
'ignore leading spaces: 2-1',
'ignore leading spaces: 2+0',
'ignore leading spaces: 2+1']
• Ignoring multiple adjacent spaces (MAS). Text strings: ['ignore MAS spaces: 2-2',
'ignore MAS spaces: 2-1',
'ignore MAS spaces: 2+0',
'ignore MAS spaces: 2+1']
• Equivalent whitespace characters. Text strings: ['Equiv. spaces: 3-3',
'Equiv. \rspaces: 3-2',
'Equiv. \x0cspaces: 3-1',
'Equiv. \x0bspaces: 3+0',
'Equiv. \nspaces: 3+1',
'Equiv. \tspaces: 3+2']
• Case Independent sort. Text strings: ['cASE INDEPENDENT: 3-2',
'caSE INDEPENDENT: 3-1',
'casE INDEPENDENT: 3+0',
'case INDEPENDENT: 3+1']
• Numeric fields as numerics. Text strings: ['foo100bar99baz0.txt',
'foo100bar10baz0.txt',
'foo1000bar99baz10.txt',
'foo1000bar99baz9.txt']
• Title sorts. Text strings: ['The Wind in the Willows',
'The 40th step more',
'The 39 steps',
'Wanda']
• Equivalent accented characters (and case). Text strings: [u'Equiv. \xfd accents: 2-2',
u'Equiv. \xdd accents: 2-1',
u'Equiv. y accents: 2+0',
u'Equiv. Y accents: 2+1']
• Separated ligatures. Text strings: [u'\u0132 ligatured ij',
'no ligature']
• Character replacements. Text strings: [u'Start with an \u0292: 2-2',
u'Start with an \u017f: 2-1',
u'Start with an \xdf: 2+0',
u'Start with an s: 2+1']
| #Pascal | Pascal |
Program Natural; Uses DOS, crt; {Simple selection.}
{Demonstrates a "natural" order of sorting text with nameish parts.}
Const null=#0; BS=#8; HT=#9; LF=#10{0A}; VT=#11{0B}; FF=#12{0C}; CR=#13{0D};
Procedure Croak(gasp: string);
Begin
WriteLn(Gasp);
HALT;
End;
Function Space(n: integer): string; {Can't use n*" " either.}
var text: string; {A scratchpad.}
var i: integer; {A stepper.}
Begin
if n > 255 then n:=255 {A value parameter,}
else if n < 0 then n:=0; {So this just messes with my copy.}
for i:=1 to n do text[i]:=' '; {Place some spaces.}
text[0]:=char(n); {Place the length thereof.}
Space:=text; {Take that.}
End; {of Space.}
Function DeFang(x: string): string; {Certain character codes cause action.}
var text: string; {A scratchpad, as using DeFang directly might imply recursion.}
var i: integer; {A stepper.}
var c: char; {Reduce repetition.}
Begin {I hope that appending is recognised by the compiler...}
text:=''; {Scrub the scratchpad.}
for i:=1 to Length(x) do {Step through the source text.}
begin {Inspecting each character.}
c:=char(x[i]); {Grab it.}
if c > CR then text:=text + c {Deemed not troublesome.}
else if c < BS then text:=text + c {Lacks an agreed alternative, and may not cause trouble.}
else text:=text + '!' + copy('btnvfr',ord(c) - ord(BS) + 1,1); {The alternative codes.}
end; {On to the next.}
DeFang:=text; {Alas, the "escape" convention lengthens the text.}
End; {of DeFang.} {But that only mars the layout, rather than ruining it.}
Const mEntry = 66; {Sufficient for demonstrations.}
Type EntryList = array[0..mEntry] of integer; {Identifies texts by their index.}
var EntryText: array[1..mEntry] of string; {Inbto this array.}
var nEntry: integer; {The current number.}
Function AddEntry(x: string): integer; {Add another text to the collection.}
Begin {Could extend to checking for duplicates via a sorted list...}
if nEntry >= mEntry then Croak('Too many entries!'); {Perhaps not!}
inc(nEntry); {So, another.}
EntryText[nEntry]:=x; {Placed.}
AddEntry:=nEntry; {The caller will want to know where.}
End; {of AddEntry.}
Function TextOrder(i,j: integer): boolean; {This is easy.}
Begin {But despite being only one statement, and simple at that,}
TextOrder:=EntryText[i] <= EntryText[j]; {Begin...End is insisted upon.}
End; {of TextOrder.}
Function NaturalOrder(e1,e2: integer): boolean;{Not so easy.}
const Article: array[1..3] of string[4] = ('A ','AN ','THE '); {Each with its trailing space.}
Function Crush(var c: char): char; {Suppresses divergence.}
Begin {To simplify comparisons.}
if c <= ' ' then Crush:=' ' {Crush the fancy control characters.}
else Crush:=UpCase(c); {Also crush a < A or a > A or a = A questions.}
End; {of Crush.}
var Wot: array[1..2] of integer; {Which text is being fingered.}
var Tail: array[1..2] of integer; {Which article has been found at the start.}
var l,lst: array[1..2] of integer; {Finger to the current point, and last character.}
Procedure Librarian; {Initial inspection of the texts.}
var Blocked: boolean; {Further progress may be obstructed.}
var a,is,i: integer; {Odds and ends.}
label Hic; {For escaping the search when a match is complete.}
Begin {There are two texts to inspect.}
for is:=1 to 2 do {Treat them alike.}
begin {This is the first encounter.}
l[is]:=1; {So start the scan with the first character.}
Tail[is]:=0; {No articles found.}
while (l[is] <= lst[is]) and (EntryText[wot[is]][l[is]] <= ' ') do inc(l[is]); {Leading spaceish.}
for a:=1 to 3 do {Try to match an article at the start of the text.}
begin {Each article's text has a trailing space to be matched also.}
i:=0; {Start a for-loop, but with early escape in mind.}
Repeat {Compare successive characters, for i:=0 to a...}
if l[is] + i > lst[is] then Blocked:=true {Probed past the end of text?}
else Blocked:=Crush(EntryText[wot[is]][l[is] + i]) <> Article[a][i + 1]; {No. Compare capitals.}
inc(i); {Stepping on to the next character.}
Until Blocked or (i > a); {Conveniently, Length(Article[a]) = a.}
if not Blocked then {Was a mismatch found?}
begin {No!}
Tail[is]:=a; {So, identify the discovery.}
l[is]:=l[is] + i; {And advance the scan to whatever follows.}
goto Hic; {Escape so as to consider the other text.}
end; {Since two texts are being considered separately.}
end; {Sigh. no "Next a" or similar syntax.}
Hic:dec(l[is]); {Backstep one, ready to advance later.}
end; {Likewise, no "for is:=1 to 2 do ... Next is" syntax.}
End; {of Librarian.}
var c: array[1..2] of string[1]; {Selected by Advance for comparison.}
var d: integer; {Their difference.}
type moody = (Done,Bored,Grist,Numeric); {Might as well have some mnemonics.}
var Mood: array[1..2] of moody; {As the scan proceeds, moods vary.}
var depth: array[1..2] of integer; {Digit depth.}
Procedure Another; {Choose a pair of characters to compare.}
{Digit sequences are special! But periods are ignored, also signs, avoiding confusion over "+6" and " 6".}
var is: integer; {Selects from one text or the other.}
var ll: integer; {Looks past the text into any Article.}
var d: char; {Possibly a digit.}
Begin
for is:=1 to 2 do {Same treatment for both texts.}
begin {Find the next character, and taste it.}
repeat {If already bored, slog through any following spaces.}
inc(l[is]); {So, advance one character onwards.}
ll:=l[is] - lst[is]; {Compare to the end of the normal text.}
if ll <= 0 then c[is]:=Crush(EntryText[wot[is]][l[is]]) {Still in the normal text.}
else if Tail[is] <= 0 then c[is]:='' {Perhaps there is no tail.}
else if ll <= 2 then c[is]:=copy(', ',ll,1) {If there is, this is the junction.}
else if ll <= 2 + Tail[is] then c[is]:=copy(Article[Tail[is]],ll - 2,1) {And this the tail.}
else c[is]:=''; {Actually, the copy would do this.}
until not ((c[is] = ' ') and (Mood[is] = Bored)); {Thus pass multiple enclosed spaces, but not the first.}
if length(c[is]) <= 0 then Mood[is]:=Done {Perhaps we ran off the end, even of the tail.}
else if c[is] = ' ' then Mood[is]:=Bored {The first taste of a space induces boredom.}
else if ('0' <= c[is]) and (c[is] <= '9') then Mood[is]:=Numeric {Paired, evokes special attention.}
else Mood[is]:=Grist; {All else is grist for my comparisons.}
end; {Switch to the next text.}
{Comparing digit sequences is to be done as if numbers. "007" vs "70" is to become vs. "070" by length matching.}
if (Mood[1] = Numeric) and (Mood[2] = Numeric) then {Are both texts yielding a digit?}
begin {Yes. Special treatment impends.}
if (Depth[1] = 0) and (Depth[2] = 0) then {Do I already know how many digits impend?}
for is:=1 to 2 do {No. So for each text,}
repeat {Keep looking until I stop seeing digits.}
inc(Depth[is]); {I am seeing a digit, so there will be one to count.}
ll:=l[is] + Depth[is]; {Finger the next position.}
if ll > lst[is] then d:=null {And if not off the end,}
else d:=EntryText[wot[is]][ll]; {Grab a potential digit.}
until (d < '0') or (d > '9'); {If it is one, probe again.}
if Depth[1] < Depth[2] then {Righto, if the first sequence has fewer digits,}
begin {Supply a free zero.}
dec(Depth[2]); {The second's digit will be consumed.}
dec(l[1]); {The first's will be re-encountered.}
c[1]:='0'; {Here is the zero}
end {For the comparison.}
else if Depth[2] < Depth[1] then {But if the second has fewer digits to come,}
begin {Don't dig into them yet.}
dec(Depth[1]); {The first's digit will be used.}
dec(l[2]); {But the second's seen again.}
c[2]:='0'; {After this has been used}
end {In the comparison.}
else {But if both have the same number of digits remaining,}
begin {Then the comparison is aligned.}
dec(Depth[1]); {So this digit will be used.}
dec(Depth[2]); {As will this.}
end; {In the comparison.}
end; {Thus, arbitrary-size numbers are allowed, as they're never numbers.}
End; {of Another.} {Possibly, the two characters will be the same, and another pair will be requested.}
Begin {of NaturalOrder.}
Wot[1]:=e1; Wot[2]:=e2; {Make the two texts accessible via indexing.}
lst[1]:=Length(EntryText[e1]); {The last character of the first text.}
lst[2]:=Length(EntryText[e2]); {And of the second. Saves on repetition.}
Mood[1]:=Bored; Mood[2]:=Bored; {Behave as if we have already seen a space.}
depth[1]:=0; depth[2]:=0; {And, no digits in concert have been seen.}
Librarian; {Start the inspection.}
repeat {Chug along, until a difference is found.}
Another; {To do so, choose another pair of characters to compare.}
d:=Length(c[2]) - Length(c[1]); {If one text has run out, favour the shorter.}
if (d = 0) and (Length(c[1]) > 0) then d:=ord(c[2][1]) - ord(c[1][1]); {Otherwise, their difference.}
until (d <> 0) or ((Mood[1] = Done) and (Mood[2] = Done)); {Well? Are we there yet?}
NaturalOrder:=d >= 0; {And so, does e1's text precede e2's?}
End; {of NatualOrder.}
var TextSort: boolean; {Because I can't pass a function as a parameter,}
Function InOrder(i,j: integer): boolean; {I can only use one function.}
Begin {Which messes with a selector.}
if TextSort then InOrder:=TextOrder(i,j) {So then,}
else InOrder:=NaturalOrder(i,j); {Which is it to be?}
End; {of InOrder.}
Procedure OrderEntry(var List: EntryList); {Passing a ordinary array is not Pascalish, damnit.}
{Crank up a Comb sort of the entries fingered by List. Working backwards, just for fun.}
{Caution: the H*10/13 means that H ought not be INTEGER*2. Otherwise, use H/1.3.}
var t: integer; {Same type as the elements of List.}
var N,i,h: integer; {Odds and ends.}
var happy: boolean; {To be attained.}
Begin
N:=List[0]; {Extract the count.}
h:=N - 1; {"Last" - "First", and not +1.}
if h <= 0 then exit; {Ha ha.}
Repeat {Start the pounding.}
h:=LongInt(h)*10 div 13; {Beware overflow, or, use /1.3.}
if h <= 0 then h:=1; {No "max" function, damnit.}
if (h = 9) or (h = 10) then h:=11; {A fiddle.}
happy:=true; {No disorder seen.}
for i:=N - h downto 1 do {So, go looking. If h = 1, this is a Bubblesort.}
if not InOrder(List[i],List[i + h]) then {How about this pair?}
begin {Alas.}
t:=List[i]; List[i]:=List[i + h]; List[i + h]:=t;{No Swap(a,b), damnit.}
happy:=false; {Disorder has been discovered.}
end; {On to the next comparison.}
Until happy and (h = 1); {No suspicion remains?}
End; {of OrderEntry.}
var Item,Fancy: EntryList; {Two lists of entry indices.}
var i: integer; {A stepper.}
var t1: string; {A scratchpad.}
BEGIN
nEntry:=0; {No entries are stored.}
i:=0; {Start a stepper.}
inc(i);Item[i]:=AddEntry('ignore leading spaces: 2-2');
inc(i);Item[i]:=AddEntry(' ignore leading spaces: 2-1');
inc(i);Item[i]:=AddEntry(' ignore leading spaces: 2+0');
inc(i);Item[i]:=AddEntry(' ignore leading spaces: 2+1');
inc(i);Item[i]:=AddEntry('ignore m.a.s spaces: 2-2');
inc(i);Item[i]:=AddEntry('ignore m.a.s spaces: 2-1');
inc(i);Item[i]:=AddEntry('ignore m.a.s spaces: 2+0');
inc(i);Item[i]:=AddEntry('ignore m.a.s spaces: 2+1');
inc(i);Item[i]:=AddEntry('Equiv.'+' '+'spaces: 3-3');
inc(i);Item[i]:=AddEntry('Equiv.'+CR+'spaces: 3-2'); {CR can't appear as itself.}
inc(i);Item[i]:=AddEntry('Equiv.'+FF+'spaces: 3-1'); {As it is used to mark line endings.}
inc(i);Item[i]:=AddEntry('Equiv.'+VT+'spaces: 3+0'); {And if typed in an editor,}
inc(i);Item[i]:=AddEntry('Equiv.'+LF+'spaces: 3+1'); {It is acted upon there and then.}
inc(i);Item[i]:=AddEntry('Equiv.'+HT+'spaces: 3+2'); {So, name instead of value.}
inc(i);Item[i]:=AddEntry('cASE INDEPENDENT: 3-2');
inc(i);Item[i]:=AddEntry('caSE INDEPENDENT: 3-1');
inc(i);Item[i]:=AddEntry('casE INDEPENDENT: 3+0');
inc(i);Item[i]:=AddEntry('case INDEPENDENT: 3+1');
inc(i);Item[i]:=AddEntry('foo100bar99baz0.txt');
inc(i);Item[i]:=AddEntry('foo100bar10baz0.txt');
inc(i);Item[i]:=AddEntry('foo1000bar99baz10.txt');
inc(i);Item[i]:=AddEntry('foo1000bar99baz9.txt');
inc(i);Item[i]:=AddEntry('The Wind in the Willows');
inc(i);Item[i]:=AddEntry('The 40th step more');
inc(i);Item[i]:=AddEntry('The 39 steps');
inc(i);Item[i]:=AddEntry('Wanda');
{inc(i);Item[i]:=AddEntry('The Worth of Wirth''s Way');}
Item[0]:=nEntry; {Complete the EntryList protocol.}
for i:=0 to nEntry do Fancy[i]:=Item[i]; {Sigh. Fancy:=Item.}
TextSort:=true; OrderEntry(Item); {Plain text ordering.}
TextSort:=false; OrderEntry(Fancy); {Natural order.}
WriteLn(' Text order Natural order');
for i:=1 to nEntry do
begin
t1:=DeFang(EntryText[Item[i]]);
WriteLn(Item[i]:3,'|',t1,Space(30 - length(t1)),' ',
Fancy[i]:3,'|',DeFang(EntryText[Fancy[i]]));
end;
END.
|
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Visual_Basic | Visual Basic | Dim dblDistance as Double |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Wren | Wren |
const namespace_name = @import("dir_name/file_name.zig");
const TypeName = @import("dir_name/TypeName.zig");
var global_var: i32 = undefined;
const const_name = 42;
const primitive_type_alias = f32;
const string_alias = []u8;
const StructName = struct {
field: i32,
};
const StructAlias = StructName;
fn functionName(param_name: TypeName) void {
var functionPointer = functionName;
functionPointer();
functionPointer = otherFunction;
functionPointer();
}
const functionAlias = functionName;
fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
return List(ChildType, fixed_size);
}
fn ShortList(comptime T: type, comptime n: usize) type {
return struct {
field_name: [n]T,
fn methodName() void {}
};
}
// The word XML loses its casing when used in Zig identifiers.
const xml_document =
\\<?xml version="1.0" encoding="UTF-8"?>
\\<document>
\\</document>
;
const XmlParser = struct {
field: i32,
};
// The initials BE (Big Endian) are just another word in Zig identifier names.
fn readU32Be() u32 {}
|
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #XPL0 | XPL0 |
const namespace_name = @import("dir_name/file_name.zig");
const TypeName = @import("dir_name/TypeName.zig");
var global_var: i32 = undefined;
const const_name = 42;
const primitive_type_alias = f32;
const string_alias = []u8;
const StructName = struct {
field: i32,
};
const StructAlias = StructName;
fn functionName(param_name: TypeName) void {
var functionPointer = functionName;
functionPointer();
functionPointer = otherFunction;
functionPointer();
}
const functionAlias = functionName;
fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
return List(ChildType, fixed_size);
}
fn ShortList(comptime T: type, comptime n: usize) type {
return struct {
field_name: [n]T,
fn methodName() void {}
};
}
// The word XML loses its casing when used in Zig identifiers.
const xml_document =
\\<?xml version="1.0" encoding="UTF-8"?>
\\<document>
\\</document>
;
const XmlParser = struct {
field: i32,
};
// The initials BE (Big Endian) are just another word in Zig identifier names.
fn readU32Be() u32 {}
|
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #Zig | Zig |
const namespace_name = @import("dir_name/file_name.zig");
const TypeName = @import("dir_name/TypeName.zig");
var global_var: i32 = undefined;
const const_name = 42;
const primitive_type_alias = f32;
const string_alias = []u8;
const StructName = struct {
field: i32,
};
const StructAlias = StructName;
fn functionName(param_name: TypeName) void {
var functionPointer = functionName;
functionPointer();
functionPointer = otherFunction;
functionPointer();
}
const functionAlias = functionName;
fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
return List(ChildType, fixed_size);
}
fn ShortList(comptime T: type, comptime n: usize) type {
return struct {
field_name: [n]T,
fn methodName() void {}
};
}
// The word XML loses its casing when used in Zig identifiers.
const xml_document =
\\<?xml version="1.0" encoding="UTF-8"?>
\\<document>
\\</document>
;
const XmlParser = struct {
field: i32,
};
// The initials BE (Big Endian) are just another word in Zig identifier names.
fn readU32Be() u32 {}
|
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #XPL0 | XPL0 | proc MakeList(Separator);
char Separator;
int Counter;
proc MakeItem;
int Ordinals;
[IntOut(0, Counter);
Text(0, Separator);
Ordinals:= [0, "first", "second", "third"];
Text(0, Ordinals(Counter));
CrLf(0);
];
for Counter:= 1 to 3 do MakeItem; \MakeList procedure
MakeList(". ") \main procedure |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #zkl | zkl | fcn makeList(separator){
counter:=Ref(1); // a container holding a one. A reference.
// 'wrap is partial application, in this case binding counter and separator
makeItem:='wrap(item){ c:=counter.inc(); String(c,separator,item,"\n") };
makeItem("first") + makeItem("second") + makeItem("third")
}
print(makeList(". ")); |
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence.
Note: Subsequences are defined structurally, not by their contents.
So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
Task: Find all non-continuous subsequences for a given sequence.
Example
For the sequence 1,2,3,4, there are five non-continuous subsequences, namely:
1,3
1,4
2,4
1,3,4
1,2,4
Goal
There are different ways to calculate those subsequences.
Demonstrate algorithm(s) that are natural for the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scala | Scala | object NonContinuousSubSequences extends App {
private def seqR(s: String, c: String, i: Int, added: Int): Unit = {
if (i == s.length) {
if (c.trim.length > added) println(c)
} else {
seqR(s, c + s(i), i + 1, added + 1)
seqR(s, c + " ", i + 1, added)
}
}
seqR("1234", "", 0, 0)
} |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #JavaScript | JavaScript | k = 26
s = k.toString(16) //gives 1a
i = parseInt('1a',16) //gives 26
//optional special case for hex:
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26. |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary (expect 21102)
Encode the decimal number 15 as negadecimal (expect 195)
In each of the above cases, convert the encoded number back to decimal.
extra credit
supply an integer, that when encoded to base -62 (or something "higher"), expresses the
name of the language being used (with correct capitalization). If the computer language has
non-alphanumeric characters, try to encode them into the negatory numerals, or use other
characters instead.
| #VBA | VBA | Const DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Dim Str(63) As String
Private Function mod2(a As Long, b As Integer) As Long
mod2 = a - (a \ b) * b
End Function
Private Function swap(a As String, b As String)
Dim t As String
t = a
a = b
b = t
End Function
Private Function EncodeNegativeBase(ByVal n As Long, base As Integer) As String
Dim ptr, idx As Long
Dim rem_ As Long
Dim result As String
If base > -1 Or base < -62 Then
EncodeNegativeBase = result
Else
If n = 0 Then
EncodeNegativeBase = "0"
Else
ptr = 0
Do While n <> 0
rem_ = mod2(n, base)
n = n \ base
If rem_ < 0 Then
n = n + 1
rem_ = rem_ - base
End If
result = result & Mid(DIGITS, rem_ + 1, 1)
Loop
End If
End If
EncodeNegativeBase = StrReverse(result)
End Function
Private Function DecodeNegativeBase(ns As String, base As Integer) As Long
Dim total As Long, bb As Long
Dim i As Integer, j As Integer
If base < -62 Or base > -1 Then DecodeNegativeBase = 0
If Mid(ns, 1, 1) = 0 Or (Mid(ns, 1, 1) = "0" And Mid(ns, 2, 1) = 0) Then DecodeNegativeBase = 0
i = Len(ns)
total = 0
bb = 1
Do While i >= 1
j = InStr(1, DIGITS, Mid(ns, i, 1), vbTextCompare) - 1
total = total + j * bb
bb = bb * base
i = i - 1
Loop
DecodeNegativeBase = total
End Function
Private Sub Driver(n As Long, b As Integer)
Dim ns As String
Dim p As Long
ns = EncodeNegativeBase(n, b)
Debug.Print CStr(n); " encoded in base "; b; " = "; ns
p = DecodeNegativeBase(ns, b)
Debug.Print ns; " decoded in base "; b; " = "; p
Debug.Print
End Sub
Public Sub main()
Driver 10, -2
Driver 146, -3
Driver 15, -10
Driver 118492, -62
End Sub |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #True_BASIC | True BASIC | LET monton = 12
LET llevar = 0
DO WHILE monton > 0
PRINT "Quedan"; monton; "fichas. ¿Cuántas te gustaría tomar";
INPUT llevar
DO WHILE llevar = 0 OR llevar > 3
PRINT "Debes tomar 1, 2, o 3 fichas. ¿Cuántas te gustaría tomar";
INPUT llevar
LOOP
PRINT "Es mi turno, tomaré"; 4-llevar; "ficha(s)."
LET monton = monton - 4
LOOP
PRINT
SET COLOR 2
PRINT "Obtuve la última ficha. ¡Gané! Mejor suerte la próxima vez."
END |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Vlang | Vlang | import os { input }
fn show_tokens(tokens int) {
println('Tokens remaining $tokens\n')
}
fn main() {
mut tokens := 12
for {
show_tokens(tokens)
t := input(' How many tokens 1, 2, or 3? ').int()
if t !in [1, 2, 3] {
println('\nMust be a number between 1 and 3, try again.\n')
} else {
ct := 4 - t
mut s := 's'
if ct == 1 {
s = ''
}
println(' Computer takes $ct token$s \n')
tokens -= 4
}
if tokens == 0 {
show_tokens(0)
println(' Computer wins!')
return
}
}
} |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #C.23 | C# |
using System;
namespace Narcissistic
{
class Narcissistic
{
public bool isNarcissistic(int z)
{
if (z < 0) return false;
string n = z.ToString();
int t = 0, l = n.Length;
foreach (char c in n)
t += Convert.ToInt32(Math.Pow(Convert.ToDouble(c - 48), l));
return t == z;
}
}
class Program
{
static void Main(string[] args)
{
Narcissistic n = new Narcissistic();
int c = 0, x = 0;
while (c < 25)
{
if (n.isNarcissistic(x))
{
if (c % 5 == 0) Console.WriteLine();
Console.Write("{0,7} ", x);
c++;
}
x++;
}
Console.WriteLine("\n\nPress any key to continue...");
Console.ReadKey();
}
}
}
|
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #C | C | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
void hue_to_rgb(double hue, double sat, unsigned char *p)
{
double x;
int c = 255 * sat;
hue /= 60;
x = (1 - fabs(fmod(hue, 2) - 1)) * 255;
switch((int)hue) {
case 0: p[0] = c; p[1] = x; p[2] = 0; return;
case 1: p[0] = x; p[1] = c; p[2] = 0; return;
case 2: p[0] = 0; p[1] = c; p[2] = x; return;
case 3: p[0] = 0; p[1] = x; p[2] = c; return;
case 4: p[0] = x; p[1] = 0; p[2] = c; return;
case 5: p[0] = c; p[1] = 0; p[2] = x; return;
}
}
int main(void)
{
const int size = 512;
int i, j;
unsigned char *colors = malloc(size * 3);
unsigned char *pix = malloc(size * size * 3), *p;
FILE *fp;
for (i = 0; i < size; i++)
hue_to_rgb(i * 240. / size, i * 1. / size, colors + 3 * i);
for (i = 0, p = pix; i < size; i++)
for (j = 0; j < size; j++, p += 3)
memcpy(p, colors + (i ^ j) * 3, 3);
fp = fopen("xor.ppm", "wb");
fprintf(fp, "P6\n%d %d\n255\n", size, size);
fwrite(pix, size * size * 3, 1, fp);
fclose(fp);
return 0;
} |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #360_Assembly | 360 Assembly | * Munchausen numbers 16/03/2019
MUNCHAU CSECT
USING MUNCHAU,R12 base register
LR R12,R15 set addressability
L R3,=F'5000' for do i=1 to 5000
LA R6,1 i=1
LOOPI SR R10,R10 s=0
LR R0,R6 ii=i
LA R11,4 for do j=1 to 4
LA R7,P10 j=1
LOOPJ L R8,0(R7) d=p10(j)
LR R4,R0 ii
SRDA R4,32 ~
DR R4,R8 (n,r)=ii/d
SLA R5,2 ~
L R1,POW(R5) pow(n+1)
AR R10,R1 s=s+pow(n+1)
LR R0,R4 ii=r
LA R7,4(R7) j++
BCT R11,LOOPJ enddo j
CR R10,R6 if s=i
BNE SKIP then
XDECO R6,PG edit i
XPRNT PG,L'PG print i
SKIP LA R6,1(R6) i++
BCT R3,LOOPI enddo i
BR R14 return to caller
POW DC F'0',F'1',F'4',F'27',F'256',F'3125',4F'0'
P10 DC F'1000',F'100',F'10',F'1'
PG DC CL12' ' buffer
REGEQU
END MUNCHAU |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
procedure Mutual_Recursion is
function M(N : Integer) return Integer;
function F(N : Integer) return Integer is
begin
if N = 0 then
return 1;
else
return N - M(F(N - 1));
end if;
end F;
function M(N : Integer) return Integer is
begin
if N = 0 then
return 0;
else
return N - F(M(N-1));
end if;
end M;
begin
for I in 0..19 loop
Put_Line(Integer'Image(F(I)));
end loop;
New_Line;
for I in 0..19 loop
Put_Line(Integer'Image(M(I)));
end loop;
end Mutual_recursion; |
http://rosettacode.org/wiki/Musical_scale | Musical scale | Task
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfège.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| #C.2B.2B | C++ |
#include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR )
{
std::cout << "Error opening MIDI Output..." << std::endl;
device = 0;
}
}
~midi()
{
midiOutReset( device );
midiOutClose( device );
}
bool isOpen() { return device != 0; }
void setInstrument( byte i )
{
message.data[0] = 0xc0; message.data[1] = i;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void playNote( byte n, unsigned i )
{
playNote( n ); Sleep( i ); stopNote( n );
}
private:
void playNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 127; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void stopNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
HMIDIOUT device;
midi_msg message;
};
int main( int argc, char* argv[] )
{
midi m;
if( m.isOpen() )
{
byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };
m.setInstrument( 42 );
for( int x = 0; x < 8; x++ )
m.playNote( notes[x], rand() % 100 + 158 );
Sleep( 1000 );
}
return 0;
}
|
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #11l | 11l | F multisplit(text, sep)
V lastmatch = 0
V i = 0
V matches = ‘’
L i < text.len
L(s) sep
V j = L.index
I text[i..].starts_with(s)
I i > lastmatch
matches ‘’= text[lastmatch .< i]
matches ‘’= ‘{’s‘}’
lastmatch = i + s.len
i += s.len
L.break
L.was_no_break
i++
I i > lastmatch
matches ‘’= text[lastmatch .< i]
R matches
print(multisplit(‘a!===b=!=c’, [‘==’, ‘!=’, ‘=’])) |
http://rosettacode.org/wiki/N-smooth_numbers | N-smooth numbers | n-smooth numbers are positive integers which have no prime factors > n.
The n (when using it in the expression) n-smooth is always prime,
there are no 9-smooth numbers.
1 (unity) is always included in n-smooth numbers.
2-smooth numbers are non-negative powers of two.
5-smooth numbers are also called Hamming numbers.
7-smooth numbers are also called humble numbers.
A way to express 11-smooth numbers is:
11-smooth = 2i × 3j × 5k × 7m × 11p
where i, j, k, m, p ≥ 0
Task
calculate and show the first 25 n-smooth numbers for n=2 ───► n=29
calculate and show three numbers starting with 3,000 n-smooth numbers for n=3 ───► n=29
calculate and show twenty numbers starting with 30,000 n-smooth numbers for n=503 ───► n=521 (optional)
All ranges (for n) are to be inclusive, and only prime numbers are to be used.
The (optional) n-smooth numbers for the third range are: 503, 509, and 521.
Show all n-smooth numbers for any particular n in a horizontal list.
Show all output here on this page.
Related tasks
Hamming numbers
humble numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A000079 2-smooth numbers or non-negative powers of two
OEIS entry: A003586 3-smooth numbers
OEIS entry: A051037 5-smooth numbers or Hamming numbers
OEIS entry: A002473 7-smooth numbers or humble numbers
OEIS entry: A051038 11-smooth numbers
OEIS entry: A080197 13-smooth numbers
OEIS entry: A080681 17-smooth numbers
OEIS entry: A080682 19-smooth numbers
OEIS entry: A080683 23-smooth numbers
| #Haskell | Haskell | import Data.Numbers.Primes (primes)
import Text.Printf (printf)
merge :: Ord a => [a] -> [a] -> [a]
merge [] b = b
merge a@(x:xs) b@(y:ys) | x < y = x : merge xs b
| otherwise = y : merge a ys
nSmooth :: Integer -> [Integer]
nSmooth p = 1 : foldr u [] factors
where
factors = takeWhile (<=p) primes
u n s = r
where r = merge s (map (n*) (1:r))
main :: IO ()
main = do
mapM_ (printf "First 25 %d-smooth:\n%s\n\n" <*> showTwentyFive) firstTenPrimes
mapM_
(printf "The 3,000 to 3,202 %d-smooth numbers are:\n%s\n\n" <*> showRange1)
firstTenPrimes
mapM_
(printf "The 30,000 to 30,019 %d-smooth numbers are:\n%s\n\n" <*> showRange2)
[503, 509, 521]
where
firstTenPrimes = take 10 primes
showTwentyFive = show . take 25 . nSmooth
showRange1 = show . ((<$> [2999 .. 3001]) . (!!) . nSmooth)
showRange2 = show . ((<$> [29999 .. 30018]) . (!!) . nSmooth) |
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
For example, if a function were to be defined as define func1( paramname1, paramname2); then it could be called normally as func1(argument1, argument2) and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
func1 must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order, for example: func1(paramname2=argument2, paramname1=argument1) which explicitly makes the same parameter/argument bindings as before.
Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL.
See also:
Varargs
Optional parameters
Wikipedia: Named parameter
| #Fortran | Fortran | subroutine a_sub(arg1, arg2, arg3)
integer, intent(in) :: arg1, arg2
integer, intent(out), optional :: arg3
! ...
end subroutine a_sub |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.