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/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.
| #Python | Python |
print("Py Nim\n")
def getTokens(curTokens):
global tokens
print("How many tokens would you like to take? ", end='')
take = int(input())
if (take < 1 or take > 3):
print("Number must be between 1 and 3.\n")
getTokens(curTokens)
return
tokens = curTokens - take
print(f'You take {take} tokens.')
print(f'{tokens} tokens remaining.\n')
def compTurn(curTokens):
global tokens
take = curTokens % 4
tokens = curTokens - take
print (f'Computer takes {take} tokens.')
print (f'{tokens} tokens remaining.\n')
tokens = 12
while (tokens > 0):
getTokens(tokens)
compTurn(tokens)
print("Computer wins!")
|
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.
| #R | R | ## Nim game
##
tokens <- 12
while(tokens > 0) {
print(paste("Tokens remaining:",tokens))
playertaken <- 0
while(playertaken == 0) {
playeropts <- c(1:min(c(tokens,3)))
playertaken <- menu(playeropts, title = "Your go, how many tokens will you take? ")
tokens <- tokens - playertaken
if(tokens == 0) {print("Well done you won, that shouldn't be possible!")}
}
cputaken <- 4 - playertaken
tokens <- tokens - cputaken
print(paste("I take",cputaken,"tokens,",tokens,"remain"))
if(tokens == 0) {print("I win!")}
}
|
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.
| #APL | APL |
∇r ← digitsOf n;digitList
digitList ← ⍬
loop:→((⌊n)=0)/done
digitList ← digitList,(⌊n|⍨10)
n ← n÷10
→loop
done: r ← ⊖digitList
∇
∇r ← getASN n;idx;list
idx ← 0
list ← 0⍴0
loop:
→(n=⍴list)/done
→(isArmstrongNumber idx)/add
→next
add:
list ← list,idx
next:
idx ← idx+1
→loop
done:
r ← list
∇
∇r ← isArmstrongNumber n;digits;nd
digits ← digitsOf n ⍝⍝ (⍎¨⍕n) is equivalent, but about 45% slower!!
nd ← ≢ digits
r ← n = +/digits * nd
∇
getASN 25
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315
|
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
| #C | C | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
return ptr;
}
bool is_prime(uint32_t n) {
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
for (uint32_t p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return false;
}
return true;
}
// Populates primes with the prime numbers between from and to and
// returns the number of primes found.
uint32_t find_primes(uint32_t from, uint32_t to, uint32_t** primes) {
uint32_t count = 0, buffer_length = 16;
uint32_t* buffer = xmalloc(sizeof(uint32_t) * buffer_length);
for (uint32_t p = from; p <= to; ++p) {
if (is_prime(p)) {
if (count >= buffer_length) {
uint32_t new_length = buffer_length * 2;
if (new_length < count + 1)
new_length = count + 1;
buffer = xrealloc(buffer, sizeof(uint32_t) * new_length);
buffer_length = new_length;
}
buffer[count++] = p;
}
}
*primes = buffer;
return count;
}
void free_numbers(mpz_t* numbers, size_t count) {
for (size_t i = 0; i < count; ++i)
mpz_clear(numbers[i]);
free(numbers);
}
// Returns an array containing first count n-smooth numbers
mpz_t* find_nsmooth_numbers(uint32_t n, uint32_t count) {
uint32_t* primes = NULL;
uint32_t num_primes = find_primes(2, n, &primes);
mpz_t* numbers = xmalloc(sizeof(mpz_t) * count);
mpz_t* queue = xmalloc(sizeof(mpz_t) * num_primes);
uint32_t* index = xmalloc(sizeof(uint32_t) * num_primes);
for (uint32_t i = 0; i < num_primes; ++i) {
index[i] = 0;
mpz_init_set_ui(queue[i], primes[i]);
}
for (uint32_t i = 0; i < count; ++i)
mpz_init(numbers[i]);
mpz_set_ui(numbers[0], 1);
for (uint32_t i = 1; i < count; ++i) {
for (uint32_t p = 0; p < num_primes; ++p) {
if (mpz_cmp(queue[p], numbers[i - 1]) == 0)
mpz_mul_ui(queue[p], numbers[++index[p]], primes[p]);
}
uint32_t min_index = 0;
for (uint32_t p = 1; p < num_primes; ++p) {
if (mpz_cmp(queue[min_index], queue[p]) > 0)
min_index = p;
}
mpz_set(numbers[i], queue[min_index]);
}
free_numbers(queue, num_primes);
free(primes);
free(index);
return numbers;
}
void print_nsmooth_numbers(uint32_t n, uint32_t begin, uint32_t count) {
uint32_t num = begin + count;
mpz_t* numbers = find_nsmooth_numbers(n, num);
printf("%u: ", n);
mpz_out_str(stdout, 10, numbers[begin]);
for (uint32_t i = 1; i < count; ++i) {
printf(", ");
mpz_out_str(stdout, 10, numbers[begin + i]);
}
printf("\n");
free_numbers(numbers, num);
}
int main() {
printf("First 25 n-smooth numbers for n = 2 -> 29:\n");
for (uint32_t n = 2; n <= 29; ++n) {
if (is_prime(n))
print_nsmooth_numbers(n, 0, 25);
}
printf("\n3 n-smooth numbers starting from 3000th for n = 3 -> 29:\n");
for (uint32_t n = 3; n <= 29; ++n) {
if (is_prime(n))
print_nsmooth_numbers(n, 2999, 3);
}
printf("\n20 n-smooth numbers starting from 30,000th for n = 503 -> 521:\n");
for (uint32_t n = 503; n <= 521; ++n) {
if (is_prime(n))
print_nsmooth_numbers(n, 29999, 20);
}
return 0;
} |
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
| #C | C | #include <stdio.h>
// 1. Named parameters
typedef struct { int x, y, z; } FTest_args;
void FTest (FTest_args args) {
printf("x: %d, y: %d, z: %d\n", args.x, args.y, args.z);
}
#define FT(...) FTest((FTest_args){ __VA_ARGS__ })
// 2. Default parameters
#define DFT(...) FTest((FTest_args){ .x = 142, .y = 143, .z = 144, __VA_ARGS__ })
// 3. Convenience wrapper to avoid accessing args as "args.name"
void FTest2 (int x, int y, int z) {
printf("x: %d, y: %d, z: %d\n", x, y, z);
}
static inline void FTest2_default_wrapper (FTest_args args) {
return FTest2(args.x, args.y, args.z);
}
#define DF2(...) FTest2_default_wrapper((FTest_args){ .x = 142, .y = 143, .z = 144, __VA_ARGS__ })
int main(int argc, char **argv)
{
// Named parameters
FTest((FTest_args){ .y = 10 });
FTest((FTest_args){ .y = 10, .z = 42 });
FT( .z = 47, .y = 10, .x = 42 );
// Default parameters
DFT();
DFT( .z = 99 );
// Default parameters with wrapper
DF2();
DF2( .z = 99 );
return 0;
} |
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.
| #CoffeeScript | CoffeeScript |
nth_root = (A, n, precision=0.0000000000001) ->
x = 1
while true
x_new = (1 / n) * ((n - 1) * x + A / Math.pow(x, n - 1))
return x_new if Math.abs(x_new - x) < precision
x = x_new
# tests
do ->
tests = [
[8, 3]
[16, 4]
[32, 5]
[343, 3]
[1024, 10]
[1000000000, 3]
[1000000000, 9]
[100, 2]
[100, 3]
[100, 5]
[100, 10]
]
for test in tests
[x, n] = test
root = nth_root x, n
console.log "#{x} root #{n} = #{root} (root^#{n} = #{Math.pow root, n})"
|
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Nth is
function Suffix(N: Natural) return String is
begin
if N mod 10 = 1 and then N mod 100 /= 11 then return "st";
elsif N mod 10 = 2 and then N mod 100 /= 12 then return "nd";
elsif N mod 10 = 3 and then N mod 100 /= 13 then return "rd";
else return "th";
end if;
end Suffix;
procedure Print_Images(From, To: Natural) is
begin
for I in From .. To loop
Ada.Text_IO.Put(Natural'Image(I) & Suffix(I));
end loop;
Ada.Text_IO.New_Line;
end Print_Images;
begin
Print_Images( 0, 25);
Print_Images( 250, 265);
Print_Images(1000, 1025);
end Nth; |
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
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <vector>
constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;
int mobiusFunction(int n) {
if (!MU.empty()) {
return MU[n];
}
// Populate array
MU.resize(MU_MAX + 1, 1);
int root = sqrt(MU_MAX);
for (int i = 2; i <= root; i++) {
if (MU[i] == 1) {
// for each factor found, swap + and -
for (int j = i; j <= MU_MAX; j += i) {
MU[j] *= -i;
}
// square factor = 0
for (int j = i * i; j <= MU_MAX; j += i * i) {
MU[j] = 0;
}
}
}
for (int i = 2; i <= MU_MAX; i++) {
if (MU[i] == i) {
MU[i] = 1;
} else if (MU[i] == -i) {
MU[i] = -1;
} else if (MU[i] < 0) {
MU[i] = 1;
} else if (MU[i] > 0) {
MU[i] = -1;
}
}
return MU[n];
}
int main() {
std::cout << "First 199 terms of the möbius function are as follows:\n ";
for (int n = 1; n < 200; n++) {
std::cout << std::setw(2) << mobiusFunction(n) << " ";
if ((n + 1) % 20 == 0) {
std::cout << '\n';
}
}
return 0;
} |
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']
| #J | J | require'strings regex'
lines=: <;.2
titleFix=: ('^\s*(the|a|an)\b';'')&rxrplc
isNum=: e.&'0123456789'
num=: ".^:(isNum@{.)
split=: <@num/.~ [:+/\1,2 ~:/\ isNum
norm=: [: split (32 9 12 13 14 15{a.) -.~ [: titleFix tolower
natSor=: lines ;@/: norm&.>@lines |
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| #Sidef | Sidef | say (File.new(__FILE__).open_r.slurp == ARGF.slurp); |
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| #Swift | Swift | #! /usr/bin/swift
import Foundation
let script = CommandLine.arguments[0]
print(script)
let mytext = try? String.init(contentsOfFile: script, encoding: .utf8)
var enteredtext = readLine()
if mytext == enteredtext {
print("Accept")
} else {
print("Reject")
} |
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| #Tcl | Tcl | apply {{} {puts [expr {[gets stdin] eq [info level 0]}]}} |
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)
| #jq | jq | // version 1.0.6
const val SOLAR_DIAMETER = 864938
enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!
class Star(val name: String) {
fun showDiameter() {
println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles")
}
}
class SolarSystem(val star: Star) {
private val planets = mutableListOf<Planet>() // some people might prefer _planets
init {
for (planet in Planet.values()) planets.add(planet)
}
fun listPlanets() {
println(planets)
}
}
fun main(args: Array<String>) {
val sun = Star("sun")
val ss = SolarSystem(sun)
sun.showDiameter()
println("\nIts planetary system comprises : ")
ss.listPlanets()
} |
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)
| #Julia | Julia | // version 1.0.6
const val SOLAR_DIAMETER = 864938
enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!
class Star(val name: String) {
fun showDiameter() {
println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles")
}
}
class SolarSystem(val star: Star) {
private val planets = mutableListOf<Planet>() // some people might prefer _planets
init {
for (planet in Planet.values()) planets.add(planet)
}
fun listPlanets() {
println(planets)
}
}
fun main(args: Array<String>) {
val sun = Star("sun")
val ss = SolarSystem(sun)
sun.showDiameter()
println("\nIts planetary system comprises : ")
ss.listPlanets()
} |
http://rosettacode.org/wiki/Next_highest_int_from_digits | Next highest int from digits | Given a zero or positive integer, the task is to generate the next largest
integer using only the given digits*1.
Numbers will not be padded to the left with zeroes.
Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).
If there is no next highest integer return zero.
*1 Alternatively phrased as: "Find the smallest integer larger than the (positive or zero) integer N
which can be obtained by reordering the (base ten) digits of N".
Algorithm 1
Generate all the permutations of the digits and sort into numeric order.
Find the number in the list.
Return the next highest number from the list.
The above could prove slow and memory hungry for numbers with large numbers of
digits, but should be easy to reason about its correctness.
Algorithm 2
Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
Exchange that digit with the digit on the right that is both more than it, and closest to it.
Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)
E.g.:
n = 12453
<scan>
12_4_53
<swap>
12_5_43
<order-right>
12_5_34
return: 12534
This second algorithm is faster and more memory efficient, but implementations
may be harder to test.
One method of testing, (as used in developing the task), is to compare results from both
algorithms for random numbers generated from a range that the first algorithm can handle.
Task requirements
Calculate the next highest int from the digits of the following numbers:
0
9
12
21
12453
738440
45072010
95322020
Optional stretch goal
9589776899767587796600
| #zkl | zkl | fcn nextHightest(N){ // N is int, BigInt or string -->String. Algorithm 2
// ds:=N.split().copy(); // mutable, int
ds:=N.toString().split("").apply("toInt").copy(); // handle "234" or BigInt
if(ds.len()<2) return(0);
m:=ds[-1];
foreach i in ([ds.len()-1 .. 0,-1]){
d:=ds[i];
if(d<m){
dz,j,z := ds[i,*], dz.sort().filter1n('>(d)), dz[j];
dz.del(j);
// return( ds[0,i].extend( z, dz.sort() ).concat().toInt() );
return( ds[0,i].extend( z, dz.sort() ).concat() );
}
m=m.max(d);
}
"0"
} |
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
| #Racket | Racket | #lang racket
(define (make-list separator)
(define counter 1)
(define (make-item item)
(begin0
(format "~a~a~a~%" counter separator item)
(set! counter (add1 counter))))
(apply string-append (map make-item '(first second third))))
(display (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
| #Raku | Raku | sub make-List ($separator = ') '){
my $count = 1;
sub make-Item ($item) { "{$count++}$separator$item" }
join "\n", <first second third>».&make-Item;
}
put 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
| #REXX | REXX | /*REXX program demonstrates that functions can be nested (an outer and inner function).*/
ctr= 0 /*initialize the CTR REXX variable.*/
call MakeList '. ' /*invoke MakeList with the separator.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
MakeItem: parse arg sep,text; ctr= ctr + 1 /*bump the counter variable. */
say ctr || sep || word($, ctr) /*display three thingys ───► terminal. */
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
MakeList: parse arg sep; $= 'first second third' /*obtain an argument; define a string.*/
do while ctr<3 /*keep truckin' until finished. */
call MakeItem sep, $ /*invoke the MakeItem function. */
end /*while*/
return |
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
| #REXX | REXX | /*REXX program sounds "ship's bells" (using PC speaker) when executing (perpetually).*/
echo= ( arg()\==0 ) /*echo time and bells if any arguments.*/
signal on halt /*allow a clean way to stop the program*/
t.1= '00:30 01:00 01:30 02:00 02:30 03:00 03:30 04:00'
t.2= '04:30 05:00 05:30 06:00 06:30 07:00 07:30 08:00'
t.3= '08:30 09:00 09:30 10:00 10:30 11:00 11:30 12:00'
do forever; t=time(); ss=right(t, 2); mn=substr(t, 4, 2) /*the current time.*/
ct=time('C') /*[↓] maybe add leading zero to time. */
hhmmc=left( right( ct, 7, 0), 5) /*HH:MM (maybe with a leading zero). */
if echo then say center(arg(1) ct, 79) /*echo the 1st argument with the time? */
if ss\==00 & mn\==00 & mn\==30 then do; call delay 60-ss; iterate
end /* [↑] delay for fraction of a minute.*/
/* [↓] the number of bells to peel {$}*/
do j=1 for 3 until $\==0; $=wordpos(hhmmc, t.j)
end /*j*/
if $\==0 & echo then say center($ "bells", 79) /*echo the number of bells? */
do k=1 for $; call sound 650,1; call delay 1 + (k//2==0)
end /*k*/ /*[↑] peel, and then pause for effect.*/
call delay 60; if rc\==0 then leave /*ensure we don't re─peel. */
end /*forever*/
halt: /*stick a fork in it, we're all done. */ |
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
| #Prolog | Prolog |
% fetch all the subsequences
ncsubs(L, LNCSL) :-
setof(NCSL, one_ncsubs(L, NCSL), LNCSL).
% how to build one subsequence
one_ncsubs(L, NCSL) :-
extract_elem(L, NCSL);
( sublist(L, L1),
one_ncsubs(L1, NCSL)).
% extract one element of the list
% this element is neither the first nor the last.
extract_elem(L, NCSL) :-
length(L, Len),
Len1 is Len - 2,
between(1, Len1, I),
nth0(I, L, Elem),
select(Elem, L, NCS1),
( NCSL = NCS1; extract_elem(NCS1, NCSL)).
% extract the first or the last element of the list
sublist(L, SL) :-
(L = [_|SL];
reverse(L, [_|SL1]),
reverse(SL1, SL)).
|
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.
| #FunL | FunL | $stdout = int( '1a', 16 ) |
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.
| #Go | Go | package main
import (
"fmt"
"math/big"
"strconv"
)
func main () {
s := strconv.FormatInt(26, 16) // returns the string "1a"
fmt.Println(s)
i, err := strconv.ParseInt("1a", 16, 64) // returns the integer (int64) 26
if err == nil {
fmt.Println(i)
}
b, ok := new(big.Int).SetString("1a", 16) // returns the big integer 26
if ok {
fmt.Println(b)
}
} |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #Standard_ML | Standard ML | let
fun loop i =
if i < 34 then (
print (Int.fmt StringCvt.BIN i ^ "\t"
^ Int.fmt StringCvt.OCT i ^ "\t"
^ Int.fmt StringCvt.DEC i ^ "\t"
^ Int.fmt StringCvt.HEX i ^ "\n");
loop (i+1)
) else ()
in
loop 0
end |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #Tcl | Tcl | for {set n 0} {$n <= 33} {incr n} {
puts [format " %3o %2d %2X" $n $n $n]
} |
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.
| #Quackery | Quackery | [ dup dip /mod
over iff
[ - dip 1+ ]
else drop ] is /mod+ ( n n --> n n )
[ over 0 = iff
[ 2drop $ "0" ]
done
temp put
$ "" swap
[ temp share /mod+
digit
rot join swap
dup 0 = until ]
drop
temp release ] is ->negabase$ ( n n --> $ )
[ over $ "0" = iff
[ 2drop 0 ]
done
temp put
0 swap
witheach
[ dip
[ temp share * ]
char->n + ]
temp release ] is negabase$-> ( $ n --> n )
10 dup echo say " -> "
-2 ->negabase$ dup echo$ say " -> "
-2 negabase$-> echo cr
146 dup echo say " -> "
-3 ->negabase$ dup echo$ say " -> "
-3 negabase$-> echo cr
15 dup echo say " -> "
-10 ->negabase$ dup echo$ say " -> "
-10 negabase$-> echo cr |
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.
| #Racket | Racket | #lang racket
(define all-digits (string->list "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"))
(define d->i-map (for/hash ((i (in-naturals)) (d all-digits)) (values d i)))
(define max-base (length all-digits))
(define (q/r n d)
(let-values (((q r) (quotient/remainder n d)))
(if (negative? r)
(values (+ q 1) (- r d))
(values q r))))
(define (negabase-convertors base)
(when (not (integer? base)) (raise "Non-integer base."))
(when (not (<= 2 (abs base) max-base)) (raise (format "(abs base) must be inside [2 ~a] interval." max-base)))
(values
(let ((q/r_base (curryr q/r base)))
(λ (num)
(define (checked->base num dig)
(match num
[0 (apply string dig)]
[(app q/r_base num/ rst) (checked->base num/ (cons (list-ref all-digits rst) dig))]))
(if (integer? num)
(checked->base num (if (zero? num) '(#\0) '()))
(raise "Non-integer number."))))
(λ (dig)
(define (loop digs acc)
(match digs [(list) acc] [(cons a d) (loop d (+ (* acc base) (hash-ref d->i-map a)))]))
(loop (string->list dig) 0))))
(define-values (->negabinary negabinary->) (negabase-convertors -2))
(define-values (->negaternary negaternary->) (negabase-convertors -3))
(define-values (->negadecimal negadecimal->) (negabase-convertors -10))
(define-values (->nega63ary nega63ary->) (negabase-convertors (- max-base)))
(module+ main
(->negaternary 146)
(->negabinary 10)
(->negadecimal 15)
(->nega63ary -26238001742))
(module+ test
(require rackunit)
;; tests from wikipedia page
(check-equal? (call-with-values (λ () (q/r 146 -3)) cons) '(-48 . 2))
(check-equal? (call-with-values (λ () (q/r -48 -3)) cons) '(16 . 0))
(check-equal? (call-with-values (λ () (q/r 16 -3)) cons) '(-5 . 1))
(check-equal? (call-with-values (λ () (q/r -5 -3)) cons) '(2 . 1))
(check-equal? (call-with-values (λ () (q/r 2 -3)) cons) '(0 . 2))
(define-values (->hexadecimal hexadecimal->) (negabase-convertors 16))
(check-equal? (->hexadecimal 31) "1F")) |
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.
| #Racket | Racket |
#lang racket
(define (print-remaining tokens-remaining)
(printf "~a tokens remain.\n" tokens-remaining))
(define (read-tokens)
(define num (read))
(cond
[(and (natural? num) (< num 4)) num]
[else
(display "Please enter a number between 1 to 3\n")
(read-tokens)]))
(define (pturn tokens-remaining)
(cond
[(not (zero? tokens-remaining))
(print-remaining tokens-remaining)
(display "Your turn. How many tokens? ")
(define n (read-tokens))
(cturn (- tokens-remaining n) n)]
[else (display "Computer wins!")]))
(define (cturn tokens-remaining p-took)
(cond
[(not (zero? tokens-remaining))
(print-remaining tokens-remaining)
(define c-take (- 4 p-took))
(printf "Computer takes ~a tokens\n" c-take)
(pturn (- tokens-remaining c-take))]
[else (display "You win!")]))
(pturn 12)
|
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.
| #Raku | Raku | say my $tokens = 12, " tokens remaining.\n";
loop {
my $player = trim prompt "How many tokens do you want to remove; 1, 2 or 3? : ";
say "Nice try. $tokens tokens remaining.\n" and
next unless $player eq any <1 2 3>;
$tokens -= 4;
say "Computer takes {4 - $player}.\n$tokens tokens remaining.\n";
say "Computer wins." and last if $tokens <= 0;
} |
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.
| #AppleScript | AppleScript | ------------------------- NARCISSI -----------------------
-- isDaffodil :: Int -> Int -> Bool
on isDaffodil(e, n)
set ds to digitList(n)
(e = length of ds) and (n = powerSum(e, ds))
end isDaffodil
-- digitList :: Int -> [Int]
on digitList(n)
if n > 0 then
{n mod 10} & digitList(n div 10)
else
{}
end if
end digitList
-- powerSum :: Int -> [Int] -> Int
on powerSum(e, ns)
script
on |λ|(a, x)
a + x ^ e
end |λ|
end script
foldl(result, 0, ns) as integer
end powerSum
-- narcissiOfLength :: Int -> [Int]
on narcissiOfLength(nDigits)
script nthPower
on |λ|(x)
{x, x ^ nDigits as integer}
end |λ|
end script
set powers to map(nthPower, enumFromTo(0, 9))
script combn
on digitTree(n, parents)
if n > 0 then
if parents ≠ {} then
script nextLayer
on |λ|(pair)
set {digit, intSum} to pair
script addPower
on |λ|(dp)
set {d, p} to dp
{d, p + intSum}
end |λ|
end script
map(addPower, items 1 thru (digit + 1) of powers)
end |λ|
end script
set nodes to concatMap(nextLayer, parents)
else
set nodes to powers
end if
digitTree(n - 1, nodes)
else
script
on |λ|(pair)
isDaffodil(nDigits, item 2 of pair)
end |λ|
end script
filter(result, parents)
end if
end digitTree
end script
script snd
on |λ|(ab)
item 2 of ab
end |λ|
end script
map(snd, combn's digitTree(nDigits, {}))
end narcissiOfLength
--------------------------- TEST -------------------------
on run
{0} & concatMap(narcissiOfLength, enumFromTo(1, 5))
-- 4 seconds, 20 narcissi
-- {0} & concatMap(narcissiOfLength, enumFromTo(1, 6))
-- 103 seconds, 21 narcissi
-- {0} & concatMap(narcissiOfLength, enumFromTo(1, 7))
-- 13.75 minutes, 25 narcissi
end run
-------------------- GENERIC FUNCTIONS -------------------
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lst to {}
set lng to length of xs
tell mReturn(f)
repeat with i from 1 to lng
set lst to (lst & |λ|(item i of xs, i, xs))
end repeat
end tell
return lst
end concatMap
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
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
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <vector>
std::vector<uint64_t> primes;
std::vector<uint64_t> smallPrimes;
template <typename T>
std::ostream &operator <<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
for (; it != end; it = std::next(it)) {
os << ", " << *it;
}
return os << ']';
}
bool isPrime(uint64_t 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;
uint64_t t = 29;
while (t * t < value) {
if (value % t == 0) return false;
value += 2;
if (value % t == 0) return false;
value += 4;
}
return true;
}
void init() {
primes.push_back(2);
smallPrimes.push_back(2);
uint64_t i = 3;
while (i <= 521) {
if (isPrime(i)) {
primes.push_back(i);
if (i <= 29) {
smallPrimes.push_back(i);
}
}
i += 2;
}
}
std::vector<uint64_t> nSmooth(uint64_t n, size_t size) {
if (n < 2 || n>521) {
throw std::runtime_error("n must be between 2 and 521");
}
if (size <= 1) {
throw std::runtime_error("size must be at least 1");
}
uint64_t bn = n;
if (primes.cend() == std::find(primes.cbegin(), primes.cend(), bn)) {
throw std::runtime_error("n must be a prime number");
}
std::vector<uint64_t> ns(size, 0);
ns[0] = 1;
std::vector<uint64_t> next;
for (auto prime : primes) {
if (prime > bn) {
break;
}
next.push_back(prime);
}
std::vector<size_t> indicies(next.size(), 0);
for (size_t m = 1; m < size; m++) {
ns[m] = *std::min_element(next.cbegin(), next.cend());
for (size_t i = 0; i < indicies.size(); i++) {
if (ns[m] == next[i]) {
indicies[i]++;
next[i] = primes[i] * ns[indicies[i]];
}
}
}
return ns;
}
int main() {
init();
for (auto i : smallPrimes) {
std::cout << "The first " << i << "-smooth numbers are:\n";
std::cout << nSmooth(i, 25) << '\n';
std::cout << '\n';
}
// there is not enough bits to fully represent the 3-smooth numbers
for (size_t i = 0; i < smallPrimes.size(); i++) {
if (i < 1) continue;
auto p = smallPrimes[i];
auto v = nSmooth(p, 3002);
v.erase(v.begin(), v.begin() + 2999);
std::cout << "The 30,000th to 30,019th " << p << "-smooth numbers are:\n";
std::cout << v << '\n';
std::cout << '\n';
}
return 0;
} |
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
| #C.23 | C# | using System;
namespace NamedParams
{
class Program
{
static void AddWidget(string parent, float x = 0, float y = 0, string text = "Default")
{
Console.WriteLine("parent = {0}, x = {1}, y = {2}, text = {3}", parent, x, y, text);
}
static void Main(string[] args)
{
AddWidget("root", 320, 240, "First");
AddWidget("root", text: "Origin");
AddWidget("root", 500);
AddWidget("root", text: "Footer", y: 400);
}
}
} |
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
| #C.2B.2B | C++ | class foo_params{
friend void foo(foo_params p);
public:
foo_params(int r):
required_param_(r),
optional_x_(0),
optional_y_(1),
optional_z_(3.1415)
{}
foo_params& x(int i){
optional_x_=i;
return *this;
}
foo_params& y(int i){
optional_y_=i;
return *this;
}
foo_params& z(float f){
optional_z_=f;
return *this;
}
private:
int required_param_;
int optional_x_;
int optional_y_;
float optional_z_;
}; |
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.
| #Common_Lisp | Common Lisp | (defun nth-root (n a &optional (epsilon .0001) (guess (1- n)))
(assert (and (> n 1) (> a 0)))
(flet ((next (x)
(/ (+ (* (1- n) x)
(/ a (expt x (1- n))))
n)))
(do* ((xi guess xi+1)
(xi+1 (next xi) (next xi)))
((< (abs (- xi+1 xi)) epsilon) xi+1)))) |
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.
| #ALGOL_68 | ALGOL 68 | # PROC to suffix a number with st, nd, rd or th as appropriate #
PROC nth = ( INT number )STRING:
BEGIN
INT number mod 100 = number MOD 100;
# RESULT #
whole( number, 0 )
+ IF number mod 100 >= 10 AND number mod 100 <= 20
THEN
# numbers in the range 10 .. 20 always have "th" #
"th"
ELSE
# not in the range 10 .. 20, suffix is st, nd, rd or th #
# depending on the final digit #
CASE number MOD 10
IN # 1 # "st"
, # 2 # "nd"
, # 3 # "rd"
OUT "th"
ESAC
FI
END; # nth #
# PROC to test nth, displays nth for all numbers in the range from .. to #
PROC test nth = ( INT from, INT to )VOID:
BEGIN
INT test count := 0;
FOR test value FROM from TO to
DO
STRING test result = nth( test value );
print( ( " "[ 1 : 8 - UPB test result ], nth( test value ) ) );
test count +:= 1;
IF test count MOD 8 = 0
THEN
print( ( newline ) )
FI
OD;
print( ( newline ) )
END; # test nth #
main: (
test nth( 0, 25 );
test nth( 250, 265 );
test nth( 1000, 1025 )
) |
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
| #D | D | import std.math;
import std.stdio;
immutable MU_MAX = 1_000_000;
int mobiusFunction(int n) {
static initialized = false;
static int[MU_MAX + 1] MU;
if (initialized) {
return MU[n];
}
// populate array
MU[] = 1;
int root = cast(int) sqrt(cast(real) MU_MAX);
for (int i = 2; i <= root; i++) {
if (MU[i] == 1) {
// for each factor found, swap + and -
for (int j = i; j <= MU_MAX; j += i) {
MU[j] *= -i;
}
// square factor = 0
for (int j = i * i; j <= MU_MAX; j += i * i) {
MU[j] = 0;
}
}
}
for (int i = 2; i <= MU_MAX; i++) {
if (MU[i] == i) {
MU[i] = 1;
} else if (MU[i] == -i) {
MU[i] = -1;
} else if (MU[i] < 0) {
MU[i] = 1;
} else if (MU[i] > 0) {
MU[i] = -1;
}
}
initialized = true;
return MU[n];
}
void main() {
writeln("First 199 terms of the möbius function are as follows:");
write(" ");
for (int n = 1; n < 200; n++) {
writef("%2d ", mobiusFunction(n));
if ((n + 1) % 20 == 0) {
writeln;
}
}
} |
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']
| #JavaScript | JavaScript |
var nsort = function(input) {
var e = function(s) {
return (' ' + s + ' ').replace(/[\s]+/g, ' ').toLowerCase().replace(/[\d]+/, function(d) {
d = '' + 1e20 + d;
return d.substring(d.length - 20);
});
};
return input.sort(function(a, b) {
return e(a).localeCompare(e(b));
});
};
console.log(nsort([
"file10.txt",
"\nfile9.txt",
"File11.TXT",
"file12.txt"
]));
// -> ['\nfile9.txt', 'file10.txt', 'File11.TXT', 'file12.txt']
|
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| #TXR | TXR | @(bind my64 "QChuZXh0IDphcmdzKUBmaWxlbmFtZUAobmV4dCBmaWxlbmFtZSlAZmlyc3RsaW5lQChmcmVlZm9ybSAiIilAcmVzdEAoYmluZCBpbjY0IEAoYmFzZTY0LWVuY29kZSByZXN0KSlAKGNhc2VzKUAgIChiaW5kIGZpcnN0bGluZSBgXEAoYmluZCBteTY0ICJAbXk2NCIpYClAICAoYmluZCBpbjY0IG15NjQpQCAgKGJpbmQgcmVzdWx0ICIxIilAKG9yKUAgIChiaW5kIHJlc3VsdCAiMCIpQChlbmQpQChvdXRwdXQpQHJlc3VsdEAoZW5kKQ==")
@(next :args)
@filename
@(next filename)
@firstline
@(freeform "")
@rest
@(bind in64 @(base64-encode rest))
@(cases)
@ (bind firstline `\@(bind my64 "@my64")`)
@ (bind in64 my64)
@ (bind result "1")
@(or)
@ (bind result "0")
@(end)
@(output)
@result
@(end)
|
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| #UNIX_Shell | UNIX Shell | cmp "$0" >/dev/null && echo accept || echo reject |
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| #VBA | VBA | Public Sub narcissist()
quote = Chr(34)
comma = Chr(44)
cont = Chr(32) & Chr(95)
rparen = Chr(41)
n = Array( _
"Public Sub narcissist()", _
" quote = Chr(34)", _
" comma = Chr(44)", _
" cont = Chr(32) & Chr(95)", _
" rparen = Chr(41)", _
" n = Array( _", _
"How many lines?", _
"Line ", _
" x = InputBox(n(5))", _
" flag = True", _
" For i = 0 To 5", _
" If InputBox(n(6) & i) <> n(i) Then flag = False", _
" Next i", _
" For i = 0 To 20", _
" If InputBox(n(6) & i + 6) <> quote & n(i) & quote & comma & cont Then flag = False", _
" Next i", _
" If InputBox(n(6) & 27) <> quote & n(21) & quote & rparen Then flag = False", _
" For i = 7 To 21", _
" If InputBox(n(6) & i + 21) <> n(i) Then flag = False", _
" Next i", _
" Debug.Print IIf(flag, 1, 0)", _
"End Sub")
x = InputBox(n(5))
flag = True
For i = 0 To 5
If InputBox(n(6) & i) <> n(i) Then flag = False
Next i
For i = 0 To 20
If InputBox(n(6) & i + 6) <> quote & n(i) & quote & comma & cont Then flag = False
Next i
If InputBox(n(6) & 27) <> quote & n(21) & quote & rparen Then flag = False
For i = 7 To 21
If InputBox(n(6) & i + 21) <> n(i) Then flag = False
Next i
Debug.Print IIf(flag, 1, 0)
End Sub |
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| #Wren | Wren | import "os" for Process, Platform
import "io" for File, Stdin, Stdout
var args = Process.allArguments
var text = File.read(args[1]).trim()
System.print("Enter the number of lines to be input followed by those lines:\n")
Stdout.flush()
var n = Num.fromString(Stdin.readLine())
var lines = List.filled(n, null)
for (i in 0...n) lines[i] = Stdin.readLine()
var joiner = Platform.isWindows ? "\r\n" : "\n"
var text2 = lines.join(joiner)
System.print()
if (text2 == text) {
System.print("accept")
} else if (text.startsWith(text2)) {
System.print("not yet finished")
} else {
System.print("reject")
} |
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)
| #Kotlin | Kotlin | // version 1.0.6
const val SOLAR_DIAMETER = 864938
enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!
class Star(val name: String) {
fun showDiameter() {
println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles")
}
}
class SolarSystem(val star: Star) {
private val planets = mutableListOf<Planet>() // some people might prefer _planets
init {
for (planet in Planet.values()) planets.add(planet)
}
fun listPlanets() {
println(planets)
}
}
fun main(args: Array<String>) {
val sun = Star("sun")
val ss = SolarSystem(sun)
sun.showDiameter()
println("\nIts planetary system comprises : ")
ss.listPlanets()
} |
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)
| #Lambdatalk | Lambdatalk |
Naming conventions
1) global names
- a name is a group of any character except space and curly braces {}
for instance "add", "+", "123", "()", "a.b.c", "...", ...
- but giving a variable the name of the 9 special forms (keywords)
["lambda", "def", "if", "let", "quote", "macro", "script", "style", "require"]
or of one of the more than 170 primitives
["div", ..., "+", ..., "cons", ..., A.new, A.first, A.rest, ..., long_add, ...]
is possible but is obviously strongly discouraged.
- when a function calls an helper function, it's better to prefix the helper function's name
with the calling function's name. For instance the function "fibonacci" sets
some initializations and calls the recursive part "fibonacci.rec".
- functions organized into sets (libraries) should be named with a common prefix.
For instance the set of functions working on complex numbers [ "C.new", "C.x", "C.y", "C.+", "C.*", ...],
suggesting object-oriented programming.
2) local names
Consider this example:
{def add {lambda {:a :b} :a+:b is equal to {+ :a :b}}}
-> add
{add 3 4}
-> 3+4 is equal to 7
When the add function is called the occurences of arguments {:a :b} are replaced by the given values, [3 4],
in the body of the function ":a+:b is equal to {+ :a :b}", leading to "3+4 is equal to {+ 3 4}" and finally
to "3+4 is equal to 7". Note that the character "a" inside the word "equal" has not been replaced.
So generally speaking:
- inside a function local defined arguments must be prefixed by a colon, ":",
- they must have a null intersection. For instance this arguments list {:a1 :a2} is valid
because the intersection of :a1 and :a2 is null, but this one {:a :a1} is not,
because the intersection of :a and :a1 is :a.
- an alternative could be to prefix and postfix names, say :a: and :a1: which have a null intersection.
It's a matter of choice let to the coder. In all cases naming must be done with the utmost care.
|
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
| #Ring | Ring |
# Project : Nested function
makeList(". ")
func makeitem(sep, counter, text)
see "" + counter + sep + text + nl
func makelist(sep)
a = ["first", "second", "third"]
counter = 0
while counter < 3
counter = counter + 1
makeitem(sep, counter, a[counter])
end
|
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
| #Ruby | Ruby | def makeList(separator)
counter = 1
makeItem = lambda {|item|
result = "#{counter}#{separator}#{item}\n"
counter += 1
result
}
makeItem["first"] + makeItem["second"] + makeItem["third"]
end
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
| #Rust | Rust | fn make_list(sep: &str) -> String {
let mut counter = 0;
let mut make_item = |label| {
counter += 1;
format!("{}{}{}", counter, sep, label)
};
format!(
"{}\n{}\n{}",
make_item("First"),
make_item("Second"),
make_item("Third")
)
}
fn main() {
println!("{}", make_list(". "))
} |
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
| #Ring | Ring |
# Project : Nautical bell
m = 0
for n = 0 to 23
if n = 23
see "23" + ":30" + " = " + "7 bells" + nl
else
m = m + 1
see "" + n%23 + ":30" + " = " + m + " bells" + nl
ok
if n = 23
see "00" + ":00" + " = " + "8 bells" + nl
else
m = m + 1
see "" + (n%23+1) + ":00" + " = " + m + " bells" + nl
if m = 8
m = 0
ok
ok
next
|
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
| #Ruby | Ruby | watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ]
watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ]
words = ["One","Two","Three","Four","Five","Six","Seven","Eight"]
sound = "ding!"
loop do
time = Time.now
if time.sec == 0 and time.min % 30 == 0
num = (time.hour * 60 + time.min) / 30 % 8
num = 8 if num == 0
hr_min = time.strftime "%H:%M"
idx = watch_ends.find_index {|t| hr_min <= t}
text = "%s - %s watch, %s bell%s gone" % [
hr_min,
watches[idx],
words[num-1],
num==1 ? "" : "s"
]
bells = (sound * num).gsub(sound + sound) {|dd| dd + ' '}
puts "%-45s %s" % [text, bells]
end
sleep 1
end |
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
| #Python | Python | def ncsub(seq, s=0):
if seq:
x = seq[:1]
xs = seq[1:]
p2 = s % 2
p1 = not p2
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else [] |
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
| #Quackery | Quackery | [ dup 1 & dip [ 1 >> ] ] is 2/mod ( n --> n n )
[ 0 swap
[ dup 0 != while
2/mod iff
[ dip 1+ ] done
again ]
[ dup 0 != while
2/mod not iff
[ dip 1+ ] done
again ]
[ dup 0 != while
2/mod iff
[ dip 1+ ] done
again ]
drop 3 = ] is noncontinuous ( n --> b )
[ [] unrot
[ dup 0 != while
dip behead tuck
1 & iff
[ nested dip rot
join unrot ]
else drop
1 >> again ]
2drop ] is bitems ( [ n --> [ )
[ [] swap
dup size bit times
[ i^ noncontinuous if
[ dup i^ bitems
nested rot
join swap ] ]
drop ] is ncsubs ( [ --> [ )
' [ 1 2 3 4 ] ncsubs echo cr
$ "quackery" ncsubs 72 wrap$ |
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.
| #Groovy | Groovy | def radixParse = { s, radix -> Integer.parseInt(s, radix) }
def radixFormat = { i, radix -> Integer.toString(i, radix) } |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #TI-89_BASIC | TI-89 BASIC | Local old
getMode("Base")→old
setMode("Base", "BIN")
Disp string(16)
setMode("Base", "HEX")
Disp string(16)
setMode("Base", "DEC")
Disp string(16)
setMode("Base", old) |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #Wren | Wren | import "/fmt" for Conv, Fmt
System.print(" 2 7 8 10 12 16 32")
System.print("------ ---- ---- ---- ---- ---- ----")
for (i in 1..33) {
var b2 = Fmt.b(6, i)
var b7 = Fmt.s(4, Conv.itoa(i, 7))
var b8 = Fmt.o(4, i)
var b10 = Fmt.d(4, i)
var b12 = Fmt.s(4, Conv.Itoa(i, 12))
var b16 = Fmt.X(4, i)
var b32 = Fmt.s(4, Conv.Itoa(i, 32))
System.print("%(b2) %(b7) %(b8) %(b10) %(b12) %(b16) %(b32)")
} |
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.
| #Raku | Raku | multi sub base ( Int $value is copy, Int $radix where -37 < * < -1) {
my $result;
while $value {
my $r = $value mod $radix;
$value div= $radix;
if $r < 0 {
$value++;
$r -= $radix
}
$result ~= $r.base(-$radix);
}
flip $result || ~0;
}
multi sub base ( Real $num, Int $radix where -37 < * < -1, :$precision = -15 ) {
return '0' unless $num;
my $value = $num;
my $result = '';
my $place = 0;
my $upper-bound = 1 / (-$radix + 1);
my $lower-bound = $radix * $upper-bound;
$value = $num / $radix ** ++$place until $lower-bound <= $value < $upper-bound;
while ($value or $place > 0) and $place > $precision {
my $digit = ($radix * $value - $lower-bound).Int;
$value = $radix * $value - $digit;
$result ~= '.' unless $place or $result.contains: '.';
$result ~= $digit == -$radix ?? ($digit-1).base(-$radix)~'0' !! $digit.base(-$radix);
$place--
}
$result
}
multi sub parse-base (Str $str, Int $radix where -37 < * < -1) {
return -1 * $str.substr(1).&parse-base($radix) if $str.substr(0,1) eq '-';
my ($whole, $frac) = $str.split: '.';
my $fraction = 0;
$fraction = [+] $frac.comb.kv.map: { $^v.parse-base(-$radix) * $radix ** -($^k+1) } if $frac;
$fraction + [+] $whole.flip.comb.kv.map: { $^v.parse-base(-$radix) * $radix ** $^k }
}
# TESTING
for <4 -4 0 -7 10 -2 146 -3 15 -10 -19 -10 107 -16
227.65625 -16 2.375 -4 -1.3e2 -8 41371457.268272761 -36> -> $v, $r {
my $nbase = $v.&base($r, :precision(-5));
printf "%20s.&base\(%3d\) = %-11s : %13s.&parse-base\(%3d\) = %s\n",
$v, $r, $nbase, "'$nbase'", $r, $nbase.&parse-base($r);
}
# 'Illegal' negative-base value
say q| '-21'.&parse-base(-10) = |, '-21'.&parse-base(-10); |
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.
| #Red | Red | Red [
date: 2021-10-24
version: 0.6.4
summary: "Demonstrate the game of Nim in Red for Rosetta Code"
]
take-tokens: function [
"Ask the user to take between 1 and 3 tokens."
][
forever [
n: trim ask "Would you like to take 1, 2, or 3 tokens (q to quit)? "
if n = "q" [quit]
n: try [to-integer n]
case [
not integer? n [print "Please enter an integer."]
any [n < 1 n > 3] [print "Please enter a number between 1 and 3."]
true [return n]
]
]
]
tokens: 12
while [tokens > 0][
print ["There are" tokens "tokens remaining."]
n: take-tokens
print ["You took" n "tokens."]
tokens: tokens - n
print ["Computer takes" 4 - n "tokens."]
tokens: subtract tokens subtract 4 n
]
print "Computer wins!" |
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.
| #REXX | REXX | /*REXX program plays the NIM game with a human opponent; the pot size can be specified. */
parse arg pot _ . 1 __ /*obtain optional argument from the CL.*/
if pot=='' | pot=="," then pot= 12 /*Not specified? Then use the default.*/
if _\=='' then do; call ser "Too many arguments entered: " __; exit 13; end
if \isNum(pot) then do; call ser "argument isn't numeric: " pot; exit 13; end
if \isInt(pot) then do; call ser "argument isn't an integer: " pot; exit 13; end
if pot<4 then do; call ser "The pot number is too small: " pot; exit 13; end
if pot>100 then do; call ser "The pot number is too large: " pot; exit 13; end
pad= copies('─', 8) /*literal used as an eyecatcher in msgs*/
pot= pot/1 /*normalize the pot (number). */
t= pot//4
if pot>12 & t\==0 then do; say pad 'The computer takes ' t " token"s(t).
pot= pot - t
end
do forever; call show pot
do until ok; ok= 1; say
say pad "How many tokens do you want to take away (1, 2, or 3) (or QUIT)?"
parse pull t _ . 1 q 1 __; upper q; say
if abbrev('QUIT',q,1) then do; say pad 'Quitting.'; exit 1; end
if t='' then call ser "No arguments entered."
if _\=='' then call ser "Too many arguments entered: " __
if \isNum(t) then call ser "Argument isn't numeric: " t
if \isInt(t) then call ser "Argument isn't an integer: " t
if t<1 then call ser "Argument can't be less than 1: " t
if t>3 then call ser "Argument can't be greater than 3: " t
end /*while*/
t= t/1 /*Normalize the number: 001 2. +3 */
#= max(1, 4-t) /*calculate the computer's take─away. */
say pad 'The computer takes ' # " token"s(#).
pot= pot - t - # /*calculate the number of tokens in pot*/
if pot==0 then do; say pad 'No tokens left.' /*No tokens left in the pot? */
say pad "The computer wins!" /*Display a braggart message.*/
exit /*exit this computer program.*/
end
end /*forever*/ /*keep looping until there's a winner. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isNum: return datatype( arg(1), 'N') /*verify that the arg is a number. */
isInt: return datatype( arg(1), 'W') /* " " " " " an integer. */
show: say; say pad "Tokens remaining: " arg(1)' ' pad; say; return
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1)
ser: if ok then say pad '***error***' arg(1); ok= 0; 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.
| #Arturo | Arturo | powers: map 0..9 'x [
map 0..9 'y [
x ^ y
]
]
getPair: function [p,sz].memoize[
if not? numeric? last p -> return powers\[to :integer to :string first p]\[sz]
return powers\[to :integer to :string first p]\[sz] + powers\[to :integer to :string last p]\[sz]
]
narcissistic?: function [n][
digs: digits n
sdigs: size digs
n = sum map split.every:2 to :string n 'p -> getPair p sdigs
]
i: new 0
counter: new 0
while [counter < 25][
if narcissistic? i [
print i
inc 'counter
]
inc 'i
] |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace NSmooth {
class Program {
static readonly List<BigInteger> primes = new List<BigInteger>();
static readonly List<int> smallPrimes = new List<int>();
static Program() {
primes.Add(2);
smallPrimes.Add(2);
BigInteger i = 3;
while (i <= 521) {
if (IsPrime(i)) {
primes.Add(i);
if (i <= 29) {
smallPrimes.Add((int)i);
}
}
i += 2;
}
}
static bool IsPrime(BigInteger 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;
BigInteger t = 29;
while (t * t < value) {
if (value % t == 0) return false;
value += 2;
if (value % t == 0) return false;
value += 4;
}
return true;
}
static List<BigInteger> NSmooth(int n, int size) {
if (n < 2 || n > 521) {
throw new ArgumentOutOfRangeException("n");
}
if (size < 1) {
throw new ArgumentOutOfRangeException("size");
}
BigInteger bn = n;
bool ok = false;
foreach (var prime in primes) {
if (bn == prime) {
ok = true;
break;
}
}
if (!ok) {
throw new ArgumentException("must be a prime number", "n");
}
BigInteger[] ns = new BigInteger[size];
ns[0] = 1;
for (int i = 1; i < size; i++) {
ns[i] = 0;
}
List<BigInteger> next = new List<BigInteger>();
foreach (var prime in primes) {
if (prime > bn) {
break;
}
next.Add(prime);
}
int[] indices = new int[next.Count];
for (int i = 0; i < indices.Length; i++) {
indices[i] = 0;
}
for (int m = 1; m < size; m++) {
ns[m] = next.Min();
for (int i = 0; i < indices.Length; i++) {
if (ns[m] == next[i]) {
indices[i]++;
next[i] = primes[i] * ns[indices[i]];
}
}
}
return ns.ToList();
}
static void Println<T>(IEnumerable<T> nums) {
Console.Write('[');
var it = nums.GetEnumerator();
if (it.MoveNext()) {
Console.Write(it.Current);
}
while (it.MoveNext()) {
Console.Write(", ");
Console.Write(it.Current);
}
Console.WriteLine(']');
}
static void Main() {
foreach (var i in smallPrimes) {
Console.WriteLine("The first {0}-smooth numbers are:", i);
Println(NSmooth(i, 25));
Console.WriteLine();
}
foreach (var i in smallPrimes.Skip(1)) {
Console.WriteLine("The 3,000 to 3,202 {0}-smooth numbers are:", i);
Println(NSmooth(i, 3_002).Skip(2_999));
Console.WriteLine();
}
foreach (var i in new int[] { 503, 509, 521 }) {
Console.WriteLine("The 30,000 to 3,019 {0}-smooth numbers are:", i);
Println(NSmooth(i, 30_019).Skip(29_999));
Console.WriteLine();
}
}
}
} |
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
| #Clojure | Clojure | (defn foo [& opts]
(let [opts (merge {:bar 1 :baz 2} (apply hash-map opts))
{:keys [bar baz]} opts]
[bar 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
| #Common_Lisp | Common Lisp | (defun print-name (&key first (last "?"))
(princ last)
(when first
(princ ", ")
(princ first))
(values)) |
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.
| #D | D | import std.stdio, std.math;
real nthroot(in int n, in real A, in real p=0.001) pure nothrow {
real[2] x = [A, A / n];
while (abs(x[1] - x[0]) > p)
x = [x[1], ((n - 1) * x[1] + A / (x[1] ^^ (n-1))) / n];
return x[1];
}
void main() {
writeln(nthroot(10, 7131.5 ^^ 10));
writeln(nthroot(6, 64));
} |
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.
| #APL | APL | nth←{
sfx←4 2⍴'stndrdth'
tens←(10<100|⍵)∧20>100|⍵
(⍕⍵),sfx[(4×tens)⌈(⍳3)⍳10|⍵;]
} |
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
| #F.23 | F# |
// Möbius function. Nigel Galloway: January 31st., 2021
let fN g=let n=primes32()
let rec fN i g e l=match (l/g,l%g,e) with (1,0,false)->i
|(n,0,false)->fN (0-i) g true n
|(_,0,true) ->0
|_ ->fN i (Seq.head n) false l
fN -1 (Seq.head n) false g
let mobius=seq{yield 1; yield! Seq.initInfinite((+)2>>fN)}
mobius|>Seq.take 500|>Seq.chunkBySize 25|>Seq.iter(fun n->Array.iter(printf "%3d") n;printfn "")
|
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
| #Factor | Factor | USING: formatting grouping io math.extras math.ranges sequences ;
"First 199 terms of the Möbius sequence:" print
199 [1,b] [ mobius ] map " " prefix 20 group
[ [ "%3s" printf ] each nl ] each |
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']
| #jq | jq | def splitup:
def tidy: if .[0] == "" then .[1:] else . end | if .[length-1] == "" then .[0:length-1] else . end ;
# a and b are assumed to be arrays:
def alternate(a;b):
reduce range(0; [a,b] | map(length) | max) as $i ([]; . + [a[$i], b[$i]]);
([splits("[0-9]+")] | tidy) as $a
| ([splits("[^0-9]+")] | tidy | map(tonumber)) as $n
| (test("^[0-9]")) as $nfirst
| if $nfirst then alternate($n; $a) else alternate($a; $n) end ;
# The following implementation of tr is more general than needed here, but the generality
# makes for adaptability.
# x and y should both be strings defining a character-by-character translation, like Unix/Linux "tr".
# if y is shorter than x, then y will in effect be padded with y's last character.
# The input may be a string or an exploded string (i.e. an array);
# the output will have the same type as the input.
def tr(x;y):
type as $type
| (x | explode) as $xe
| (y | explode) as $ye
| $ye[-1] as $last
| if $type == "string" then explode else . end
| map( . as $n | ($xe|index($n)) as $i | if $i then $ye[$i]//$last else . end)
| if $type == "string" then implode else . end;
# NOTE: the order in which the filters are applied is consequential!
def natural_sort:
def naturally:
gsub("\\p{M}"; "") # combining characters (accents, umlauts, enclosures, etc)
| tr("ÀÁÂÃÄÅàáâãäåÇçÈÉÊËèéêëÌÍÎÏìíîïÒÓÔÕÖØòóôõöøÑñÙÚÛÜùúûüÝÿý";
"AAAAAAaaaaaaCcEEEEeeeeIIIIiiiiOOOOOOooooooNnUUUUuuuuYyy")
# Ligatures:
| gsub("Æ"; "AE")
| gsub("æ"; "ae")
| gsub("\u0132"; "IJ") # IJ
| gsub("\u0133"; "ij") # ij
| gsub("\u0152"; "Oe") # Œ
| gsub("\u0153"; "oe") # œ
| gsub("ffl"; "ffl")
| gsub("ffi"; "ffi")
| gsub("fi" ; "fi")
| gsub("ff" ; "ff")
| gsub("fl" ; "fl")
# Illustrative replacements:
| gsub("ß" ; "ss") # German scharfes S
| gsub("ſ|ʒ"; "s") # LATIN SMALL LETTER LONG S and LATIN SMALL LETTER EZH
| ascii_downcase
| gsub("\\p{Cc}+";" ") # control characters
| gsub("^(the|a|an) "; "") # leading the/a/an (as words)
| gsub("\\s+"; " ") # whitespace
| sub("^ *";"") # leading whitespace
| sub(" *$";"") # trailing whitespace
| splitup # embedded integers
;
sort_by(naturally); |
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| #zkl | zkl | stdin:=File.stdin.read();
thisFileSrc:=File(System.argv[1]).read();
println((stdin==thisFileSrc) and "input matches "+System.argv[1] or "No match"); |
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)
| #Lua | Lua | - constants use UPCASE_SNAKE
- variable names use lower_case_snake
- class-like structures use CamelCase
- other functions use smallCamelCase
- Use _ for unneeded variables
- Don't use Hungarian Notation
|
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)
| #M2000_Interpreter | M2000 Interpreter |
Class Alfa$ {
Private:
myValue$
Public:
Set {
Read .myValue$
}
Value {
=.myValue$
}
Module Doit {
Function TwoChars$(A$) {
=Left$(Left$(a$,1)+Right$(a$,1)+"??",2)
}
Print TwoChars$(.myValue$)
Dim A$(3)
A$(0)="zero","one","two"
Print A$(1)
k$=Lambda$ A$() (x) -> {
if x>0 and x<3 then {=A$(x)} else =A$(0)
}
Print k$(2)
Dim A$()
Print Len(A$())=0
Print k$(2)="two"
}
}
A$=Alfa$()
Module CheckIt(&B$) {
Input "name:", B$
B.Doit
}
Checkit &A$
Print A$
|
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)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | # Constants can start with either a lower case or upper case letter.
const aConstant = 42
const FooBar = 4.2
var aVariable = "Meep" # Variables must start with a lowercase letter.
# Types must start with an uppercase letter.
type
FooBar = object |
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)
| #Nim | Nim | # Constants can start with either a lower case or upper case letter.
const aConstant = 42
const FooBar = 4.2
var aVariable = "Meep" # Variables must start with a lowercase letter.
# Types must start with an uppercase letter.
type
FooBar = object |
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)
| #OASYS_Assembler | OASYS Assembler | $ALL_CAPS_HERE constants
$Some_Caps_Here package-wide global/static
$no_caps_here function scope my/our/local variables
$_internal_use private
|
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
| #Scala | Scala |
def main(args: Array[String]) {
val sep: String=". "
var c:Int=1;
def go(s: String):Unit={
println(c+sep+s)
c=c+1
}
go("first")
go("second")
go("third")
}
|
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
| #Scheme | Scheme | (define (make-list separator)
(define counter 1)
(define (make-item item)
(let ((result (string-append (number->string counter) separator item "\n")))
(set! counter (+ counter 1))
result))
(string-append (make-item "first") (make-item "second") (make-item "third")))
(display (make-list ". ")) |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
include "duration.s7i";
include "keybd.s7i";
const array string: watch is [] ("Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First");
const array string: bells is [] ("One Bell", "Two Bells", "Three Bells", "Four Bells", "Five Bells", "Six Bells", "Seven Bells", "Eight Bells");
const func time: truncToHalfHour (in time: aTime) is func
result
var time: truncatedTime is time.value;
begin
truncatedTime := aTime;
truncatedTime.minute := aTime.minute div 30 * 30;
truncatedTime.second := 0;
truncatedTime.micro_second := 0;
end func;
const proc: main is func
local
var time: nextTime is time.value;
var time: midnight is time.value;
var integer: minutes is 0;
begin
writeln;
nextTime := truncToHalfHour(time(NOW));
midnight := truncToDay(nextTime);
while TRUE do
nextTime +:= 30 . MINUTES;
await(nextTime);
minutes := toMinutes(nextTime - midnight);
writeln(str_hh_mm(nextTime, ":") <& " - " <&
watch[succ((minutes - 30) mdiv 240 mod 6)] <& " watch - " <&
bells[succ((minutes - 30) mdiv 30 mod 8)] <& " Gone.");
flush(OUT);
end while;
end func; |
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
| #Tcl | Tcl | # More sophisticated versions are possible, such as playing a bell sample
# using the Snack library.
proc ringTheBell {} {
puts -nonewline "\a"
}
# The code to convert the (parsed) time into rings of the ship's bell and
# printing of the name of the bell.
proc strikeBell {hour minute} {
global suppressNormalOutput
set watches {
Middle Middle Morning Morning Forenoon Forenoon
Afternoon Afternoon {First dog} {Last dog} First First
}
set cardinals {one two three four five six seven eight}
set bells [expr {(($hour % 4) * 2 + $minute / 30)}]
if {!$bells} {set bells 8}
puts -nonewline [format "%02d:%02d %9s watch, %6s bell%s gone: \t" \
$hour $minute [lindex $watches [expr {
($hour/2 - ($minute==0 && $hour%2==0)) % 12
}]] [lindex $cardinals [expr {$bells - 1}]] \
[expr {$bells == 1 ? "" : "s"}]]
# Set up the ringing of the bells to be done asynchronously
set t 0
set suppressNormalOutput 1
for {set i 0} {$i < $bells-1} {incr i 2} {
after $t {
ringTheBell
puts -nonewline "\u266b "
}
incr t 250
after $t {
ringTheBell
}
incr t 750
}
if {$bells % 2} {
after $t {
ringTheBell
puts -nonewline "\u266a\n"
set suppressNormalOutput 0
}
} else {
after $t {
puts ""
set suppressNormalOutput 0
}
}
}
# Main handler; designed to be called every second, which is plenty.
proc nauticalBell {} {
global last suppressNormalOutput
scan [clock format [clock seconds] -format "%H:%M" -gmt 1] "%d:%d" h m
if {$last != $m} {
set last $m
if {$m%30 == 0} {
strikeBell $h $m
} elseif {!$suppressNormalOutput} {
puts -nonewline [format "%02d:%02d\r" $h $m]
}
}
}
# Set things up, using Tcl's event loop to do the processing
proc every {delay script} {
after $delay [list every $delay $script]
uplevel #0 $script
}
set last ""
set suppressNormalOutput 0
fconfigure stdout -buffering none
every 1000 nauticalBell
vwait forever; # Only needed if not running an event loop otherwise |
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
| #R | R | ncsub <- function(x)
{
n <- length(x)
a <- seq_len(n)
seqlist <- list()
for(i in 2:(n-1))
{
seqs <- combn(a, i) # Get all subseqs
ok <- apply(seqs, 2, function(x) any(diff(x)!=1)) # Find noncts ones
newseqs <- unlist(apply(seqs[,ok], 2, function(x) list(x)), recursive=FALSE) # Convert matrix to list of its columns
seqlist <- c(seqlist, newseqs) # Append to existing list
}
lapply(seqlist, function(index) x[index])
}
# Example usage
ncsub(1:4)
ncsub(letters[1:5]) |
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
| #Racket | Racket |
(define (subsets l)
(if (null? l) '(())
(append (for/list ([l2 (subsets (cdr l))]) (cons (car l) l2))
(subsets (cdr l)))))
|
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.
| #Haskell | Haskell | Prelude> Numeric.showIntAtBase 16 Char.intToDigit 42 ""
"2a"
Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a"
42 |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #XPL0 | XPL0 | include c:\cxpl\codes;
int N;
[N:= 2;
repeat HexOut(0, N); Text(0, " ");
IntOut(0, N); CrLf(0);
N:= N*N;
until N=0;
] |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #Yabasic | Yabasic | for i = 1 to 33
print "decimal: ", i, " hex: ", hex$(i), " bin: ", bin$(i)
next
|
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #zkl | zkl | const N=16;
var fmt=[2..N].pump(String,"%%5.%dB".fmt); // %5.2B%5.3B%5.4B%5.5B ...
foreach n in (17){fmt.fmt(n.pump(N,List,n.fp(n)).xplode()).println()} |
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.
| #REXX | REXX | /*REXX pgm converts & displays a base ten integer to a negative base number (up to -10).*/
@=' converted to base '; numeric digits 300 /*be able to handle ginormous numbers. */
n= 10; b= -2; q= nBase(n, b); say right(n, 20) @ right(b, 3) '────►' q ok()
n= 146; b= -3; q= nBase(n, b); say right(n, 20) @ right(b, 3) '────►' q ok()
n= 15; b= -10; q= nBase(n, b); say right(n, 20) @ right(b, 3) '────►' q ok()
n= -15; b= -10; q= nBase(n, b); say right(n, 20) @ right(b, 3) '────►' q ok()
n= 0; b= -5; q= nBase(n, b); say right(n, 20) @ right(b, 3) '────►' q ok()
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
nBase: procedure; parse arg x,r; $= /*obtain args; $ is the integer result.*/
if r<-10 | r>-2 then do; say 'base' r "must be in range: -2 ───► -10"; exit 13; end
do while x\==0 /*keep processing while X isn't zero.*/
z= x // r; x= x % r /*calculate remainder; calculate int ÷.*/
if z<0 then do; z= z - r /*subtract a negative R from Z ◄──┐ */
x= x + 1 /*bump X by one. │ */
end /* Funny "add" ►───┘ */
$= z || $ /*prepend new digit (numeral) to result*/
end /*while*/
return word($ 0, 1) /*possibly adjust for a zero value. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ok: ?=; if pBase(q, b)\=n then ?= ' ◄──error in negative base calculation'; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
pBase: procedure; parse arg x,r; p= 0; $= 0 /*obtain args; $ is the integer result.*/
if r<-10 | r>-2 then do; say 'base' r "must be in range: -2 ───► -10"; exit 13; end
do j=length(x) by -1 for length(x) /*process each of the numerals in X. */
$= $ + substr(x,j,1) * r ** p /*add value of a numeral to $ (result).*/
p= p + 1 /*bump the power by 1. */
end /*j*/ /* [↓] process the number "bottom-up".*/
return $ |
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.
| #Ring | Ring |
# Project : CalmoSoft Nim Game
# Date : 16/04/2020-13:27:07
# Update : 31/03/2021-19:41:09
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
load "stdlib.ring"
load "guilib.ring"
limit = 4
limit1 = 1
limit2 = 3
limit3 = 5
limit4 = 7
match1 = limit1
match2 = limit2
match3 = limit3
match4 = limit4
move1 = 0
move2 = 0
move3 = 0
move4 = 0
Button1 = list(limit1)
Button2 = list(limit2)
Button3 = list(limit3)
Button4 = list(limit4)
pcMove = 0
width = 60
height = 60
yourScore = 0
pcScore = 0
C_FONTSIZE = 15
C_NIM = "images/nim.jpg"
C_COMPUTER = "images/computer.jpg"
C_PROGRAMMER = "images/programmer.jpg"
app = new qApp
{
win = new qWidget() {
app.StyleFusionBlack()
setWindowTitle('CalmoSoft Nim Game')
setWinIcon(self,"images/nim.jpg")
setWindowFlags(Qt_SplashScreen | Qt_CustomizeWindowHint)
reSize(620,460)
for Col = 1 to limit1
Button1[Col] = new QPushButton(win) {
y = 230+(Col-1)*height
setgeometry(y+10,70,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
}
next
for Col = 1 to limit2
Button2[Col] = new QPushButton(win) {
y = 170+(Col-1)*height
setgeometry(y+10,150,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
}
next
for Col = 1 to limit3
Button3[Col] = new QPushButton(win) {
y = 110+(Col-1)*height
setgeometry(y+10,230,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
}
next
for Col = 1 to limit4
Button4[Col] = new QPushButton(win) {
y = 50+(Col-1)*height
setgeometry(y+10,310,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
}
next
Row1 = new QPushButton(win) {
setgeometry(500,70,width,height)
setStyleSheet("color:Black;background-color:Orange")
setSizePolicy(1,1)
setclickevent("deleteRow1()")
settext("Row1") }
Row2 = new QPushButton(win) {
setgeometry(500,150,width,height)
setStyleSheet("color:Black;background-color:Orange")
setSizePolicy(1,1)
setclickevent("deleteRow2()")
settext("Row2") }
Row3 = new QPushButton(win) {
setgeometry(500,230,width,height)
setStyleSheet("color:Black;background-color:Orange")
setSizePolicy(1,1)
setclickevent("deleteRow3()")
settext("Row3") }
Row4 = new QPushButton(win) {
setgeometry(500,310,width,height)
setStyleSheet("color:Black;background-color:Orange")
setSizePolicy(1,1)
setclickevent("deleteRow4()")
settext("Row4") }
labelYourScore = new QLabel(win) { setgeometry(60,20,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("Your score: 0") }
labelComputerScore = new QLabel(win) { setgeometry(350,20,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("PC score: 0") }
btnNewGame = new QPushButton(win) { setgeometry(60,400,80,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("New")
setclickevent("newGame()") }
btnExit = new QPushButton(win) { setgeometry(400,400,80,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("Exit")
setclickevent("pQuit()") }
btnPcMove = new QPushButton(win) { setgeometry(200,400,140,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("PC move")
setclickevent("pcMove()") }
show()
}
exec()
}
func deleteRow1()
if move2 = 1 or move3 = 1 or move4 = 1
move1 = 0
return
else
move1 = 1
ok
if (match1 > 0) and (move1 = 1)
if pcMove = 1
Button1[match1] { seticon(new qicon(new qpixmap(C_COMPUTER)))
setIconSize(new qSize(55,55))
setenabled(false) }
match1 = match1 - 1
move1 = 0
ok
if pcMove = 0
Button1[match1] { seticon(new qicon(new qpixmap(C_PROGRAMMER)))
setIconSize(new qSize(55,55))
setenabled(false) }
match1 = match1 - 1
ok
gameOver()
ok
func deleteRow2()
if move1 = 1 or move3 = 1 or move4 = 1
move2 = 0
return
else
move2 = 1
ok
if match2 > 0 and move2 = 1
if pcMove = 1
Button2[match2] { seticon(new qicon(new qpixmap(C_COMPUTER)))
setIconSize(new qSize(55,55))
setenabled(false) }
match2 = match2 - 1
move2 = 0
ok
if pcMove = 0
Button2[match2] { seticon(new qicon(new qpixmap(C_PROGRAMMER)))
setIconSize(new qSize(55,55))
setenabled(false) }
match2 = match2 - 1
ok
gameOver()
ok
func deleteRow3()
if move1 = 1 or move2 = 1 or move4 = 1
move3 = 0
return
else
move3 = 1
ok
if match3 > 0 and move3 = 1
if pcMove = 1
Button3[match3] { seticon(new qicon(new qpixmap(C_COMPUTER)))
setIconSize(new qSize(55,55))
setenabled(false) }
match3 = match3 - 1
move3 = 0
ok
if pcMove = 0
Button3[match3] { seticon(new qicon(new qpixmap(C_PROGRAMMER)))
setIconSize(new qSize(55,55))
setenabled(false) }
match3 = match3 - 1
ok
gameOver()
ok
func deleteRow4()
if move1 = 1 or move2 = 1 or move3 = 1
move4 = 0
return
else
move4 = 1
ok
if match4 > 0 and move4 = 1
if pcMove = 1
Button4[match4] { seticon(new qicon(new qpixmap(C_COMPUTER)))
setIconSize(new qSize(55,55))
setenabled(false) }
match4 = match4 - 1
move4 = 0
ok
if pcMove = 0
Button4[match4] { seticon(new qicon(new qpixmap(C_PROGRAMMER)))
setIconSize(new qSize(55,55))
setenabled(false) }
match4 = match4 - 1
ok
gameOver()
ok
func pcMove()
move1 = 0
move2 = 0
move3 = 0
move4 = 0
pcMove = 1
for n = 1 to limit
if match1 > 0
rnd = random(match1-1)+1
for m = 1 to rnd
deleteRow1()
next
exit
ok
if match2 > 0
rnd = random(match2-1)+1
for m = 1 to rnd
deleteRow2()
next
exit
ok
if match3 > 0
rnd = random(match3-1)+1
for m = 1 to rnd
deleteRow3()
next
exit
ok
if match4 > 0
rnd = random(match4-1)+1
for m = 1 to rnd
deleteRow4()
next
exit
ok
next
pcMove = 0
func gameOver()
if (match1 = 0) and (match2 = 0) and (match3 = 0) and (match4 = 0)
if pcMove = 0
pcScore = pcScore + 1
labelComputerScore.settext("PC score: " + string(pcScore))
msgBox("Game Over! You Lost!")
else
yourScore = yourScore + 1
labelYourScore.settext("Your score: " + string(yourScore))
msgBox("Game Over! You Win!")
ok
ok
func newGame()
match1 = limit1
match2 = limit2
match3 = limit3
match4 = limit4
move1 = 0
move2 = 0
move3 = 0
move4 = 0
pcMove = 0
for Col = 1 to limit1
Button1[Col] = new QPushButton(win) {
y = 230+(Col-1)*height
setgeometry(y+10,70,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
show()
}
next
for Col = 1 to limit2
Button2[Col] = new QPushButton(win) {
y = 170+(Col-1)*height
setgeometry(y+10,150,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
show()
}
next
for Col = 1 to limit3
Button3[Col] = new QPushButton(win) {
y = 110+(Col-1)*height
setgeometry(y+10,230,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
show()
}
next
for Col = 1 to limit4
Button4[Col] = new QPushButton(win) {
y = 50+(Col-1)*height
setgeometry(y+10,310,width,height)
setSizePolicy(1,1)
seticon(new qicon(new qpixmap(C_NIM)))
setIconSize(new qSize(60,60))
show()
}
next
func msgBox(cText)
mb = new qMessageBox(win) {
setWindowTitle('CalmoSoft Nim Game')
setText(cText)
setstandardbuttons(QMessageBox_OK)
result = exec()
}
func pQuit()
win.close()
app.Quit()
|
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.
| #Ruby | Ruby | [12, 8, 4].each do |remaining|
puts "There are #{remaining} dots.\nHow many dots would you like to take? "
unless (num=gets.to_i).between?(1, 3)
puts "Please enter one of 1, 2 or 3"
redo
end
puts "You took #{num} dots, leaving #{remaining-num}.\nComputer takes #{4-num}.\n\n"
end
puts "Computer took the last and 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.
| #AutoHotkey | AutoHotkey |
#NoEnv ; Do not try to use environment variables
SetBatchLines, -1 ; Execute as quickly as you can
StartCount := A_TickCount
Narc := Narc(25)
Elapsed := A_TickCount - StartCount
MsgBox, Finished in %Elapsed%ms`n%Narc%
return
Narc(m)
{
Found := 0, Lower := 0
Progress, B2
Loop
{
Max := 10 ** Digits:=A_Index
Loop, 10
Index := A_Index-1, Powers%Index% := Index**Digits
While Lower < Max
{
Sum := 0
Loop, Parse, Lower
Sum += Powers%A_LoopField%
Loop, 10
{
if (Lower + (Index := A_Index-1) == Sum + Powers%Index%)
{
Out .= Lower+Index . (Mod(++Found,5) ? ", " : "`n")
Progress, % Found/M*100
if (Found >= m)
{
Progress, Off
return Out
}
}
}
Lower += 10
}
}
}
|
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.
| #Action.21 | Action! | PROC PutBigPixel(BYTE x,y,c)
BYTE i
Color=c
x=x*3+16
y=y*12
FOR i=0 TO 11
DO
Plot(x,y+i)
DrawTo(x+2,y+i)
OD
RETURN
PROC Main()
BYTE
CH=$02FC, ;Internal hardware value for last key pressed
x,y
Graphics(9)
FOR y=0 TO 15
DO
FOR x=0 TO 15
DO
PutBigPixel(x,y,x!y)
OD
OD
DO UNTIL CH#$FF OD
CH=$FF
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
| #Crystal | Crystal | require "big"
def prime?(n) # P3 Prime Generator primality test
return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5
sqrt_n = Math.isqrt(n) # For Crystal < 1.2.0 use Math.sqrt(n).to_i
pc = typeof(n).new(5)
while pc <= sqrt_n
return false if n % pc == 0 || n % (pc + 2) == 0
pc += 6
end
true
end
def gen_primes(a, b)
(a..b).select { |pc| pc if prime? pc }
end
def nsmooth(n, limit)
raise "Exception(n or limit)" if n < 2 || n > 521 || limit < 1
raise "Exception(must be a prime number: n)" unless prime? n
primes = gen_primes(2, n)
ns = [0.to_big_i] * limit
ns[0] = 1.to_big_i
nextp = primes[0..primes.index(n)].map { |prm| prm.to_big_i }
indices = [0] * nextp.size
(1...limit).each do |m|
ns[m] = nextp.min
(0...indices.size).each do |i|
if ns[m] == nextp[i]
indices[i] += 1
nextp[i] = primes[i] * ns[indices[i]]
end
end
end
ns
end
gen_primes(2, 29).each do |prime|
print "The first 25 #{prime}-smooth numbers are: \n"
print nsmooth(prime, 25)
puts
end
puts
gen_primes(3, 29).each do |prime|
print "The 3000 to 3202 #{prime}-smooth numbers are: "
print nsmooth(prime, 3002)[2999..]
puts
end
puts
gen_primes(503, 521).each do |prime|
print "The 30,000 to 30,019 #{prime}-smooth numbers are: \n"
print nsmooth(prime, 30019)[29999..]
puts
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
| #Delphi | Delphi |
program Named_parameters;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TParams = record
fx, fy, fz: Integer;
function x(value: Integer): TParams;
function y(value: Integer): TParams;
function z(value: Integer): TParams;
class function _: TParams; static;
end;
function Sum(Param: TParams): Integer;
begin
Result := Param.fx + Param.fy + Param.fz;
end;
{ TParams }
function TParams.x(value: Integer): TParams;
begin
Result := Self;
Result.fx := value;
end;
function TParams.y(value: Integer): TParams;
begin
Result := Self;
Result.fy := value;
end;
function TParams.z(value: Integer): TParams;
begin
Result := Self;
Result.fz := value;
end;
class function TParams._: TParams;
begin
Result.fx := 0; // default x
Result.fy := 0; // default y
Result.fz := 0; // default z
end;
begin
writeln(sum(TParams._.x(2).y(3).z(4))); // 9
writeln(sum(TParams._.z(4).x(3).y(5))); // 12
{$IFNDEF UNIX} readln; {$ENDIF}
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.
| #Delphi | Delphi |
USES
Math;
function NthRoot(A, Precision: Double; n: Integer): Double;
var
x_p, X: Double;
begin
x_p := Sqrt(A);
while Abs(A - Power(x_p, n)) > Precision do
begin
x := (1/n) * (((n-1) * x_p) + (A/(Power(x_p, n - 1))));
x_p := x;
end;
Result := x_p;
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.
| #AppleScript | AppleScript | -- ORDINAL STRINGS -----------------------------------------------------------
-- ordinalString :: Int -> String
on ordinalString(n)
(n as string) & ordinalSuffix(n)
end ordinalString
-- ordinalSuffix :: Int -> String
on ordinalSuffix(n)
set modHundred to n mod 100
if (11 ≤ modHundred) and (13 ≥ modHundred) then
"th"
else
item ((n mod 10) + 1) of ¬
{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}
end if
end ordinalSuffix
-- TEST ----------------------------------------------------------------------
on run
-- showOrdinals :: [Int] -> [String]
script showOrdinals
on |λ|(lstInt)
map(ordinalString, lstInt)
end |λ|
end script
map(showOrdinals, ¬
map(uncurry(enumFromTo), ¬
[[0, 25], [250, 265], [1000, 1025]]))
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- uncurry :: Handler (a -> b -> c) -> Script |λ| ((a, b) -> c)
on uncurry(f)
script
on |λ|(xy)
set {x, y} to xy
mReturn(f)'s |λ|(x, y)
end |λ|
end script
end uncurry |
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
| #Fortran | Fortran |
program moebius
use iso_fortran_env, only: output_unit
integer, parameter :: mu_max=1000000, line_break=20
integer, parameter :: sqroot=int(sqrt(real(mu_max)))
integer :: i, j
integer, dimension(mu_max) :: mu
mu = 1
do i = 2, sqroot
if (mu(i) == 1) then
do j = i, mu_max, i
mu(j) = mu(j) * (-i)
end do
do j = i**2, mu_max, i**2
mu(j) = 0
end do
end if
end do
do i = 2, mu_max
if (mu(i) == i) then
mu(i) = 1
else if (mu(i) == -i) then
mu(i) = -1
else if (mu(i) < 0) then
mu(i) = 1
else if (mu(i) > 0) then
mu(i) = -1
end if
end do
write(output_unit,*) "The first 199 terms of the Möbius sequence are:"
write(output_unit,'(3x)', advance="no") ! Alignment of first number
do i = 1, 199
write(output_unit,'(I2,x)', advance="no") mu(i)
if (modulo(i+1, line_break) == 0) write(output_unit,*)
end do
end program moebius
|
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']
| #Julia | Julia | #1
natural1(x, y) = strip(x) < strip(y)
#2
natural2(x, y) = replace(x, r"\s+" => " ") < replace(y, r"\s+" => " ")
#3
natural3(x, y) = lowercase(x) < lowercase(y)
#4
splitbynum(x) = split(x, r"(?<=\D)(?=\d)|(?<=\d)(?=\D)")
numstringtonum(arr) = [(n = tryparse(Float32, e)) != nothing ? n : e for e in arr]
function natural4(x, y)
xarr = numstringtonum(splitbynum(x))
yarr = numstringtonum(splitbynum(y))
for i in 1:min(length(xarr), length(yarr))
if typeof(xarr[i]) != typeof(yarr[i])
a = string(xarr[i]); b = string(yarr[i])
else
a = xarr[i]; b = yarr[i]
end
if a == b
continue
else
return a < b
end
end
return length(xarr) < length(yarr)
end
#5
deart(x) = replace(x, r"^The\s+|^An\s+|^A\s+"i => "")
natural5(x, y) = deart(x) < deart(y)
#6
const accentdict = Dict(
'À'=> 'A', 'Á'=> 'A', 'Â'=> 'A', 'Ã'=> 'A', 'Ä'=> 'A',
'Å'=> 'A', 'Ç'=> 'C', 'È'=> 'E', 'É'=> 'E',
'Ê'=> 'E', 'Ë'=> 'E', 'Ì'=> 'I', 'Í'=> 'I', 'Î'=> 'I',
'Ï'=> 'I', 'Ñ'=> 'N', 'Ò'=> 'O', 'Ó'=> 'O',
'Ô'=> 'O', 'Õ'=> 'O', 'Ö'=> 'O', 'Ù'=> 'U', 'Ú'=> 'U',
'Û'=> 'U', 'Ü'=> 'U', 'Ý'=> 'Y', 'à'=> 'a', 'á'=> 'a',
'â'=> 'a', 'ã'=> 'a', 'ä'=> 'a', 'å'=> 'a', 'è'=> 'e',
'é'=> 'e', 'ê'=> 'e', 'ë'=> 'e', 'ì'=> 'i', 'í'=> 'i',
'î'=> 'i', 'ï'=> 'i', 'ð'=> 'd', 'ñ'=> 'n', 'ò'=> 'o',
'ó'=> 'o', 'ô'=> 'o', 'õ'=> 'o', 'ö'=> 'o', 'ù'=> 'u',
'ú'=> 'u', 'û'=> 'u', 'ü'=> 'u', 'ý'=> 'y', 'ÿ'=> 'y')
function tr(str, dict=accentdict)
for (i, ch) in enumerate(str)
if haskey(dict, ch)
arr = split(str, "")
arr[i] = string(dict[ch])
str = join(arr)
end
end
str
end
natural6(x, y) = tr(x) < tr(y)
#7
const ligaturedict = Dict('œ' => "oe", 'Œ' => "OE", 'æ' => "ae", 'Æ' => "AE", 'IJ' => "IJ")
natural7(x, y) = tr(x, ligaturedict) < tr(y, ligaturedict)
#8
const altsdict = Dict('ß' => "ss", 'ſ' => 's', 'ʒ' => 's')
natural8(x, y) = tr(x, altsdict) < tr(y, altsdict)
preprocessors = [natural1, natural2, natural2, natural3, natural4, natural5, natural6, natural7, natural8]
const testarrays = Vector{Vector{String}}([
["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1"],
["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"],
["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 INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"],
["foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"],
["The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"],
["Equiv. ý accents: 2-2", "Equiv. Ý accents: 2-1", "Equiv. y accents: 2+0", "Equiv. Y accents: 2+1"],
["IJ ligatured ij", "no ligature"],
["Start with an ʒ: 2-2", "Start with an ſ: 2-1", "Start with an ß: 2+0", "Start with an s: 2+1"]])
for (i, ltfunction) in enumerate(preprocessors)
println("Testing sorting mod number $i. Sorted is: $(sort(testarrays[i], lt=ltfunction)).")
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)
| #Oforth | Oforth | $ALL_CAPS_HERE constants
$Some_Caps_Here package-wide global/static
$no_caps_here function scope my/our/local variables
$_internal_use private
|
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)
| #Pascal | Pascal | $ALL_CAPS_HERE constants
$Some_Caps_Here package-wide global/static
$no_caps_here function scope my/our/local variables
$_internal_use private
|
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)
| #Perl | Perl | $ALL_CAPS_HERE constants
$Some_Caps_Here package-wide global/static
$no_caps_here function scope my/our/local variables
$_internal_use private
|
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)
| #Phix | Phix | - Global variables start with an asterisk '*'
- Global constants may be written all-uppercase
- Functions and other global symbols start with a lower case letter
- Locally bound symbols start with an upper case letter
- Local functions start with an underscore '_'
- Classes start with a plus-sign '+', where the first letter
- is in lower case for abstract classes
- and in upper case for normal classes
- Methods end with a right arrow '>'
- Class variables may be indicated by an upper case letter |
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)
| #PicoLisp | PicoLisp | - Global variables start with an asterisk '*'
- Global constants may be written all-uppercase
- Functions and other global symbols start with a lower case letter
- Locally bound symbols start with an upper case letter
- Local functions start with an underscore '_'
- Classes start with a plus-sign '+', where the first letter
- is in lower case for abstract classes
- and in upper case for normal classes
- Methods end with a right arrow '>'
- Class variables may be indicated by an upper case letter |
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)
| #PowerShell | PowerShell | #lang racket
render-game-state
send-message-to-client
traverse-forest |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func string: makeList (in string: separator) is func
result
var string: itemList is "";
local
var integer: counter is 1;
const func string: makeItem (in string: item) is func
result
var string: anItem is "";
begin
anItem := counter <& separator <& item <& "\n";
incr(counter);
end func
begin
itemList := makeItem("first") & makeItem("second") & makeItem("third");
end func;
const proc: main is func
begin
write(makeList(". "));
end func; |
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
| #Sidef | Sidef | func make_list(separator = ') ') {
var count = 1
func make_item(item) {
[count++, separator, item].join
}
<first second third>.map(make_item).join("\n")
}
say 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
| #Simula | Simula | COMMENT CLASS SIMSET IS SIMULA'S STANDARD LINKED LIST DATA TYPE
CLASS HEAD IS THE LIST ITSELF
CLASS LINK IS THE ELEMENT OF A LIST
PROCEDURE IS THE TERM USED FOR FUNCTIONS IN SIMULA
TEXT IS THE TERM USED FOR STRINGS IN SIMULA ;
SIMSET
BEGIN
LINK CLASS ITEM(TXT); TEXT TXT;;
COMMENT CREATING THE LIST AS A WHOLE WITH THE SEPARATOR ". "
GIVEN AS AN ARGUMENT;
REF(HEAD) PROCEDURE MAKELIST(SEPARATOR); TEXT SEPARATOR;
BEGIN
COMMENT VARIABLE TO KEEP TRACK OF THE ITEM NUMBER ;
INTEGER COUNTER;
COMMENT THIS IS THE NESTED FUNCTION ;
REF(ITEM) PROCEDURE MAKEITEM(TXT); TEXT TXT;
BEGIN
TEXT NUM;
TEXT ITEMTEXT;
COMMENT CONVERT NUMBER TO STRING ;
NUM :- BLANKS(5);
NUM.PUTINT(COUNTER);
COMMENT ACCESS SEPARATOR AND MODIFY COUNTER;
COUNTER := COUNTER + 1;
ITEMTEXT :- NUM & SEPARATOR & TXT;
MAKEITEM :- NEW ITEM(ITEMTEXT);
END MAKEITEM;
REF(HEAD) HD;
HD :- NEW HEAD;
COUNTER := 1;
MAKEITEM("FIRST").INTO(HD);
MAKEITEM("SECOND").INTO(HD);
MAKEITEM("THIRD").INTO(HD);
MAKELIST :- HD;
END MAKELIST;
REF(HEAD) LIST;
REF(ITEM) IT;
LIST :- MAKELIST(". ");
COMMENT NAVIGATE THROUGH THE LIST ;
IT :- LIST.FIRST;
WHILE IT =/= NONE DO
BEGIN
OUTTEXT(IT.TXT);
OUTIMAGE;
IT :- IT.SUC;
END;
END.
|
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.