task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Nautical_bell | Nautical bell |
Task
Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.
The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.
It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type.
Related task
Sleep
| #Go | Go | package main
import (
"fmt"
"strings"
"time"
)
func main() {
watches := []string{
"First", "Middle", "Morning", "Forenoon",
"Afternoon", "Dog", "First",
}
for {
t := time.Now()
h := t.Hour()
m := t.Minute()
s := t.Second()
if (m == 0 || m == 30) && s == 0 {
bell := 0
if m == 30 {
bell = 1
}
bells := (h*2 + bell) % 8
watch := h/4 + 1
if bells == 0 {
bells = 8
watch--
}
sound := strings.Repeat("\a", bells)
pl := "s"
if bells == 1 {
pl = " "
}
w := watches[watch] + " watch"
if watch == 5 {
if bells < 5 {
w = "First " + w
} else {
w = "Last " + w
}
}
fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w)
}
time.Sleep(1 * time.Second)
}
} |
http://rosettacode.org/wiki/Nested_templated_data | Nested templated data | A template for data is an arbitrarily nested tree of integer indices.
Data payloads are given as a separate mapping, array or other simpler, flat,
association of indices to individual items of data, and are strings.
The idea is to create a data structure with the templates' nesting, and the
payload corresponding to each index appearing at the position of each index.
Answers using simple string replacement or regexp are to be avoided. The idea is
to use the native, or usual implementation of lists/tuples etc of the language
and to hierarchically traverse the template to generate the output.
Task Detail
Given the following input template t and list of payloads p:
# Square brackets are used here to denote nesting but may be changed for other,
# clear, visual representations of nested data appropriate to ones programming
# language.
t = [
[[1, 2],
[3, 4, 1],
5]]
p = 'Payload#0' ... 'Payload#6'
The correct output should have the following structure, (although spacing and
linefeeds may differ, the nesting and order should follow):
[[['Payload#1', 'Payload#2'],
['Payload#3', 'Payload#4', 'Payload#1'],
'Payload#5']]
1. Generate the output for the above template, t.
Optional Extended tasks
2. Show which payloads remain unused.
3. Give some indication/handling of indices without a payload.
Show output on this page.
| #VBA | VBA | Public Sub test()
Dim t(2) As Variant
t(0) = [{1,2}]
t(1) = [{3,4,1}]
t(2) = 5
p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}]
Dim q(6) As Boolean
For i = LBound(t) To UBound(t)
If IsArray(t(i)) Then
For j = LBound(t(i)) To UBound(t(i))
q(t(i)(j)) = True
t(i)(j) = p(t(i)(j) + 1)
Next j
Else
q(t(i)) = True
t(i) = p(t(i) + 1)
End If
Next i
For i = LBound(t) To UBound(t)
If IsArray(t(i)) Then
Debug.Print Join(t(i), ", ")
Else
Debug.Print t(i)
End If
Next i
For i = LBound(q) To UBound(q)
If Not q(i) Then Debug.Print p(i + 1); " is not used"
Next i
End Sub |
http://rosettacode.org/wiki/Nested_templated_data | Nested templated data | A template for data is an arbitrarily nested tree of integer indices.
Data payloads are given as a separate mapping, array or other simpler, flat,
association of indices to individual items of data, and are strings.
The idea is to create a data structure with the templates' nesting, and the
payload corresponding to each index appearing at the position of each index.
Answers using simple string replacement or regexp are to be avoided. The idea is
to use the native, or usual implementation of lists/tuples etc of the language
and to hierarchically traverse the template to generate the output.
Task Detail
Given the following input template t and list of payloads p:
# Square brackets are used here to denote nesting but may be changed for other,
# clear, visual representations of nested data appropriate to ones programming
# language.
t = [
[[1, 2],
[3, 4, 1],
5]]
p = 'Payload#0' ... 'Payload#6'
The correct output should have the following structure, (although spacing and
linefeeds may differ, the nesting and order should follow):
[[['Payload#1', 'Payload#2'],
['Payload#3', 'Payload#4', 'Payload#1'],
'Payload#5']]
1. Generate the output for the above template, t.
Optional Extended tasks
2. Show which payloads remain unused.
3. Give some indication/handling of indices without a payload.
Show output on this page.
| #Wren | Wren | import "/set" for Set
import "/sort" for Sort
var withPayload // recursive function
withPayload = Fn.new { |template, payload, used|
return template.map { |item|
if (item is List) {
return withPayload.call(item, payload, used)
} else {
used.add(item)
return "'%(payload[item])'"
}
}.toList
}
var p = ["Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"]
var t = [[[1, 2], [3, 4, 1], 5]]
var used = []
System.print(withPayload.call(t, p, used))
System.print()
var unused = Set.new(0..6).except(Set.new(used)).toList
Sort.insertion(unused)
System.print("The unused payloads have indices of %(unused).") |
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)
| #Picat | Picat | import util, sat.
main =>
Hr = "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
Hc = "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",
Lr = [token_to_hints(Token) : Token in split(Hr)],
Lc = [token_to_hints(Token) : Token in split(Hc)],
MaxR = len(Lr),
MaxC = len(Lc),
foreach (Hints in Lr)
constrain_starts(Hints,MaxC)
end,
foreach (Hints in Lc)
constrain_starts(Hints,MaxR)
end,
M = new_array(MaxR,MaxC),
M :: 0..1,
foreach ({R,Hints} in zip(1..MaxR, Lr))
sum([M[R,C] : C in 1..MaxC]) #= sum([Num : (Num,_) in Hints])
end,
foreach ({R,Hints} in zip(1..MaxR, Lr), (Num,Start) in Hints, C in 1..MaxC-Num+1)
Start #= C #=> sum([M[R,C+I] : I in 0..Num-1]) #= Num
end,
%
foreach ({C,Hints} in zip(1..MaxC, Lc))
sum([M[R,C] : R in 1..MaxR]) #= sum([Num : (Num,_) in Hints])
end,
foreach ({C,Hints} in zip(1..MaxC, Lc), (Num,Start) in Hints, R in 1..MaxR-Num+1)
Start #= R #=> sum([M[R+I,C] : I in 0..Num-1]) #= Num
end,
solve((Lr,Lc,M)),
foreach (R in 1..MaxR)
foreach (C in 1..MaxC)
printf("%2c", cond(M[R,C] == 1, '#', '.'))
end,
nl
end.
% convert "BCB" to [(2,_),(3,_),(2,_)]
% a hint is a pair (Num,Start), where Num is the length of the 1 segment and Start is the starting row number or column number
token_to_hints([]) = [].
token_to_hints([C|Cs]) = [(ord(C)-ord('A')+1, _)|token_to_hints(Cs)].
% there must be a gap between two neighboring segments
constrain_starts([(Num,Start)],Max) =>
Start :: 1..Max,
Start+Num-1 #<= Max.
constrain_starts([(Num1,Start1),(Num2,Start2)|L],Max) =>
Start1 :: 1..Max,
Start1+Num1 #< Start2,
constrain_starts([(Num2,Start2)|L],Max).
|
http://rosettacode.org/wiki/Nonoblock | Nonoblock | Nonoblock is a chip off the old Nonogram puzzle.
Given
The number of cells in a row.
The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.
Task
show all possible positions.
show the number of positions of the blocks for the following cases within the row.
show all output on this page.
use a "neat" diagram of the block positions.
Enumerate the following configurations
5 cells and [2, 1] blocks
5 cells and [] blocks (no blocks)
10 cells and [8] blocks
15 cells and [2, 3, 2, 3] blocks
5 cells and [2, 3] blocks (should give some indication of this not being possible)
Example
Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:
|_|_|_|_|_| # 5 cells and [2, 1] blocks
And would expand to the following 3 possible rows of block positions:
|A|A|_|B|_|
|A|A|_|_|B|
|_|A|A|_|B|
Note how the sets of blocks are always separated by a space.
Note also that it is not necessary for each block to have a separate letter.
Output approximating
This:
|#|#|_|#|_|
|#|#|_|_|#|
|_|#|#|_|#|
This would also work:
##.#.
##..#
.##.#
An algorithm
Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).
The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.
for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block.
(This is the algorithm used in the Nonoblock#Python solution).
Reference
The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
| #Wren | Wren | import "/math" for Nums
var genSequence // recursive
genSequence = Fn.new { |ones, numZeros|
if (ones.isEmpty) return ["0" * numZeros]
var result = []
for (x in 1...numZeros - ones.count + 2) {
var skipOne = ones[1..-1]
for (tail in genSequence.call(skipOne, numZeros - x)) {
result.add("0" * x + ones[0] + tail)
}
}
return result
}
var printBlock = Fn.new { |data, len|
var a = data.toList
var sumChars = Nums.sum(a.map { |c| c.bytes[0] - 48 }.toList)
System.print("\nblocks %(a), cells %(len)")
if (len - sumChars <= 0) {
System.print("No solution")
return
}
var prep = a.map { |c| "1" * (c.bytes[0] - 48) }.toList
for (r in genSequence.call(prep, len - sumChars + 1)) {
System.print(r[1..-1])
}
}
printBlock.call("21", 5)
printBlock.call("", 5)
printBlock.call("8", 10)
printBlock.call("2323", 15)
printBlock.call("23", 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
| #J | J | allmasks=: 2 #:@i.@^ #
firstend=:1 0 i.&1@E."1 ]
laststart=: 0 1 {:@I.@E."1 ]
noncont=: <@#~ (#~ firstend < laststart)@allmasks |
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
| #Java | Java | public class NonContinuousSubsequences {
public static void main(String args[]) {
seqR("1234", "", 0, 0);
}
private static void seqR(String s, String c, int i, int added) {
if (i == s.length()) {
if (c.trim().length() > added)
System.out.println(c);
} else {
seqR(s, c + s.charAt(i), i + 1, added + 1);
seqR(s, c + ' ', i + 1, added);
}
}
} |
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.
| #C.2B.2B | C++ | #include <string>
#include <cstdlib>
#include <algorithm>
#include <cassert>
std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
std::string to_base(unsigned long num, int base)
{
if (num == 0)
return "0";
std::string result;
while (num > 0) {
std::ldiv_t temp = std::div(num, (long)base);
result += digits[temp.rem];
num = temp.quot;
}
std::reverse(result.begin(), result.end());
return result;
}
unsigned long from_base(std::string const& num_str, int base)
{
unsigned long result = 0;
for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)
result = result * base + digits.find(num_str[pos]);
return result;
} |
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.
| #PicoLisp | PicoLisp | (de parseNumber (S Base)
(let N 0
(for C (chop S)
(when (> (setq C (- (char C) `(char "0"))) 9)
(dec 'C 39) )
(setq N (+ C (* N Base))) )
N ) )
(println (parseNumber "91g5dcg2h6da7260a9f3c4a" 19)) |
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.
| #PL.2FI | PL/I | declare N fixed binary;
get edit (N) (A(7)); /* decimal input of 7 columns */
put skip list (N);
declare BS bit (32);
get edit (BS) (B(32)); /* Binary input of 32 binary digits. */
put skip edit (BS) (B); |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #Nim | Nim | import strutils
for i in 0..33:
echo toBin(i, 6)," ",toOct(i, 3)," ",align($i,2)," ",toHex(i,2) |
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.
| #OCaml | OCaml | for n = 0 to 33 do
Printf.printf " %3o %2d %2X\n" n n n (* binary not supported *)
done |
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.
| #PARI.2FGP | PARI/GP | printbinary(n)={
n=binary(n);
for(i=1,#n,print1(n[i]))
};
printdecimal(n)={
print1(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.
| #D | D | import std.stdio;
immutable DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
void main() {
driver(10, -2);
driver(146, -3);
driver(15, -10);
driver(13, -62);
}
void driver(long n, int b) {
string ns = encodeNegBase(n, b);
writefln("%12d encoded in base %3d = %12s", n, b, ns);
long p = decodeNegBase(ns, b);
writefln("%12s decoded in base %3d = %12d", ns, b, p);
writeln;
}
string encodeNegBase(long n, int b) in {
import std.exception : enforce;
enforce(b <= -1 && b >= -62);
} body {
if (n==0) return "0";
char[] output;
long nn = n;
while (nn != 0) {
int rem = nn % b;
nn /= b;
if (rem < 0) {
nn++;
rem -= b;
}
output ~= DIGITS[rem];
}
import std.algorithm : reverse;
reverse(output);
return cast(string) output;
}
long decodeNegBase(string ns, int b) in {
import std.exception : enforce;
enforce(b <= -1 && b >= -62);
} body {
if (ns == "0") return 0;
long total = 0;
long bb = 1;
foreach_reverse (c; ns) {
foreach(i,d; DIGITS) {
if (c==d) {
total += i * bb;
bb *= b;
break;
}
}
}
return total;
} |
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.
| #SQL | SQL |
SELECT val, to_char(to_date(val,'j'),'jsp') name
FROM
(
SELECT
round( dbms_random.VALUE(1, 5373484)) val
FROM dual
CONNECT BY level <= 5
);
SELECT to_char(to_date(5373485,'j'),'jsp') FROM dual;
|
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
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
numbers=RANDOM_NUMBERS (1,9,9),nr=0
SECTION check
LOOP o,n=numbers
IF (n!=o) THEN
DO PRINT
EXIT
ELSEIF (n==9&&o==9) THEN
DO PRINT
PRINT " You made it ... in round ",r
STOP
ELSE
CYCLE
ENDIF
ENDLOOP
ENDSECTION
SECTION print
PRINT numbers
ENDSECTION
DO PRINT
LOOP r=1,14
IF (nr>=0&&nr<10) THEN
ASK "Reverse - how many?": nr=""
i=""
LOOP n=1,nr
i=APPEND(i,n)
ENDLOOP
numbers =SPLIT (numbers)
reverse_nr=SELECT (numbers,#i,keep_nr), reverse_nr=REVERSE(reverse_nr)
numbers =APPEND (reverse_nr,keep_nr), numbers =JOIN (numbers)
DO check
ENDIF
ENDLOOP
|
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.
| #GW-BASIC | GW-BASIC | 10 HEAP = 12
20 WHILE HEAP>0
30 TAKE = 0
40 PRINT "There are ";HEAP;" tokens left."
50 WHILE TAKE < 1 OR TAKE > 3 OR TAKE > HEAP
60 INPUT "How many would you like to take? ", TAKE
70 IF TAKE = HEAP THEN GOTO 140
80 WEND
90 PRINT "I will take ";4-TAKE;" tokens."
100 HEAP = HEAP - 4
110 WEND
120 PRINT "I got the last token. Better luck next time."
130 END
140 PRINT "You got the last token. Congratulations!"
150 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.
| #Haskell | Haskell | import Data.Char (isDigit, digitToInt)
import System.IO
prompt :: String
prompt = "How many do you take? 1, 2 or 3? "
getPlayerSelection :: IO Int
getPlayerSelection = do
hSetBuffering stdin NoBuffering
c <- getChar
putChar '\n'
if isDigit c && digitToInt c <= 3 then
pure (digitToInt c)
else do
putStrLn "Invalid input"
putStr prompt
getPlayerSelection
play :: Int -> IO ()
play n = do
putStrLn $ show n ++ token n ++ " remain."
if n == 0 then putStrLn "Computer Wins!"
else do
putStr prompt
playerSelection <- getPlayerSelection
let computerSelection
| playerSelection > 4 = playerSelection - 4
| otherwise = 4 - playerSelection
putStrLn $ "Computer takes " ++ show computerSelection ++ token computerSelection ++ ".\n"
play (n - computerSelection - playerSelection)
where token 1 = " token"
token _ = " tokens"
main :: IO ()
main = play 12 |
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.
| #AWK | AWK |
#!/usr/bin/awk -f
BEGIN {
# test
print nthroot(8,3)
print nthroot(16,2)
print nthroot(16,4)
print nthroot(125,3)
print nthroot(3,3)
print nthroot(3,2)
}
function nthroot(y,n) {
eps = 1e-15; # relative accuracy
x = 1;
do {
d = ( y / ( x^(n-1) ) - x ) / n ;
x += d;
e = eps*x; # absolute accuracy
} while ( d < -e || d > e )
return x
}
|
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.
| #Befunge | Befunge | 900:0g~>:::0>`#0\#:5#:5#:+#<#~-#g*#0\#:5#+8#1+#\-#!*#-_$$"E"-!>_9-!.@ |
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.
| #C | C | extern void*stdin;main(){ char*p = "extern void*stdin;main(){ char*p = %c%s%c,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }",a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); } |
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.
| #C.23 | C# |
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Narcisisst
{
class Program
{
public static void Main(string[] args)
{
const string path = @"E:\Narcisisst";
string[] thisFile = Directory.GetFiles(path , "Program.cs");
StringBuilder sb = new StringBuilder();
foreach (string readLine in File.ReadLines(thisFile[0]))
{
sb.Append(readLine);
sb.Append("\n");
}
Console.WriteLine(sb);
string input =String.Empty;
input = Console.ReadLine();
Console.WriteLine((Regex.IsMatch(sb.ToString(),input))?"accept":"reject");
Console.ReadKey();
}
}
}
|
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
| #jq | jq | # Generate a stream of all the permutations of the input array
def permutations:
# Given an array as input, generate a stream by inserting $x at different positions
def insert($x):
range (0; length + 1) as $pos
| .[0:$pos] + [$x] + .[$pos:];
if length <= 1 then .
else
.[0] as $first
| .[1:] | permutations | insert($first)
end;
def next_highest:
(tostring | explode) as $digits
| ([$digits | permutations] | unique) as $permutations
| ($permutations | bsearch($digits)) as $i
| if $i == (($permutations|length) - 1) then 0
else $permutations[$i+1] | implode
end;
def task:
0,
9,
12,
21,
12453,
738440,
45072010,
95322020;
task | "\(.) => \(next_highest)" |
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
| #Julia | Julia | using Combinatorics, BenchmarkTools
asint(dig) = foldl((i, j) -> 10i + Int128(j), dig)
"""
Algorithm 1(A)
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.
"""
function nexthighest_1A(N)
n = Int128(abs(N))
dig = digits(n)
perms = unique(sort([asint(arr) for arr in permutations(digits(n))]))
length(perms) < 2 && return 0
((N > 0 && perms[end] == n) || (N < 0 && perms[1] == n)) && return 0
pos = findfirst(x -> x == n, perms)
ret = N > 0 ? perms[pos + 1] : -perms[pos - 1]
return ret == N ? 0 : ret
end
"""
Algorithm 1(B)
Iterate through the permutations of the digits of a number and get the permutation that
represents the integer having a minimum distance above the given number.
Return the number plus the minimum distance. Does not store all the permutations.
This saves memory versus algorithm 1A, but we still go through all permutations (slow).
"""
function nexthighest_1B(N)
n = Int128(abs(N))
dig = reverse(digits(n))
length(dig) < 2 && return 0
mindelta = n
for perm in permutations(dig)
if (perm[1] != 0) && ((N > 0 && perm > dig) || (N < 0 && perm < dig))
delta = abs(asint(perm) - n)
if delta < mindelta
mindelta = delta
end
end
end
return mindelta < n ? N + mindelta : 0
end
"""
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.
Very fast, as it does not need to run through all the permutations of digits.
"""
function nexthighest_2(N)
n = Int128(abs(N))
dig, ret = digits(n), N
length(dig) < 2 && return 0
for (i, d) in enumerate(dig)
if N > 0 && i > 1
rdig = dig[1:i-1]
if (j = findfirst(x -> x > d, rdig)) != nothing
dig[i], dig[j] = dig[j], dig[i]
arr = (i == 2) ? dig : [sort(dig[1:i-1], rev=true); dig[i:end]]
ret = asint(reverse(arr))
break
end
elseif N < 0 && i > 1
rdig = dig[1:i-1]
if (j = findfirst(x -> x < d, rdig)) != nothing
dig[i], dig[j] = dig[j], dig[i]
arr = (i == 2) ? dig : [sort(dig[1:i-1]); dig[i:end]]
ret = -asint(reverse(arr))
break
end
end
end
return ret == N ? 0 : ret
end
println(" N 1A 1B 2\n", "="^98)
for n in [0, 9, 12, 21, -453, -8888, 12453, 738440, 45072010, 95322020, -592491602, 9589776899767587796600]
println(rpad(n, 25), abs(n) > typemax(Int) ? " "^50 : rpad(nexthighest_1A(n), 25) *
rpad(nexthighest_1B(n), 25), nexthighest_2(n))
end
const n = 7384440
@btime nexthighest_1A(n)
println(" for method 1A and n $n.")
@btime nexthighest_1B(n)
println(" for method 1B and n $n.")
@btime nexthighest_2(n)
println(" for method 2 and n $n.")
|
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub makeItem(sep As String, ByRef counter As Integer, text As String)
counter += 1
Print counter; sep; text
End Sub
Sub makeList(sep As String)
Dim a(0 To 2) As String = {"first", "second", "third"}
Dim counter As Integer = 0
While counter < 3
makeItem(sep, counter, a(counter))
Wend
End Sub
makeList ". "
Print
Print "Press any key to quit"
Sleep
|
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func makeList(separator string) string {
counter := 1
makeItem := func(item string) string {
result := fmt.Sprintf("%d%s%s\n", counter, separator, item)
counter += 1
return result
}
return makeItem("first") + makeItem("second") + makeItem("third")
}
func main() {
fmt.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
| #Haskell | Haskell |
import Control.Concurrent
import Control.Monad
import Data.Time
import Text.Printf
type Microsecond = Int
type Scheduler = TimeOfDay -> Microsecond
-- Scheduling
--------------
getTime :: TimeZone -> IO TimeOfDay
getTime tz = do
t <- getCurrentTime
return $ localTimeOfDay $ utcToLocalTime tz t
getGMTTime = getTime utc
getLocalTime = getCurrentTimeZone >>= getTime
-- Returns the difference between 'y' and the closest higher multiple of 'x'
nextInterval x y
| x > y = x - y
| mod y x > 0 = x - mod y x
| otherwise = 0
-- Given a interval in seconds, this function returns time delta in microseconds.
onInterval :: Int -> Scheduler
onInterval interval time = toNext dMS
where
toNext = nextInterval (1000000 * interval)
tDelta = timeOfDayToTime time
dMS = truncate $ 1000000 * tDelta
doWithScheduler :: Scheduler -> (Int -> IO ()) -> IO ThreadId
doWithScheduler sched task = forkIO $ forM_ [0..] exec
where
exec n = do
t <- getLocalTime
threadDelay $ sched t
task n
-- Output
---------
watchNames = words "Middle Morning Forenoon Afternoon Dog First"
countWords = words "One Two Three Four Five Six Seven Eight"
-- Executes IO action and then waits for n microseconds
postDelay n fn = fn >> threadDelay n
termBell = putStr "\a"
termBells n = replicateM_ n $ postDelay 100000 termBell
termBellSeq seq = forM_ seq $ postDelay 500000 . termBells
toNoteGlyph 1 = "♪"
toNoteGlyph 2 = "♫"
toNoteGlyph _ = ""
ringBells :: Int -> IO ()
ringBells n = do
t <- getLocalTime
let numBells = 1 + (mod n 8)
watch = watchNames!!(mod (div n 8) 8)
count = countWords!!(numBells - 1)
(twos,ones) = quotRem numBells 2
pattern = (replicate twos 2) ++ (replicate ones 1)
notes = unwords $ map toNoteGlyph pattern
plural = if numBells > 1 then "s" else ""
strFMT = show t ++ ": %s watch, %5s bell%s: " ++ notes ++ "\n"
printf strFMT watch count plural
termBellSeq pattern
-- Usage
---------
bellRinger :: IO ThreadId
bellRinger = doWithScheduler (onInterval (30*60)) ringBells
|
http://rosettacode.org/wiki/Nested_templated_data | Nested templated data | A template for data is an arbitrarily nested tree of integer indices.
Data payloads are given as a separate mapping, array or other simpler, flat,
association of indices to individual items of data, and are strings.
The idea is to create a data structure with the templates' nesting, and the
payload corresponding to each index appearing at the position of each index.
Answers using simple string replacement or regexp are to be avoided. The idea is
to use the native, or usual implementation of lists/tuples etc of the language
and to hierarchically traverse the template to generate the output.
Task Detail
Given the following input template t and list of payloads p:
# Square brackets are used here to denote nesting but may be changed for other,
# clear, visual representations of nested data appropriate to ones programming
# language.
t = [
[[1, 2],
[3, 4, 1],
5]]
p = 'Payload#0' ... 'Payload#6'
The correct output should have the following structure, (although spacing and
linefeeds may differ, the nesting and order should follow):
[[['Payload#1', 'Payload#2'],
['Payload#3', 'Payload#4', 'Payload#1'],
'Payload#5']]
1. Generate the output for the above template, t.
Optional Extended tasks
2. Show which payloads remain unused.
3. Give some indication/handling of indices without a payload.
Show output on this page.
| #zkl | zkl | var payloads=[1..6].pump(List,"Payload#".append);
fcn get(n){ try{ payloads[n - 1] }catch{ Void } }
fcn sub(list){ list.pump(List, fcn(n){ if(n.isType(List)) sub(n) else get(n) }) } |
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)
| #Prolog | Prolog | /*
* Nonogram/paint-by-numbers solver in SWI-Prolog. Uses CLP(FD),
* in particular the automaton/3 (finite-state/RE) constraint.
* Copyright (c) 2011 Lars Buitinck.
* Do with this code as you like, but don't remove the copyright notice.
*/
:- use_module(library(clpfd)).
nono(RowSpec, ColSpec, Grid) :-
rows(RowSpec, Grid),
transpose(Grid, GridT),
rows(ColSpec, GridT).
rows([], []).
rows([C|Cs], [R|Rs]) :-
row(C, R),
rows(Cs, Rs).
row(Ks, Row) :-
sum(Ks, #=, Ones),
sum(Row, #=, Ones),
arcs(Ks, Arcs, start, Final),
append(Row, [0], RowZ),
automaton(RowZ, [source(start), sink(Final)], [arc(start,0,start) | Arcs]).
% Make list of transition arcs for finite-state constraint.
arcs([], [], Final, Final).
arcs([K|Ks], Arcs, CurState, Final) :-
gensym(state, NextState),
( K == 0
-> Arcs = [arc(CurState,0,CurState), arc(CurState,0,NextState) | Rest],
arcs(Ks, Rest, NextState, Final)
; Arcs = [arc(CurState,1,NextState) | Rest],
K1 #= K-1,
arcs([K1|Ks], Rest, NextState, Final)).
make_grid(Grid, X, Y, Vars) :-
length(Grid,X),
make_rows(Grid, Y, Vars).
make_rows([], _, []).
make_rows([R|Rs], Len, Vars) :-
length(R, Len),
make_rows(Rs, Len, Vars0),
append(R, Vars0, Vars).
print([]).
print([R|Rs]) :-
print_row(R),
print(Rs).
print_row([]) :- nl.
print_row([X|R]) :-
( X == 0
-> write(' ')
; write('x')),
print_row(R).
nonogram(Rows, Cols) :-
length(Rows, X),
length(Cols, Y),
make_grid(Grid, X, Y, Vars),
nono(Rows, Cols, Grid),
label(Vars),
print(Grid). |
http://rosettacode.org/wiki/Nonoblock | Nonoblock | Nonoblock is a chip off the old Nonogram puzzle.
Given
The number of cells in a row.
The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.
Task
show all possible positions.
show the number of positions of the blocks for the following cases within the row.
show all output on this page.
use a "neat" diagram of the block positions.
Enumerate the following configurations
5 cells and [2, 1] blocks
5 cells and [] blocks (no blocks)
10 cells and [8] blocks
15 cells and [2, 3, 2, 3] blocks
5 cells and [2, 3] blocks (should give some indication of this not being possible)
Example
Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:
|_|_|_|_|_| # 5 cells and [2, 1] blocks
And would expand to the following 3 possible rows of block positions:
|A|A|_|B|_|
|A|A|_|_|B|
|_|A|A|_|B|
Note how the sets of blocks are always separated by a space.
Note also that it is not necessary for each block to have a separate letter.
Output approximating
This:
|#|#|_|#|_|
|#|#|_|_|#|
|_|#|#|_|#|
This would also work:
##.#.
##..#
.##.#
An algorithm
Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).
The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.
for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block.
(This is the algorithm used in the Nonoblock#Python solution).
Reference
The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
| #zkl | zkl | fcn nonoblocks(blocks,cells){
if(not blocks or blocks[0]==0) vm.yield( T(T(0,0)) );
else{
if(not ( blocks.sum(0) + blocks.len() -1<=cells ))
throw(Exception.AssertionError("Those blocks will not fit in those cells"));
blength,brest:=blocks[0], blocks[1,*]; # Deal with the first block of length
minspace4rest:=brest.reduce('+(1),0); # The other blocks need space
# Slide the start position from left to max RH index allowing for other blocks.
foreach bpos in (cells - minspace4rest - blength +1){
if(not brest) # No other blocks to the right so just yield this one.
vm.yield(T(T(bpos,blength)));
else{
# More blocks to the right so create a *sub-problem* of placing
# the brest blocks in the cells one space to the right of the RHS of
# this block.
offset:=bpos + blength +1;
# recursive call to nonoblocks yields multiple sub-positions
foreach subpos in (Utils.Generator(nonoblocks,brest,cells - offset)){
# Remove the offset from sub block positions
rest:=subpos.pump(List,'wrap([(bp,bl)]){ T(offset + bp, bl) });
# Yield this block plus sub blocks positions
vm.yield(T( T(bpos,blength) ).extend(rest) );
}
}
}
}
}
# Pretty print each run of blocks with a different letter for each block of filled cells
fcn pblock(vec,cells){
vector,ch:=cells.pump(List(),"_".copy), ["A".."Z"];
vec.apply2('wrap([(a,b)]){ a.walker(b).pump(Void,vector.set.fp1(ch.next())) });
String("|",vector.concat("|"),"|");
} |
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
| #JavaScript | JavaScript | function non_continuous_subsequences(ary) {
var non_continuous = new Array();
for (var i = 0; i < ary.length; i++) {
if (! is_array_continuous(ary[i])) {
non_continuous.push(ary[i]);
}
}
return non_continuous;
}
function is_array_continuous(ary) {
if (ary.length < 2)
return true;
for (var j = 1; j < ary.length; j++) {
if (ary[j] - ary[j-1] != 1) {
return false;
}
}
return true;
}
load('json2.js'); /* http://www.json.org/js.html */
print(JSON.stringify( non_continuous_subsequences( powerset([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.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Utils.Number [ Abstract ]
{
ClassMethod ConvertBase10ToN(pNum As %Integer = "", pBase As %Integer = "", pBaseStr As %String = "", pPos As %Integer = 0) As %String
{
If pNum=0 Quit ""
Set str=..ConvertBase10ToN(pNum\pBase, pBase, pBaseStr, pPos+1)
Quit str_$Extract(pBaseStr, pNum#pBase+1)
}
ClassMethod ConvertBaseNTo10(pStr As %String = "", pBase As %Integer = "", pBaseStr As %String = "", pPos As %Integer = 0) As %Integer
{
If pStr="" Quit 0
Set num=..ConvertBaseNTo10($Extract(pStr, 1, *-1), pBase, pBaseStr, pPos+1)
Set dec=$Find(pBaseStr, $Extract(pStr, *))-2
Quit num+(dec*(pBase**pPos))
}
ClassMethod ConvertBase(pStr As %String = "", pFrom As %Integer = 10, pTo As %Integer = 10, pBaseStr As %String = "", pLen As %Integer = 0) As %String
{
// some initialisation
If pBaseStr="" Set pBaseStr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// check input values
If pFrom=10 Set pStr=$Number(pStr, "i", 0) If pStr="" Quit ""
Set pFrom=$Number(pFrom, "i", 2, 94) If pFrom="" Quit ""
Set pTo=$Number(pTo, "i", 2, 94) If pTo="" Quit ""
Set pLen=$Number(pLen, "i", 0, 32) If pLen="" Quit ""
// does base number exceed base string?
If pFrom>$Length(pBaseStr) Quit ""
If pTo>$Length(pBaseStr) Quit ""
// allow for upper/lowercase values
If pTo=10 {
If $Match(pStr, "^[0-9a-z]+$"), $Match($Extract(pBaseStr, 1, pFrom), "^[0-9A-Z]+$") {
Set pStr=$ZConvert(pStr, "U")
}
If $Match(pStr, "^[0-9A-Z]+$"), $Match($Extract(pBaseStr, 1, pFrom), "^[0-9a-z]+$") {
Set pStr=$ZConvert(pStr, "L")
}
}
// do the conversion
If pFrom=pTo {
Set pStr=pStr
} ElseIf pFrom=10 {
Set pStr=..ConvertBase10ToN($Select(pStr=0: "", 1: pStr), pTo, pBaseStr)
} ElseIf pTo=10 {
Set pStr=..ConvertBaseNTo10(pStr, pFrom, pBaseStr)
} Else {
Set pStr=..ConvertBase10ToN(..ConvertBaseNTo10(pStr, pFrom, pBaseStr), pTo, pBaseStr)
}
// return value
If pLen=0 Quit pStr
If pTo'=10 Quit ..PadStr(pStr, pLen, $Extract(pBaseStr))
Quit ..PadStr(pStr, pLen)
}
ClassMethod PadStr(pStr As %String, pLen As %Integer, pZero As %String = 0) As %String [ Private ]
{
If $Length(pStr)>pLen Quit pStr
Quit $Translate($Justify(pStr, pLen), " ", pZero)
}
} |
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.
| #PowerShell | PowerShell |
function Select-NumberFromString
{
[CmdletBinding(DefaultParameterSetName="Decimal")]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string]
$InputObject,
[Parameter(ParameterSetName="Decimal")]
[Alias("d","Dec")]
[switch]
$Decimal,
[Parameter(ParameterSetName="Hexadecimal")]
[Alias("h","Hex")]
[switch]
$Hexadecimal,
[Parameter(ParameterSetName="Octal")]
[Alias("o","Oct")]
[switch]
$Octal,
[Parameter(ParameterSetName="Binary")]
[Alias("b","Bin")]
[switch]
$Binary
)
Begin
{
switch ($PSCmdlet.ParameterSetName)
{
"Decimal" {$base = 10; $pattern = '[+-]?\b[0-9]+\b'; break}
"Hexadecimal" {$base = 16; $pattern = '\b[0-9A-F]+\b' ; break}
"Octal" {$base = 8; $pattern = '\b[0-7]+\b' ; break}
"Binary" {$base = 2; $pattern = '\b[01]+\b' ; break}
"Default" {$base = 10; $pattern = '[+-]?\b[0-9]+\b'; break}
}
}
Process
{
foreach ($object in $InputObject)
{
if ($object -match $pattern)
{
$string = $Matches[0]
}
else
{
$string = $null
}
try
{
$value = [Convert]::ToInt32($string, $base)
}
catch
{
$value = $null
}
[PSCustomObject]@{
Number = $value
String = $string
Base = $base
IsNumber = $value -is [int]
InputString = $object
}
}
}
}
|
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.
| #Perl | Perl | foreach my $n (0..33) {
printf " %6b %3o %2d %2X\n", $n, $n, $n, $n;
} |
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.
| #Phix | Phix | with javascript_semantics
for i=2 to 32 by 10 do
printf(1,"decimal:%3d hex:%3x octal:%3o binary:%7b\n",i)
end for
|
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.
| #F.23 | F# |
//I provide 2 fuctions D2N takes a radix and an integer returning a sequence of integers
// N2D takse a radix and a sequence of integers returning an integer
//Note that the radix may be either positive or negative. Nigel Galloway, May 10th., 2019
let D2N n g=if g=0 then seq[0] else Seq.unfold(fun g->let α,β=g/n,g%n in match (compare g 0,β) with
(0,_)->None
|(1,_) |(_,0)->Some(β,α)
|_->Some(g-(α+1)*n,α+1)) g|>Seq.rev
let N2D n g=fst(Seq.foldBack(fun g (Σ,α)->(Σ+α*g,n*α)) g (0,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.
| #Factor | Factor | USING: formatting fry kernel make math math.combinators
math.extras math.functions math.parser sequences ;
: /mod* ( x y -- z w )
[ /mod ] keep '[ [ 1 + ] dip _ abs + ] when-negative ;
: >nega ( n radix -- str )
[ '[ _ /mod* # ] until-zero ] "" make reverse ;
: nega> ( str radix -- n )
swap <reversed> [ ^ swap digit> * ] with map-index sum ;
: .round-trip ( n radix -- )
dupd [ >nega ] keep 2dup 2dup nega>
"%d_10 is %s_%d\n%s_%d is %d_10\n\n" printf ;
10 -2 146 -3 15 -10 [ .round-trip ] 2tri@ |
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.
| #Swift | Swift | extension Int {
private static let bigNames = [
1_000: "thousand",
1_000_000: "million",
1_000_000_000: "billion",
1_000_000_000_000: "trillion",
1_000_000_000_000_000: "quadrillion",
1_000_000_000_000_000_000: "quintillion"
]
private static let names = [
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "fourteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen",
20: "twenty",
30: "thirty",
40: "forty",
50: "fifty",
60: "sixty",
70: "seventy",
80: "eighty",
90: "ninety"
]
public var numberName: String {
guard self != 0 else {
return "zero"
}
let neg = self < 0
let maxNeg = self == Int.min
var nn: Int
if maxNeg {
nn = -(self + 1)
} else if neg {
nn = -self
} else {
nn = self
}
var digits3 = [Int](repeating: 0, count: 7)
for i in 0..<7 {
digits3[i] = (nn % 1000)
nn /= 1000
}
func threeDigitsToText(n: Int) -> String {
guard n != 0 else {
return ""
}
var ret = ""
let hundreds = n / 100
let remainder = n % 100
if hundreds > 0 {
ret += "\(Int.names[hundreds]!) hundred"
if remainder > 0 {
ret += " "
}
}
if remainder > 0 {
let tens = remainder / 10
let units = remainder % 10
if tens > 1 {
ret += Int.names[tens * 10]!
if units > 0 {
ret += "-\(Int.names[units]!)"
}
} else {
ret += Int.names[remainder]!
}
}
return ret
}
let strings = (0..<7).map({ threeDigitsToText(n: digits3[$0]) })
var name = strings[0]
var big = 1000
for i in 1...6 {
if digits3[i] > 0 {
var name2 = "\(strings[i]) \(Int.bigNames[big]!)"
if name.count > 0 {
name2 += ", "
}
name = name2 + name
}
big &*= 1000
}
if maxNeg {
name = String(name.dropLast(5) + "eight")
}
return neg ? "minus \(name)" : name
}
}
let nums = [
0, 1, 7, 10, 18, 22, 67, 99, 100, 105, 999, -1056, 1000005000,
2074000000, 1234000000745003, Int.min
]
for number in nums {
print("\(number) => \(number.numberName)")
} |
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
| #UNIX_Shell | UNIX Shell | print "\nWelcome to the number reversal game!\n"
print "You must put the numbers in order from 1 to 9."
print "Your only moves are to reverse groups of numbers"
print "on the left side of the list."
integer list score
# start a new game
function newgame {
integer i j t
# score = number of moves
((score = 0))
# list = array of numbers
set -A list 1 2 3 4 5 6 7 8 9
while true; do
# Knuth shuffle
((i = 9))
while ((i > 1)); do
# get random j from 0 to i - 1
((j = RANDOM))
((j < 32768 % i)) && continue
((j %= i))
# decrement i, swap list[i] with list[j]
((i -= 1))
((t = list[i]))
((list[i] = list[j]))
((list[j] = t))
done
win || break
done
}
# numbers in order?
function win {
integer i
# check if list[0] == 1, list[1] == 2, ...
((i = 0))
while ((i < 9)); do
((list[i] != i + 1)) && return 1
((i += 1))
done
return 0
}
# reverse first $1 elements of list
function reverse {
integer left right t
((left = 0))
((right = $1 - 1))
while ((right > left)); do
((t = list[left]))
((list[left] = list[right]))
((list[right] = t))
((left += 1))
((right -= 1))
done
}
integer i
newgame
while true; do
print -n "\nYour list: "
((i = 0))
while ((i < 8)); do
printf "%d, " ${list[i]}
((i += 1))
done
printf "%d\n" ${list[8]}
if win; then
print "YOU WIN!"
printf "Your score is %d moves.\n" $score
print -n "Would you like to play again (y/n)? "
if read again && [[ $again = @(y|Y)* ]]; then
newgame
else
print "\n\nBye!"
exit
fi
else
print -n "How many numbers to reverse? "
if read i; then
((score += 1))
reverse $i
else
print "\n\nBye!"
exit
fi
fi
done |
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.
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Nim.bas"
110 RANDOMIZE
120 CLEAR SCREEN
130 LET TOKENS=12
140 PRINT "Starting with";TOKENS;"tokens.":PRINT
150 DO
160 PRINT "How many tokens will you take? (1-3) ";
170 DO
180 LET K=VAL(INKEY$)
190 LOOP UNTIL K>0 AND K<4
200 LET TOKENS=MAX(TOKENS-K,0):LET G=0
210 PRINT K:PRINT TAB(19);TOKENS;"remainig.":PRINT
220 IF TOKENS>0 THEN
230 LET L=MOD(TOKENS,4)
240 IF L=0 THEN LET L=MIN(RND(3)+1,TOKENS)
250 LET TOKENS=TOKENS-L:LET G=-1
260 PRINT "Computer takes";L;"tokens.";TOKENS;"remaining.":PRINT
270 END IF
280 LOOP WHILE TOKENS>0
290 IF G THEN
300 PRINT "Computer wins!"
310 ELSE
320 PRINT "You win!"
330 END IF |
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.
| #J | J | nim=: {{
prompt tokens=: 12
}}
prompt=: {{
echo 'tokens: ',":tokens
if. 1>tokens do.
echo 'game over'
else.
echo 'take 1, 2 or 3 tokens'
end.
}}
take=: {{
assert. y e.1 2 3
assert. 0=#$y
echo 'tokens: ',":tokens=:tokens-y
echo 'I take ',(":t=. 4-y),' tokens'
prompt tokens=:tokens-t
}} |
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.
| #BASIC | BASIC | FUNCTION RootX (tBase AS DOUBLE, tExp AS DOUBLE, diffLimit AS DOUBLE) AS DOUBLE
DIM tmp1 AS DOUBLE, tmp2 AS DOUBLE
' Initial guess:
tmp1 = tBase / tExp
DO
tmp2 = tmp1
' 1# tells compiler that "1" is a double, not an integer
tmp1 = (((tExp - 1#) * tmp2) + (tBase / (tmp2 ^ (tExp - 1#)))) / tExp
LOOP WHILE (ABS(tmp1 - tmp2) > diffLimit)
RootX = tmp1
END FUNCTION |
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.
| #Common_Lisp | Common Lisp | #1=(PRINT (EQUAL (WRITE-TO-STRING '#1# :CIRCLE 1) (READ-LINE *STANDARD-INPUT*))) |
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.
| #D | D | import std.file; import std.stdio; import std.string; void main() { auto source = readText("narcissist.d").chomp; auto input = readln().chomp(); if (source == input) writeln("accept"); else writeln("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.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | !. = !prompt "Enter my code: " concat( swap !decode!utf-8 !encode!quoted dup swap ) "!. = !prompt \qEnter my code: \q concat( swap !decode!utf-8 !encode!quoted dup swap ) " |
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.
| #Forth | Forth | : narcissist [ source ] sliteral compare 0= ; |
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
| #Kotlin | Kotlin | import java.math.BigInteger
import java.text.NumberFormat
fun main() {
for (s in arrayOf(
"0",
"9",
"12",
"21",
"12453",
"738440",
"45072010",
"95322020",
"9589776899767587796600",
"3345333"
)) {
println("${format(s)} -> ${format(next(s))}")
}
testAll("12345")
testAll("11122")
}
private val FORMAT = NumberFormat.getNumberInstance()
private fun format(s: String): String {
return FORMAT.format(BigInteger(s))
}
private fun testAll(str: String) {
var s = str
println("Test all permutations of: $s")
val sOrig = s
var sPrev = s
var count = 1
// Check permutation order. Each is greater than the last
var orderOk = true
val uniqueMap: MutableMap<String, Int> = HashMap()
uniqueMap[s] = 1
while (next(s).also { s = it }.compareTo("0") != 0) {
count++
if (s.toLong() < sPrev.toLong()) {
orderOk = false
}
uniqueMap.merge(s, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
sPrev = s
}
println(" Order: OK = $orderOk")
// Test last permutation
val reverse = StringBuilder(sOrig).reverse().toString()
println(" Last permutation: Actual = $sPrev, Expected = $reverse, OK = ${sPrev.compareTo(reverse) == 0}")
// Check permutations unique
var unique = true
for (key in uniqueMap.keys) {
if (uniqueMap[key]!! > 1) {
unique = false
}
}
println(" Permutations unique: OK = $unique")
// Check expected count.
val charMap: MutableMap<Char, Int> = HashMap()
for (c in sOrig.toCharArray()) {
charMap.merge(c, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
}
var permCount = factorial(sOrig.length.toLong())
for (c in charMap.keys) {
permCount /= factorial(charMap[c]!!.toLong())
}
println(" Permutation count: Actual = $count, Expected = $permCount, OK = ${count.toLong() == permCount}")
}
private fun factorial(n: Long): Long {
var fact: Long = 1
for (num in 2..n) {
fact *= num
}
return fact
}
private fun next(s: String): String {
val sb = StringBuilder()
var index = s.length - 1
// 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.
while (index > 0 && s[index - 1] >= s[index]) {
index--
}
// Reached beginning. No next number.
if (index == 0) {
return "0"
}
// Find digit on the right that is both more than it, and closest to it.
var index2 = index
for (i in index + 1 until s.length) {
if (s[i] < s[index2] && s[i] > s[index - 1]) {
index2 = i
}
}
// Found data, now build string
// Beginning of String
if (index > 1) {
sb.append(s.subSequence(0, index - 1))
}
// Append found, place next
sb.append(s[index2])
// Get remaining characters
val chars: MutableList<Char> = ArrayList()
chars.add(s[index - 1])
for (i in index until s.length) {
if (i != index2) {
chars.add(s[i])
}
}
// Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right.
chars.sort()
for (c in chars) {
sb.append(c)
}
return sb.toString()
} |
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
| #Go | Go | package main
import "fmt"
func makeList(separator string) string {
counter := 1
makeItem := func(item string) string {
result := fmt.Sprintf("%d%s%s\n", counter, separator, item)
counter += 1
return result
}
return makeItem("first") + makeItem("second") + makeItem("third")
}
func main() {
fmt.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
| #Haskell | Haskell | import Control.Monad.ST
import Data.STRef
makeList :: String -> String
makeList separator = concat $ runST $ do
counter <- newSTRef 1
let makeItem item = do
x <- readSTRef counter
let result = show x ++ separator ++ item ++ "\n"
modifySTRef counter (+ 1)
return result
mapM makeItem ["first", "second", "third"]
main :: IO ()
main = putStr $ 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
| #J | J | require 'strings printf'
WATCH =: <;._1 ' Middle Morning Forenoon Afternoon Dog First'
ORDINAL =: <;._1 ' One Two Three Four Five Six Seven Eight'
BELL =: 7{a. NB. Terminal bell code (\a or ^G)
time =: 6!:0
sleep =: 6!:3
print =: ucp 1!:2 4:
shipsWatch =: verb define
PREV_MARK =. _1 _1
while. do. NB. Loop forever
now =. 3 4 { time '' NB. Current hour & minute
NB. If we just flipped over to a new half-hour mark
if. (0 30 e.~ {: now) > now -: PREV_MARK do.
PREV_MARK =. now
'allsWell notes'=.callWatch now
print allsWell
(ringBell"0~ -@# {. 2|#) notes
print CRLF
end.
sleep 15.0
end.
)
callWatch =: verb define
'watch bells' =. clock2ship y
NB. Plural for 0~:bells ordinals are origin-1, not origin-0
NB. (and similarly 1+bells for notes).
fields=.(0{y);(1{y);(watch{::WATCH);(bells{::ORDINAL);('s'#~0~:bells)
notes =. ; (0 2#:1+bells) #&.> u:16b266b 16b266a NB. ♫♪
notes ;~ '%02d:%02d %s watch, %s Bell%s Gone: \t' sprintf fields
)
clock2ship =: verb define"1
NB. Convert from "24 hours of 60 minutes" to
NB. "6 watches of 8 bells", and move midnight
NB. from index-origin 0 (0 hrs, 0 minutes)
NB. index-origin 1 (0 watches, 1 bell).
6 8 #: 48 | _1 + 24 2 #. (, (30-1)&I.)/ y
)
ringBell =: dyad define
print BELL,y
NB. x indicates two rings (0) or just one (1)
if. 0=x do.
sleep 0.75
print BELL
sleep 0.25
else.
sleep 1.0
end.
y
) |
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)
| #Python | Python | from itertools import izip
def gen_row(w, s):
"""Create all patterns of a row or col that match given runs."""
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]
def deduce(hr, vr):
"""Fix inevitable value of cells, and propagate."""
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
"""See if any value in a given column is fixed;
if so, mark its corresponding row for future fixup."""
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
"""Ditto, for rows."""
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
# If there's 'x', something is wrong.
# If there's '?', needs more work.
for x in m:
print " ".join("x#.?"[i] for i in x)
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
# Initially mark all columns for update.
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print "Solution would be unique" # but could be incorrect!
else:
print "Solution may not be unique, doing exhaustive search:"
# We actually do exhaustive search anyway. Unique solution takes
# no time in this phase anyway, but just in case there's no
# solution (could happen?).
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print "No solution."
elif n == 1:
print "Unique solution."
else:
print n, "solutions."
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print "Horizontal runs:", s[0]
print "Vertical runs:", s[1]
deduce(s[0], s[1])
def main():
# Read problems from file.
fn = "nonogram_problems.txt"
for p in (x for x in open(fn).read().split("\n\n") if x):
solve(p)
print "Extra example not solvable by deduction alone:"
solve("B B A A\nB B A A")
print "Extra example where there is no solution:"
solve("B A A\nA A A")
main() |
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
| #jq | jq | # Generate a stream of subsets of the input array
def subsets:
if length == 0 then []
else .[0] as $first
| (.[1:] | subsets)
| ., ([$first] + .)
end ;
# Generate a stream of non-continuous indices in the range 0 <= i < .
def non_continuous_indices:
[range(0;.)] | subsets
| select(length > 1 and length != 1 + .[length-1] - .[0]) ;
def non_continuous_subsequences:
(length | non_continuous_indices) as $ix
| [.[ $ix[] ]] ; |
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
| #Julia | Julia | using Printf, IterTools
import Base.IteratorSize, Base.iterate, Base.length
iscontseq(n::Integer) = count_zeros(n) == leading_zeros(n) + trailing_zeros(n)
iscontseq(n::BigInt) = !ismatch(r"0", rstrip(bin(n), '0'))
function makeint2seq(n::Integer)
idex = collect(1:n)
function int2seq(m::Integer)
d = digits(m, base=2, pad=n)
idex[d .== 1]
end
return int2seq
end
struct NCSubSeq{T<:Integer}
n::T
end
mutable struct NCSubState{T<:Integer}
m::T
m2s::Function
end
Base.IteratorSize(::NCSubSeq) = Base.HasLength()
Base.length(a::NCSubSeq) = 2 ^ a.n - a.n * (a.n + 1) ÷ 2 - 1
function Base.iterate(a::NCSubSeq, as::NCSubState=NCSubState(5, makeint2seq(a.n)))
if 2 ^ a.n - 3 < as.m
return nothing
end
s = as.m2s(as.m)
as.m += 1
while iscontseq(as.m)
as.m += 1
end
return (s, as)
end
n = 4
println("Testing NCSubSeq for ", n, " items:\n ", join(NCSubSeq(n), " "))
s = "Rosetta"
cs = split(s, "")
m = 10
n = length(NCSubSeq(length(cs))) - m
println("\nThe first and last ", m, " NC sub-sequences of \"", s, "\":")
for (i, a) in enumerate(NCSubSeq(length(s)))
i <= m || n < i || continue
println(@sprintf "%6d %s" i join(cs[a], ""))
i == m || continue
println(" .. ......")
end
println("\nThe first and last ", m, " NC sub-sequences of \"", s, "\"")
for x in IterTools.Iterators.flatten([1:10; 20:10:40; big.(50:50:200)])
@printf "%7d → %d\n" x length(NCSubSeq(x))
end
|
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.
| #Common_Lisp | Common Lisp | (parse-integer "1a" :radix 16) ; returns multiple values: 26, 2
(write-to-string 26 :base 16) ; also "1A" |
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.
| #PureBasic | PureBasic | ;Val() parses integer strings
; decimal numbers have no prefix, hexadecimal needs a prefix of '$', binary needs a prefix of '%'
Val("1024102410241024") ; => 1024102410241024
Val("$10FFFFFFFF") ; => 73014444031
Val("%1000") ; => 8 |
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.
| #Python | Python | >>> text = '100'
>>> for base in range(2,21):
print ("String '%s' in base %i is %i in base 10"
% (text, base, int(text, base)))
String '100' in base 2 is 4 in base 10
String '100' in base 3 is 9 in base 10
String '100' in base 4 is 16 in base 10
String '100' in base 5 is 25 in base 10
String '100' in base 6 is 36 in base 10
String '100' in base 7 is 49 in base 10
String '100' in base 8 is 64 in base 10
String '100' in base 9 is 81 in base 10
String '100' in base 10 is 100 in base 10
String '100' in base 11 is 121 in base 10
String '100' in base 12 is 144 in base 10
String '100' in base 13 is 169 in base 10
String '100' in base 14 is 196 in base 10
String '100' in base 15 is 225 in base 10
String '100' in base 16 is 256 in base 10
String '100' in base 17 is 289 in base 10
String '100' in base 18 is 324 in base 10
String '100' in base 19 is 361 in base 10
String '100' in base 20 is 400 in base 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.
| #Phixmonti | Phixmonti | 33 for
dup "decimal: " print print " bin: " print 8 int>bit print nl
endfor |
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.
| #PHP | PHP | <?php
foreach (range(0, 33) as $n) {
echo decbin($n), "\t", decoct($n), "\t", $n, "\t", dechex($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.
| #Go | Go | package main
import (
"fmt"
"log"
"strings"
)
const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
func reverse(bs []byte) []byte {
for i, j := 0, len(bs)-1; i < len(bs)/2; i, j = i+1, j-1 {
bs[i], bs[j] = bs[j], bs[i]
}
return bs
}
func encodeNegBase(n, b int64) (string, error) {
if b < -62 || b > -1 {
return "", fmt.Errorf("base must be between -62 and -1 inclusive")
}
if n == 0 {
return "0", nil
}
var out []byte
for n != 0 {
rem := n % b
n /= b
if rem < 0 {
n++
rem -= b
}
out = append(out, digits[int(rem)])
}
reverse(out)
return string(out), nil
}
func decodeNegBase(ns string, b int64) (int64, error) {
if b < -62 || b > -1 {
return 0, fmt.Errorf("base must be between -62 and -1 inclusive")
}
if ns == "0" {
return 0, nil
}
total := int64(0)
bb := int64(1)
bs := []byte(ns)
reverse(bs)
for _, c := range bs {
total += int64(strings.IndexByte(digits, c)) * bb
bb *= b
}
return total, nil
}
func main() {
numbers := []int64{10, 146, 15, -942, 1488588316238}
bases := []int64{-2, -3, -10, -62, -62}
for i := 0; i < len(numbers); i++ {
n := numbers[i]
b := bases[i]
ns, err := encodeNegBase(n, b)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%13d encoded in base %-3d = %s\n", n, b, ns)
n, err = decodeNegBase(ns, b)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%13s decoded in base %-3d = %d\n\n", ns, b, 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.
| #Tcl | Tcl | proc int2words {n} {
if { ! [regexp -- {^(-?\d+)$} $n -> n]} {
error "not a decimal integer"
}
if {$n == 0} {
return zero
}
if {$n < 0} {
return "negative [int2words [expr {abs($n)}]]"
}
if {[string length $n] > 36} {
error "value too large to represent"
}
set groups [get_groups $n]
set l [llength $groups]
foreach group $groups {
incr l -1
# ensure any group with a leading zero is not treated as octal
set val [scan $group %d]
if {$val > 0} {
lappend result [group2words $val $l]
}
}
return [join $result ", "]
}
set small {"" one two three four five six seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen seventeen eighteen nineteen}
set tens {"" "" twenty thirty forty fifty sixty seventy eighty ninety}
set powers {"" thousand}
foreach p {m b tr quadr quint sext sept oct non dec} {lappend powers ${p}illion}
proc group2words {n level} {
global small tens powers
if {$n < 20} {
lappend result [lindex $small $n]
} elseif {$n < 100} {
lassign [divmod $n 10] a b
set result [lindex $tens $a]
if {$b > 0} {
append result - [lindex $small $b]
}
} else {
lassign [divmod $n 100] a b
lappend result [lindex $small $a] hundred
if {$b > 0} {
lappend result and [group2words $b 0]
}
}
return [join [concat $result [lindex $powers $level]]]
}
proc divmod {n d} {
return [list [expr {$n / $d}] [expr {$n % $d}]]
}
proc get_groups {num} {
# from http://wiki.tcl.tk/5000
while {[regsub {^([-+]?\d+)(\d\d\d)} $num {\1 \2} num]} {}
return [split $num]
}
foreach test {
0 -0 5 -5 10 25 99 100 101 999 1000 1008 1010 54321 1234567890
0x7F
123456789012345678901234567890123456
1234567890123456789012345678901234567
} {
catch {int2words $test} result
puts "$test -> $result"
} |
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
| #VBA | VBA | Private Function shuffle(ByVal a As Variant) As Variant
Dim t As Variant, i As Integer
For i = UBound(a) To LBound(a) + 1 Step -1
j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))
t = a(i)
a(i) = a(j)
a(j) = t
Next i
shuffle = a
End Function
Private Sub reverse(ByRef a As Variant, n As Integer)
Dim b As Variant
b = a
For i = 1 To n
a(i) = b(n + 1 - i)
Next i
End Sub
Public Sub game()
Debug.Print "Given a jumbled list of the numbers 1 to 9"
Debug.Print "you must select how many digits from the left to reverse."
Debug.Print "Your goal is to get the digits in order with 1 on the left and 9 on the right."
inums = [{1,2,3,4,5,6,7,8,9}]
Dim nums As Variant
Dim turns As Integer, flip As Integer
shuffled = False
Do While Not shuffled
nums = shuffle(inums)
For i = LBound(nums) To UBound(nums)
If nums(i) <> inums(i) Then
shuffled = True
Exit For
End If
Next i
Loop
Do While True
Debug.Print turns; ":";
For Each x In nums: Debug.Print x;: Next x
Debug.Print
flag = False
For i = LBound(nums) To UBound(nums)
If nums(i) <> inums(i) Then
flag = True
Exit For
End If
Next i
If flag Then
flip = InputBox(" -- How many numbers should be flipped? ")
reverse nums, flip
turns = turns + 1
Else
Exit Do
End If
Loop
Debug.Print "You took"; turns; "turns to put the digits in order."
End Sub |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Java | Java |
import java.util.Scanner;
public class NimGame {
public static void main(String[] args) {
runGame(12);
}
private static void runGame(int tokens) {
System.out.printf("Nim game.%n%n");
Scanner in = new Scanner(System.in);;
do {
boolean humanInputOk = false;
int humanTokens = 0;
while ( ! humanInputOk ) {
System.out.printf("Human takes how many tokens? ");
String input = in.next();
try {
humanTokens = Integer.parseInt(input);
if ( humanTokens >= 1 && humanTokens <= 3 ) {
humanInputOk = true;
}
else {
System.out.printf("Try a number between 1 and 3.%n");
}
}
catch (NumberFormatException e) {
System.out.printf("Invalid input. Try a number between 1 and 3.%n");
}
}
tokens -= humanTokens;
System.out.printf("You take %d token%s.%n%d token%s remaining.%n%n", humanTokens, humanTokens > 1 ? "s" : "", tokens, tokens != 1 ? "s" : "");
if ( tokens == 0 ) {
System.out.printf("You win!!.%n%n");
break;
}
int computerTokens = 4 - humanTokens;
tokens -= computerTokens;
System.out.printf("Computer takes %d token%s.%n%d token%s remaining.%n%n", computerTokens, computerTokens != 1 ? "s" : "", tokens, tokens != 1 ? "s" : "");
if ( tokens == 0 ) {
System.out.printf("Computer wins!!.%n%n");
}
} while (tokens > 0);
in.close();
}
}
|
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.
| #Basic09 | Basic09 |
PROCEDURE nth
PARAM N : INTEGER; A, P : REAL
DIM TEMP0, TEMP1 : REAL
TEMP0 := A
TEMP1 := A/N
WHILE ( abs(TEMP0 - TEMP1) > P) DO
TEMP0 := TEMP1
TEMP1 := (( N - 1.0) * TEMP1 + A / TEMP1 ^ (N - 1.0)) / N
ENDWHILE
PRINT "Root Number Precision"
PRINT N, A, P
PRINT "The Root is: ";TEMP1
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.
| #BASIC256 | BASIC256 | function nth_root(n, a)
precision = 0.0001
dim x(2)
x[0] = a
x[1] = a /n
while abs(x[1] - x[0]) > precision
x[0] = x[1]
x[1] = ((n -1.0) * x[1] +a / x[1]^(n -1.0)) / n
end while
return x[1]
end function
print " n 5643 ^ 1 / n nth_root ^ n"
print " --------------------------------------"
for n = 3 to 11 step 2
tmp = nth_root(n, 5643)
print " "; n; " "; tmp; chr(9); (tmp ^ n)
next n
print
for n = 25 to 125 step 25
tmp = nth_root(n, 5643)
print n; " "; tmp; chr(9); (tmp ^ n)
next n |
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.
| #FreeBASIC | FreeBASIC | Dim As String a, s = "Dim As String a, s = Input a : Print (a = Left(s, 21) + Chr(34) + s + Chr(34) + Mid(s, 47, 3) + Mid(s, 23, 108)) + Mid(s, 54, 3)" : Input a : Print (a = Left(s, 21) + Chr(34) + s + Chr(34) + Mid(s, 47, 3) + Mid(s, 23, 108)) |
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.
| #Go | Go | package main; import "os"; import "fmt"; import "bytes"; import "io/ioutil"; func main() {ios := "os"; ifmt := "fmt"; ibytes := "bytes"; iioutil := "io/ioutil"; zero := "Reject"; one := "Accept"; x := "package main; import %q; import %q; import %q; import %q; func main() {ios := %q; ifmt := %q; ibytes := %q; iioutil := %q; zero := %q; one := %q; x := %q; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}\n"; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};} |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[NextHighestIntFromDigits]
NextHighestIntFromDigits[n_Integer?NonNegative]:=Module[{digs},
digs=IntegerDigits[n];
digs=FromDigits/@Permutations[digs];
digs=Select[digs,GreaterEqualThan[n]];
If[Length[digs]==1,First[digs],RankedMin[digs,2]]
]
NextHighestIntFromDigits/@{0,9,12,21,12453,738440,45072010,95322020} |
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
| #Nim | Nim | import algorithm
type Digit = range[0..9]
func digits(n: Natural): seq[Digit] =
## Return the list of digits of "n" in reverse order.
if n == 0: return @[Digit 0]
var n = n
while n != 0:
result.add n mod 10
n = n div 10
func nextHighest(n: Natural): Natural =
## Find the next highest integer of "n".
## If none is found, "n" is returned.
var d = digits(n) # Warning: in reverse order.
var m = d[0]
for i in 1..d.high:
if d[i] < m:
# Find the digit greater then d[i] and closest to it.
var delta = m - d[i] + 1
var best: int
for j in 0..<i:
let diff = d[j] - d[i]
if diff > 0 and diff < delta:
# Greater and closest.
delta = diff
best = j
# Exchange digits.
swap d[i], d[best]
# Sort previous digits.
d[0..<i] = sorted(d.toOpenArray(0, i - 1), Descending)
break
else:
m = d[i]
# Compute the value from the digits.
for val in reversed(d):
result = 10 * result + val
when isMainModule:
for n in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020]:
echo n, " → ", nextHighest(n) |
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
| #Io | Io | makeList := method(separator,
counter := 1
makeItem := method(item,
result := counter .. separator .. item .. "\n"
counter = counter + 1
result
)
makeItem("first") .. makeItem("second") .. makeItem("third")
)
makeList(". ") 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
| #J | J | MakeList=: dyad define
sep_MakeList_=: x
cnt_MakeList_=: 0
;MakeItem each y
)
MakeItem=: verb define
cnt_MakeList_=: cnt_MakeList_+1
(":cnt_MakeList_),sep_MakeList_,y,LF
) |
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
| #Java | Java | import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class NestedFunctionsDemo {
static String makeList(String separator) {
AtomicInteger counter = new AtomicInteger(1);
Function<String, String> makeItem = item -> counter.getAndIncrement() + separator + item + "\n";
return makeItem.apply("first") + makeItem.apply("second") + makeItem.apply("third");
}
public static void main(String[] args) {
System.out.println(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
| #Java | Java | import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class NauticalBell extends Thread {
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000)); // midnight
while (next < time) {
next += 30 * 60 * 1000; // 30 minutes
numBells = 1 + (numBells % 8);
}
while (true) {
long wait = 100L;
time = System.currentTimeMillis();
if (time - next >= 0) {
String bells = numBells == 1 ? "bell" : "bells";
String timeString = sdf.format(time);
System.out.printf("%s : %d %s\n", timeString, numBells, bells);
next += 30 * 60 * 1000;
wait = next - time;
numBells = 1 + (numBells % 8);
}
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
return;
}
}
}
} |
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)
| #Racket | Racket | #lang racket
;;; --------------------------------------------------------------------------------------------------
;;; Representaiton is done with bits: the bit patterns for a block being:
;;; -------------------------------------------------------------------------
;;; #b00 (0) - block is not in representation (also a terminator on the left)
;;; #b01 (1) - block is white
;;; #b10 (2) - block is black
;;; #b11 (3) - block is undecided
;;; None of the problems has > 32 columns, so 64-bits should be fine
;;; If we go above 64-bits, then a. we have a difficult problem
;;; b. racket will use bignums rather
;;; than fixnums
;;;
;;; A "blocks" is an integer formed of two-bit block codes (above)
;;;
;;; A "representation" is a sequence (list) of black stretch lengths; which need to be separated by at
;;; least one white between, and optionally prefixed and suffied with whites
;;;
;;; A "candidate" is a sequence (list) of <white-length [black-length white-length]...>, specifying
;;; one instance of a "representation".
;;;
;;; A "puzzle" is a sequence (vector) of blocks
;;; -- if the puzzle is <= 32 blocks wide, this could well be an fxvector (but ignore that
;;; possibility for now)
;;;
;;; "Options" is a sequence (list) of blocks
;;;
;;; white is often abbreviated (in variables etc. to W), black to "B"
;;; --------------------------------------------------------------------------------------------------
(module+ test (require rackunit))
(define *problems-file-name* "nonogram_problems.txt")
;;; --------------------------------------------------------------------------------------------------
;;; Parsing Input
;;; --------------------------------------------------------------------------------------------------
(define (letter-rep->number-rep c) (+ 1 (- (char->integer (char-upcase c)) (char->integer #\A))))
;; takes the letters representation, returns a list of list of numbers. The list returned is an
;; "option" - a list of ([white-width black-width] ... white-width)
(define (letters-rep->list²-rep s)
(for/list ((b (regexp-split #rx" +" s)))
(map letter-rep->number-rep (string->list b))))
(define (read-nonogram-description prt)
(match (read-line prt)
[(? eof-object?) #f]
["" (read-nonogram-description prt)]
[(? string? l)
(vector (letters-rep->list²-rep l)
(letters-rep->list²-rep (read-line prt)))]))
(define (read-one-nonogram-from-file file-name)
(call-with-input-file file-name read-nonogram-description))
(module+ test
(check-equal? (map letter-rep->number-rep '(#\A #\a #\B #\C)) '(1 1 2 3))
(check-equal? (letters-rep->list²-rep "C BA CB BB F AE F A B")
'([3] [2 1] [3 2] [2 2] [6] [1 5] [6] [1] [2]))
(check-equal? (letters-rep->list²-rep "AB CA AE GA E C D C")
'([1 2] [3 1] [1 5] [7 1] [5] [3] [4] [3]))
(check-equal? (read-one-nonogram-from-file *problems-file-name*)
#(([3] [2 1] [3 2] [2 2] [6] [1 5] [6] [1] [2])
([1 2] [3 1] [1 5] [7 1] [5] [3] [4] [3]))))
;;; --------------------------------------------------------------------------------------------------
;;; Generate Candidates
;;; --------------------------------------------------------------------------------------------------
(define (rep->candidates n-cells blacks)
(define (inr cells-remain bs leftmost?)
(define bs-l (sequence-length bs))
(define min-space-needed (- (apply + bs-l bs) 1))
(cond
[(null? bs) (list (list cells-remain))]
[(> min-space-needed cells-remain) null]
[else
(define initial-whites-min-size (if leftmost? 0 1))
(define intial-whites-range
(in-range initial-whites-min-size (add1 (- cells-remain min-space-needed))))
(for*/list ((intial-whites intial-whites-range)
(tl (in-list (inr (- cells-remain intial-whites (car bs)) (cdr bs) #f))))
(list* intial-whites (car bs) tl))]))
(inr n-cells blacks #t))
(module+ test
(check-match
(rep->candidates 5 '(1)) (list-no-order '(0 1 4) '(1 1 3) '(2 1 2) '(3 1 1) '(4 1 0)))
(check-match
(rep->candidates 5 '(1 1))
(list-no-order '(0 1 1 1 2) '(0 1 2 1 1) '(0 1 3 1 0) '(1 1 1 1 1) '(1 1 2 1 0) '(2 1 1 1 0))))
(define (make-Ws l) (for/fold ((rv 0)) ((_ l)) (+ (* 4 rv) #b01)))
(define (make-Bs l) (* 2 (make-Ws l)))
(module+ test
(check-eq? (make-Ws 0) #b00)
(check-eq? (make-Bs 0) #b00)
(check-eq? (make-Ws 1) #b01)
(check-eq? (make-Bs 1) #b10)
(check-eq? (make-Ws 3) #b010101)
(check-eq? (make-Bs 3) #b101010))
(define (candidate->blocks cand)
(define (inr cand rv)
(match cand
[(list (and W (app make-Ws Ws)) (and B (app make-Bs Bs)) r ...)
(inr r (+ (arithmetic-shift rv (* 2 (+ B W))) (arithmetic-shift Ws (* 2 B)) Bs))]
[(list (and W (app make-Ws Ws))) (+ (arithmetic-shift rv (* 2 W)) Ws)]))
(inr cand 0))
(module+ test
(check-eq? (candidate->blocks '(0)) 0)
(check-eq? (candidate->blocks '(1)) #b01)
(check-eq? (candidate->blocks '(1 1 1)) #b011001)
(check-equal?
(map candidate->blocks
'((0 1 1 1 2) (0 1 2 1 1) (0 1 3 1 0) (1 1 1 1 1) (1 1 2 1 0) (2 1 1 1 0)))
'(#b1001100101 #b1001011001 #b1001010110 #b0110011001 #b0110010110 #b0101100110)))
;; Given a (non-empty) sequence of blocks return a list of blocks which must be black, must be
;; white or have to be dertermined another way (through matching along the other axis).
(define (find-definite-blocks blocks)
(for/fold ((known (sequence-ref blocks 0))) ((merge blocks))
(bitwise-ior known merge)))
(module+ test
(check-eq? (find-definite-blocks '(#b010101 #b010110 #b100110)) #b110111)
)
;; returns the list of blocks (from options) that can be overlaid over the solution
;; this means that the following must hold false for all bits (if it holds false, we can do a zero?
;; test, which is easiser than an all-significant-bits-set? test:
;; pattern cand
;; 0 0 F
;; 0 1 T
;; 1 0 F
;; 1 1 F
;; (cand !bitwise-impl pattern) = !(pattern | !cand) = (!pattern & cand)
(define (filter-against-partial-solution part-sltn options)
(define not-part-sltn (bitwise-not part-sltn))
(define (option-fits? cand) (zero? (bitwise-and cand not-part-sltn)))
(filter option-fits? options))
(module+ test
(check-equal?
(filter-against-partial-solution #b011110 '(#b101010 #b010110 #b011010))
'(#b010110 #b011010)))
;;; --------------------------------------------------------------------------------------------------
;;; Rendering -- it's pretty tough to see what's going on, when you have no pictures!
;;; --------------------------------------------------------------------------------------------------
(define ((render-puzzle knil kons-W kons-B kons-_ compose-lines) pzl)
(define (render-blocks bs)
(define (inr bs acc)
(match (bitwise-and bs #b11)
[#b00 acc]
[#b01 (inr (arithmetic-shift bs -2) (kons-W acc))]
[#b10 (inr (arithmetic-shift bs -2) (kons-B acc))]
[#b11 (inr (arithmetic-shift bs -2) (kons-_ acc))]))
(inr bs knil))
(compose-lines (map render-blocks pzl)))
(define string-render-puzzle
(render-puzzle ""
(curry string-append ".")
(curry string-append "#")
(curry string-append "?")
(curryr string-join "\n")))
(module+ test
(check-equal? (string-render-puzzle '(#b101010 #b010101 #b111111)) "###\n...\n???"))
;;; We need to work on x and y blocks uniformly, so this will convert from one to t'other
;;; Rotates a sequence of blocks
(define (rotate-blocks x-blocks)
(define x-width- (integer-length (sequence-ref x-blocks 0)))
(define x-width (if (odd? x-width-) (add1 x-width-) x-width-))
;(printf "~a ~a" x-width x-blocks)
(for/list ((block-idx (in-range x-width 0 -2)))
(for/fold ((y-block 0))
((x-block x-blocks))
(+ (arithmetic-shift y-block 2)
(bitwise-bit-field x-block (- block-idx 2) block-idx)))))
(module+ test
(check-equal? (rotate-blocks '(#b1110 #b0111)) '(#b1101 #b1011))
(check-equal? (rotate-blocks '(#b0110 #b0111)) '(#b0101 #b1011)))
;;; --------------------------------------------------------------------------------------------------
;;; SOLVER (finally!):
;;; --------------------------------------------------------------------------------------------------
;;; solve the nonogram... both "solvers" return as values:
;;; solution-changed? did the solution change -- if not we either have a solution or as good a
;;; solution as the program can provide
;;; new-solution the newly-changed solution
;;; new-x-blocks x-blocks that are now available as candidates
;;; new-y-blocks y-blocks that are now available as candidates
(define (solved? blocks) (for/and ((b blocks)) (= (sequence-length b) 1)))
(define (solve-nonogram x-rep.y-rep) ; pair of reps as read from e.g. read-nonogram-from-file
(match-define (vector x-rep y-rep) x-rep.y-rep)
(define width (sequence-length y-rep))
(define height (sequence-length x-rep))
(define x-candidates (map (curry rep->candidates width) x-rep))
(define y-candidates (map (curry rep->candidates height) y-rep))
(define x-options (for/list ((cnds x-candidates)) (map candidate->blocks cnds)))
(define y-options (for/list ((cnds y-candidates)) (map candidate->blocks cnds)))
(define-values (solution complete?) (sub-solve-nonogram x-options y-options))
(unless complete? (displayln "INCOMPLETE SOLUTION"))
solution)
(define (sub-solve-nonogram x-options y-options)
(define known-x (map find-definite-blocks x-options))
(define known-y (map find-definite-blocks y-options))
(cond
[(solved? x-options) (values known-x #t)]
[else
(define new-y-options (map filter-against-partial-solution (rotate-blocks known-x) y-options))
(define new-x-options (map filter-against-partial-solution (rotate-blocks known-y) x-options))
(displayln (string-render-puzzle (map find-definite-blocks new-x-options)) (current-error-port))
(newline (current-error-port))
(if (and (equal? x-options new-x-options) (equal? y-options new-y-options))
(values known-x #f) ; oh... we can't get any further
(sub-solve-nonogram new-x-options new-y-options))]))
;;;; TESTING
(module+ test
(define chicken #<<EOS
.###....
##.#....
.###..##
..##..##
..######
#.#####.
######..
....#...
...##...
EOS
)
(check-equal?
(string-render-puzzle (solve-nonogram (read-one-nonogram-from-file *problems-file-name*)))
chicken))
;;; IMAGE RENDERING
(require pict racket/gui/base)
(define *cell-size* 10)
(define ((paint-cell fill-colour) dc dx dy)
(define C (- *cell-size* 1))
(define old-brush (send dc get-brush))
(define old-pen (send dc get-pen))
(define path (new dc-path%))
(send path rectangle 0 0 C C)
(send* dc
(set-brush (new brush% [color fill-colour]))
(set-pen (new pen% [width 1] [color "black"]))
(draw-path path dx dy)
(set-brush old-brush)
(set-pen old-pen)))
(define (draw-cell fill-colour)
(dc (paint-cell fill-colour)
*cell-size* *cell-size*))
(define ((row-append-cell colour) row-so-far)
(hc-append (draw-cell colour) row-so-far))
(define image-render-puzzle
(render-puzzle
(blank)
(row-append-cell "white")
(row-append-cell "black")
(row-append-cell "yellow")
(λ (rows) (apply vc-append rows))))
(module+ test
; test though visual inspection... it's a style thing, really
(image-render-puzzle (solve-nonogram (read-one-nonogram-from-file *problems-file-name*))))
;;; MAIN
(module+ main
(unless (directory-exists? "images") (make-directory "images"))
(call-with-input-file *problems-file-name*
(lambda (prt)
(let loop ((idx 1) (pzl (read-nonogram-description prt)) (collage (blank)))
(cond
[pzl
(define img (image-render-puzzle (solve-nonogram pzl)))
(send (pict->bitmap img) save-file (build-path "images" (format "nonogram-~a.png" idx))
'png)
(displayln (image-render-puzzle (solve-nonogram pzl)))
(loop (add1 idx) (read-nonogram-description prt) (vl-append 2 collage img))]
[else
(send (pict->bitmap collage) save-file (build-path "images" (format "nonogram-all.png"))
'png)
(displayln collage)]))))) |
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
| #Kotlin | Kotlin | // version 1.1.2
fun <T> ncs(a: Array<T>) {
fun generate(m: Int, k: Int, c: IntArray) {
if (k == m) {
if (c[m - 1] != c[0] + m - 1) {
for (i in 0 until m) print("${a[c[i]]} ")
println()
}
}
else {
for (j in 0 until a.size) {
if (k == 0 || j > c[k - 1]) {
c[k] = j
generate(m, k + 1, c)
}
}
}
}
for (m in 2 until a.size) {
val c = IntArray(m)
generate(m, 0, c)
}
}
fun main(args: Array<String>) {
val a = arrayOf(1, 2, 3, 4)
ncs(a)
println()
val ca = arrayOf('a', 'b', 'c', 'd', 'e')
ncs(ca)
} |
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.
| #D | D | import std.stdio, std.conv, std.string, std.ascii;
void main() {
"1abcd".to!int(16).writeln;
writeln(60_272_032_366.to!string(36, LetterCase.lower), ' ',
591_458.to!string(36, LetterCase.lower));
} |
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.
| #R | R | # parse a string to decimal
as.numeric("20") # 20
# parse a hex-string to decimal
as.numeric("0x20") # 32
# parse a string to hexadecimal
as.hexmode(as.numeric("32")) # "20"
# parse a string to octal
as.octmode(as.numeric("20")) # "24" |
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.
| #Racket | Racket |
#lang racket
;; Number literals can use #x, #o, and #b for different radices
(list 123 #x7B #o173 #b1111011)
;; -> '(123 123 123 123)
;; Explicit conversion of strings can use any radix up to 16
(list (string->number "123")
(string->number "123" 10)
(string->number "7B" 16)
(string->number "83" 15)
(string->number "96" 13)
(string->number "173" 8)
(string->number "11120" 3)
(string->number "1111011" 2))
;; -> '(123 123 123 123 123 123 123 123)
|
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.
| #PicoLisp | PicoLisp | (de printNumber (N Base)
(when (>= N Base)
(printNumber (/ N Base) Base) )
(let C (% N Base)
(and (> C 9) (inc 'C 39))
(prin (char (+ C `(char "0")))) ) )
(printNumber 26 16))
(prinl)
(printNumber 123456789012345678901234567890 36))
(prinl) |
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.
| #PL.2FI | PL/I |
get list (n);
put skip list (n); /* Prints N in decimal */
put skip edit (n) (B); /* prints N as a bit string, N > 0 */
|
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #PowerShell | PowerShell | foreach ($n in 0..33) {
"Base 2: " + [Convert]::ToString($n, 2)
"Base 8: " + [Convert]::ToString($n, 8)
"Base 10: " + $n
"Base 10: " + [Convert]::ToString($n, 10)
"Base 10: " + ("{0:D}" -f $n)
"Base 16: " + [Convert]::ToString($n, 16)
"Base 16: " + ("{0:X}" -f $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.
| #Haskell | Haskell | import Data.Char (chr, ord)
import Numeric (showIntAtBase)
-- The remainder and quotient of n/d, where the remainder is guaranteed to be
-- non-negative. The divisor, d, is assumed to be negative.
quotRemP :: Integral a => a -> a -> (a, a)
quotRemP n d = let (q, r) = quotRem n d
in if r < 0 then (q+1, r-d) else (q, r)
-- Convert the number n to base b, where b is assumed to be less than zero.
toNegBase :: Integral a => a -> a -> a
toNegBase b n = let (q, r) = quotRemP n b
in if q == 0 then r else negate b * toNegBase b q + r
-- Convert n to a string, where n is assumed to be a base b number, with b less
-- than zero.
showAtBase :: (Integral a, Show a) => a -> a -> String
showAtBase b n = showIntAtBase (abs b) charOf n ""
where charOf m | m < 10 = chr $ m + ord '0'
| m < 36 = chr $ m + ord 'a' - 10
| otherwise = '?'
-- Print a number in base b, where b is assumed to be less than zero.
printAtBase :: (Integral a, Show a) => a -> a -> IO ()
printAtBase b = putStrLn . showAtBase b . toNegBase b
main :: IO ()
main = do
printAtBase (-2) 10
printAtBase (-3) 146
printAtBase (-10) 15
printAtBase (-16) 107
printAtBase (-36) 41371458 |
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.
| #VBA | VBA | Public twenties As Variant
Public decades As Variant
Public orders As Variant
Private Sub init()
twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}]
decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}]
orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}]
End Sub
Private Function Twenty(N As Variant)
Twenty = twenties(N Mod 20 + 1)
End Function
Private Function Decade(N As Variant)
Decade = decades(N Mod 10 - 1)
End Function
Private Function Hundred(N As Variant)
If N < 20 Then
Hundred = Twenty(N)
Exit Function
Else
If N Mod 10 = 0 Then
Hundred = Decade((N \ 10) Mod 10)
Exit Function
End If
End If
Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10)
End Function
Private Function Thousand(N As Variant, withand As String)
If N < 100 Then
Thousand = withand & Hundred(N)
Exit Function
Else
If N Mod 100 = 0 Then
Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred"
Exit Function
End If
End If
Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100)
End Function
Private Function Triplet(N As Variant)
Dim Order, High As Variant, Low As Variant
Dim Name As String, res As String
For i = 1 To UBound(orders)
Order = orders(i, 1)
Name = orders(i, 2)
High = WorksheetFunction.Floor_Precise(N / Order)
Low = N - High * Order 'N Mod Order
If High <> 0 Then
res = res & Thousand(High, "") & " " & Name
End If
N = Low
If Low = 0 Then Exit For
If Len(res) And High <> 0 Then
res = res & ", "
End If
Next i
If N <> 0 Or res = "" Then
res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and "))
N = N - Int(N)
If N > 0.000001 Then
res = res & " point"
For i = 1 To 10
n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)
res = res & " " & twenties(n_ + 1)
N = N * 10 - n_
If Abs(N) < 0.000001 Then Exit For
Next i
End If
End If
Triplet = res
End Function
Private Function spell(N As Variant)
Dim res As String
If N < 0 Then
res = "minus "
N = -N
End If
res = res & Triplet(N)
spell = res
End Function
Private Function smartp(N As Variant)
Dim res As String
If N = WorksheetFunction.Floor_Precise(N) Then
smartp = CStr(N)
Exit Function
End If
res = CStr(N)
If InStr(1, res, ".") Then
res = Left(res, InStr(1, res, "."))
End If
smartp = res
End Function
Sub Main()
Dim si As Variant
init
Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]
Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]
For i = 1 To UBound(Samples1)
si = Samples1(i)
Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si)
Next i
For i = 1 To UBound(Samples2)
si = Samples2(i)
Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si)
Next i
End Sub |
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
| #Wren | Wren |
import "/sort" for Sort
import "random" for Random
import "io" for Stdin, Stdout
var r= Random.new()
var count = 0
var numbers = [0] * 9
numbers[0] = r.int(2, 10) // this will ensure list isn't ascending
for (i in 1..8) {
var rn
while(true) {
rn = r.int(1, 10)
if (!numbers.contains(rn)) break
}
numbers[i] = rn
}
System.print("Here's your first list : %(numbers)")
while (true) {
var rev
while (true) {
System.write("How many numbers from the left are to be reversed : ")
Stdout.flush()
rev = Num.fromString(Stdin.readLine())
if (rev.type == Num && rev.isInteger && rev >= 2 && rev <= 9) break
}
count = count + 1
var i = 0
var j = rev - 1
while (i < j) {
var temp = numbers[i]
numbers[i] = numbers[j]
numbers[j] = temp
i = i + 1
j = j - 1
}
if (Sort.isSorted(numbers)) {
System.print("Here's your final list : %(numbers)")
break
}
System.print("Here's your list now : %(numbers)")
}
System.print("So you've completed the game with a score of %(count)") |
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.
| #JavaScript | JavaScript |
class Nim {
constructor(tokens, printFun) {
this.startTokens = tokens;
this.tokens = tokens;
this.printFun = printFun;
}
playerTurn(take) {
take = Math.round(take);
if (take < 1 || take > 3) {
this.printFun("take must be between 1 and 3.\n")
return false;
}
this.tokens -= take;
this.printFun("Player takes " + take + " tokens.");
this.printRemaining()
if (this.tokens === 0) {
this.printFun("Player wins!\n");
}
return true;
}
computerTurn() {
let take = this.tokens % 4;
this.tokens -= take;
this.printFun("Computer takes " + take + " tokens.");
this.printRemaining();
if (this.tokens === 0) {
this.printFun("Computer wins.\n");
}
}
printRemaining() {
this.printFun(this.tokens + " tokens remaining.\n");
}
}
let game = new Nim(12, console.log);
while (true) {
if (game.playerTurn(parseInt(prompt("How many tokens would you like to take?")))){
game.computerTurn();
}
if (game.tokens == 0) {
break;
}
}
|
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.
| #BBC_BASIC | BBC BASIC | *FLOAT 64
@% = &D0D
PRINT "Cube root of 5 is "; FNroot(3, 5, 0)
PRINT "125th root of 5643 is "; FNroot(125, 5643, 0)
END
DEF FNroot(n%, a, d)
LOCAL x0, x1 : x0 = a / n% : REM Initial guess
REPEAT
x1 = ((n% - 1)*x0 + a/x0^(n%-1)) / n%
SWAP x0, x1
UNTIL ABS (x0 - x1) <= d
= x0 |
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']
| #11l | 11l | T.enum Kind
STRING
NUMBER
T KeyItem
Kind kind
String s
Int num
F natOrderKey(=s)
// Remove leading and trailing white spaces.
s = s.trim((‘ ’, "\t", "\r", "\n"))
// Make all whitespace characters equivalent and remove adjacent spaces.
s = s.replace(re:‘\s+’, ‘ ’)
// Switch to lower case.
s = s.lowercase()
// Remove leading "the ".
I s.starts_with(‘the ’) & s.len > 4
s = s[4..]
// Split into fields.
[KeyItem] result
V idx = 0
L idx < s.len
V e = idx
L e < s.len & !s[e].is_digit()
e++
I e > idx
V ki = KeyItem()
ki.kind = Kind.STRING
ki.s = s[idx .< e]
result.append(ki)
idx = e
L e < s.len & s[e].is_digit()
e++
I e > idx
V ki = KeyItem()
ki.kind = Kind.NUMBER
ki.num = Int(s[idx .< e])
result.append(ki)
idx = e
R result
F scmp(s1, s2)
I s1 < s2 {R -1}
I s1 > s2 {R 1}
R 0
F naturalCmp(String sa, String sb)
V a = natOrderKey(sa)
V b = natOrderKey(sb)
L(i) 0 .< min(a.len, b.len)
V ai = a[i]
V bi = b[i]
I ai.kind == bi.kind
V result = I ai.kind == STRING {scmp(ai.s, bi.s)} E ai.num - bi.num
I result != 0
R result
E
R I ai.kind == STRING {1} E -1
R I a.len < b.len {-1} E (I a.len == b.len {0} E 1)
F test(title, list)
print(title)
print(sorted(list, key' cmp_to_key(naturalCmp)).map(s -> ‘'’s‘'’).join("\n"))
print()
test(‘Ignoring leading spaces.’,
[‘ignore leading spaces: 2-2’,
‘ ignore leading spaces: 2-1’,
‘ ignore leading spaces: 2+0’,
‘ ignore leading spaces: 2+1’])
test(‘Ignoring multiple adjacent spaces (MAS).’,
[‘ignore MAS spaces: 2-2’,
‘ignore MAS spaces: 2-1’,
‘ignore MAS spaces: 2+0’,
‘ignore MAS spaces: 2+1’])
test(‘Equivalent whitespace characters.’,
[‘Equiv. spaces: 3-3’,
"Equiv. \rspaces: 3-2",
"Equiv. \x0cspaces: 3-1",
"Equiv. \x0bspaces: 3+0",
"Equiv. \nspaces: 3+1",
"Equiv. \tspaces: 3+2"])
test(‘Case Independent sort.’,
[‘cASE INDEPENDENT: 3-2’,
‘caSE INDEPENDENT: 3-1’,
‘casE INDEPENDENT: 3+0’,
‘case INDEPENDENT: 3+1’])
test(‘Numeric fields as numerics.’,
[‘foo100bar99baz0.txt’,
‘foo100bar10baz0.txt’,
‘foo1000bar99baz10.txt’,
‘foo1000bar99baz9.txt’])
test(‘Title sorts.’,
[‘The Wind in the Willows’,
‘The 40th step more’,
‘The 39 steps’,
‘Wanda’]) |
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.
| #Haskell | Haskell | main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q " |
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.
| #Huginn | Huginn | #! /bin/sh
exec huginn --no-argv -E "${0}"
#! huginn
main() {
c = "#! /bin/sh{1}~"
"exec huginn --no-argv -E {3}${{0}}{3}{1}#! huginn{1}{1}~"
"main() {{{1}{2}c = {3}{0}{3};{1}~"
"{2}s = {3}{3};{1}~"
"{2}while ( ( line = input() ) != none ) {{{1}~"
"{2}{2}s += line;{1}~"
"{2}}}{1}~"
"{2}self = copy( c ).replace( {3}{5}{3}, {3}{3} )~"
".format({1}{2}{2}c.replace( {3}{5}{3}, ~"
"{3}{5}{4}{3}{4}n{4}t{4}t{4}{3}{3} ), ~"
"{3}{4}n{3}, {3}{4}t{3}, {3}{4}{3}{3}, {3}{4}{4}{3}, ~"
"{3}{5}{3}{1}{2});{1}~"
"{2}print( s == self ? {3}1{4}n{3} : {3}0{4}n{3} );{1}}}{1}{1}";
s = "";
while ( ( line = input() ) != none ) {
s += line;
}
self = copy( c ).replace( "~", "" ).format(
c.replace( "~", "~\"\n\t\t\"" ), "\n", "\t", "\"", "\\", "~"
);
print( s == self ? "1\n" : "0\n" );
}
|
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main();yes:="Accept";no:="Reject";pat:="procedure main();yes:=$;no:=$;pat:=$;a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end";a:=[yes,no,pat];narc:=char(0)[0:0];pat?{while narc||:=tab(find(char(36))) do{narc||:=image(get(a));move(1)};narc||:=tab(0)};write(if read()==narc then yes else no);end |
http://rosettacode.org/wiki/Naming_conventions | Naming conventions | Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.
The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)
Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:
Procedure and operator names. (Intrinsic or external)
Class, Subclass and instance names.
Built-in versus libraries names.
If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.
If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "__" to make a member function "private".
See also
Wikipedia: Naming convention (programming)
| #11l | 11l | 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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use bigint;
use List::Util 'first';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub next_greatest_index {
my($str) = @_;
my @i = reverse split //, $str;
@i-1 - (1 + first { $i[$_] > $i[$_+1] } 0 .. @i-1);
}
sub next_greatest_integer {
my($num) = @_;
my $numr;
return 0 if length $num < 2;
return ($numr = 0 + reverse $num) > $num ? $numr : 0 if length $num == 2;
return 0 unless my $i = next_greatest_index( $num ) // 0;
my $digit = substr($num, $i, 1);
my @rest = sort split '', substr($num, $i);
my $next = first { $rest[$_] > $digit } 1..@rest;
join '', substr($num, 0, $i), (splice(@rest, $next, 1)), @rest;
}
say 'Next largest integer able to be made from these digits, or zero if no larger exists:';
for (0, 9, 12, 21, 12453, 738440, 45072010, 95322020, 9589776899767587796600, 3345333) {
printf "%30s -> %s\n", comma($_), comma next_greatest_integer $_;
} |
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
| #JavaScript | JavaScript | function makeList(separator) {
var counter = 1;
function makeItem(item) {
return counter++ + separator + item + "\n";
}
return makeItem("first") + makeItem("second") + makeItem("third");
}
console.log(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
| #jq | jq | def makeList(separator):
# input: {text: _, counter: _}
def makeItem(item):
(.counter + 1) as $counter
| .text += "\($counter)\(separator)\(item)\n"
| .counter = $counter;
{text:"", counter:0} | makeItem("first") | makeItem("second") | makeItem("third")
| .text
;
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
| #Jsish | Jsish | /* Nested function, in Jsish */
function makeList(separator) {
var counter = 1;
function makeItem(item) {
return counter++ + separator + item + "\n";
}
return makeItem("first") + makeItem("second") + makeItem("third");
}
;makeList('. ');
/*
=!EXPECTSTART!=
makeList('. ') ==> 1. first
2. second
3. third
=!EXPECTEND!=
*/ |
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
| #Julia | Julia | using Dates
"""
nauticalbells(DateTime)
Return a string according to the "simpler system" of nautical bells
listed in the table in Wikipedia at
en.wikipedia.org/wiki/Ship%27s_bell#Simpler_system.
Note the traditional time zone was determined by local sun position
and so should be local time without daylight savings time.
"""
function nauticalbells(dt::DateTime)
hr = hour(dt)
mn = minute(dt)
if hr in [00, 12, 4, 8, 16, 20]
return mn == 00 ? "2 2 2 2" : "1"
elseif hr in [1, 5, 9, 13, 17, 21]
return mn == 00 ? "2" : "2 1"
elseif hr in [2, 6, 10, 14, 18, 22]
return mn == 00 ? "2 2" : "2 2 1"
elseif hr in [3, 7, 11, 15, 19, 23]
return mn == 00 ? "2 2 2" : "2 2 2 1"
else
return "Gong pattern error: time $dt, hour $hr, minutes $mn"
end
end
function nauticalbelltask()
untilnextbell = ceil(now(), Dates.Minute(30)) - now()
delay = untilnextbell.value / 1000
println("Nautical bell task starting -- next bell in $delay seconds.")
# The timer wakes its task every half hour. May drift very slightly so restart yearly.
timer = Timer(delay; interval=1800)
while true
wait(timer)
gong = nauticalbells(now())
println("Nautical bell gong strikes ", gong)
end
end
nauticalbelltask()
|
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
| #Kotlin | Kotlin | // version 1.1.3
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.TimeZone
class NauticalBell: Thread() {
override fun run() {
val sdf = SimpleDateFormat("HH:mm:ss")
sdf.timeZone = TimeZone.getTimeZone("UTC")
var numBells = 0
var time = System.currentTimeMillis()
var next = time - (time % (24 * 60 * 60 * 1000)) // midnight
while (next < time) {
next += 30 * 60 * 1000 // 30 minutes
numBells = 1 + (numBells % 8)
}
while (true) {
var wait = 100L
time = System.currentTimeMillis()
if ((time - next) >= 0) {
val bells = if (numBells == 1) "bell" else "bells"
val timeString = sdf.format(time)
println("%s : %d %s".format(timeString, numBells, bells))
next += 30 * 60 * 1000
wait = next - time
numBells = 1 + (numBells % 8)
}
try {
Thread.sleep(wait)
}
catch (ie: InterruptedException) {
return
}
}
}
}
fun main(args: Array<String>) {
val bells = NauticalBell()
with (bells) {
setDaemon(true)
start()
try {
join()
}
catch (ie: InterruptedException) {
println(ie.message)
}
}
} |
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)
| #Raku | Raku | # 20220401 Raku programming solution
sub reduce(\a, \b) {
my \countRemoved = $ = 0;
for ^+a -> \i {
my \commonOn = @ = True xx b.elems;
my \commonOff = @ = False xx b.elems;
a[i].map: -> \candidate { commonOn <<?&=>> candidate ;
commonOff <<?|=>> candidate }
# remove from b[j] all candidates that don't share the forced values
for ^+b -> \j {
my (\fi,\fj) = i, j;
for ((+b[j])^...0) -> \k {
my \cnd = b[j][k];
if (commonOn[fj] ?& !cnd[fi]) ?| (!commonOff[fj] ?& cnd[fi]) {
b[j][k..*-2] = b[j][k+1..*-1];
b[j].pop;
countRemoved++
}
}
return -1 if b[j].elems == 0
}
}
return countRemoved
}
sub genSequence(\ones, \numZeros) {
if ( my \le = ones.elems ) == 0 { return [~] '0' xx numZeros }
my @result;
loop ( my $x = 1; $x < ( numZeros -le+2); $x++ ) {
my @skipOne = ones[1..*];
for genSequence(@skipOne, numZeros -$x) -> \tail {
@result.push: ( '0' x $x )~ones[0]~tail
}
}
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).
sub reduceMutual(\cols, \rows) {
return -1 if ( my \countRemoved1 = reduce(cols, rows) ) == -1 ;
return -1 if ( my \countRemoved2 = reduce(rows, cols) ) == -1 ;
return countRemoved1 + countRemoved2
}
# collect all possible solutions for the given clues
sub getCandidates(@data, \len) {
return gather for @data -> \s {
my \sumBytes = [+] (my @a = s.ords)>>.&{ $_ - 'A'.ord + 1 }
my @prep = @a.values.map: { [~] '1' xx ($_ - 'A'.ord + 1) }
take ( gather for genSequence(@prep, len -sumBytes+1) -> \r {
my \bits = r.substr(1..*).ords;
take ( bits.values.map: *.chr == '1' ).Array
} ).Array
}
}
sub newPuzzle (@data) {
my (@rowData,@colData) := @data.map: *.split: ' ' ;
my \rows = getCandidates(@rowData, @colData.elems);
my \cols = getCandidates(@colData, @rowData.elems);
loop {
my \numChanged = reduceMutual(cols, rows);
given (numChanged) { when -1 { say "No solution" andthen return }
when 0 { last } }
}
for rows -> \row {
for ^+cols -> \k { print row[0][k] ?? '# ' !! '. ' }
print "\n"
}
print "\n"
}
newPuzzle $_ for (
( "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" ),
); |
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
| #M2000_Interpreter | M2000 Interpreter |
Module Non_continuous_subsequences (item$(), display){
Function positions(n) {
function onebit {
=lambda b=false (&c)-> {
=b :if c then b~:c=not b
}
}
dim k(n)=onebit(), p(n)
m=true
flush
for i=1 to 2^n {
for j=0 to n-1 :p(j)= k(j)(&m) :next
m1=p(0)
m2=0
for j=1 to n-1
if m2 then if m1>p(j) then m2=2:exit for
if m1 < p(j) then m2++
m1=p(j)
next
if m2=2 then data cons(p())' push a copy of p() to end of stack
m=true
}
=array([])
}
a=positions(len(item$()))
if display then
For i=0 to len(a)-1
b=array(a,i)
line$=format$("{0::-5})",i+1,)
for j=0 to len(b)-1
if array(b,j) then line$+=" "+item$(j)
next
print line$
doc$<=line$+{
}
next
end if
line$="Non continuous subsequences:"+str$(len(a))
Print line$
doc$<=line$+{
}
}
global doc$
document doc$ ' change string to document object
Non_continuous_subsequences ("1","2","3","4"), true
Non_continuous_subsequences ("a","e","i","o","u"), true
Non_continuous_subsequences ("R","o","s","e","t","t","a"), true
Non_continuous_subsequences ("1","2","3","4","5","6","7","8","9","0"), false
clipboard doc$
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | GoodBad[i_List]:=Not[MatchQ[Differences[i],{1..}|{}]]
n=5
Select[Subsets[Range[n]],GoodBad] |
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.
| #E | E | def stringToInteger := __makeInt
def integerToString(i :int, base :int) {
return i.toString(base)
} |
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.