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/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated).
The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that.
The reverse operation is in task Non-decimal radices/Output
For general number base conversion, see Non-decimal radices/Convert.
| #Raku | Raku | say 0b11011; # -> 27
say 0o11011; # -> 4617
say 0d11011; # -> 11011
say 0x11011; # -> 69649 |
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated).
The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that.
The reverse operation is in task Non-decimal radices/Output
For general number base conversion, see Non-decimal radices/Convert.
| #REXX | REXX | ╔══════════════════════════════════════════════════════════════════════════════════╗
║ In REXX, there are no numeric-type variables (integer, float, real, unsigned, ║
║ logical, binary, complex, double, etc), only character. Everything is stored ║
║ as a character string. Arithmetic is done almost exactly the way a schoolchild ║
║ would perform it. Putting it simply, to add, align the two numbers up (right ║
║ justified, with the decimal being the pivot) and add the columns up, adding the ║
║ carries and honoring the signs. ║
║ ║
║ Multiplications and divisions are similarly performed. ║
╚══════════════════════════════════════════════════════════════════════════════════╝
|
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.
| #PureBasic | PureBasic | For i=105 To 115
Bin$=RSet(Bin(i),8,"0") ;- Convert to wanted type & pad with '0'
Hex$=RSet(Hex(i),4,"0")
Dec$=RSet(Str(i),3)
PrintN(Dec$+" decimal = %"+Bin$+" = $"+Hex$+".")
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.
| #Python | Python | for n in range(34):
print " %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.
| #J | J | >>> # python divmod
>>> [divmod(i, -2) for i in (2, 3, 4, 5)]
[(-1, 0), (-2, -1), (-2, 0), (-3, -1)]
>>>
|
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.
| #Java | Java | import java.util.List;
import java.util.Map;
import java.util.Objects;
public class NegativeBaseNumbers {
private static final String DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static String encodeNegBase(long n, int b) {
if (b < -62 || b > -1) throw new IllegalArgumentException("Parameter b is out of bounds");
if (n == 0) return "0";
StringBuilder out = new StringBuilder();
long nn = n;
while (nn != 0) {
int rem = (int) (nn % b);
nn /= b;
if (rem < 0) {
nn++;
rem -= b;
}
out.append(DIGITS.charAt(rem));
}
out.reverse();
return out.toString();
}
private static long decodeNegBase(String ns, int b) {
if (b < -62 || b > -1) throw new IllegalArgumentException("Parameter b is out of bounds");
if (Objects.equals(ns, "0")) return 0;
long total = 0;
long bb = 1;
for (int i = ns.length() - 1; i >= 0; i--) {
char c = ns.charAt(i);
total += DIGITS.indexOf(c) * bb;
bb *= b;
}
return total;
}
public static void main(String[] args) {
List<Map.Entry<Long, Integer>> nbl = List.of(
Map.entry(10L, -2),
Map.entry(146L, -3),
Map.entry(15L, -10),
Map.entry(-4393346L, -62)
);
for (Map.Entry<Long, Integer> p : nbl) {
String ns = encodeNegBase(p.getKey(), p.getValue());
System.out.printf("%12d encoded in base %-3d = %s\n", p.getKey(), p.getValue(), ns);
long n = decodeNegBase(ns, p.getValue());
System.out.printf("%12s decoded in base %-3d = %d\n\n", ns, p.getValue(), n);
}
}
} |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Visual_Basic | Visual Basic | Option Explicit
Private small As Variant, tens As Variant, big As Variant
Sub Main()
small = Array("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", _
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", _
"eighteen", "nineteen")
tens = Array("twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety")
big = Array("thousand", "million", "billion")
Dim tmpInt As Long
tmpInt = Val(InputBox("Gimme a number!", "NOW!", Trim$(Year(Now)) & IIf(Month(Now) < 10, "0", "") & _
Trim$(Month(Now)) & IIf(Day(Now) < 10, "0", "") & Trim$(Day(Now))))
MsgBox int2Text$(tmpInt)
End Sub
Function int2Text$(number As Long)
Dim num As Long, outP As String, unit As Integer
Dim tmpLng1 As Long
If 0 = number Then
int2Text$ = "zero"
Exit Function
End If
num = Abs(number)
Do
tmpLng1 = num Mod 100
Select Case tmpLng1
Case 1 To 19
outP = small(tmpLng1 - 1) + " " + outP
Case 20 To 99
Select Case tmpLng1 Mod 10
Case 0
outP = tens((tmpLng1 \ 10) - 2) + " " + outP
Case Else
outP = tens((tmpLng1 \ 10) - 2) + "-" + small(tmpLng1 Mod 10) + " " + outP
End Select
End Select
tmpLng1 = (num Mod 1000) \ 100
If tmpLng1 Then
outP = small(tmpLng1 - 1) + " hundred " + outP
End If
num = num \ 1000
If num < 1 Then Exit Do
tmpLng1 = num Mod 1000
If tmpLng1 Then outP = big(unit) + " " + outP
unit = unit + 1
Loop
If number < 0 Then outP = "negative " & outP
int2Text$ = Trim$(outP)
End Function |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #XPL0 | XPL0 | int Taken, I, Digit, Num, Score, Rev, Temp;
char List(9);
include c:\cxpl\codes;
\make jumbled list of digits 1 to 9
[loop [Taken:= 0; \bit array indicates which digits are taken
for I:= 0 to 9-1 do
[repeat Digit:= Ran(9)+1 until (Taken & 1<<Digit) = 0;
Taken:= Taken + 1<<Digit; \mark digit as taken
List(I):= Digit; \add digit to the list
];
for I:= 0 to 9-2 do if List(I) > List(I+1) then quit;
]; \quit loop when digits are not in ascending order
Score:= 0;
loop [for I:= 0 to 9-1 do [IntOut(0, List(I)); ChOut(0, ^ )];
Num:= 0; for I:= 0 to 9-1 do Num:= Num*10 + List(I);
if Num = 123456789 then quit;
Text(0, "^M^JReverse how many digits? "); Rev:= IntIn(0);
for I:= 0 to Rev/2-1 do
[Temp:= List(I); List(I):= List(Rev-1-I); List(Rev-1-I):= Temp];
Score:= Score+1;
];
Text(0, "^M^JCongrats! You did it in "); IntOut(0, Score);
Text(0, " moves!!^M^J");
] |
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.
| #Julia | Julia | function nimgame()
tcount = 12
takenum = 0
while true
while true
permitted = collect(1:min(3,tcount))
println("$tcount tokens remain.\nHow many do you take ($permitted)? ")
takenum = parse(Int, strip(readline(stdin)))
if takenum in permitted
break
end
end
tcount -= 4
println("Computer takes $(4 - takenum). There are $tcount tokens left.")
if tcount < 1
println("Computer wins as expected.")
break
end
end
end
nimgame()
|
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.
| #Kotlin | Kotlin | // Version 1.3.21
fun showTokens(tokens: Int) {
println("Tokens remaining $tokens\n")
}
fun main() {
var tokens = 12
while (true) {
showTokens(tokens)
print(" How many tokens 1, 2 or 3? ")
var t = readLine()!!.toIntOrNull()
if (t == null || t < 1 || t > 3) {
println("\nMust be a number between 1 and 3, try again.\n")
} else {
var ct = 4 - t
var s = if (ct > 1) "s" else ""
println(" Computer takes $ct token$s\n")
tokens -= 4
}
if (tokens == 0) {
showTokens(0)
println(" Computer wins!")
return
}
}
} |
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.
| #bc | bc | /* Take the nth root of 'a' (a positive real number).
* 'n' must be an integer.
* Result will have 'd' digits after the decimal point.
*/
define r(a, n, d) {
auto e, o, x, y, z
if (n == 0) return(1)
if (a == 0) return(0)
o = scale
scale = d
e = 1 / 10 ^ d
if (n < 0) {
n = -n
a = 1 / a
}
x = 1
while (1) {
y = ((n - 1) * x + a / x ^ (n - 1)) / n
z = x - y
if (z < 0) z = -z
if (z < e) break
x = y
}
scale = o
return(y)
} |
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']
| #AppleScript | AppleScript | use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use sorter : script "Custom Iterative Ternary Merge Sort" -- <https://macscripter.net/viewtopic.php?pid=194430#p194430>
on naturalSort(listOfText)
-- Produce versions of the strings for sorting purposes, doctored to get round
-- the situations AppleScript's comparison attributes don't handle naturally.
script o
property input : listOfText
property doctored : {}
end script
set regex to current application's NSRegularExpressionSearch
repeat with i from 1 to (count listOfText)
set thisString to (current application's class "NSMutableString"'s stringWithString:(item i of o's input))
-- AppleScript's 'ignoring white space' setting ignores ALL white space. So, since the existence of
-- white space between words has to be considered, physically remove or alter any to be ignored.
-- Firstly reduce runs of any type of white space to single 'space' characters.
tell thisString to replaceOccurrencesOfString:("\\s++") withString:(space) options:(regex) range:({0, its |length|()})
-- Then remove any leading and/or trailing spaces.
tell thisString to replaceOccurrencesOfString:("^ | $") withString:("") options:(regex) range:({0, its |length|()})
-- Move any instance of "The ", "A ", or "An " at the front of a string to the end assuming the string to be a title.
-- This allows the article to act as a tie-breaker if necessary.
tell thisString to replaceOccurrencesOfString:("^(?i)(The|An?) (.++)$") withString:("$2 $1") options:(regex) ¬
range:({0, its |length|()})
-- For the sake of this task, replace any instances of "ſ" or "ʒ" with "s".
tell thisString to replaceOccurrencesOfString:("[\\u0292\\u017f]") withString:("s") options:(regex) ¬
range:({0, its |length|()})
set end of o's doctored to thisString as text
end repeat
-- Set AppleScript's string comparison attributes for the sort.
-- Ligatures are always compared by their component characters and AppleScript has no setting to change this.
-- 'Numeric strings' are runs of digit characters only.
-- The white space, hyphens, and case settings here are the defaults,
-- but are set explicitly in case this handler's called from a different setting.
considering numeric strings, white space and hyphens but ignoring diacriticals, punctuation and case
-- Sort items 1 thru -1 of the doctored strings, rearranging the original list in parallel.
tell sorter to sort(o's doctored, 1, -1, {slave:{listOfText}})
end considering
return listOfText
end naturalSort
(* Tests: *)
-- Leading, trailing, and multiple white spaces ignored:
naturalSort({" ignore superfluous spaces: 1-3", "ignore superfluous spaces: 1-1", " ignore superfluous spaces: 1-2", ¬
" ignore superfluous spaces: 1-4", "ignore superfluous spaces: 1-7", "ignore superfluous spaces: 1-5 ", ¬
"ignore superfluous spaces: 1-6", " ignore superfluous spaces: 1-8"})
--> {"ignore superfluous spaces: 1-1", " ignore superfluous spaces: 1-2", " ignore superfluous spaces: 1-3", " ignore superfluous spaces: 1-4", "ignore superfluous spaces: 1-5 ", "ignore superfluous spaces: 1-6", "ignore superfluous spaces: 1-7", " ignore superfluous spaces: 1-8"}
-- All white space characters treated as equivalent:
naturalSort({"Equiv. spaces: 2-6", "Equiv." & return & "spaces: 2-5", "Equiv." & (character id 12) & "spaces: 2-4", ¬
"Equiv." & (character id 11) & "spaces: 2-3", "Equiv." & linefeed & "spaces: 2-2", "Equiv." & tab & "spaces: 2-1"})
(* -->
{"Equiv. spaces: 2-1", "Equiv.
spaces: 2-2", "Equiv.�spaces: 2-3", "Equiv.�spaces: 2-4", "Equiv.
spaces: 2-5", "Equiv. spaces: 2-6"}
*)
-- Case ignored. (The order would actually be the same with case considered,
-- because case only decides the issue when strings are otherwise identical.)
naturalSort({"cASE INDEPENDENT: 3-1", "caSE INDEPENDENT: 3-2", "CASE independent: 3-3", "casE INDEPENDENT: 3-4", ¬
"case INDEPENDENT: 3-5"})
--> {"cASE INDEPENDENT: 3-1", "caSE INDEPENDENT: 3-2", "CASE independent: 3-3", "casE INDEPENDENT: 3-4", "case INDEPENDENT: 3-5"}
-- Numerics considered by number value:
naturalSort({"foo1000bar99baz10.txt", "foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz9.txt"})
--> {"foo100bar10baz0.txt", "foo100bar99baz0.txt", "foo1000bar99baz9.txt", "foo1000bar99baz10.txt"}
-- Title sort:
naturalSort({"The Wind in the Willows", "The 40th Step More", "A Matter of Life and Death", "The 39 steps", ¬
"An Inspector Calls", "Wanda"})
--> {"The 39 steps", "The 40th Step More", "An Inspector Calls", "A Matter of Life and Death", "Wanda", "The Wind in the Willows"}
--> Diacriticals (and case) ignored:
naturalSort({"Equiv. " & (character id 253) & " accents: 6-1", "Equiv. " & (character id 221) & " accents: 6-3", ¬
"Equiv. y accents: 6-4", "Equiv. Y accents: 6-2"})
--> {"Equiv. ý accents: 6-1", "Equiv. Y accents: 6-2", "Equiv. Ý accents: 6-3", "Equiv. y accents: 6-4"}
-- Ligatures:
naturalSort({(character id 306) & " ligatured", "of", "ij no ligature", (character id 339), "od"})
--> {"IJ ligatured", "ij no ligature", "od", "œ", "of"}
-- Custom "s" equivalents and Esszet (Esszet normalises to ss):"
naturalSort({"Start with an " & (character id 658) & ": 8-1", "Start with an " & (character id 383) & ": 8-2", ¬
"Start with an " & (character id 223) & ": 8-3", "Start with an s: 8-4", "Start with an ss: 8-5"})
--> {"Start with an ʒ: 8-1", "Start with an ſ: 8-2", "Start with an s: 8-4", "Start with an ß: 8-3", "Start with an ss: 8-5"} |
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.
| #J | J | #!/j602/bin/jconsole
main=:3 : 0
self=: '#!/j602/bin/jconsole',LF,'main=:',(5!:5<'main'),LF,'main''''',LF
echo self -: stdin''
)
main'' |
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.
| #Java | Java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Narcissist {
private static final String SOURCE = "import java.io.BufferedReader;%nimport java.io.IOException;%nimport java.io.InputStreamReader;%n%npublic class Narcissist {%n private static final String SOURCE = %c%s%c;%n private static final char QUOTE = 0x22;%n%n public static void main(String[] args) throws IOException {%n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));%n StringBuilder sb = new StringBuilder();%n%n while (true) {%n String line = br.readLine();%n if (null == line) break;%n sb.append(line).append(System.lineSeparator());%n }%n%n String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);%n if (program.equals(sb.toString())) {%n System.out.println(%caccept%c);%n } else {%n System.out.println(%creject%c);%n }%n }%n}%n";
private static final char QUOTE = 0x22;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
while (true) {
String line = br.readLine();
if (null == line) break;
sb.append(line).append(System.lineSeparator());
}
String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);
if (program.equals(sb.toString())) {
System.out.println("accept");
} else {
System.out.println("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)
| #360_Assembly | 360 Assembly | MODE ℵ SIMPLEOUT = UNION (≮ℒ INT≯, ≮ℒ REAL≯, ≮ℒ COMPL≯, BOOL, ≮ℒ BITS≯, CHAR, [ ] CHAR);
PROC ℓ cos = (ℒ REAL x) ℒ REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;
PROC ℓ complex cos = (ℒ COMPL z) ℒ COMPL: ¢ a ℒ complex value close to the cosine of 'z' ¢;
PROC ℓ arccos = (ℒ REAL x) ℒ REAL: ¢ if ABS x ≤ ℒ 1, a ℒ real value close
to the inverse cosine of 'x', ℒ 0 ≤ ℒ arccos (x) ≤ ℒ pi ¢; |
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)
| #6502_Assembly | 6502 Assembly | MODE ℵ SIMPLEOUT = UNION (≮ℒ INT≯, ≮ℒ REAL≯, ≮ℒ COMPL≯, BOOL, ≮ℒ BITS≯, CHAR, [ ] CHAR);
PROC ℓ cos = (ℒ REAL x) ℒ REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;
PROC ℓ complex cos = (ℒ COMPL z) ℒ COMPL: ¢ a ℒ complex value close to the cosine of 'z' ¢;
PROC ℓ arccos = (ℒ REAL x) ℒ REAL: ¢ if ABS x ≤ ℒ 1, a ℒ real value close
to the inverse cosine of 'x', ℒ 0 ≤ ℒ arccos (x) ≤ ℒ pi ¢; |
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)
| #ALGOL_68 | ALGOL 68 | MODE ℵ SIMPLEOUT = UNION (≮ℒ INT≯, ≮ℒ REAL≯, ≮ℒ COMPL≯, BOOL, ≮ℒ BITS≯, CHAR, [ ] CHAR);
PROC ℓ cos = (ℒ REAL x) ℒ REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;
PROC ℓ complex cos = (ℒ COMPL z) ℒ COMPL: ¢ a ℒ complex value close to the cosine of 'z' ¢;
PROC ℓ arccos = (ℒ REAL x) ℒ REAL: ¢ if ABS x ≤ ℒ 1, a ℒ real value close
to the inverse cosine of 'x', ℒ 0 ≤ ℒ arccos (x) ≤ ℒ pi ¢; |
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
| #Phix | Phix | function nigh(string n)
sequence p = repeat("",factorial(length(n)))
for i=1 to length(p) do
p[i] = permute(i,n)
end for
p = sort(p)
integer k = rfind(n,p)
return iff(k=length(p)?"0",p[k+1])
end function
constant tests = {"0","9","12","21","12453",
"738440","45072010","95322020"}
-- (crashes on) "9589776899767587796600"}
atom t0 = time()
for i=1 to length(tests) do
string t = tests[i]
printf(1,"%22s => %s\n",{t,nigh(t)})
end for
?elapsed(time()-t0)
|
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
| #Julia | Julia | function makelist(sep::String)
cnt = 1
function makeitem(item::String)
rst = string(cnt, sep, item, '\n')
cnt += 1
return rst
end
return 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
| #Kotlin | Kotlin | // version 1.0.6
fun makeList(sep: String): String {
var count = 0
fun makeItem(item: String): String {
count++
return "$count$sep$item\n"
}
return makeItem("first") + makeItem("second") + makeItem("third")
}
fun main(args: Array<String>) {
print(makeList(". "))
} |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | LocalSubmit[ScheduledTask[
EmitSound[Sound[Table[{
SoundNote["C",750/1000,"TubularBells"],SoundNote[None,500/1000,"TubularBells"]
},Mod[Round[Total[DateList[][[{4,5}]]{2,1/30}]],8,1]]]]
,DateObject[{_,_,_,_,_,30|0}]]] |
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
| #Nim | Nim | import os, strformat, times
const
Watches = ["First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First"]
WatchEnds = [(0, 0), (4, 0), (8, 0), (12, 0), (16, 0), (18, 0), (20, 0), (23, 59)]
Bells = array[1..8, string](["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"])
Ding = "ding!"
proc nb(h, m: Natural) =
var bell = (h * 60 + m) div 30 mod 8
if bell == 0: bell = 8
let hm = (h, m)
var watch = 0
while hm > WatchEnds[watch]: inc watch
let plural = if bell == 1: ' ' else: 's'
var dings = Ding
for i in 2..bell:
if i mod 2 != 0: dings.add ' '
dings.add Ding
echo &"{h:02d}:{m:02d} {Watches[watch]:>9} watch {Bells[bell]:>5} bell{plural} {dings}"
proc simulateOneDay() =
for h in 0..23:
for m in [0, 30]:
nb(h, m)
nb(0, 0)
when isMainModule:
simulateOneDay()
while true:
let d = getTime().utc()
var m = d.second + (d.minute mod 30) * 60
if m == 0:
nb(d.hour, d.minute)
sleep((1800 - m) * 1000) # In milliseconds. |
http://rosettacode.org/wiki/Nonogram_solver | Nonogram solver | A nonogram is a puzzle that provides
numeric clues used to fill in a grid of cells,
establishing for each cell whether it is filled or not.
The puzzle solution is typically a picture of some kind.
Each row and column of a rectangular grid is annotated with the lengths
of its distinct runs of occupied cells.
Using only these lengths you should find one valid configuration
of empty and occupied cells, or show a failure message.
Example
Problem: Solution:
. . . . . . . . 3 . # # # . . . . 3
. . . . . . . . 2 1 # # . # . . . . 2 1
. . . . . . . . 3 2 . # # # . . # # 3 2
. . . . . . . . 2 2 . . # # . . # # 2 2
. . . . . . . . 6 . . # # # # # # 6
. . . . . . . . 1 5 # . # # # # # . 1 5
. . . . . . . . 6 # # # # # # . . 6
. . . . . . . . 1 . . . . # . . . 1
. . . . . . . . 2 . . . # # . . . 2
1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3
2 1 5 1 2 1 5 1
The problem above could be represented by two lists of lists:
x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]
y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]
A more compact representation of the same problem uses strings,
where the letters represent the numbers, A=1, B=2, etc:
x = "C BA CB BB F AE F A B"
y = "AB CA AE GA E C D C"
Task
For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content
(the blank lines are separators):
C BA CB BB F AE F A B
AB CA AE GA E C D C
F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC
D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA
CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC
BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC
E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G
E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM
Extra credit: generate nonograms with unique solutions, of desired height and width.
This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).
Related tasks
Nonoblock.
See also
Arc Consistency Algorithm
http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)
http://twanvl.nl/blog/haskell/Nonograms (Haskell)
http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
| #REXX | REXX | /*REXX*/
Parse Arg fn
Parse Var fn ou'.'
maxpn = 10000 /* maximum possibilities to check through */
output = ou'.out.txt'
/* read row/col values into rowpp. and colpp. arrays */
cc = linein(fn)
rows = words(cc)
dd = linein(fn)
cols = words(dd)
char = '0ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk'
cntr = 0
Do i = 1 To rows
rowpp.i = CV(cc,i)
cntr = cntr + sum
End
cntc = 0
Do i = 1 To cols
colpp.i = CV(dd,i)
cntc = cntc + sum
End
If (cntr <> cntc)|(cntr = 0) Then Do
Say 'error Sum of rows <> sum of cols'
Exit 999
End
Say cntr 'colored cells'
ar = copies('-',rows*cols)
/* values are -=unknown .=blank @=Color */
/* PREFILL array */
'erase' output
/**********COL PREFILL ************/
Do col = 1 To cols
r = colpp.col
Parse Var r z r
Do While r <> ''
Parse Var r q r
z = z + q + 1
End
result = copies('-',rows)
If z = rows Then result = FILL_LINE(colpp.col)
Else If z = 0 Then result = copies('.',rows)
Do row = 1 To rows
ar = overlay(substr(result,row,1),ar,(row-1)*cols+col)
End
End
/**********ROW PREFILL ************/
Do row = 1 To rows
c = rowpp.row
Parse Var c t c
Do While c <> ''
Parse Var c q c
t = t + q + 1
End
result = substr(ar,(row-1)*cols+1,cols)
If t = cols Then result = left(FILL_LINE(rowpp.row),cols)
Else If t = 0 Then result = copies('.',cols)
ar = overlay(result,ar,(row-1)*cols+1)
End
/********** ok here we loop ************/
cnttry = 1
nexttry = 2
next.cnttry = ar
sol = 0
Do label nextpos While cnttry < nexttry
Say 'trying' cnttry 'of' nexttry-1
ar = next.cnttry
cnttry = cnttry + 1
Do Until sar = ar
sar = ar
Do row = 1 To rows
/**********process rows ************/
rowcol = substr(ar,(row-1)*cols+1,cols)
pp = rowpp.row
If PROCESSROW() Then Iterate nextpos
Else ar = overlay(left(rowcol,cols),ar,(row-1)*cols+1)
End
Do col = 1 To cols
rowcol = ''
Do row = 1 To rows
rowcol = rowcol || substr(ar,(row-1)*cols+ col,1)
End
pp = colpp.col
If PROCESSROW() Then Iterate nextpos
Do row = 1 To rows
ar = overlay(substr(rowcol,row,1),ar,(row-1)*cols + col)
End
End
If pos('-',ar) = 0 Then Do /* hurray we have a solution */
/* at this point we need to verify solution */
If CHECKBOARD() Then Iterate nextpos /* too bad didn't match */
sol = sol + 1
Call LINEOUT output,'This is solution no:' sol
Call DUMPBOARD
Iterate nextpos
End
If sar = ar Then Do
fnd = pos('-',ar)
next.nexttry = overlay('.',ar,fnd)
nexttry = nexttry + 1
ar = overlay('@',ar,fnd)
End
End
End nextpos
If sol = 0 Then sol = 'No'
Say sol 'solutions found'
Exit
CHECKBOARD:
Do row = 1 To rows
/**********process rows ************/
rowcol = substr(ar,(row-1)*cols+1,cols)
pp = rowpp.row
If CHECKROW() Then Return 1
End
Do col = 1 To cols
rowcol = ''
Do row = 1 To rows
rowcol = rowcol || substr(ar,(row-1)*cols+ col,1)
End
pp = colpp.col
If CHECKROW() Then Return 1
End
Return 0 /* we did it */
CHECKROW:
len_item = length(rowcol)
st = 1
If pp = 0 Then Return rowcol <> copies('.',len_item)
Else If pp = len_item Then Return rowcol <> copies('@',len_item)
Do While (pp <> '') & (st <= len_item)
Parse Var pp p1 pp
of = pos('@',rowcol'@',st)
If of > len_item Then Return 1
If substr(rowcol,of,p1) <> copies('@',p1) Then Return 1
st = of + p1
If substr(rowcol'.',st,1) <> '.' Then Return 1
End
Return 0
DUMPBOARD:
Parse Arg qr
p = '..'
q = '..'
Do i = 1 To cols
n = right(i,2)
p = p left(n,1)
q = q right(n,1)
End
Call LINEOUT output, p
Call LINEOUT output, q
Do i = 1 To rows
o = right(i,2)
p = substr(ar,(i-1)*cols+1,cols)
Do j = 1 To cols
Parse Var p z +1 p
o = o z
End
Call LINEOUT output, o
End
Return
FILL_LINE:
Parse Arg items
oo = ''
Do While items <> ''
Parse Var items a items
oo = oo||copies('@',a)'.'
End
Return oo
CV:
Parse Arg cnts, rwcl
str = word(cnts,rwcl)
ret = ''
sum = 0
Do k = 1 To length(str)
this = pos(substr(str,k,1),char)-1
ret = ret this
sum = sum + this
End
Return space(ret)
PROCESSROW: /* rowcol pp in, rowcol pp of ol */
prerow = rowcol
len_item = length(rowcol)
If pos('-',rowcol) = 0 Then Do
pp = ''
Return 0
End
of = 1
kcnt = 0
/* reduce the left side with already populated values */
Do While (of < len_item) & (pp <> '')
kcnt = kcnt + 1
If kcnt > len_item Then Return 1
If substr(rowcol,of,1) = '.' Then Do
k = verify(substr(rowcol,of)'%','.')
of = of + k - 1
Iterate
End
nl = word(pp,1)
len = verify(substr(rowcol,of)'%','-@') - 1
If len < nl Then Do
rowcol = overlay(copies('.',len),rowcol,of)
of = of + len
Iterate
End
If (len = nl) & (pos('@',substr(rowcol,of,nl))>0) Then Do
rowcol = overlay(copies('@',nl),rowcol,of)
of = of + nl
pp = subword(pp,2)
Iterate
End
If substr(rowcol,of,1) = '@' Then Do
rowcol = overlay(copies('@',nl)'.',rowcol,of)
of = of + nl
pp = subword(pp,2)
Iterate
End
Leave
End
/* reduce the right side with already populated values */
ofm = len_item + 1 - of
ol = 1
kcnt = 0
Do While (ol < ofm) & (pp <> '')
kcnt = kcnt + 1
If kcnt > len_item Then Return 1
revrow = reverse(rowcol)
If substr(revrow,ol,1) = '.' Then Do
k = verify(substr(revrow,ol)'%','.')
ol = ol + k - 1
Iterate
End
nl = word(pp,words(pp))
len = verify(substr(revrow,ol)'%','-@') - 1
If len < nl Then Do
rowcol = overlay(copies('.',len),rowcol,len_item-ol-len+2)
ol = ol + len
Iterate
End
If (len = nl) & (pos('@',substr(revrow,ol,nl))>0) Then Do
rowcol = overlay(copies('@',nl),rowcol,len_item-ol-nl+2)
ol = ol + nl
pp = subword(pp,1,words(pp)-1)
Iterate
End
If substr(revrow,ol,1) = '@' Then Do
rowcol = overlay('.'copies('@',nl),rowcol,len_item-ol-nl+1)
ol = ol + nl
pp = subword(pp,1,words(pp)-1)
Iterate
End
Leave
End
If pp = 0 Then pp = ''
If pp = '' Then rowcol = changestr('-',rowcol,'.')
If pp <> '' Then Do
lv = len_item-of-ol+2
pos. = ''
pn = 0
pi = substr(rowcol,of,lv)
If (copies('-',length(pi)) = pi) Then Do
len = CNT(pp)
If (len + mx) <= lv Then Do
Return 0
End
End
/* oh oh need to check for posibilities */
Call TRY '',pp
If pn > maxpn Then Do
over = over + 1
Return 0
End
fnd = 0
fu = pos.1
Do z = 2 To pn
Do j = 1 To lv
If substr(fu,j,1) <> substr(pos.z,j,1) Then fu = overlay('-',fu,j)
End
End
Do z = 1 To lv
If substr(fu,z,1) <> '-' Then rowcol = overlay(substr(fu,z,1),rowcol,of+z-1)
End
End
Return 0
TRY: Procedure Expose pn pos. maxpn lv pi
Parse Arg prev,pp
If pp = '' Then Do
rem = substr(pi,length(prev)+1)
If translate(rem,'..','.-') <> copies('.',length(rem)) Then Return
prev = left(prev||copies('.',lv),lv)
pn = pn + 1
If pn > maxpn Then Return
pos.pn = prev
Return
End
Parse Var pp p1 pp
If length(prev)+p1 > lv Then Return
Do i = 0 To lv - length(prev)-p1
If translate(substr(pi,length(prev)+1,i),'..','.-') = copies('.',i) Then
If translate(substr(pi,length(prev)+i+1,p1),'@@','@-') = copies('@',p1) Then
If substr(pi,length(prev)+i+p1+1,1) <> '@' Then
Call TRY prev||copies('.',i)||copies('@',p1)'.',pp
End
Return
CNT: Procedure Expose mx
Parse Arg len items
mx = len
Do While items <> ''
Parse Var items ii items
len = len + ii + 1
If ii > mx Then mx = ii
End
Return len |
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
| #Nim | Nim | import sequtils
proc ncsub[T](se: seq[T], s = 0): seq[seq[T]] =
result = @[]
if se.len > 0:
let
x = se[0..0]
xs = se[1 .. ^1]
p2 = s mod 2
p1 = (s + 1) mod 2
for ys in ncsub(xs, s + p1):
result.add(x & ys)
result.add(ncsub(xs, s + p2))
elif s >= 3:
result.add(@[])
echo "ncsub(", toSeq 1.. 3, ") = ", ncsub(toSeq 1..3)
echo "ncsub(", toSeq 1.. 4, ") = ", ncsub(toSeq 1..4)
echo "ncsub(", toSeq 1.. 5, ") = ", ncsub(toSeq 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
| #OCaml | OCaml | let rec fence s = function
[] ->
if s >= 3 then
[[]]
else
[]
| x :: xs ->
if s mod 2 = 0 then
List.map
(fun ys -> x :: ys)
(fence (s + 1) xs)
@
fence s xs
else
List.map
(fun ys -> x :: ys)
(fence s xs)
@
fence (s + 1) xs
let ncsubseq = fence 0 |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Elixir | Elixir | iex(1)> String.to_integer("ffff", 16)
65535
iex(2)> Integer.to_string(255, 2)
"11111111"
iex(3)> String.to_integer("NonDecimalRadices", 36)
188498506820338115928429652 |
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated).
The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that.
The reverse operation is in task Non-decimal radices/Output
For general number base conversion, see Non-decimal radices/Convert.
| #Ring | Ring |
see number("0") + nl
see number("123456789") + nl
see number("-987654321") + nl
|
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated).
The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that.
The reverse operation is in task Non-decimal radices/Output
For general number base conversion, see Non-decimal radices/Convert.
| #Ruby | Ruby | dec1 = "0123459"
hex2 = "abcf123"
oct3 = "7651"
bin4 = "101011001"
p dec1.to_i # => 123459
p hex2.hex # => 180154659
p oct3.oct # => 4009
# nothing for binary |
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.
| #R | R | # dec to oct
as.octmode(x)
# dec to hex
as.hexmode(x)
# oct or hex to dec
as.integer(x)
# or
as.numeric(x) |
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.
| #Racket | Racket |
#lang racket
;; Explicit conversion of numbers can use the standard radices
(map (λ(r) (number->string 123 r)) '(2 8 10 16))
;; -> '("1111011" "173" "123" "7b")
;; There is also the `~r' formatting function that works with any radix
;; up to 36
(for/list ([r (in-range 2 37)]) (~r 123 #:base r))
;; -> '("1111011" "02111" "3231" "344" "323" "432" "173" "641" "123" "201"
;; "3a" "69" "b8" "38" "7b" "47" "f6" "96" "36" "i5" "d5" "85" "35"
;; "n4" "j4" "f4" "b4" "74" "34" "u3" "r3" "o3" "l3" "i3" "f3")
|
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.
| #jq | jq | def trunc: if . >= 0 then floor else -(-(.)|trunc) end; |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary (expect 21102)
Encode the decimal number 15 as negadecimal (expect 195)
In each of the above cases, convert the encoded number back to decimal.
extra credit
supply an integer, that when encoded to base -62 (or something "higher"), expresses the
name of the language being used (with correct capitalization). If the computer language has
non-alphanumeric characters, try to encode them into the negatory numerals, or use other
characters instead.
| #Julia | Julia |
function negbase(n, b)
if n == 0 return "0" end
out = IOBuffer()
while n != 0
n, r = divrem(n, b)
if r < 0
n += 1
r -= b
end
print(out, r)
end
return reverse(String(out))
end
invnegbase(nst, b) = sum((ch - '0') * b ^ (i - 1) for (i, ch) in enumerate(reverse(nst)))
testset = Dict(
(10, -2) => "11110",
(143, -3) => "21102",
(15, -10) => "195")
for ((num, base), rst) in testset
encoded = negbase(num, base)
decoded = invnegbase(encoded, base)
println("\nencode $num in base $base:\n-> expected: $rst\n-> resulted: $encoded\n-> decoded: $decoded")
end |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Dim i As Integer
Console.WriteLine("Enter a number")
i = Console.ReadLine()
Console.WriteLine(words(i))
Console.ReadLine()
End Sub
Function words(ByVal Number As Integer) As String
Dim small() As String = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"}
Dim tens() As String = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}
Select Case Number
Case Is < 20
words = small(Number)
Case 20 To 99
words = tens(Number \ 10) + " " + small(Number Mod 10)
Case 100 To 999
words = small(Number \ 100) + " hundred " + IIf(((Number Mod 100) <> 0), "and ", "") + words(Number Mod 100)
Case 1000
words = "one thousand"
End Select
End Function
End Module |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Yabasic | Yabasic | // Rosetta Code problem: https://www.rosettacode.org/wiki/Number_reversal_game
// by Jjuanhdez, 06/2022
print "Given a jumbled list of the numbers 1 to 9, "
print "you must select how many digits from the left "
print "to reverse. Your goal is to get the digits in "
print "order with 1 on the left and 9 on the right.\n"
dim nums(10)
dim a(10)
intentos = 0: denuevo = true: colum = 6
//valores iniciales
for i = 1 to 9
nums(i) = i
next i
for i = 9 to 2 step -1
n = int(ran(i)) + 1
if n <> i then
a(i) = nums(i)
nums(i) = nums(n)
nums(n) = a(i)
fi
next i
repeat
if intentos < 10 print " ";
print intentos, ": ";
for i = 1 to 9
print nums(i), " ";
next i
if not denuevo break
input " -- How many do we flip " volteo
if volteo < 0 or volteo > 9 volteo = 0
for i = 1 to int(volteo / 2)
a(i) = nums(volteo - i + 1)
nums(volteo - i + 1) = nums(i)
nums(i) = a(i)
next i
denuevo = false
//comprobamos el orden
for i = 1 to 8
if nums(i) > nums(i + 1) then
denuevo = true
break
fi
next i
if volteo > 0 intentos = intentos + 1
until false
print "\n\n You needed ", intentos, " attempts."
end |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Lua | Lua |
tokens = 12
print("Nim Game\n")
print("Starting with " .. tokens .. " tokens.\n\n")
function printRemaining()
print(tokens .. " tokens remaining.\n")
end
function playerTurn(take)
take = math.floor(take)
if (take < 1 or take > 3) then
print ("\nTake must be between 1 and 3.\n")
return false
end
tokens = tokens - take
print ("\nPlayer takes " .. take .. " tokens.")
printRemaining()
return true
end
function computerTurn()
take = tokens % 4
tokens = tokens - take
print("Computer takes " .. take .. " tokens.")
printRemaining()
end
while (tokens > 0) do
io.write("How many tokens would you like to take?: ")
if playerTurn(io.read("*n")) then
computerTurn()
end
end
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | n = 12;
While[n > 0,
c = ChoiceDialog["Current amount = " <> ToString[n] <> "\nHow many do you want to pick?", {1 -> 1, 2 -> 2, 3 -> 3}];
n -= c;
ChoiceDialog["Current amount = " <> ToString[n] <> "\nComputer takes " <> ToString[4 - c]];
n -= (4 - c);
]
ChoiceDialog["Current amount = " <> ToString[n] <> "\n You lost!"] |
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.
| #BQN | BQN | _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Root ← √
Root1 ← ⋆⟜÷˜
Root2 ← {
n 𝕊 a‿prec:
1⊑{
p‿x:
⟨
x
((p × n - 1) + a ÷ p ⋆ n - 1) ÷ n
⟩
} _while_ {
p‿x:
prec ≤ | p - x
} ⟨a, ⌊a÷n⟩;
𝕨 𝕊 𝕩: 𝕨 𝕊 𝕩‿1E¯5
}
•Show 3 Root 5
•Show 3 Root1 5
•Show 3 Root2 5
•Show 3 Root2 5‿1E¯16 |
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.
| #Bracmat | Bracmat | ( ( root
= n a d x0 x1 d2 rnd 10-d
. ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. }
= N r
. !arg:(?N.?r)
& div$(!N*!r+1/2.1)*!r^-1
)
& !arg:(?n,?a,?d)
& !a*!n^-1:?x0
& 10^(-1*!d):?10-d
& whl
' ( ( rnd$(((!n+-1)*!x0+!a*!x0^(1+-1*!n))*!n^-1.10^!d)
. !x0
)
: (?x0.?x1)
& (!x0+-1*!x1)^2:~<!10-d { Exit loop when required precision is reached. }
)
& flt$(!x0,!d) { Convert rational number to floating point representation. }
)
& ( show
= N A precision
. !arg:(?N,?A,?precision)
& out$(str$(!A "^(" !N^-1 ")=" root$(!N,!A,!precision)))
)
& show$(10,1024,20)
& show$(3,27,20)
& show$(2,2,100)
& show$(125,5642,20)
) |
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']
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <wctype.h>
#include <string.h>
#include <locale.h>
typedef struct wstr {
wchar_t *s;
int n, alloc;
} wstr;
#define w_del(w) { free(w->s); free(w); }
#define forchars(i, c, w) for(i = 0, c = w->s[0]; i < w->n && c; c = w->s[++i])
wstr *w_new()
{
wstr *w = malloc(sizeof(wstr));
w->alloc = 1;
w->n = 0;
w->s = malloc(sizeof(wchar_t));
w->s[0] = 0;
return w;
}
void w_append(wstr *w, wchar_t c)
{
int n = w->n + 1;
if (n >= w->alloc) {
w->alloc *= 2;
w->s = realloc(w->s, w->alloc * sizeof(wchar_t));
}
w->s[w->n++] = c;
w->s[w->n] = 0;
}
wstr *w_make(wchar_t *s)
{
int i, len = wcslen(s);
wstr *w = w_new();
for (i = 0; i < len; i++) w_append(w, s[i]);
return w;
}
typedef void (*wtrans_func)(wstr *, wstr *);
void w_transform(wstr *in, wtrans_func f)
{
wstr t, *out = w_new();
f(in, out);
t = *in; *in = *out; *out = t;
w_del(out);
}
#define transfunc(x) void w_##x(wstr *in, wstr *out)
transfunc(nocase) {
int i;
wchar_t c;
forchars(i, c, in) w_append(out, towlower(c));
}
transfunc(despace) {
int i, gotspace = 0;
wchar_t c;
forchars(i, c, in) {
if (!iswspace(c)) {
if (gotspace && out->n)
w_append(out, L' ');
w_append(out, c);
gotspace = 0;
} else gotspace = 1;
}
}
static const wchar_t *const tbl_accent[] = { /* copied from Raku code */
L"Þ", L"TH", L"þ", L"th", L"Ð", L"TH", L"ð", L"th", L"À", L"A",
L"Á", L"A", L"Â", L"A", L"Ã", L"A", L"Ä", L"A", L"Å", L"A", L"à",
L"a", L"á", L"a", L"â", L"a", L"ã", L"a", L"ä", L"a", L"å", L"a",
L"Ç", L"C", L"ç", L"c", L"È", L"E", L"É", L"E", L"Ê", L"E", L"Ë",
L"E", L"è", L"e", L"é", L"e", L"ê", L"e", L"ë", L"e", L"Ì",
L"I", L"Í", L"I", L"Î", L"I", L"Ï", L"I", L"ì", L"i", L"í",
L"i", L"î", L"i", L"ï", L"i", L"Ò", L"O", L"Ó", L"O", L"Ô",
L"O", L"Õ", L"O", L"Ö", L"O", L"Ø", L"O", L"ò", L"o", L"ó", L"o",
L"ô", L"o", L"õ", L"o", L"ö", L"o", L"ø", L"o", L"Ñ", L"N", L"ñ", L"n",
L"Ù", L"U", L"Ú", L"U", L"Û", L"U", L"Ü", L"U", L"ù", L"u", L"ú", L"u",
L"û", L"u", L"ü", L"u", L"Ý", L"Y", L"ÿ", L"y", L"ý", L"y" };
static const wchar_t *const tbl_ligature[] = {
L"Æ", L"AE", L"æ", L"ae", L"ß", L"ss",
L"ffl", L"ffl", L"ffi", L"ffi", L"fi", L"fi", L"ff", L"ff", L"fl", L"fl",
L"ſ", L"s", L"ʒ", L"z", L"st", L"st", /* ... come on ... */
};
void w_char_repl(wstr *in, wstr *out, const wchar_t *const *tbl, int len)
{
int i, j, k;
wchar_t c;
forchars(i, c, in) {
for (j = k = 0; j < len; j += 2) {
if (c != tbl[j][0]) continue;
for (k = 0; tbl[j + 1][k]; k++)
w_append(out, tbl[j + 1][k]);
break;
}
if (!k) w_append(out, c);
}
}
transfunc(noaccent) {
w_char_repl(in, out, tbl_accent, sizeof(tbl_accent)/sizeof(wchar_t*));
}
transfunc(noligature) {
w_char_repl(in, out, tbl_ligature, sizeof(tbl_ligature)/sizeof(wchar_t*));
}
static const wchar_t *const tbl_article[] = {
L"the", L"a", L"of", L"to", L"is", L"it" };
#define N_ARTICLES sizeof(tbl_article)/sizeof(tbl_article[0])
transfunc(noarticle) {
int i, j, n;
wchar_t c, c0 = 0;
forchars(i, c, in) {
if (!c0 || (iswalnum(c) && !iswalnum(c0))) { /* word boundary */
for (j = N_ARTICLES - 1; j >= 0; j--) {
n = wcslen(tbl_article[j]);
if (wcsncasecmp(in->s + i, tbl_article[j], n))
continue;
if (iswalnum(in->s[i + n])) continue;
i += n;
break;
}
if (j < 0) w_append(out, c);
} else
w_append(out, c);
c0 = c;
}
}
enum { wi_space = 0, wi_case, wi_accent, wi_lig, wi_article, wi_numeric };
#define WS_NOSPACE (1 << wi_space)
#define WS_NOCASE (1 << wi_case)
#define WS_ACCENT (1 << wi_accent)
#define WS_LIGATURE (1 << wi_lig)
#define WS_NOARTICLE (1 << wi_article)
#define WS_NUMERIC (1 << wi_numeric)
const wtrans_func trans_funcs[] = {
w_despace, w_nocase, w_noaccent, w_noligature, w_noarticle, 0
};
const char *const flagnames[] = {
"collapse spaces",
"case insensitive",
"disregard accent",
"decompose ligatures",
"discard common words",
"numeric",
};
typedef struct { wchar_t* s; wstr *w; } kw_t;
int w_numcmp(const void *a, const void *b)
{
wchar_t *pa = ((const kw_t*)a)->w->s, *pb = ((const kw_t*)b)->w->s;
int sa, sb, ea, eb;
while (*pa && *pb) {
if (iswdigit(*pa) && iswdigit(*pb)) {
/* skip leading zeros */
sa = sb = 0;
while (pa[sa] == L'0') sa++;
while (pb[sb] == L'0') sb++;
/* find end of numbers */
ea = sa; eb = sb;
while (iswdigit(pa[ea])) ea++;
while (iswdigit(pb[eb])) eb++;
if (eb - sb > ea - sa) return -1;
if (eb - sb < ea - sa) return 1;
while (sb < eb) {
if (pa[sa] > pb[sb]) return 1;
if (pa[sa] < pb[sb]) return -1;
sa++; sb++;
}
pa += ea; pb += eb;
}
else if (iswdigit(*pa)) return 1;
else if (iswdigit(*pb)) return -1;
else {
if (*pa > *pb) return 1;
if (*pa < *pb) return -1;
pa++; pb++;
}
}
return (!*pa && !*pb) ? 0 : *pa ? 1 : -1;
}
int w_cmp(const void *a, const void *b)
{
return wcscmp(((const kw_t*)a)->w->s, ((const kw_t*)b)->w->s);
}
void natural_sort(wchar_t **strings, int len, int flags)
{
int i, j;
kw_t *kws = malloc(sizeof(kw_t) * len);
for (i = 0; i < len; i++) {
kws[i].s = strings[i];
kws[i].w = w_make(strings[i]);
for (j = 0; j < wi_numeric; j++)
if (flags & (1 << j) && trans_funcs[j])
w_transform(kws[i].w, trans_funcs[j]);
}
qsort(kws, len, sizeof(kw_t), (flags & WS_NUMERIC) ? w_numcmp : w_cmp);
for (i = 0; i < len; i++) {
w_del(kws[i].w);
strings[i] = kws[i].s;
}
free(kws);
}
const wchar_t *const test[] = {
L" 0000098 nina", L"100 niño", L"99 Ninja", L"100 NINA",
L" The work is so difficult to do it took ſome 100 aeons. ",
L"The work is so difficult it took some 100 aeons.",
L" The work is so difficult it took ſome 99 æons. ",
};
#define N_STRINGS sizeof(test)/sizeof(*test)
void test_sort(int flags)
{
int i, j;
const wchar_t *str[N_STRINGS];
memcpy(str, test, sizeof(test));
printf("Sort flags: (");
for (i = 0, j = flags; j; i++, j >>= 1)
if ((j & 1))
printf("%s%s", flagnames[i], j > 1 ? ", ":")\n");
natural_sort((wchar_t **)str, N_STRINGS, flags);
for (i = 0; i < N_STRINGS; i++)
printf("%ls\n", str[i]);
printf("\n");
}
int main()
{
setlocale(LC_CTYPE, "");
test_sort(WS_NOSPACE);
test_sort(WS_NOCASE);
test_sort(WS_NUMERIC);
test_sort(WS_NOARTICLE|WS_NOSPACE);
test_sort(WS_NOCASE|WS_NOSPACE|WS_ACCENT);
test_sort(WS_LIGATURE|WS_NOCASE|WS_NOSPACE|WS_NUMERIC|WS_ACCENT|WS_NOARTICLE);
return 0;
} |
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.
| #JavaScript | JavaScript | var code='var q=String.fromCharCode(39);print("var code=" + q + code + q + "; eval(code)" == readline())'; eval(code) |
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.
| #Julia | Julia | mysource = Base.read(Base.source_path(), String)
println(Int(ARGS[1] == mysource)) |
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.
| #Kotlin | Kotlin | // version 1.1.0 (run on Windows 10)
fun main(args: Array<String>) {
val text = java.io.File("narcissist.kt").readText()
println("Enter the number of lines to be input followed by those lines:\n")
val n = readLine()!!.toInt()
val lines = Array<String>(n) { readLine()!! }
if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject")
} |
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)
| #AntLang | AntLang | variables-are-often-lower-case-and-seperated-like-this-one |
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)
| #Arturo | Arturo |
# Field names begin with $ so $1 is the first field, $2 the second and $NF the
# last. $0 references the entire input record.
#
# Function and variable names are case sensitive and begin with an alphabetic
# character or underscore followed by any number of: a-z, A-Z, 0-9, _
#
# The awk language is type less; variables are either string or number
# depending upon usage. Variables can be coerced to string by concatenating ""
# or to number by adding zero. For example:
# str = x ""
# num = x + 0
#
# Below are the names of the built-in functions, built-in variables and other
# reserved words in the awk language separated into categories. Also shown are
# the names of gawk's enhancements.
#
# patterns:
# BEGIN END
# BEGINFILE ENDFILE (gawk)
# actions:
# break continue delete do else exit for if in next return while
# case default switch (gawk)
# arithmetic functions:
# atan2 cos exp int log rand sin sqrt srand
# bit manipulation functions:
# and compl lshift or rshift xor (gawk)
# i18n functions:
# bindtextdomain dcgettext dcngettext (gawk)
# string functions:
# gsub index length match split sprintf sub substr tolower toupper
# asort asorti gensub patsplit strtonum (gawk)
# time functions:
# mktime strftime systime (gawk)
# miscellaneous functions:
# isarray (gawk)
# variables:
# ARGC ARGV CONVFMT ENVIRON FILENAME FNR FS NF NR OFMT OFS ORS RLENGTH RS RSTART SUBSEP
# ARGIND BINMODE ERRNO FIELDWIDTHS FPAT FUNCTAB IGNORECASE LINT PREC PROCINFO ROUNDMODE RT SYMTAB TEXTDOMAIN (gawk)
# function definition:
# func function
# input-output:
# close fflush getline nextfile print printf system
# pre-processor directives:
# @include @load (gawk)
# special files:
# /dev/stdin /dev/stdout /dev/error
|
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)
| #AWK | AWK |
# Field names begin with $ so $1 is the first field, $2 the second and $NF the
# last. $0 references the entire input record.
#
# Function and variable names are case sensitive and begin with an alphabetic
# character or underscore followed by any number of: a-z, A-Z, 0-9, _
#
# The awk language is type less; variables are either string or number
# depending upon usage. Variables can be coerced to string by concatenating ""
# or to number by adding zero. For example:
# str = x ""
# num = x + 0
#
# Below are the names of the built-in functions, built-in variables and other
# reserved words in the awk language separated into categories. Also shown are
# the names of gawk's enhancements.
#
# patterns:
# BEGIN END
# BEGINFILE ENDFILE (gawk)
# actions:
# break continue delete do else exit for if in next return while
# case default switch (gawk)
# arithmetic functions:
# atan2 cos exp int log rand sin sqrt srand
# bit manipulation functions:
# and compl lshift or rshift xor (gawk)
# i18n functions:
# bindtextdomain dcgettext dcngettext (gawk)
# string functions:
# gsub index length match split sprintf sub substr tolower toupper
# asort asorti gensub patsplit strtonum (gawk)
# time functions:
# mktime strftime systime (gawk)
# miscellaneous functions:
# isarray (gawk)
# variables:
# ARGC ARGV CONVFMT ENVIRON FILENAME FNR FS NF NR OFMT OFS ORS RLENGTH RS RSTART SUBSEP
# ARGIND BINMODE ERRNO FIELDWIDTHS FPAT FUNCTAB IGNORECASE LINT PREC PROCINFO ROUNDMODE RT SYMTAB TEXTDOMAIN (gawk)
# function definition:
# func function
# input-output:
# close fflush getline nextfile print printf system
# pre-processor directives:
# @include @load (gawk)
# special files:
# /dev/stdin /dev/stdout /dev/error
|
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
| #Python | Python | def closest_more_than(n, lst):
"(index of) closest int from lst, to n that is also > n"
large = max(lst) + 1
return lst.index(min(lst, key=lambda x: (large if x <= n else x)))
def nexthigh(n):
"Return nxt highest number from n's digits using scan & re-order"
assert n == int(abs(n)), "n >= 0"
this = list(int(digit) for digit in str(int(n)))[::-1]
mx = this[0]
for i, digit in enumerate(this[1:], 1):
if digit < mx:
mx_index = closest_more_than(digit, this[:i + 1])
this[mx_index], this[i] = this[i], this[mx_index]
this[:i] = sorted(this[:i], reverse=True)
return int(''.join(str(d) for d in this[::-1]))
elif digit > mx:
mx, mx_index = digit, i
return 0
if __name__ == '__main__':
for x in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020,
9589776899767587796600]:
print(f"{x:>12_d} -> {nexthigh(x):>12_d}") |
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
| #Lua | Lua | function makeList (separator)
local counter = 0
local function makeItem(item)
counter = counter + 1
return counter .. separator .. item .. "\n"
end
return 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
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Make_List(". ")
Sub Make_List(Separator$)
Local Counter=0
Make_Item("First")
Make_Item("Second")
Make_Item("Third")
End Sub
Sub Make_Item(Item_Name$)
Counter++
Print Str$(Counter,"")+Separator$+Item_Name$
End Sub
}
Checkit
Module Make_List {
Global Counter=0, Separator$=Letter$
Make_Item("First")
Make_Item("Second")
Make_Item("Third")
Sub Make_Item(Item_Name$)
Counter++
Print Str$(Counter,"")+Separator$+Item_Name$
End Sub
}
Make_List ". "
Module Make_List1 {
Global Counter=0, Separator$=Letter$
Module Make_Item (Item_Name$) {
Counter++
Print Str$(Counter,"")+Separator$+Item_Name$
}
Make_Item "First"
Make_Item "Second"
Make_Item "Third"
}
Make_List1 ". "
|
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
| #Maple | Maple |
makelist:=proc()
local makeitem,i;
i:=1;
makeitem:=proc(i)
if i=1 then
printf("%a\n", "1. first");
elif i=2 then
printf("%a\n","2. second");
elif i=3 then
printf("%a\n", "3. third");
else
return NULL;
end if;
end proc;
while i<4 do
makeitem(i);
i:=i+1;
end do;
end proc;
|
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
| #OoRexx | OoRexx | /*REXX pgm beep's "bells" (using PC speaker) when running (perpetually).*/
Parse Arg msg
If msg='?' Then Do
Say 'Ring a nautical bell'
Exit
End
Signal on Halt /* allow a clean way to stop prog.*/
Do Forever
Parse Value time() With hh ':' mn ':' ss
ct=time('C')
hhmmc=left(right(ct,7,0),5) /* HH:MM (leading zero). */
If msg>'' Then
Say center(arg(1) ct time(),79) /* echo arg1 with time ? */
If ss==00 & ( mn==00 | mn==30 ) Then Do /*It's time to ring bell */
dd=dd(hhmmc) /* compute number of times */
If msg>'' Then
Say center(dd "bells",79) /* echo bells? */
Do k=1 For dd
Call beep 650,500
Call syssleep 1+(k//2==0)
End
Call syssleep 60 /* ensure don't re-peel. */
End
Else
Call syssleep (60-ss)
End
/* test
time:
If arg(1)='C' Then
res='8:30am'
Else
res='08:30:00'
Return res
*/
dd: Parse Arg hhmmc
Parse Var hhmmc hh +2 ':' mm .
h=hh//4
If h=0 Then
If mm=00 Then res=8
Else res=1
Else
res=2*h+(mm=30)
Return res
halt: |
http://rosettacode.org/wiki/Nonogram_solver | Nonogram solver | A nonogram is a puzzle that provides
numeric clues used to fill in a grid of cells,
establishing for each cell whether it is filled or not.
The puzzle solution is typically a picture of some kind.
Each row and column of a rectangular grid is annotated with the lengths
of its distinct runs of occupied cells.
Using only these lengths you should find one valid configuration
of empty and occupied cells, or show a failure message.
Example
Problem: Solution:
. . . . . . . . 3 . # # # . . . . 3
. . . . . . . . 2 1 # # . # . . . . 2 1
. . . . . . . . 3 2 . # # # . . # # 3 2
. . . . . . . . 2 2 . . # # . . # # 2 2
. . . . . . . . 6 . . # # # # # # 6
. . . . . . . . 1 5 # . # # # # # . 1 5
. . . . . . . . 6 # # # # # # . . 6
. . . . . . . . 1 . . . . # . . . 1
. . . . . . . . 2 . . . # # . . . 2
1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3
2 1 5 1 2 1 5 1
The problem above could be represented by two lists of lists:
x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]
y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]
A more compact representation of the same problem uses strings,
where the letters represent the numbers, A=1, B=2, etc:
x = "C BA CB BB F AE F A B"
y = "AB CA AE GA E C D C"
Task
For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content
(the blank lines are separators):
C BA CB BB F AE F A B
AB CA AE GA E C D C
F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC
D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA
CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC
BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC
E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G
E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM
Extra credit: generate nonograms with unique solutions, of desired height and width.
This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).
Related tasks
Nonoblock.
See also
Arc Consistency Algorithm
http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)
http://twanvl.nl/blog/haskell/Nonograms (Haskell)
http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
| #Wren | Wren | import "/pattern" for Pattern
import "/math" for Nums, Boolean
import "/fmt" for Conv
var p = Pattern.new("/s")
var genSequence // recursive
genSequence = Fn.new { |ones, numZeros|
if (ones.isEmpty) return ["0" * numZeros]
var result = []
var x = 1
while (x < numZeros - ones.count + 2) {
var skipOne = ones.skip(1).toList
for (tail in genSequence.call(skipOne, numZeros - x)) {
result.add("0" * x + ones[0] + tail)
}
x = x + 1
}
return result
}
/* If all the candidates for a row have a value in common for a certain cell,
then it's the only possible outcome, and all the candidates from the
corresponding column need to have that value for that cell too. The ones
that don't, are removed. The same for all columns. It goes back and forth,
until no more candidates can be removed or a list is empty (failure).
*/
var reduce = Fn.new { |a, b|
var countRemoved = 0
for (i in 0...a.count) {
var commonOn = List.filled(b.count, true)
var commonOff = List.filled(b.count, false)
// determine which values all candidates of a[i] have in common
for (candidate in a[i]) {
for (i in 0...b.count) {
commonOn[i] = Boolean.and(commonOn[i], candidate[i])
commonOff[i] = Boolean.or(commonOff[i], candidate[i])
}
}
// remove from b[j] all candidates that don't share the forced values
for (j in 0...b.count) {
var fi = i
var fj = j
var removals = false
b[j].each { |cnd|
if ((commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi])) {
b[j].remove(cnd)
removals = true
}
}
if (removals) countRemoved = countRemoved + 1
if (b[j].isEmpty) return -1
}
}
return countRemoved
}
var reduceMutual = Fn.new { |cols, rows|
var countRemoved1 = reduce.call(cols, rows)
if (countRemoved1 == -1) return -1
var countRemoved2 = reduce.call(rows, cols)
if (countRemoved2 == -1) return -1
return countRemoved1 + countRemoved2
}
// collect all possible solutions for the given clues
var getCandidates = Fn.new { |data, len|
var result = []
for (s in data) {
var lst = []
var a = s.bytes
var sumChars = Nums.sum(a.map { |b| b - 64 })
var prep = a.map { |b| "1" * (b - 64) }.toList
for (r in genSequence.call(prep, len - sumChars + 1)) {
var bits = r[1..-1].bytes
var len = bits.count
if (len % 64 != 0) len = (len/64).ceil * 64
var bitset = List.filled(len, false)
for (i in 0...bits.count.min(bitset.count)) bitset[i] = bits[i] == 49
lst.add(bitset)
}
result.add(lst)
}
return result
}
var newPuzzle = Fn.new { |data|
var rowData = p.splitAll(data[0])
var colData = p.splitAll(data[1])
var rows = getCandidates.call(rowData, colData.count)
var cols = getCandidates.call(colData, rowData.count)
while (true) {
var numChanged = reduceMutual.call(cols, rows)
if (numChanged == -1) {
System.print("No solution")
return
}
if (numChanged <= 0) break
}
for (row in rows) {
for (i in 0...cols.count) {
System.write(row[0][i] ? "# " : ". ")
}
System.print()
}
System.print()
}
var p1 = ["C BA CB BB F AE F A B", "AB CA AE GA E C D C"]
var p2 = [
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"
]
var p3 = [
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC"
]
var p4 = [
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"
]
for (puzzleData in [p1, p2, p3, p4]) newPuzzle.call(puzzleData) |
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
| #Oz | Oz | declare
fun {NCSubseq SeqList}
Seq = {FS.value.make SeqList}
proc {Script Result}
%% the result is a subset of Seq
{FS.subset Result Seq}
%% at least one element of Seq is missing
local Gap in
{FS.include Gap Seq}
{FS.exclude Gap Result}
%% and this element is between the smallest
%% and the largest elements of the subsequence
Gap >: {FS.int.min Result}
Gap <: {FS.int.max Result}
end
%% enumerate all such sets
{FS.distribute naive [Result]}
end
in
{Map {SearchAll Script} FS.reflect.lowerBoundList}
end
in
{Inspect {NCSubseq [1 2 3 4]}} |
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.
| #Erlang | Erlang | 12> erlang:list_to_integer("ffff", 17).
78300
13> erlang:integer_to_list(63, 3).
"2100"
|
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated).
The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that.
The reverse operation is in task Non-decimal radices/Output
For general number base conversion, see Non-decimal radices/Convert.
| #Rust | Rust | fn main() {
println!(
"Parse from plain decimal: {}",
"123".parse::<u32>().unwrap()
);
println!(
"Parse with a given radix (2-36 supported): {}",
u32::from_str_radix("deadbeef", 16).unwrap()
);
} |
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated).
The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that.
The reverse operation is in task Non-decimal radices/Output
For general number base conversion, see Non-decimal radices/Convert.
| #Scala | Scala | object Main extends App {
val (s, bases) = ("100", Seq(2, 8, 10, 16, 19, 36))
bases.foreach(base => println(f"String $s in base $base%2d is $BigInt(s, base)%5d"))
} |
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.
| #Raku | Raku | say 30.base(2); # "11110"
say 30.base(8); # "36"
say 30.base(10); # "30"
say 30.base(16); # "1E"
say 30.base(30); # "10" |
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.
| #REXX | REXX | /*REXX pgm shows REXX's ability to show decimal numbers in binary & hex.*/
do j=0 to 50 /*show some low-value num conversions*/
say right(j,3) ' in decimal is',
right(d2b(j),12) " in binary",
right(d2x(j),12) ' in hexadecimal.'
end /*j*/
exit /*stick a fork in it, we're done.*/
/*────────────────────────────D2B subroutine────────────────────────────*/
d2b: return word(strip(x2b(d2x(arg(1))),'L',0) 0,1) /*convert dec──►bin*/ |
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.
| #Kotlin | Kotlin | // version 1.1.2
const val DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
fun encodeNegBase(n: Long, b: Int): String {
require(b in -62 .. -1)
if (n == 0L) return "0"
val out = mutableListOf<Char>()
var nn = n
while (nn != 0L) {
var rem = (nn % b).toInt()
nn /= b
if (rem < 0) {
nn++
rem -= b
}
out.add(DIGITS[rem])
}
out.reverse()
return out.joinToString("")
}
fun decodeNegBase(ns: String, b: Int): Long {
require(b in -62 .. -1)
if (ns == "0") return 0
var total = 0L
var bb = 1L
for (c in ns.reversed()) {
total += DIGITS.indexOf(c) * bb
bb *= b
}
return total
}
fun main(args:Array<String>) {
val nbl = listOf(10L to -2, 146L to -3, 15L to -10, -17596769891 to -62)
for (p in nbl) {
val ns = encodeNegBase(p.first, p.second)
System.out.printf("%12d encoded in base %-3d = %s\n", p.first, p.second, ns)
val n = decodeNegBase(ns, p.second)
System.out.printf("%12s decoded in base %-3d = %d\n\n", ns, p.second, n)
}
} |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Vlang | Vlang | const (
small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
illions = ["", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"]
)
fn say(n i64) string {
mut t := ''
mut nn := n
if n < 0 {
t = "negative "
// Note, for math.MinInt64 this leaves n negative.
nn = -n
}
if nn < 20 {
t += small[nn]
}
else if nn < 100 {
t += tens[nn/10]
s := nn % 10
if s > 0 {
t += "-" + small[s]
}
}
else if nn < 1000 {
t += small[nn/100] + " hundred"
s := nn % 100
if s > 0 {
t += " " + say(s)
}
}
else {
// work right-to-left
mut sx := ""
for i := 0; nn > 0; i++ {
p := nn % 1000
nn /= 1000
if p > 0 {
mut ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
fn main(){
mut nums := []i64{}
nums = [i64(12), i64(1048576), i64(9e18), i64(-2), i64(0)]
for n in nums {
println(say(n))
}
} |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #zkl | zkl | correctList,scrambledList,N:=[1..9].walk(), correctList.shuffle(),correctList.len();
correctList,scrambledList=correctList.concat(""), scrambledList.concat(""); // list to string
attempts:=0;
while(scrambledList!=correctList){ // Repeat until the sequence is correct
n:=ask(("[%d] %s How many numbers (from the left) should be flipped? ")
.fmt(attempts,scrambledList));
try{ n=n.toInt() }catch{ println("Not a number"); continue; }
if(not (0<=n<N)){ println("Out of range"); continue; }
attempts+=1;
// Reverse the first part of the string and add the second part
scrambledList=scrambledList[0,n].reverse() + scrambledList[n,*];
}
println("You took %d attempts to get the correct sequence.".fmt(attempts)); |
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.
| #MiniScript | MiniScript | tokens = 12
print "Nim Game"
print "Starting with " + tokens + " tokens."
print
printRemaining = function()
print tokens + " tokens remaining."
print
end function
playerTurn = function(take)
take = floor(val(take))
if take < 1 or take > 3 then
print "Take must be between 1 and 3."
return false
end if
globals.tokens = tokens - take
print "Player takes " + take + " tokens."
printRemaining
return true
end function
computerTurn = function()
take = tokens % 4
globals.tokens = tokens - take
print "Computer takes " + take + " tokens."
printRemaining
end function
while tokens > 0
if playerTurn(input("How many tokens would you like to take? ")) then
computerTurn
end if
end while
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.
| #Nim | Nim | import strutils
import terminal
var tokens = 12
styledEcho(styleBright, "Nim in Nim\n")
proc echoTokens() =
styledEcho(styleBright, "Tokens remaining: ", resetStyle, $tokens, "\n")
proc player() =
var take = '0'
styledEcho(styleBright, "- Your turn -")
echo "How many tokens will you take?"
while true:
stdout.styledWrite(styleDim, "Take (1–3): ", resetStyle)
take = getch()
stdout.write(take, '\n')
if take in {'1'..'3'}:
tokens -= parseInt($take)
break
else:
echo "Please choose a number between 1 and 3."
echoTokens()
proc computer() =
styledEcho(styleBright, "- Computer's turn -")
let take = tokens mod 4
tokens -= take
styledEcho("Computer took ", styleBright, $take, " ",
if take == 1: "token"
else: "tokens")
echoTokens()
while tokens > 0:
player()
computer()
styledEcho(styleBright, "Computer wins!") |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #11l | 11l | F narcissists(m)
[Int] result
L(digits) 0..
V digitpowers = (0.<10).map(i -> i ^ @digits)
L(n) Int(10 ^ (digits - 1)) .< 10 ^ digits
V (div, digitpsum) = (n, 0)
L div != 0
(div, V mod) = divmod(div, 10)
digitpsum += digitpowers[mod]
I n == digitpsum
result [+]= n
I result.len == m
R result
L(n) narcissists(25)
print(n, end' ‘ ’)
I (L.index + 1) % 5 == 0
print() |
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
| #11l | 11l | F sqlen(x = 0, y = 0, z = 0)
R x*x + y*y + z*z
print(sqlen(z' 3)) // equivalent to print(sqlen(0, 0, 3)) |
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.
| #C | C | #include <stdio.h>
#include <float.h>
double pow_ (double x, int e) {
int i;
double r = 1;
for (i = 0; i < e; i++) {
r *= x;
}
return r;
}
double root (int n, double x) {
double d, r = 1;
if (!x) {
return 0;
}
if (n < 1 || (x < 0 && !(n&1))) {
return 0.0 / 0.0; /* NaN */
}
do {
d = (x / pow_(r, n - 1) - r) / n;
r += d;
}
while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10);
return r;
}
int main () {
int n = 15;
double x = pow_(-3.14159, 15);
printf("root(%d, %g) = %g\n", n, x, root(n, x));
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']
| #D | D | import std.stdio, std.string, std.algorithm, std.array, std.conv,
std.ascii, std.range;
string[] naturalSort(string[] arr) /*pure @safe*/ {
static struct Part {
string s;
int opCmp(in ref Part other) const pure {
return (s[0].isDigit && other.s[0].isDigit) ?
cmp([s.to!ulong], [other.s.to!ulong]) :
cmp(s, other.s);
}
}
static mapper(in string txt) /*pure nothrow @safe*/ {
auto r = txt
.strip
.tr(whitespace, " ", "s")
.toLower
.chunkBy!isDigit
.map!(p => Part(p.text))
.array;
return (r.length > 1 && r[0].s == "the") ? r.dropOne : r;
}
return arr.schwartzSort!mapper.release;
}
void main() /*@safe*/ {
const tests = [
// Ignoring leading spaces.
["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", "
ignore leading spaces: 2+1", " ignore leading spaces: 2+0"],
// Ignoring multiple adjacent spaces (m.a.s).
["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"],
// Equivalent whitespace characters.
["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2",
"Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0",
"Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"],
// Case Indepenent [sic] sort.
["cASE INDEPENENT: 3-2" /* [sic] */, "caSE INDEPENENT: 3-1" /* [sic] */,
"casE INDEPENENT: 3+0" /* [sic] */, "case INDEPENENT: 3+1" /* [sic] */],
// Numeric fields as numerics.
["foo100bar99baz0.txt", "foo100bar10baz0.txt",
"foo1000bar99baz10.txt", "foo1000bar99baz9.txt"],
// Title sorts.
["The Wind in the Willows", "The 40th step more",
"The 39 steps", "Wanda"]];
void printTexts(Range)(string tag, Range range) {
const sic = range.front.canFind("INDEPENENT") ? " [sic]" : "";
writefln("\n%s%s:\n%-( |%s|%|\n%)", tag, sic, range);
}
foreach (test; tests) {
printTexts("Test strings", test);
printTexts("Normally sorted", test.dup.sort());
printTexts("Naturally sorted", test.dup.naturalSort());
}
}
|
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.
| #Liberty_BASIC | Liberty BASIC |
s$ = "s$ = Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100)) + Mid$(s$, 23, 3)" : Input a$ : Print (a$ = Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 14, 3) + Mid$(s$, 6, 100))
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | prog = "prog = ``;\nPrint[InputString[] == \n ToString[StringForm[prog, ToString[prog, InputForm]]]];";
Print[InputString[] == ToString[StringForm[prog, ToString[prog, InputForm]]]]; |
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.
| #Nanoquery | Nanoquery | import Nanoquery.IO
// get a file tied to this program's source
$f = new(File, $args[len($args) - 1])
// get the source and split across lines
$source = split($f.readAll(), "\n")
// read that amount of lines from the console
$in = list(len($source))
for ($i = 0) ($i < len($source)) ($i = $i + 1)
append $in input()
end
// check line by line
for ($i = 0) ($i < len($in)) ($i = $i + 1)
// check if the lines are equal
if ($in[$i] != $source[$i])
println "Reject"
exit
end
end
// if we got here, the lines are the same
println "Accept" |
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.
| #Nim | Nim |
import strutils; let a = "import strutils; let a = $#; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))"; echo ord(stdin.readAll == a % (chr(34) & a & chr(34)) & chr(10))
|
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)
| #BASIC | BASIC | DEF PROC_foo(bar, baz$(), quux%, RETURN fred%, RETURN jim%) |
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)
| #BBC_BASIC | BBC BASIC | DEF PROC_foo(bar, baz$(), quux%, RETURN fred%, RETURN jim%) |
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)
| #C | C | O_RDONLY, O_WRONLY, or O_RDWR. O_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC |
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)
| #C.23 | C# | public enum Planet {
Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
[Flags]
public enum Days {
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
Workdays = Monday | Tuesday | Wednesday | Thursday | Friday
AllWeek = Sunday | Saturday | Workdays
} |
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
| #Raku | Raku | use Lingua::EN::Numbers;
sub next-greatest-index ($str, &op = &infix:«<» ) {
my @i = $str.comb;
(1..^@i).first: { &op(@i[$_ - 1], @i[$_]) }, :end, :k;
}
multi next-greatest-integer (Int $num where * >= 0) {
return 0 if $num.chars < 2;
return $num.flip > $num ?? $num.flip !! 0 if $num.chars == 2;
return 0 unless my $i = next-greatest-index( $num ) // 0;
my $digit = $num.substr($i, 1);
my @rest = (flat $num.substr($i).comb).sort(+*);
my $next = @rest.first: * > $digit, :k;
$digit = @rest.splice($next,1);
join '', flat $num.substr(0,$i), $digit, @rest;
}
multi next-greatest-integer (Int $num where * < 0) {
return 0 if $num.chars < 3;
return $num.abs.flip < -$num ?? -$num.abs.flip !! 0 if $num.chars == 3;
return 0 unless my $i = next-greatest-index( $num, &CORE::infix:«>» ) // 0;
my $digit = $num.substr($i, 1);
my @rest = (flat $num.substr($i).comb).sort(-*);
my $next = @rest.first: * < $digit, :k;
$digit = @rest.splice($next,1);
join '', flat $num.substr(0,$i), $digit, @rest;
}
say "Next largest integer able to be made from these digits, or zero if no larger exists:";
printf "%30s -> %s%s\n", .&comma, .&next-greatest-integer < 0 ?? '' !! ' ', .&next-greatest-integer.&comma for
flat 0, (9, 12, 21, 12453, 738440, 45072010, 95322020, 9589776899767587796600, 3345333,
95897768997675877966000000000000000000000000000000000000000000000000000000000000000000).map: { $_, -$_ }; |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | makeList[sep_String]:=Block[
{counter=0, makeItem},
makeItem[item_String]:=ToString[++counter]<>sep<>item;
makeItem /@ {"first", "second", "third"}
]
Scan[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
| #min | min | (
:separator
1 :counter
(
:item
item separator counter string ' append append "" join
counter succ @counter
) :make-item
("first" "second" "third") 'make-item map "\n" join
) :make-list
". " make-list print |
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
| #MiniScript | MiniScript | makeList = function(sep)
counter = 0
makeItem = function(item)
outer.counter = counter + 1
return counter + sep + item
end function
return [makeItem("first"), makeItem("second"), makeItem("third")]
end function
print makeList(". ") |
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
| #Perl | Perl | use utf8;
binmode STDOUT, ":utf8";
use DateTime;
$| = 1; # to prevent output buffering
my @watch = <Middle Morning Forenoon Afternoon Dog First>;
my @ordinal = <One Two Three Four Five Six Seven Eight>;
my $thishour;
my $thisminute = '';
while () {
my $utc = DateTime->now( time_zone => 'UTC' );
if ($utc->minute =~ /^(00|30)$/ and $utc->minute != $thisminute) {
$thishour = $utc->hour;
$thisminute = $utc->minute;
bell($thishour, $thisminute);
}
printf "%s%02d:%02d:%02d", "\r", $utc->hour, $utc->minute, $utc->second;
sleep(1);
}
sub bell {
my($hour, $minute) = @_;
my $bells = (($hour % 4) * 2 + int $minute/30) || 8;
printf "%s%02d:%02d%9s watch,%6s Bell%s Gone: \t", "\b" x 9, $hour, $minute,
$watch[(int($hour/4) - (0==($minute + $hour % 4)) + 6) % 6],
$ordinal[$bells - 1], $bells == 1 ? '' : 's';
chime($bells);
}
sub chime {
my($count) = shift;
for (1..int($count/2)) {
print "\a♫ "; sleep .25;
print "\a"; sleep .75;
}
if ($count % 2) {
print "\a♪"; sleep 1;
}
print "\n";
} |
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
| #PARI.2FGP | PARI/GP | noncontig(n)=n>>=valuation(n,2);n++;n>>=valuation(n,2);n>1;
nonContigSubseq(v)={
for(i=5,2^#v-1,
if(noncontig(i),
print(vecextract(v,i))
)
)
};
nonContigSubseq([1,2,3])
nonContigSubseq(["a","b","c","d","e"]) |
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.
| #Euphoria | Euphoria | function to_base(integer i, integer base)
integer rem
sequence s
s = ""
while i > 0 do
rem = remainder(i,base)
if rem < 10 then
s = prepend(s, '0'+rem)
else
s = prepend(s, 'a'-10+rem)
end if
i = floor(i/base)
end while
if length(s) = 0 then
s = "0"
end if
return s
end function
function from_base(sequence s, integer base)
integer i,d
i = 0
for n = 1 to length(s) do
i *= base
if s[n] >= '0' and s[n] <= '9' then
d = s[n]-'0'
elsif s[n] >= 'a' then
d = s[n]-'a'+10
end if
i += d
end for
return i
end function |
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated).
The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that.
The reverse operation is in task Non-decimal radices/Output
For general number base conversion, see Non-decimal radices/Convert.
| #Scheme | Scheme | > (string->number "abcf123" 16) ; hex
180154659
> (string->number "123459" 10) ; decimal, the "10" is optional
123459
> (string->number "7651" 8) ; octal
4009
> (string->number "101011001" 2) ; binary
345 |
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated).
The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that.
The reverse operation is in task Non-decimal radices/Output
For general number base conversion, see Non-decimal radices/Convert.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
begin
writeln(integer("0123459", 10));
writeln(integer("abcf123", 16));
writeln(integer("7651", 8));
writeln(integer("1010011010", 2));
writeln(integer("tplig0", 32));
writeln(integer("gc0uy9", 36));
end func; |
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.
| #Ring | Ring |
# Project : Non Decimal radices/Output
see string(0) + nl
see string(123456789) + nl
see string(-987654321) + nl
see upper(hex(43981)) + nl
see upper(hex(-1)) + nl
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | EncodeBase[number_,base_]:=Module[{
out={},
rem,n=number,b=base
},
While[
n!=0,
{n,rem}={Floor[Divide[n,b]],Mod[n,b]};
If[
rem<0,
n+=1;
rem-=b
];
PrependTo[out,rem]
];
out
];
DecodeBase[list_,base_]:=Total[list*base^Range[Length[list]-1,0,-1]];
Print[EncodeNegBase[10,-2],"=",DecodeBase[EncodeNegBase[10,-2],-2]];
Print[EncodeNegBase[146,-3],"=",DecodeBase[EncodeNegBase[146,-3],-3]];
Print[EncodeNegBase[15,-10],"=",DecodeBase[EncodeNegBase[15,-10],-10]]; |
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.
| #Modula-2 | Modula-2 | MODULE NegativeBase;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
CONST DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
TYPE String = ARRAY[0..63] OF CHAR;
PROCEDURE EncodeNegativeBase(n : LONGINT; base : LONGINT) : String;
PROCEDURE Mod(a,b : LONGINT) : LONGINT;
BEGIN
RETURN a - (a / b) * b
END Mod;
PROCEDURE Swap(VAR a,b : CHAR);
VAR t : CHAR;
BEGIN
t := a;
a := b;
b := t
END Swap;
VAR
ptr,idx : CARDINAL;
rem : LONGINT;
result : String;
BEGIN
IF (base > -1) OR (base < -62) THEN
RETURN result
ELSIF n = 0 THEN
result := "0"
ELSE
ptr := 0;
WHILE n # 0 DO
rem := Mod(n, base);
n := n / base;
IF rem < 0 THEN
INC(n);
rem := rem - base
END;
result[ptr] := DIGITS[rem];
INC(ptr);
END
END;
result[ptr] := 0C;
idx := 0;
DEC(ptr);
WHILE idx < ptr DO
Swap(result[idx], result[ptr]);
INC(idx);
DEC(ptr)
END;
RETURN result
END EncodeNegativeBase;
PROCEDURE DecodeNegativeBase(ns : String; base : LONGINT) : LONGINT;
VAR
total,bb,i,j : LONGINT;
BEGIN
IF (base < -62) OR (base > -1) THEN
RETURN 0
ELSIF (ns[0] = 0C) OR ((ns[0] = '0') AND (ns[1] = 0C)) THEN
RETURN 0
ELSE
FOR i:=0 TO HIGH(ns) DO
IF ns[i] = 0C THEN
BREAK
END
END;
DEC(i);
total := 0;
bb := 1;
WHILE i >= 0 DO
FOR j:=0 TO HIGH(DIGITS) DO
IF ns[i] = DIGITS[j] THEN
total := total + j * bb;
bb := bb * base;
BREAK
END
END;
DEC(i)
END;
END;
RETURN total
END DecodeNegativeBase;
PROCEDURE Driver(n,b : LONGINT);
VAR
ns,buf : String;
p : LONGINT;
BEGIN
ns := EncodeNegativeBase(n, b);
FormatString("%12l encoded in base %3l = %12s\n", buf, n, b, ns);
WriteString(buf);
p := DecodeNegativeBase(ns, b);
FormatString("%12s decoded in base %3l = %12l\n", buf, ns, b, p);
WriteString(buf);
WriteLn
END Driver;
BEGIN
Driver(10, -2);
Driver(146, -3);
Driver(15, -10);
Driver(-19425187910, -62);
ReadChar
END NegativeBase. |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Wren | Wren | var small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
var illions = ["", " thousand", " million", " billion"," trillion", " quadrillion", " quintillion"]
var say
say = Fn.new { |n|
var t = ""
if (n < 0) {
t = "negative "
n = -n
}
if (n < 20) {
t = t + small[n]
} else if (n < 100) {
t = t + tens[(n/10).floor]
var s = n % 10
if (s > 0) t = t + "-" + small[s]
} else if (n < 1000) {
t = t + small[(n/100).floor] + " hundred"
var s = n % 100
System.write("") // guards against VM recursion bug
if (s > 0) t = t + " " + say.call(s)
} else {
var sx = ""
var i = 0
while (n > 0) {
var p = n % 1000
n = (n/1000).floor
if (p > 0) {
System.write("") // guards against VM recursion bug
var ix = say.call(p) + illions[i]
if (sx != "") ix = ix + " " + sx
sx = ix
}
i = i + 1
}
t = t + sx
}
return t
}
for (n in [12, 1048576, 9e18, -2, 0]) System.print(say.call(n)) |
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.
| #OCaml | OCaml | let rec player_turn () =
print_string "How many tokens would you like to take? ";
let n = read_int_opt () |> Option.value ~default:0 in
if n >= 1 && n <= 3 then n
else (
print_endline "Number must be between 1 and 3";
player_turn ())
let computer_turn tokens = tokens mod 4
let plural_suffix = function 1 -> "" | _ -> "s"
let turn_report prefix taken tokens =
Printf.printf "%s %d token%s.\n%d token%s remaining.\n%!" prefix taken
(plural_suffix taken) tokens (plural_suffix tokens)
let rec play_game tokens =
let player_tokens = player_turn () in
let tokens = tokens - player_tokens in
turn_report "You take" player_tokens tokens;
let computer_tokens = computer_turn tokens in
let tokens = tokens - computer_tokens in
turn_report "Computer takes" computer_tokens tokens;
if tokens = 0 then print_endline "Computer wins!" else play_game tokens
let () = play_game 12 |
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Narcissistic is
function Is_Narcissistic(N: Natural) return Boolean is
Decimals: Natural := 1;
M: Natural := N;
Sum: Natural := 0;
begin
while M >= 10 loop
M := M / 10;
Decimals := Decimals + 1;
end loop;
M := N;
while M >= 1 loop
Sum := Sum + (M mod 10) ** Decimals;
M := M/10;
end loop;
return Sum=N;
end Is_Narcissistic;
Count, Current: Natural := 0;
begin
while Count < 25 loop
if Is_Narcissistic(Current) then
Ada.Text_IO.Put(Integer'Image(Current));
Count := Count + 1;
end if;
Current := Current + 1;
end loop;
end Narcissistic; |
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
| #Ada | Ada | procedure Foo (Arg_1 : Integer; Arg_2 : Float := 0.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
| #ALGOL_68 | ALGOL 68 | BEGIN
MODE OPTNAME = STRUCT(STRING name),
OPTSPECIES = STRUCT(STRING species),
OPTBREED = STRUCT(STRING breed),
OWNER=STRUCT(STRING first name, middle name, last name);
# Version 2 of Algol 68G would not allow empty options to be specified as () so #
# VOID would need to be included in the MODEs for options and Empty option lists #
# would need to be written as (EMPTY) #
MODE OPTIONS = FLEX[1:0]UNION(OPTNAME,OPTSPECIES,OPTBREED,OWNER); # add ,VOID for Algol 68G version 2 #
# due to the Yoneda ambiguity simple arguments must have an unique operator defined #
# E.g. a string cannot be coerced to a structure with a single string field #
OP NAME = (STRING name)OPTNAME: (OPTNAME opt; name OF opt := name; opt),
SPECIES = (STRING species)OPTSPECIES: (OPTSPECIES opt; species OF opt := species; opt),
BREED = (STRING breed)OPTBREED: (OPTBREED opt; breed OF opt := breed; opt);
PROC print pet = (OPTIONS option)VOID: (
STRING name:="Rex", species:="Dinosaur", breed:="Tyrannosaurus"; # Defaults #
OWNER owner := ("George","W.","Bush");
FOR i TO UPB option DO
CASE option[i] IN
(OPTNAME option): name := name OF option,
(OPTSPECIES option): species := species OF option,
(OPTBREED option): breed := breed OF option,
(OWNER option): owner := option
ESAC
OD;
print(("Details: "
,IF CHAR c = breed[LWB breed]; char in string( c, NIL, "AaEeIiOoUu" ) THEN "an " ELSE "a " FI
,breed, " ", species, " named ",name," owned by ",owner, newline))
);
print pet((NAME "Mike", SPECIES "Dog", BREED "Irish Setter", OWNER("Harry", "S.", "Truman")));
print pet(()) # use print pet((EMPTY)) for Algol 68G version 2 #
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.
| #C.23 | C# |
static void Main(string[] args)
{
Console.WriteLine(NthRoot(81,2,.001));
Console.WriteLine(NthRoot(1000,3,.001));
Console.ReadLine();
}
public static double NthRoot(double A,int n, double p)
{
double _n= (double) n;
double[] x = new double[2];
x[0] = A;
x[1] = A/_n;
while(Math.Abs(x[0] -x[1] ) > p)
{
x[1] = x[0];
x[0] = (1/_n)*(((_n-1)*x[1]) + (A/Math.Pow(x[1],_n-1)));
}
return x[0];
}
|
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.
| #11l | 11l | V _suffix = [‘th’, ‘st’, ‘nd’, ‘rd’, ‘th’, ‘th’, ‘th’, ‘th’, ‘th’, ‘th’]
F nth(n)
R ‘#.'#.’.format(n, I n % 100 <= 10 | n % 100 > 20 {:_suffix[n % 10]} E ‘th’)
L(j) (0..1000).step(250)
print_elements(Array(j.+25).map(i -> nth(i))) |
http://rosettacode.org/wiki/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n:
μ(1) is defined to be 1.
μ(n) = 1 if n is a square-free positive integer with an even number of prime factors.
μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
μ(n) = 0 if n has a squared prime factor.
Task
Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
See also
Wikipedia: Möbius function
Related Tasks
Mertens function
| #ALGOL_68 | ALGOL 68 | BEGIN
# show the first 199 values of the moebius function #
INT sq root = 1 000;
INT mu max = sq root * sq root;
[ 1 : mu max ]INT mu;
FOR i FROM LWB mu TO UPB mu DO mu[ i ] := 1 OD;
FOR i FROM 2 TO sq root DO
IF mu[ i ] = 1 THEN
# for each factor found, swap + and - #
FOR j FROM i BY i TO UPB mu DO mu[ j ] *:= -i OD;
FOR j FROM i * i BY i * i TO UPB mu DO mu[ j ] := 0 OD
FI
OD;
FOR i FROM 2 TO UPB mu DO
IF mu[ i ] = i THEN mu[ i ] := 1
ELIF mu[ i ] = -i THEN mu[ i ] := -1
ELIF mu[ i ] < 0 THEN mu[ i ] := 1
ELIF mu[ i ] > 0 THEN mu[ i ] := -1
# ELSE mu[ i ] = 0 so no change #
FI
OD;
print( ( "First 199 terms of the möbius function are as follows:", newline, " " ) );
FOR i TO 199 DO
print( ( whole( mu[ i ], -4 ) ) );
IF ( i + 1 ) MOD 20 = 0 THEN print( ( newline ) ) FI
OD
END |
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']
| #Elixir | Elixir | defmodule Natural do
def sorting(texts) do
Enum.sort_by(texts, fn text -> compare_value(text) end)
end
defp compare_value(text) do
text
|> String.downcase
|> String.replace(~r/\A(a |an |the )/, "")
|> String.split
|> Enum.map(fn word ->
Regex.scan(~r/\d+|\D+/, word)
|> Enum.map(fn [part] ->
case Integer.parse(part) do
{num, ""} -> num
_ -> part
end
end)
end)
end
def task(title, input) do
IO.puts "\n#{title}:"
IO.puts "< input >"
Enum.each(input, &IO.inspect &1)
IO.puts "< normal sort >"
Enum.sort(input) |> Enum.each(&IO.inspect &1)
IO.puts "< natural sort >"
Enum.sort_by(input, &compare_value &1) |> Enum.each(&IO.inspect &1)
end
end
[{"Ignoring leading spaces",
["ignore leading spaces: 2-2", " ignore leading spaces: 2-1",
" ignore leading spaces: 2+0", " ignore leading spaces: 2+1"]},
{"Ignoring multiple adjacent spaces (m.a.s)",
["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"]},
{"Equivalent whitespace characters",
["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\x0cspaces: 3-1",
"Equiv.\x0bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"]},
{"Case Indepenent sort",
["cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1",
"casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"]},
{"Numeric fields as numerics",
["foo100bar99baz0.txt", "foo100bar10baz0.txt",
"foo1000bar99baz10.txt", "foo1000bar99baz9.txt"]},
{"Title sorts",
["The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"]}
]
|> Enum.each(fn {title, input} -> Natural.task(title, input) 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.
| #PARI.2FGP | PARI/GP | narcissist()=input()==narcissist |
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.
| #Perl | Perl | # this is file narc.pl
local $/;
print do { open 0; <0> } eq <> ? "accept" : "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.
| #Phix | Phix | without js -- (file i/o)
puts(1,{"\n\ntrue\n\n","\n\nfalse\n\n"}[1+(gets(open(command_line()[2],"r"))!=gets(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)
| #Clojure | Clojure | var xs = Array.Empty(10)
var ys = Array(1, 2, 3)
var str = xs.ToString()
type Maybe = Some(x) or None()
var x = Maybe.Some(42) |
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)
| #Common_Lisp | Common Lisp | var xs = Array.Empty(10)
var ys = Array(1, 2, 3)
var str = xs.ToString()
type Maybe = Some(x) or None()
var x = Maybe.Some(42) |
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.