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/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.
| #Bracmat | Bracmat | ( get$("[
[[1, 2],
[3, 4, 1],
5]]",MEM,JSN)
: ?template
& (0.payload#0)
(1.payload#1)
(2.payload#2)
(3.payload#3)
(4.payload#4)
(5.payload#5)
(6.payload#6)
: ?payloads
& ( instantiate
= tmplt plds pld a b
. !arg:(?tmplt.?plds)
& ( !tmplt:#
& !plds:? (!tmplt.?pld) ?
& !pld
| !tmplt:%?a_%?b
& (instantiate$(!a.!plds))_(instantiate$(!b.!plds))
)
)
& out$(jsn$(instantiate$(!template.!payloads)))
); |
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.
| #C.2B.2B | C++ | #include <iostream>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
// print a single payload
template<typename P>
void PrintPayloads(const P &payloads, int index, bool isLast)
{
if(index < 0 || index >= (int)size(payloads)) cout << "null";
else cout << "'" << payloads[index] << "'";
if (!isLast) cout << ", "; // add a comma between elements
}
// print a tuple of playloads
template<typename P, typename... Ts>
void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)
{
std::apply // recursively call PrintPayloads on each element of the tuple
(
[&payloads, isLast](Ts const&... tupleArgs)
{
size_t n{0};
cout << "[";
(PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);
cout << "]";
cout << (isLast ? "\n" : ",\n");
}, nestedTuple
);
}
// find the unique index of a single index (helper for the function below)
void FindUniqueIndexes(set<int> &indexes, int index)
{
indexes.insert(index);
}
// find the unique indexes in the tuples
template<typename... Ts>
void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)
{
std::apply
(
[&indexes](Ts const&... tupleArgs)
{
(FindUniqueIndexes(indexes, tupleArgs),...);
}, nestedTuple
);
}
// print the payloads that were not used
template<typename P>
void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)
{
for(size_t i = 0; i < size(payloads); i++)
{
if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n";
}
}
int main()
{
// define the playloads, they can be in most containers
vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"};
const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"}; // as a C array
// define the indexes as a nested tuple
auto tpl = make_tuple(make_tuple(
make_tuple(1, 2),
make_tuple(3, 4, 1),
5));
cout << "Mapping indexes to payloads:\n";
PrintPayloads(payloads, tpl);
cout << "\nFinding unused payloads:\n";
set<int> usedIndexes;
FindUniqueIndexes(usedIndexes, tpl);
PrintUnusedPayloads(usedIndexes, payloads);
cout << "\nMapping to some out of range payloads:\n";
PrintPayloads(shortPayloads, tpl);
return 0;
} |
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)
| #F.23 | F# |
(*
I define a discriminated union to provide Nonogram Solver functionality.
Nigel Galloway May 28th., 2016
*)
type N =
|X |B |V
static member fn n i =
let fn n i = [for g = 0 to i-n do yield Array.init (n+g) (fun e -> if e >= g then X else B)]
let rec fi n i = [
match n with
| h::t -> match t with
| [] -> for g in fn h i do yield Array.append g (Array.init (i-g.Length) (fun _ -> B))
| _ -> for g in fn h ((i-List.sum t)+t.Length) do for a in fi t (i-g.Length-1) do yield Array.concat[g;[|B|];a]
| [] -> yield Array.init i (fun _ -> B)
]
fi n i
static member fi n i = Array.map2 (fun n g -> match (n,g) with |X,X->X |B,B->B |_->V) n i
static member fg (n: N[]) (i: N[][]) g = n |> Seq.mapi (fun e n -> i.[e].[g] = n || i.[e].[g] = V) |> Seq.forall (fun n -> n)
static member fe (n: N[][]) = n|> Array.forall (fun n -> Array.forall (fun n -> n <> V) n)
static member fl n = n |> Array.Parallel.map (fun n -> Seq.reduce (fun n g -> N.fi n g) n)
static member fa (nga: list<N []>[]) ngb = Array.Parallel.mapi (fun i n -> List.filter (fun n -> N.fg n ngb i) n) nga
static member fo n i g e =
let na = N.fa n e
let ia = N.fl na
let ga = N.fa g ia
(na, ia, ga, (N.fl ga))
static member toStr n = match n with |X->"X"|B->"."|V->"?"
static member presolve ((na: list<N []>[]), (ga: list<N []>[])) =
let nb = N.fl na
let x = N.fa ga nb
let rec fn n i g e l =
let na,ia,ga,ea = N.fo n i g e
let el = ((Array.map (fun n -> List.length n) na), (Array.map (fun n -> List.length n) ga))
if ((fst el) = (fst l)) && ((snd el) = (snd l)) then (n,i,g,e,(Array.forall (fun n -> n = 1) (fst l))) else fn na ia ga ea el
fn na nb x (N.fl x) ((Array.map (fun n -> List.length n) na), (Array.map (fun n -> List.length n) ga))
|
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.
| #Perl | Perl | use strict;
use warnings;
while( <DATA> )
{
print "\n$_", tr/\n/=/cr;
my ($cells, @blocks) = split;
my $letter = 'A';
$_ = join '.', map { $letter++ x $_ } @blocks;
$cells < length and print("no solution\n"), next;
$_ .= '.' x ($cells - length) . "\n";
1 while print, s/^(\.*)\b(.*?)\b(\w+)\.\B/$2$1.$3/;
}
__DATA__
5 2 1
5
10 8
15 2 3 2 3
5 2 3 |
http://rosettacode.org/wiki/Non-transitive_dice | Non-transitive dice | Let our dice select numbers on their faces with equal probability, i.e. fair dice.
Dice may have more or less than six faces. (The possibility of there being a
3D physical shape that has that many "faces" that allow them to be fair dice,
is ignored for this task - a die with 3 or 33 defined sides is defined by the
number of faces and the numbers on each face).
Throwing dice will randomly select a face on each die with equal probability.
To show which die of dice thrown multiple times is more likely to win over the
others:
calculate all possible combinations of different faces from each die
Count how many times each die wins a combination
Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice.
If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively.
Example 1
If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its
faces then the equal possibility outcomes from throwing both, and the winners
is:
X Y Winner
= = ======
1 2 Y
1 3 Y
1 4 Y
3 2 X
3 3 -
3 4 Y
6 2 X
6 3 X
6 4 X
TOTAL WINS: X=4, Y=4
Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y
Transitivity
In mathematics transitivity are rules like:
if a op b and b op c then a op c
If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers
we get the familiar if a < b and b < c then a < c
Non-transitive dice
These are an ordered list of dice where the '>' operation between successive
dice pairs applies but a comparison between the first and last of the list
yields the opposite result, '<'.
(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).
Three dice S, T, U with appropriate face values could satisfy
S < T, T < U and yet S > U
To be non-transitive.
Notes
The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task show only the permutation in lowest-first sorted order i.e. 1, 2, 3 (and remove any of its perms).
A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4
Rotations: Any rotation of non-transitive dice from an answer is also an answer. You may optionally compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions.
Task
====
Find all the ordered lists of three non-transitive dice S, T, U of the form
S < T, T < U and yet S > U; where the dice are selected from all four-faced die
, (unique w.r.t the notes), possible by having selections from the integers
one to four on any dies face.
Solution can be found by generating all possble individual die then testing all
possible permutations, (permutations are ordered), of three dice for
non-transitivity.
Optional stretch goal
Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal.
Show the results here, on this page.
References
The Most Powerful Dice - Numberphile Video.
Nontransitive dice - Wikipedia.
| #Raku | Raku | # 20201225 Raku programming solution
my @dicepool = ^4 xx 4 ;
sub FaceCombs(\N, @dp) { # for brevity, changed to use 0-based dice on input
my @res = my @found = [];
for [X] @dp {
unless @found[ my \key = [+] ( N «**« (N-1…0) ) Z* .sort ] {
@found[key] = True;
@res.push: $_ »+» 1
}
}
@res
}
sub infix:<⚖️>(@x, @y) { +($_{Less} <=> $_{More}) given (@x X<=> @y).Bag }
sub findIntransitive(\N, \cs) {
my @res = [];
race for [X] ^+cs xx N -> @lot {
my $skip = False;
for @lot.rotor(2 => -1) {
{ $skip = True and last } unless cs[ @_[0] ] ⚖️ cs[ @_[1] ] == -1
}
next if $skip;
if cs[ @lot[0] ] ⚖️ cs[ @lot[*-1] ] == 1 { @res.push: [ cs[ @lot ] ] }
}
@res
}
say "Number of eligible 4-faced dice : ", +(my \combs = FaceCombs(4,@dicepool));
for 3, 4 {
my @output = findIntransitive($_, combs);
say +@output, " ordered lists of $_ non-transitive dice found, namely:";
.say for @output;
} |
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
| #C.2B.2B | C++ |
/*
* Nigel Galloway, July 19th., 2017 - Yes well is this any better?
*/
class N{
uint n,i,g,e,l;
public:
N(uint n): n(n-1),i{},g{},e(1),l(n-1){}
bool hasNext(){
g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;
if (l==2) {l=--n; e=1; return true;}
if (e<((1<<(l-1))-1)) {++e; return true;}
e=1; --l; return (l>0);
}
uint next() {return g;}
};
|
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.
| #ALGOL_W | ALGOL W | begin
% returns with numberInBase set to the number n converted to a string in %
% the specified base. Number must be non-negative and base must be in %
% range 2 to 36 %
procedure convertToBase( integer value n
; integer value base
; string(32) result numberInBase
) ;
begin
string(36) baseDigits;
integer val, strPos;
assert( n >= 0 and base >= 2 and base <= 36 );
baseDigits := "0123456789abcdefghijklmnopqrstuvwxyz";
numberInBase := " ";
val := n;
strPos := 31;
while
begin
% a(b//c) is the substring of a starting at b with length c. %
% The first character is at position 0. The length must be %
% an integer literal so it is known at compile time. %
numberInBase( strPos // 1 ) := baseDigits( val rem base // 1 );
val := val div base;
strPos := strPos - 1;
val > 0
end
do begin end
end convertToBase ;
% returns the string numberInBase converted to an integer assuming %
% numberInBase ia a string in the specified base %
% base must be in range 2 to 36, invalid digits will cause the program %
% to crash, spaces are ignored %
integer procedure convertFromBase( string(32) value numberInBase
; integer value base
) ;
begin
string(36) baseDigits;
integer val, cPos;
assert( base >= 2 and base <= 36 );
baseDigits := "0123456789abcdefghijklmnopqrstuvwxyz";
val := 0;
for strPos := 0 until 31 do begin
string(1) c;
c := numberInBase( strPos // 1 );
if c not = " " then begin
cPos := 0;
while baseDigits( cPos // 1 ) not = c do cPos := cPos + 1;
val := ( val * base ) + cPos;
end
end;
val
end convertFromBase ;
% test the procedures %
string(32) baseNumber;
i_w := 3; % set integer output width %
for i := 2 until 36 do begin
convertToBase( 35, i, baseNumber );
write( 35, i, baseNumber, " ", convertFromBase( baseNumber, i ) );
end
end. |
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.
| #Icon_and_Unicon | Icon and Unicon |
procedure convert (str)
write (left(str, 10) || " = " || integer(str))
end
procedure main ()
convert (" 2r1001")
convert (" 8r7135")
convert ("16rABC1234")
convert ("36r1Z")
write ("2r1001" + "36r1Z") # shows type conversion, string->integer
end
|
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.
| #J | J | baseN=: (, '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.
| #Forth | Forth | : main 34 1 do cr i dec. i hex. loop ;
main
...
11 $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.
| #Fortran | Fortran | do n = 1, 33
write(*, "(b6, o4, i4, z4)") n, n, n, n
end do |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim ui(1 To 4) As UInteger = {10, 26, 52, 100}
Print "Decimal Hex Octal Binary"
Print "======= ======== ======= ======"
For i As Integer = 1 To 4
Print Str(ui(i)); Tab(12); Hex(ui(i)); Tab(23); Oct(ui(i)); Tab(31); Bin(ui(i))
Next
Sleep |
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.
| #REXX | REXX |
OneList=["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tenList=["" , "" , "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
millionStr="Million"
thousandStr="Thousand"
hundredStr="Hundred"
andStr="And"
pointStr=" Point "
while true
see "enter number to convert:"
give theNumber
pointSplited=splitString(theNumber,".")
fraction=0
useFr=false
if len(pointSplited) >=1 theNumber=pointSplited[1] ok
if len(pointSplited) >=2 useFr=true fraction=pointSplited[2] ok
pointSplited=null
see getName(number(theNumber))
if useFr=true see pointStr + getName(number(fraction)) ok
see nl
end
func getName num
rtn=null
if num=0
rtn += OneList[floor(num+1)]
return rtn
ok
if num<0
return "minus " + getName(fabs(num))
ok
if num>= 1000000
rtn += getName(num / 1000000) +" "+ millionStr
num%=1000000
ok
if num>=1000
if len(rtn)>0 rtn += ", " ok
rtn += getName(num / 1000)+ " " + thousandStr
num%=1000
ok
if num >=100
if len(rtn)>0 rtn += ", " ok
rtn += OneList[floor((num / 100)+1)] + " " + hundredStr
num%=100
ok
if num=0
return rtn +
ok
if len(rtn)>0 rtn += " " + andStr + " " ok
if(num>=20)
rtn += tenList[floor((num / 10)+1)]
num%=10
ok
if num=0
return rtn
ok
if len(rtn)>0 rtn += " " ok
rtn += OneList[num+1]
return rtn
func splitString str,chr
for i in str if strcmp(i,chr)=0 i=nl ok next
return str2list(str)
|
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
| #Ruby | Ruby | ary = (1..9).to_a
ary.shuffle! while ary == ary.sort
score = 0
until ary == ary.sort
print "#{ary.inspect} -- How many digits to reverse? "
num = gets.to_i # should validate input
ary[0, num] = ary[0, num].reverse
score += 1
end
p ary
puts "Your score: #{score}" |
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.
| #ALGOL-M | ALGOL-M |
BEGIN
PROCEDURE WELCOME;
BEGIN
WRITE("THE GAME OF NIM");
WRITE("");
WRITE("WE BEGIN WITH 12 TOKENS. ON EACH TURN, A");
WRITE("PLAYER MAY TAKE BETWEEN 1 AND 3 TOKENS.");
WRITE("THE PLAYER WHO TAKES THE LAST TOKEN WINS.");
WRITE("");
END;
PROCEDURE SHOW(N);
INTEGER N;
BEGIN
WRITE("REMAINING TOKENS:",N);
END;
INTEGER FUNCTION GETNUM(LOWLIM, TOPLIM);
INTEGER LOWLIM, TOPLIM;
BEGIN
INTEGER OK, N;
OK := 0;
WHILE OK = 0 DO
BEGIN
WRITE("YOU TAKE:");
READ(N);
IF N < LOWLIM OR N > TOPLIM THEN
BEGIN
WRITE("MUST TAKE BETWEEN",LOWLIM," AND",TOPLIM,".");
WRITE("TRY AGAIN.");
END
ELSE
OK := 1;
END;
GETNUM := N;
END;
INTEGER FUNCTION PLAY(PLAYER, TOKENS, TAKEN);
INTEGER PLAYER, TOKENS, TAKEN;
BEGIN
IF PLAYER = 1 THEN % HUMAN PLAYER'S MOVE %
TAKEN := GETNUM(1,3)
ELSE % MACHINE'S MOVE %
TAKEN := 4 - TAKEN;
PLAY := TAKEN;
END;
PROCEDURE REPORT(WINNER);
INTEGER WINNER; % MACHINE = 0, HUMAN = 1 %
BEGIN
IF WINNER = 0 THEN
WRITE("I TOOK THE LAST ONE, SO I WIN. SORRY ABOUT THAT.")
ELSE
WRITE("YOU TOOK THE LAST ONE. YOU WIN. CONGRATULATIONS!");
END;
% MAIN CODE BEGINS HERE %
INTEGER PLAYER, TOKENS, TAKEN, HUMAN, MACHINE;
MACHINE := 0;
HUMAN := 1;
TOKENS := 12;
TAKEN := 0;
PLAYER := HUMAN;
WELCOME;
WRITE("YOU GO FIRST.");
WHILE TOKENS > 0 DO
BEGIN
SHOW(TOKENS);
TAKEN := PLAY(PLAYER, TOKENS, TAKEN);
TOKENS := TOKENS - TAKEN;
IF PLAYER = MACHINE THEN WRITE("I TOOK:",TAKEN);
IF TOKENS > 0 THEN PLAYER := 1 - PLAYER;
END;
REPORT(PLAYER);
WRITE("THANKS FOR PLAYING!");
END |
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #Applesoft_BASIC | Applesoft BASIC | 0ST$(0)="YOU MUST TAKE 1, 2, OR 3 TOKENS.":FORHEAP=12TO1STEP-4:PRINT"THERE ARE "HEAP" TOKENS REMAINING.":FORI=0TO1:INPUT"HOW MANY WOULD YOU LIKE TO TAKE?";T%:I=T%>0ANDT%<4:PRINTST$(I):NEXTI:PRINT"ON MY TURN I WILL TAKE "4-T%" TOKENS.":NEXTHEAP |
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.
| #Arturo | Arturo | total: 12
while ø [
tk: 0
print "YOUR turn:"
while [not? contains? 1..3 tk: <= to :integer input "How many tokens will you take? (1-3) "][]
total: total-tk
print [total "tokens remaining\n"]
print ["COMPUTER's turn:"]
print ["taking:" 4-tk]
total: total-(4-tk)
print [total "tokens remaining\n"]
if total=0 [
print "COMPUTER won. :)"
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.
| #11l | 11l | F nthroot(a, n)
V result = a
V x = a / n
L abs(result - x) > 10e-15
x = result
result = (1.0 / n) * (((n - 1) * x) + (a / pow(x, n - 1)))
R result
print(nthroot(34.0, 5))
print(nthroot(42.0, 10))
print(nthroot(5.0, 2)) |
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
| #11l | 11l | F closest_more_than(n, lst)
V large = max(lst) + 1
R lst.index(min(lst, key' x -> (I x <= @n {@large} E x)))
F nexthigh(n)
V this = reversed(Array(n.map(digit -> Int(digit))))
V mx = this[0]
L(digit) this[1..]
V i = L.index + 1
I digit < mx
V mx_index = closest_more_than(digit, this[0 .< i + 1])
swap(&this[mx_index], &this[i])
this.sort_range(0 .< i, reverse' 1B)
R reversed(this).map(d -> String(d)).join(‘’)
E I digit > mx
mx = digit
R ‘0’
L(x) [‘0’, ‘9’, ‘12’, ‘21’, ‘12453’, ‘738440’, ‘45072010’, ‘95322020’,
‘9589776899767587796600’]
print(‘#12 -> #12’.format(x, nexthigh(x))) |
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
| #11l | 11l | F makeList(separator)
V counter = 1
F makeItem(item)
-V result = @counter‘’@separator‘’item"\n"
@counter++
R result
R makeItem(‘first’)‘’makeItem(‘second’)‘’makeItem(‘third’)
print(makeList(‘. ’)) |
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.
| #Crystal | Crystal | def with_payload(template, payload, used = nil)
template.map do |item|
if item.is_a? Enumerable
with_payload(item, payload, used)
else
used << item
payload[item]
end
end
end
p = {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"}
t = { { {1, 2}, {3, 4, 1}, 5}}
used = Set(Int32).new
puts with_payload(t, p, used)
unused = Set(Int32).new((0..6).to_a) - used
puts "Unused indices: #{unused}" |
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.
| #Factor | Factor | USING: formatting kernel literals math sequences sequences.deep ;
IN: rosetta-code.nested-template-data
CONSTANT: payloads $[ 7 <iota> [ "Payload#%d" sprintf ] map ]
: insert-payloads ( template -- data-structure )
[ dup fixnum? [ payloads ?nth ] when ] deep-map ;
{ { { 1 2 }
{ 3 4 1 }
5 } }
{ { { 1 2 }
{ 10 4 1 }
5 } }
[ dup insert-payloads "Template: %u\nData Structure: %u\n"
printf ] bi@ |
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)
| #Go | Go | package main
import (
"fmt"
"strings"
)
type BitSet []bool
func (bs BitSet) and(other BitSet) {
for i := range bs {
if bs[i] && other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func (bs BitSet) or(other BitSet) {
for i := range bs {
if bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
// collect all possible solutions for the given clues
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", 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).
*/
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
// determine which values all candidates of a[i] have in common
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
// remove from b[j] all candidates that don't share the forced values
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"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",
}
p3 := [2]string{
"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",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
} |
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.
| #Phix | Phix | with javascript_semantics
function nobr(sequence res, string neat, integer ni, integer ch, sequence blocks)
if length(blocks)=0 then
res = append(res,neat)
else
integer b = blocks[1]
blocks = blocks[2..$]
integer l = (sum(blocks)+length(blocks)-1)*2,
e = length(neat)-l-b*2
for i=ni to e by 2 do
for j=i to i+b*2-2 by 2 do
neat[j] = ch
end for
res = nobr(res,neat,i+b*2+2,ch+1,blocks)
neat[i] = ' '
end for
end if
return res
end function
function nonoblock(integer len, sequence blocks)
string neat = "|"&join(repeat(' ',len),'|')&"|"
return nobr({},neat,2,'A',blocks)
end function
sequence tests = {{5,{2,1}},
{5,{}},
{10,{8}},
{15,{2, 3, 2, 3}},
{10,{4, 3}},
{5,{2,1}},
{10,{3, 1}},
{5,{2, 3}}}
integer len
sequence blocks, res
for i=1 to length(tests) do
{len,blocks} = tests[i]
string ti = sprintf("%d cells with blocks %s",{len,sprint(blocks)})
printf(1,"%s\n%s\n",{ti,repeat('=',length(ti))})
res = nonoblock(len,blocks)
if length(res)=0 then
printf(1,"No solutions.\n")
else
for ri=1 to length(res) do
printf(1,"%3d: %s\n",{ri,res[ri]})
end for
end if
printf(1,"\n")
end for
|
http://rosettacode.org/wiki/Non-transitive_dice | Non-transitive dice | Let our dice select numbers on their faces with equal probability, i.e. fair dice.
Dice may have more or less than six faces. (The possibility of there being a
3D physical shape that has that many "faces" that allow them to be fair dice,
is ignored for this task - a die with 3 or 33 defined sides is defined by the
number of faces and the numbers on each face).
Throwing dice will randomly select a face on each die with equal probability.
To show which die of dice thrown multiple times is more likely to win over the
others:
calculate all possible combinations of different faces from each die
Count how many times each die wins a combination
Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice.
If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively.
Example 1
If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its
faces then the equal possibility outcomes from throwing both, and the winners
is:
X Y Winner
= = ======
1 2 Y
1 3 Y
1 4 Y
3 2 X
3 3 -
3 4 Y
6 2 X
6 3 X
6 4 X
TOTAL WINS: X=4, Y=4
Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y
Transitivity
In mathematics transitivity are rules like:
if a op b and b op c then a op c
If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers
we get the familiar if a < b and b < c then a < c
Non-transitive dice
These are an ordered list of dice where the '>' operation between successive
dice pairs applies but a comparison between the first and last of the list
yields the opposite result, '<'.
(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).
Three dice S, T, U with appropriate face values could satisfy
S < T, T < U and yet S > U
To be non-transitive.
Notes
The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task show only the permutation in lowest-first sorted order i.e. 1, 2, 3 (and remove any of its perms).
A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4
Rotations: Any rotation of non-transitive dice from an answer is also an answer. You may optionally compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions.
Task
====
Find all the ordered lists of three non-transitive dice S, T, U of the form
S < T, T < U and yet S > U; where the dice are selected from all four-faced die
, (unique w.r.t the notes), possible by having selections from the integers
one to four on any dies face.
Solution can be found by generating all possble individual die then testing all
possible permutations, (permutations are ordered), of three dice for
non-transitivity.
Optional stretch goal
Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal.
Show the results here, on this page.
References
The Most Powerful Dice - Numberphile Video.
Nontransitive dice - Wikipedia.
| #Wren | Wren | import "/sort" for Sort
var fourFaceCombs = Fn.new {
var res = []
var found = List.filled(256, false)
for (i in 1..4) {
for (j in 1..4) {
for (k in 1..4) {
for (l in 1..4) {
var c = [i, j, k, l]
Sort.insertion(c)
var key = 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3]-1)
if (!found[key]) {
found[key] = true
res.add(c)
}
}
}
}
}
return res
}
var cmp = Fn.new { |x, y|
var xw = 0
var yw = 0
for (i in 0..3) {
for (j in 0..3) {
if (x[i] > y[j]) {
xw = xw + 1
} else if (y[j] > x[i]) {
yw = yw + 1
}
}
}
return (xw - yw).sign
}
var findIntransitive3 = Fn.new { |cs|
var c = cs.count
var res = []
for (i in 0...c) {
for (j in 0...c) {
for (k in 0...c) {
var first = cmp.call(cs[i], cs[j])
if (first == -1) {
var second = cmp.call(cs[j], cs[k])
if (second == -1) {
var third = cmp.call(cs[i], cs[k])
if (third == 1) res.add([cs[i], cs[j], cs[k]])
}
}
}
}
}
return res
}
var findIntransitive4 = Fn.new { |cs|
var c = cs.count
var res = []
for (i in 0...c) {
for (j in 0...c) {
for (k in 0...c) {
for (l in 0...c) {
var first = cmp.call(cs[i], cs[j])
if (first == -1) {
var second = cmp.call(cs[j], cs[k])
if (second == -1) {
var third = cmp.call(cs[k], cs[l])
if (third == -1) {
var fourth = cmp.call(cs[i], cs[l])
if (fourth == 1) res.add([cs[i], cs[j], cs[k], cs[l]])
}
}
}
}
}
}
}
return res
}
var combs = fourFaceCombs.call()
System.print("Number of eligible 4-faced dice: %(combs.count)")
var it = findIntransitive3.call(combs)
System.print("\n%(it.count) ordered lists of 3 non-transitive dice found, namely:")
System.print(it.join("\n"))
it = findIntransitive4.call(combs)
System.print("\n%(it.count) ordered lists of 4 non-transitive dice found, namely:")
System.print(it.join("\n")) |
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence.
Note: Subsequences are defined structurally, not by their contents.
So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
Task: Find all non-continuous subsequences for a given sequence.
Example
For the sequence 1,2,3,4, there are five non-continuous subsequences, namely:
1,3
1,4
2,4
1,3,4
1,2,4
Goal
There are different ways to calculate those subsequences.
Demonstrate algorithm(s) that are natural for the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Clojure | Clojure |
(use '[clojure.contrib.combinatorics :only (subsets)])
(defn of-min-length [min-length]
(fn [s] (>= (count s) min-length)))
(defn runs [c l]
(map (partial take l) (take-while not-empty (iterate rest c))))
(defn is-subseq? [c sub]
(some identity (map = (runs c (count sub)) (repeat sub))))
(defn non-continuous-subsequences [s]
(filter (complement (partial is-subseq? s)) (subsets s)))
(filter (of-min-length 2) (non-continuous-subsequences [:a :b :c :d]))
|
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.
| #AppleScript | AppleScript | -- toBase :: Int -> Int -> String
on toBase(intBase, n)
if (intBase < 36) and (intBase > 0) then
inBaseDigits(items 1 thru intBase of "0123456789abcdefghijklmnopqrstuvwxyz", n)
else
"not defined for base " & (n as string)
end if
end toBase
-- inBaseDigits :: String -> Int -> [String]
on inBaseDigits(strDigits, n)
set intBase to length of strDigits
script nextDigit
on |λ|(residue)
set {divided, remainder} to quotRem(residue, intBase)
if divided > 0 then
{just:(item (remainder + 1) of strDigits), new:divided, nothing:false}
else
{nothing:true}
end if
end |λ|
end script
reverse of unfoldr(nextDigit, n) as string
end inBaseDigits
-- OTHER FUNCTIONS DERIVABLE FROM inBaseDigits -------------------------------
-- inUpperHex :: Int -> String
on inUpperHex(n)
inBaseDigits("0123456789ABCDEF", n)
end inUpperHex
-- inDevanagariDecimal :: Int -> String
on inDevanagariDecimal(n)
inBaseDigits("०१२३४५६७८९", n)
end inDevanagariDecimal
-- TEST ----------------------------------------------------------------------
on run
script
on |λ|(x)
{{binary:toBase(2, x), octal:toBase(8, x), hex:toBase(16, x)}, ¬
{upperHex:inUpperHex(x), dgDecimal:inDevanagariDecimal(x)}}
end |λ|
end script
map(result, [255, 240])
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
set lst to {}
set recM to {nothing:false, new:v}
tell mReturn(f)
repeat while (not (nothing of recM))
set recM to |λ|(new of recM)
if not nothing of recM then set end of lst to just of recM
end repeat
end tell
lst
end unfoldr
-- quotRem :: Integral a => a -> a -> (a, a)
on quotRem(m, n)
{m div n, m mod n}
end quotRem
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
http://rosettacode.org/wiki/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.
| #Java | Java | Scanner sc = new Scanner(System.in); //or any other InputStream or String
sc.useRadix(base); //any number from Character.MIN_RADIX (2) to CHARACTER.MAX_RADIX (36)
sc.nextInt(); //read in a value |
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.
| #JavaScript | JavaScript | +"0123459"; // 123459
+"0xabcf123"; // 180154659
// also supports negative numbers, but not for hex:
+"-0123459"; // -123459
+"-0xabcf123"; // NaN |
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.
| #Gema | Gema | 0x<A>=$0 (@radix{16;10;$1}, 0@radix{16;8;$1})
0<D>=$0 (@radix{8;10;$1}, 0x@radix{8;16;$1})
<D>=$0 (0x@radix{10;16;$1}, 0@radix{10;8;$1}) |
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.
| #Go | Go | package main
import (
"fmt"
"math/big"
"strconv"
)
func main() {
// fmt.Print formats integer types directly as bases 2, 8, 10, and 16.
fmt.Printf("%b\n", 13)
fmt.Printf("%o\n", 13)
fmt.Printf("%d\n", 13)
fmt.Printf("%x\n", 13)
// big ints work with fmt as well.
d := big.NewInt(13)
fmt.Printf("%b\n", d)
fmt.Printf("%o\n", d)
fmt.Printf("%d\n", d)
fmt.Printf("%x\n", d)
// strconv.FormatInt handles arbitrary bases from 2 to 36 for the
// int64 type. There is also strconv.FormatUInt for the uint64 type.
// There no equivalent for big ints.
fmt.Println(strconv.FormatInt(1313, 19))
} |
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.
| #Ring | Ring |
OneList=["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tenList=["" , "" , "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
millionStr="Million"
thousandStr="Thousand"
hundredStr="Hundred"
andStr="And"
pointStr=" Point "
while true
see "enter number to convert:"
give theNumber
pointSplited=splitString(theNumber,".")
fraction=0
useFr=false
if len(pointSplited) >=1 theNumber=pointSplited[1] ok
if len(pointSplited) >=2 useFr=true fraction=pointSplited[2] ok
pointSplited=null
see getName(number(theNumber))
if useFr=true see pointStr + getName(number(fraction)) ok
see nl
end
func getName num
rtn=null
if num=0
rtn += OneList[floor(num+1)]
return rtn
ok
if num<0
return "minus " + getName(fabs(num))
ok
if num>= 1000000
rtn += getName(num / 1000000) +" "+ millionStr
num%=1000000
ok
if num>=1000
if len(rtn)>0 rtn += ", " ok
rtn += getName(num / 1000)+ " " + thousandStr
num%=1000
ok
if num >=100
if len(rtn)>0 rtn += ", " ok
rtn += OneList[floor((num / 100)+1)] + " " + hundredStr
num%=100
ok
if num=0
return rtn +
ok
if len(rtn)>0 rtn += " " + andStr + " " ok
if(num>=20)
rtn += tenList[floor((num / 10)+1)]
num%=10
ok
if num=0
return rtn
ok
if len(rtn)>0 rtn += " " ok
rtn += OneList[num+1]
return rtn
func splitString str,chr
for i in str if strcmp(i,chr)=0 i=nl ok next
return str2list(str)
|
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
| #Run_BASIC | Run BASIC | for i = 1 to 9 ' get numbers 1 to 9
n(i) = i
next i
numShuffles = 3
' ----------------------------------
' shuffle numbers
' ----------------------------------
for i = 1 to 9 * numShuffles
i1 = int(rnd(1)*9) + 1
i2 = int(rnd(1)*9) + 1
h2 = n(i1)
n(i1) = n(i2)
n(i2) = h2
next i
for i = 1 to 9
a$ = a$ + str$(n(i)) + " "
next i
count = 0
[loop]
count = count + 1
print count;" : ";a$
for i = 1 to 9 ' check if in sequence
j = i * 2
if mid$(a$,j-1,1) > mid$(a$,j,1) then goto [notOrdered]
next i
print "It took ";count;" tries"
end
[notOrdered]
input "How many numbers to flip:";i
i = ((i-1) * 2) + 1
b$ = ""
for j = i to 1 step -2
b$ = b$ + mid$(a$,j,2)
next j
a$ = b$ + mid$(a$,i + 2)
goto [loop]
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.
| #AsciiDots | AsciiDots |
%$LMRTX
.-$"Nim Dots"-$""-
/$_"Number must be "\
T /----~------\ |
*M /---+-*-[o] | |
R [-]\ .>#3-+[>][<]-1#<.| |
.-#12>--^ \"stod "$-#_$-" ekat uoY"_$---/ \--*----*-/ |
.>$_"How many dots would you like to take"---#?---/ |
\X X---------<".3 dna 1 neewteb"$/
/-----*L |
[-]--\ R |
| *-$_"Computer takes "-$_#-$" dots"/
M-*#4[%]
\---/
/----------------$"computer wins!"-&
/---~--
*#0[=]
L-------------*---*>$_#-$" dots remaining."-$""
T
|
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.
| #AutoHotkey | AutoHotkey | Play:
tokens := 12
while tokens {
while !(D>0 && D<4)
InputBox, D, Nim Game, % "Tokens Remaining = " tokens
. "`nHow many tokens would you like to take?"
. "`nChoose 1, 2 or 3"
tokens -= D
MsgBox % "Computer Takes " 4-D
tokens -= 4-d, d:=0
}
MsgBox, 262212,,Computer Always Wins!`nWould you like to play again?
IfMsgBox, Yes
gosub Play
else
ExitApp
return |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #360_Assembly | 360 Assembly | * Nth root - x**(1/n) - 29/07/2018
NTHROOT CSECT
USING NTHROOT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
BAL R14,ROOTN call rootn(x,n)
LE F0,XN xn=rootn(x,n)
LA R0,6 decimals=6
BAL R14,FORMATF edit xn
MVC PG(13),0(R1) output xn
XPRNT PG,L'PG print buffer
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
ROOTN MVC ZN,=E'0' zn=0 ----------------------------
MVC ZN,N n
MVI ZN,X'46' zn=unnormalize(n)
LE F0,ZN zn
AE F0,=E'0' normalized
STE F0,ZN zn=normalize(n)
LE F6,=E'0' xm=0
LE F0,X x
DE F0,ZN /zn
STE F0,XN xn=x/zn
WHILEA LE F0,XN xn
SER F0,F6 xn-xm
LPER F0,F0 abs((xn-xm)
DE F0,XN /xn
CE F0,EPSILON while abs((xn-xm)/xn)>epsilon
BNH EWHILEA ~
LE F6,XN xm=xn
LE F0,ZN zn
SE F0,=E'1' zn-1
MER F0,F6 f0=(zn-1)*xm
L R2,N n
BCTR R2,0 n-1
LE F2,=E'1' xm
POW MER F2,F6 *xm
BCT R2,POW f2=xm**(n-1)
LE F4,X x
DER F4,F2 x/xm**(n-1)
AER F0,F4 (zn-1)*xm+x/xm**(n-1)
DE F0,ZN /zn
STE F0,XN xn=((zn-1)*xm+x/xm**(n-1))/zn
B WHILEA endwhile
EWHILEA LE F0,XN xn
BR R14 return ---------------------------
COPY FORMATF format a float
X DC E'2' x <== input
N DC F'2' n <== input
EPSILON DC E'1E-6' imprecision
XN DS E xn :: output
ZN DS E zn=float(n)
PG DC CL80' ' buffer
REGEQU
END NTHROOT |
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
| #AutoHotkey | AutoHotkey | Next_highest_int(num){
Arr := []
for i, v in permute(num)
Arr[v] := true
for n, v in Arr
if found
return n
else if (n = num)
found := true
return 0
}
permute(str, k:=0, l:=1){
static res:=[]
r := StrLen(str)
k := k ? k : r
if (l = r)
return SubStr(str, 1, k)
i := l
while (i <= r){
str := swap(str, l, i)
x := permute(str, k, l+1)
if (x<>"")
res.push(x)
str := swap(str, l, i++)
}
if (l=1)
return x:=res, res := []
}
swap(str, l, i){
x := StrSplit(str), var := x[l], x[l] := x[i], x[i] := var
Loop, % x.count()
res .= x[A_Index]
return res
} |
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
| #Ada | Ada | with Ada.Text_IO;
procedure Nested_Functions is -- 'Nested_Functions' is the name of 'main'
type List is array(Natural range <>) of String(1 .. 10);
function Make_List(Separator: String) return List is
Counter: Natural := 0;
function Make_Item(Item_Name: String) return String is
begin
Counter := Counter + 1; -- local in Make_List, global in Make_Item
return(Natural'Image(Counter) & Separator & Item_Name);
end Make_Item;
begin
return (Make_Item("First "), Make_Item("Second"), Make_Item("Third "));
end Make_List;
begin -- iterate through the result of Make_List
for Item of Make_List(". ") loop
Ada.Text_IO.Put_Line(Item);
end loop;
end Nested_Functions; |
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
| #68000_Assembly | 68000 Assembly | ;program starts here, after loading palettes etc.
MOVE.W #3,D1
MOVE.W #'.',D4
JSR MakeList
jmp * ;halt
MakeList:
MOVE.W #1,D0
loop_MakeList:
MOVE.W D0,-(SP)
JSR PrintHex
MOVE.B D4,D0 ;load separator into D0
JSR PrintChar
MOVE.B #' ',D0
JSR PrintChar
MOVE.W (SP)+,D0
JSR MakeItem
CMP.W D0,D1
BCC loop_MakeList ;back to start
RTS
MakeItem:
MOVE.W D0,D2
SUBQ.W #1,D2
LSL.W #2,D2
LEA PointerToText,A0
MOVE.L (A0,D2),A3
JSR PrintString
JSR NewLine
ADDQ.W #1,D0
RTS
PointerToText:
DC.L FIRST,SECOND,THIRD
FIRST:
DC.B "FIRST",0
EVEN
SECOND:
DC.B "SECOND",0
EVEN
THIRD:
DC.B "THIRD",0
EVEN |
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.
| #Go | Go | {{index .P n}} |
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.
| #Haskell | Haskell | {-# language DeriveTraversable #-}
data Template a = Val a | List [Template a]
deriving ( Show
, Functor
, Foldable
, Traversable ) |
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)
| #Java | Java | import java.util.*;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.toList;
public class NonogramSolver {
static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"};
static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE "
+ "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"};
static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH "
+ "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF "
+ "AAAAD BDG CEF CBDB BBB FC"};
static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q "
+ "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ "
+ "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"};
public static void main(String[] args) {
for (String[] puzzleData : new String[][]{p1, p2, p3, p4})
newPuzzle(puzzleData);
}
static void newPuzzle(String[] data) {
String[] rowData = data[0].split("\\s");
String[] colData = data[1].split("\\s");
List<List<BitSet>> cols, rows;
rows = getCandidates(rowData, colData.length);
cols = getCandidates(colData, rowData.length);
int numChanged;
do {
numChanged = reduceMutual(cols, rows);
if (numChanged == -1) {
System.out.println("No solution");
return;
}
} while (numChanged > 0);
for (List<BitSet> row : rows) {
for (int i = 0; i < cols.size(); i++)
System.out.print(row.get(0).get(i) ? "# " : ". ");
System.out.println();
}
System.out.println();
}
// collect all possible solutions for the given clues
static List<List<BitSet>> getCandidates(String[] data, int len) {
List<List<BitSet>> result = new ArrayList<>();
for (String s : data) {
List<BitSet> lst = new LinkedList<>();
int sumChars = s.chars().map(c -> c - 'A' + 1).sum();
List<String> prep = stream(s.split(""))
.map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList());
for (String r : genSequence(prep, len - sumChars + 1)) {
char[] bits = r.substring(1).toCharArray();
BitSet bitset = new BitSet(bits.length);
for (int i = 0; i < bits.length; i++)
bitset.set(i, bits[i] == '1');
lst.add(bitset);
}
result.add(lst);
}
return result;
}
// permutation generator, translated from Python via D
static List<String> genSequence(List<String> ones, int numZeros) {
if (ones.isEmpty())
return asList(repeat(numZeros, "0"));
List<String> result = new ArrayList<>();
for (int x = 1; x < numZeros - ones.size() + 2; x++) {
List<String> skipOne = ones.stream().skip(1).collect(toList());
for (String tail : genSequence(skipOne, numZeros - x))
result.add(repeat(x, "0") + ones.get(0) + tail);
}
return result;
}
static String repeat(int n, String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s);
return sb.toString();
}
/* 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). */
static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {
int countRemoved1 = reduce(cols, rows);
if (countRemoved1 == -1)
return -1;
int countRemoved2 = reduce(rows, cols);
if (countRemoved2 == -1)
return -1;
return countRemoved1 + countRemoved2;
}
static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {
int countRemoved = 0;
for (int i = 0; i < a.size(); i++) {
BitSet commonOn = new BitSet();
commonOn.set(0, b.size());
BitSet commonOff = new BitSet();
// determine which values all candidates of ai have in common
for (BitSet candidate : a.get(i)) {
commonOn.and(candidate);
commonOff.or(candidate);
}
// remove from bj all candidates that don't share the forced values
for (int j = 0; j < b.size(); j++) {
final int fi = i, fj = j;
if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))
|| (!commonOff.get(fj) && cnd.get(fi))))
countRemoved++;
if (b.get(j).isEmpty())
return -1;
}
}
return countRemoved;
}
} |
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.
| #Python | Python | def nonoblocks(blocks, cells):
if not blocks or blocks[0] == 0:
yield [(0, 0)]
else:
assert sum(blocks) + len(blocks)-1 <= cells, \
'Those blocks will not fit in those cells'
blength, brest = blocks[0], blocks[1:] # Deal with the first block of length
minspace4rest = sum(1+b for b in brest) # The other blocks need space
# Slide the start position from left to max RH index allowing for other blocks.
for bpos in range(0, cells - minspace4rest - blength + 1):
if not brest:
# No other blocks to the right so just yield this one.
yield [(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
nonoargs = (brest, cells - offset) # Pre-compute arguments to nonoargs
# recursive call to nonoblocks yields multiple sub-positions
for subpos in nonoblocks(*nonoargs):
# Remove the offset from sub block positions
rest = [(offset + bp, bl) for bp, bl in subpos]
# Yield this block plus sub blocks positions
vec = [(bpos, blength)] + rest
yield vec
def pblock(vec, cells):
'Prettyprints each run of blocks with a different letter A.. for each block of filled cells'
vector = ['_'] * cells
for ch, (bp, bl) in enumerate(vec, ord('A')):
for i in range(bp, bp + bl):
vector[i] = chr(ch) if vector[i] == '_' else'?'
return '|' + '|'.join(vector) + '|'
if __name__ == '__main__':
for blocks, cells in (
([2, 1], 5),
([], 5),
([8], 10),
([2, 3, 2, 3], 15),
# ([4, 3], 10),
# ([2, 1], 5),
# ([3, 1], 10),
([2, 3], 5),
):
print('\nConfiguration:\n %s # %i cells and %r blocks' % (pblock([], cells), cells, blocks))
print(' Possibilities:')
for i, vector in enumerate(nonoblocks(blocks, cells)):
print(' ', pblock(vector, cells))
print(' A total of %i Possible configurations.' % (i+1)) |
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence.
Note: Subsequences are defined structurally, not by their contents.
So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
Task: Find all non-continuous subsequences for a given sequence.
Example
For the sequence 1,2,3,4, there are five non-continuous subsequences, namely:
1,3
1,4
2,4
1,3,4
1,2,4
Goal
There are different ways to calculate those subsequences.
Demonstrate algorithm(s) that are natural for the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #CoffeeScript | CoffeeScript |
is_contigous_binary = (n) ->
# return true if binary representation of n is
# of the form 1+0+
# examples:
# 0 true
# 1 true
# 100 true
# 110 true
# 1001 false
# 1010 false
# special case zero, or you'll get an infinite loop later
return true if n == 0
# first remove 0s from end
while n % 2 == 0
n = n / 2
# next, take advantage of the fact that a continuous
# run of 1s would be of the form 2^n - 1
is_power_of_two(n + 1)
is_power_of_two = (m) ->
while m % 2 == 0
m = m / 2
m == 1
seq_from_bitmap = (arr, n) ->
# grabs elements from array according to a bitmap
# e.g. if n == 13 (1101), and arr = ['a', 'b', 'c', 'd'],
# then return ['a', 'c', 'd'] (flipping bits to 1011, so
# that least significant bit comes first)
i = 0
new_arr = []
while n > 0
if n % 2 == 1
new_arr.push arr[i]
n -= 1
n /= 2
i += 1
new_arr
non_contig_subsequences = (arr) ->
# Return all subsqeuences from an array that have a "hole" in
# them. The order of the subsequences is not specified here.
# This algorithm uses binary counting, so it is limited to
# small lists, but large lists would be unwieldy regardless.
bitmasks = [0...Math.pow(2, arr.length)]
(seq_from_bitmap arr, n for n in bitmasks when !is_contigous_binary n)
arr = [1,2,3,4]
console.log non_contig_subsequences arr
for n in [1..10]
arr = [1..n]
num_solutions = non_contig_subsequences(arr).length
console.log "for n=#{n} there are #{num_solutions} solutions"
|
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.
| #Arturo | Arturo | fromBase: function [x,base][
if base=2 [ return from.binary x ]
if base=8 [ return from.octal x ]
if base=16 [ return from.hex x ]
return to :integer x
]
toBase: function [x,base][
if base=2 [ return as.binary x ]
if base=8 [ return as.octal x ]
if base=16 [ return as.hex x ]
return to :string x
]
loop 1..20 'i ->
print [
i "base2:" toBase i 2 "base8:" toBase i 8 "base16:" toBase i 16
]
print ""
print ["101 => from base2:" fromBase "101" 2 "from base8:" fromBase "101" 8 "from base16:" fromBase "101" 16]
print ["123 => from base8:" fromBase "123" 8 "from base16:" fromBase "123" 16]
print ["456 => from base8:" fromBase "456" 8 "from base16:" fromBase "456" 16] |
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.
| #Julia | Julia | # Version 5.2
txt = "100"
for base = 2:21
base10 = parse(Int, txt, base)
println("String $txt in base $base is $base10 in base 10")
end
|
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.
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
val s = "100"
val bases = intArrayOf(2, 8, 10, 16, 19, 36)
for (base in bases)
println("$s in base ${"%2d".format(base)} is ${s.toInt(base)}")
} |
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.
| #Haskell | Haskell | import Text.Printf
main :: IO ()
main = mapM_ f [0..33] where
f :: Int -> IO ()
f n = printf " %3o %2d %2X\n" n n n -- binary not supported |
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.
| #HicEst | HicEst | DO n = 1, 33
WRITE(Format="b6.0, o4.0, i4.0, z4.0") n, n, n, n
ENDDO |
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.
| #Ruby | Ruby | SMALL = %w(zero one two three four five six seven eight nine ten
eleven twelve thirteen fourteen fifteen sixteen seventeen
eighteen nineteen)
TENS = %w(wrong wrong twenty thirty forty fifty sixty seventy
eighty ninety)
BIG = [nil, "thousand"] +
%w( m b tr quadr quint sext sept oct non dec).map{ |p| "#{p}illion" }
def wordify number
case
when number < 0
"negative #{wordify -number}"
when number < 20
SMALL[number]
when number < 100
div, mod = number.divmod(10)
TENS[div] + (mod==0 ? "" : "-#{wordify mod}")
when number < 1000
div, mod = number.divmod(100)
"#{SMALL[div]} hundred" + (mod==0 ? "" : " and #{wordify mod}")
else
# separate into 3-digit chunks
chunks = []
div = number
while div != 0
div, mod = div.divmod(1000)
chunks << mod # will store smallest to largest
end
raise ArgumentError, "Integer value too large." if chunks.size > BIG.size
chunks.map{ |c| wordify c }.
zip(BIG). # zip pairs up corresponding elements from the two arrays
find_all { |c| c[0] != 'zero' }.
map{ |c| c.join ' '}. # join ["forty", "thousand"]
reverse.
join(', '). # join chunks
strip
end
end
data = [-1123, 0, 1, 20, 123, 200, 220, 1245, 2000, 2200, 2220, 467889,
23_000_467, 23_234_467, 2_235_654_234, 12_123_234_543_543_456,
987_654_321_098_765_432_109_876_543_210_987_654,
123890812938219038290489327894327894723897432]
data.each do |n|
print "#{n}: "
begin
puts "'#{wordify n}'"
rescue => e
puts "Error: #{e}"
end
end |
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
| #Rust | Rust | use rand::prelude::*;
use std::io::stdin;
fn is_sorted(seq: &[impl PartialOrd]) -> bool {
if seq.len() < 2 {
return true;
}
// Look for any instance where the previous number is larger than the following
!seq.iter()
.zip(seq[1..].iter())
.any(|(prev, foll)| prev > foll)
}
fn main() {
println!(
"Number reversal game:
Given a jumbled list of the numbers 1 to 9, put the numbers in order.
Each attempt you can reverse up to n digits starting from the left.
The score is the count of the reversals needed to attain the ascending order."
);
let mut rng = thread_rng();
let mut sequence: Vec<u8> = (1..10).collect();
while is_sorted(&sequence) {
sequence.shuffle(&mut rng);
}
let mut attempt = 1;
while !is_sorted(&sequence) {
println!(
"Attempt {}: {:?} - How many numbers do you want to flip?",
attempt, sequence
);
let flip = {
let mut input = String::new();
stdin().read_line(&mut input).unwrap();
input.trim().parse().unwrap()
};
sequence[..flip].reverse();
attempt += 1;
}
println!(
"Congrats! It took you {} attempts to sort the sequence.",
attempt - 1 // Remove additionally counted attempt
);
} |
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.
| #AWK | AWK |
# syntax: GAWK -f NIM_GAME.AWK
BEGIN {
tokens = 12
printf("Nim game - using %d tokens\n",tokens)
while (tokens > 0) {
for (;;) {
printf("how many tokens 1-3? ")
getline ans
if (ans ~ /^[123]$/) {
tokens -= ans
prn("player")
break
}
print("invalid input, try again")
}
tokens -= ans = tokens % 4
prn("computer")
}
print("computer wins")
exit(0)
}
function prn(who) {
printf("%s takes %d token%s; there are %d remaining\n",who,ans,(ans==1)?"":"s",tokens)
}
|
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.
| #BlooP | BlooP |
DEFINE PROCEDURE ''DIVIDE'' [A,B]:
BLOCK 0: BEGIN
IF A < B, THEN:
QUIT BLOCK 0;
CELL(0) <= 1;
OUTPUT <= 1;
LOOP AT MOST A TIMES:
BLOCK 2: BEGIN
IF OUTPUT * B = A, THEN:
QUIT BLOCK 0;
OUTPUT <= OUTPUT + 1;
IF OUTPUT * B > A, THEN:
BLOCK 3: BEGIN
OUTPUT <= CELL(0);
QUIT BLOCK 0;
BLOCK 3: END;
CELL(0) <= OUTPUT;
BLOCK 2: END;
BLOCK 0: END.
DEFINE PROCEDURE ''MINUS'' [A,B]:
BLOCK 0: BEGIN
IF A < B, THEN:
QUIT BLOCK 0;
LOOP AT MOST A TIMES:
BLOCK 1: BEGIN
IF OUTPUT + B = A, THEN:
QUIT BLOCK 0;
OUTPUT <= OUTPUT + 1;
BLOCK 1: END;
BLOCK 0: END.
DEFINE PROCEDURE ''MODULUS'' [A,B]:
BLOCK 0: BEGIN
CELL(0) <= DIVIDE[A,B];
OUTPUT <= MINUS[A,CELL(0) * B];
BLOCK 0: END.
DEFINE PROCEDURE ''PLAYER_TURN'' [TOKENS_LEFT, TAKE]:
BLOCK 0: BEGIN
CELL(0) <= TAKE;
IF TAKE > 3, THEN:
BLOCK 1: BEGIN
CELL(0) <= MODULUS [TAKE, 3] + 1;
PRINT ['take must be between 1 and 3. setting take to ', CELL(0), '.'];
BLOCK 1: END;
IF TAKE < 1, THEN:
BLOCK 2: BEGIN
CELL(0) <= 1;
PRINT ['take must be between 1 and 3. setting take to 1.'];
BLOCK 2: END;
OUTPUT <= MINUS [TOKENS_LEFT, CELL(0)];
PRINT ['player takes ', CELL(0), ' tokens.'];
PRINT ['tokens remaining: ', OUTPUT];
PRINT [''];
BLOCK 0: END.
DEFINE PROCEDURE ''COMPUTER_TURN'' [TOKENS_LEFT]:
BLOCK 0: BEGIN
CELL(0) <= MODULUS [TOKENS_LEFT, 4];
OUTPUT <= MINUS [TOKENS_LEFT, CELL(0)];
PRINT ['computer takes ', CELL(0), ' tokens.'];
PRINT ['tokens remaining: ', OUTPUT];
PRINT [''];
BLOCK 0: END.
DEFINE PROCEDURE ''PLAY_GAME'' [FST, SEC, THD]:
BLOCK 0: BEGIN
CELL(0) <= FST;
CELL(1) <= SEC;
CELL(2) <= THD;
OUTPUT <= 12;
LOOP 3 TIMES:
BLOCK 1: BEGIN
OUTPUT <= PLAYER_TURN [OUTPUT, CELL(0)];
CELL(0) <= CELL(1);
CELL(1) <= CELL(2);
OUTPUT <= COMPUTER_TURN [OUTPUT];
BLOCK 1: END;
PRINT ['computer wins!'];
BLOCK 0: END.
PLAY_GAME [1,4,3];
|
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program nroot64.s */
/* link with gcc. Use C function for display float */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szFormat1: .asciz "Root= %+09.15f\n"
.align 4
qNumberA: .quad 1024
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
/* root 10ieme de 1024 */
ldr x0,qAdriNumberA // number address
ldr d0,[x0] // load number in registre d0
scvtf d0,d0 // conversion in float
mov x0,#10 // N
bl nthRoot
ldr x0,qAdrszFormat1 // format
bl printf // call C function !!!
// Attention register dn lost !!!
/* square root of 2 */
fmov d0,2 // conversion 2 in float register d0
mov x0,#2 // N
bl nthRoot
ldr x0,qAdrszFormat1 // format
// d0 contains résult
bl printf // call C function !!!
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrszFormat1: .quad szFormat1
qAdriNumberA: .quad qNumberA
/******************************************************************/
/* compute nth root */
/******************************************************************/
/* x0 contains N */
/* d0 contains the value */
/* x0 return result */
nthRoot:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp d1,d2,[sp,-16]! // save float registers
stp d3,d4,[sp,-16]! // save float registers
stp d5,d6,[sp,-16]! // save float registers
stp d7,d8,[sp,-16]! // save float registers
fmov d6,x0 //
scvtf d6,d6 // N conversion in float double précision (64 bits)
sub x1,x0,#1 // N - 1
fmov d8,x1 //
scvtf d4,d8 //conversion in float double précision
fmov d2,d0 // a = A
fdiv d3,d0,d6 // b = A/n
adr x2,dfPrec // load précision
ldr d8,[x2]
1: // begin loop
fmov d2,d3 // a <- b
fmul d5,d3,d4 // (N-1)*b
fmov d1,1 // constante 1 -> float
mov x2,0 // loop indice
2: // compute pow (n-1)
fmul d1,d1,d3 //
add x2,x2,1
cmp x2,x1 // n -1 ?
blt 2b // no -> loop
fdiv d7,d0,d1 // A / b pow (n-1)
fadd d7,d7,d5 // + (N-1)*b
fdiv d3,d7,d6 // / N -> new b
fsub d1,d3,d2 // compute gap
fabs d1,d1 // absolute value
fcmp d1,d8 // compare float maj FPSCR
bgt 1b // if gap > précision -> loop
fmov d0,d3 // end return result in d0
100:
ldp d7,d8,[sp],16 // restaur 2 float registers
ldp d5,d6,[sp],16 // restaur 2 float registers
ldp d3,d4,[sp],16 // restaur 2 float registers
ldp d1,d2,[sp],16 // restaur 2 float registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
dfPrec: .double 0f1E-10 // précision
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void swap(char* str, int i, int j) {
char c = str[i];
str[i] = str[j];
str[j] = c;
}
void reverse(char* str, int i, int j) {
for (; i < j; ++i, --j)
swap(str, i, j);
}
bool next_permutation(char* str) {
int len = strlen(str);
if (len < 2)
return false;
for (int i = len - 1; i > 0; ) {
int j = i, k;
if (str[--i] < str[j]) {
k = len;
while (str[i] >= str[--k]) {}
swap(str, i, k);
reverse(str, j, len - 1);
return true;
}
}
return false;
}
uint32_t next_highest_int(uint32_t n) {
char str[16];
snprintf(str, sizeof(str), "%u", n);
if (!next_permutation(str))
return 0;
return strtoul(str, 0, 10);
}
int main() {
uint32_t numbers[] = {0, 9, 12, 21, 12453, 738440, 45072010, 95322020};
const int count = sizeof(numbers)/sizeof(int);
for (int i = 0; i < count; ++i)
printf("%d -> %d\n", numbers[i], next_highest_int(numbers[i]));
// Last one is too large to convert to an integer
const char big[] = "9589776899767587796600";
char next[sizeof(big)];
memcpy(next, big, sizeof(big));
next_permutation(next);
printf("%s -> %s\n", big, next);
return 0;
} |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #ALGOL_68 | ALGOL 68 | PROC make list = ( STRING separator )STRING:
BEGIN
INT counter := 0;
PROC make item = ( STRING item )STRING:
BEGIN
counter +:= 1;
whole( counter, 0 ) + separator + item + REPR 10
END; # make item #
make item( "first" ) + make item( "second" ) + make item( "third" )
END; # make list #
print( ( make list( ". " ) ) )
|
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #ALGOL_W | ALGOL W | begin
string(30) procedure makeList ( string(2) value separator ) ;
begin
string(30) listValue;
integer counter;
string(10) procedure makeItem ( string(6) value item
; integer value length
) ;
begin
string(10) listItem;
counter := counter + 1;
listItem( 0 // 1 ) := code( decode( "0" ) + counter );
listItem( 1 // 2 ) := separator;
listItem( 3 // 6 ) := item;
listItem( 3 + length // 1 ) := code( 10 );
listItem
end; % makeItem %
counter := 0;
listValue := makeItem( "first", 5 );
listValue( 9 // 10 ) := makeItem( "second", 6 );
listValue( 19 // 10 ) := makeItem( "third", 5 );
listValue
end; % makeList %
write( makeList( ". " ) )
end. |
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.
| #J | J | Substitute=: ({.@:[)`(I.@:(= {:)~)`]}
NB. aside: demonstrate Substitution
] A =: ;/ i. 8
┌─┬─┬─┬─┬─┬─┬─┬─┐
│0│1│2│3│4│5│6│7│
└─┴─┴─┴─┴─┴─┴─┴─┘
] B =: ('xxxx' ; 3)
┌────┬─┐
│xxxx│3│
└────┴─┘
B Substitute A
┌─┬─┬─┬────┬─┬─┬─┬─┐
│0│1│2│xxxx│4│5│6│7│
└─┴─┴─┴────┴─┴─┴─┴─┘
B Substitute A , < 3
┌─┬─┬─┬────┬─┬─┬─┬─┬────┐
│0│1│2│xxxx│4│5│6│7│xxxx│
└─┴─┴─┴────┴─┴─┴─┴─┴────┘
|
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.
| #jq | jq |
#!/bin/bash
function template {
cat<<EOF
[
[[1, 2],
[3, 4, 1],
5 ]]
EOF
}
function payload {
for i in $(seq 0 6) ; do
echo Payload#$i
done
}
# Task 1: Template instantiation
payload | jq -Rn --argfile t <(template) '
([inputs] | with_entries(.key |= tostring)) as $dict
| $t
| walk(if type == "number" then $dict[tostring] else . end)
'
|
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)
| #Julia | Julia | using Base.Iterators
struct NonogramPuzzle
nrows::Int
ncols::Int
xhints::Vector{Vector{Int}}
yhints::Vector{Vector{Int}}
solutions:: Vector{Any}
NonogramPuzzle(xh, yh) = new(length(xh), length(yh), xh, yh, Vector{NTuple{4,Array{Int64,1}}}())
end
ycols2xrows(ycols) = [[ycols[i][j] for i in eachindex(ycols)] for j in eachindex(ycols[1])]
function hintsfromcol(rowvec, col, nrows)
hints = Vector{Int}()
hintrun = 0
for row in rowvec
if row[col] != 0
hintrun += 1
if col == nrows
push!(hints, hintrun)
end
elseif hintrun > 0
push!(hints, hintrun)
hintrun = 0
end
end
hints
end
function nonoblocks(hints, len)
minsized(arr) = vcat(map(x -> vcat(fill(1, x), [0]), arr)...)[1:end-1]
minlen(arr) = sum(arr) + length(arr) - 1
if isempty(hints)
return fill(0, len)
elseif minlen(hints) == len
return minsized(hints)
end
possibilities = Vector{Vector{Int}}()
allbuthead = hints[2:end]
for leftspace in 0:(len - minlen(hints))
header = vcat(fill(0, leftspace), fill(1, hints[1]), [0])
rightspace = len - length(header)
if isempty(allbuthead)
push!(possibilities, rightspace <= 0 ? header[1:len] : vcat(header, fill(0, rightspace)))
elseif minlen(allbuthead) == rightspace
push!(possibilities, vcat(header, minsized(allbuthead)))
else
foreach(x -> push!(possibilities, vcat(header, x)), nonoblocks(allbuthead, rightspace))
end
end
possibilities
end
function exclude!(xchoices, ychoices)
andvec(a) = findall(x -> x == 1, foldl((x, y) -> [x[i] & y[i] for i in 1:length(x)], a))
orvec(a) = findall(x -> x == 0, foldl((x, y) -> [x[i] | y[i] for i in 1:length(x)], a))
filterbyval!(arr, val, pos) = if !isempty(arr) filter!(x -> x[pos] == val, arr); end
ensurevecvec(arr::Vector{Vector{Int}}) = arr
ensurevecvec(arr::Vector{Int}) = [arr]
function excl!(choices, otherchoices)
for i in 1:length(choices)
if length(choices[i]) > 0
all1 = andvec(choices[i])
all0 = orvec(choices[i])
foreach(n -> filterbyval!(otherchoices[n], 1, i), all1)
foreach(n -> filterbyval!(otherchoices[n], 0, i), all0)
end
end
end
xclude!(x, y) = (excl!(x, y); x = map(ensurevecvec, x); y = map(ensurevecvec, y); (x, y))
xlen, ylen = sum(map(length, xchoices)), sum(map(length, ychoices))
while true
ychoices, xchoices = xclude!(ychoices, xchoices)
if any(isempty, xchoices)
return
end
xchoices, ychoices = xclude!(xchoices, ychoices)
if any(isempty, ychoices)
return
end
newxlen, newylen = sum(map(length, xchoices)), sum(map(length, ychoices))
if newxlen == xlen && newylen == ylen
return
end
xlen, ylen = newxlen, newylen
end
end
function trygrids(nonogram)
xchoices = [nonoblocks(nonogram.xhints[i], nonogram.ncols) for i in 1:nonogram.nrows]
ychoices = [nonoblocks(nonogram.yhints[i], nonogram.nrows) for i in 1:nonogram.ncols]
exclude!(xchoices, ychoices)
if all(x -> length(x) == 1, xchoices)
println("Unique solution.")
push!(nonogram.solutions, [x[1] for x in xchoices])
elseif all(x -> length(x) == 1, ychoices)
println("Unique solution.")
ycols = [y[1] for y in ychoices]
push!(nonogram.solutions, ycols2xrows(ycols))
else
println("Brute force: $(prod(map(length, xchoices))) possibilities.")
for stack in product(xchoices...)
arr::Vector{Vector{Int}} = [i isa Vector ? i : [i] for i in stack]
if all(x -> length(x) == nonogram.ncols, arr) &&
all(y -> hintsfromcol(arr, y, nonogram.nrows) == nonogram.yhints[y], 1:nonogram.ncols)
push!(nonogram.solutions, arr)
end
end
nsoln = length(nonogram.solutions)
println(nsoln == 0 ? "No" : nsoln, " solutions.")
end
end
# The first puzzle below requires brute force, and the second has no solutions.
const testnonograms = """
B B A A
B B A A
B A A
A A A
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
"""
function processtestpuzzles(txt)
solutiontxt(a) = (s = ""; for r in a for c in r; s *= (c == 0 ? "." : "#") end; s *= "\n" end; s)
txtline2ints(s) = [[UInt8(ch - 'A' + 1) for ch in r] for r in split(s, r"\s+")]
linepairs = uppercase.(string.(split(txt, "\n\n")))
pcount = 0
for xyhints in linepairs
xh, yh = map(x -> txtline2ints(strip(x)), split(xyhints, "\n"))
nonogram = NonogramPuzzle(xh, yh)
println("\nPuzzle $(pcount += 1):")
trygrids(nonogram)
foreach(x -> println(solutiontxt(x), "\n"), nonogram.solutions)
end
end
processtestpuzzles(testnonograms)
|
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.
| #Racket | Racket | #lang racket
(require racket/trace)
(define add1-to-car (match-lambda [(cons (app add1 p1) t) (cons p1 t)]))
;; inputs:
;; cells -- available cells
;; blocks -- list of block widths
;; output:
;; gap-block+gaps
;; where gap-block+gaps is:
;; (list gap) -- a single gap
;; (list gap block-width gap-block+gaps) -- padding to left, a block, right hand side
(define (nonoblock cells blocks)
(match* ((- cells (apply + (length blocks) -1 blocks)) #| padding available on both sides |# blocks)
[(_ (list)) (list (list cells))] ; generates an empty list of padding
[((? negative?) _) null] ; impossible to satisfy
[((and avp
;; use add1 with in-range because we actually want from 0 to available-padding
;; without add1, in-range iterates from 0 to (available-padding - 1)
(app add1 avp+1))
(list block))
(for/list ((l-pad (in-range 0 avp+1)))
(define r-pad (- avp l-pad)) ; what remains goes to right
(list l-pad block r-pad))]
[((app add1 avp+1) (list block more-blocks ...))
(for*/list ((l-pad (in-range 0 avp+1))
(cells-- (in-value (- cells block l-pad 1)))
(r-blocks (in-value (nonoblock cells-- more-blocks)))
(r-block (in-list r-blocks)))
(list* l-pad block (add1-to-car r-block)))])) ; put a single space pad on left of r-block
(define (neat rslt)
(define dots (curryr make-string #\.))
(define Xes (curryr make-string #\X))
(define inr
(match-lambda
[(list 0 (app Xes b) t ...)
(string-append b (inr t))]
[(list (app dots p) (app Xes b) t ...)
(string-append p b (inr t))]
[(list (app dots p)) p]))
(define (neat-row r)
(string-append "|" (inr r) "|"))
(string-join (map neat-row rslt) "\n"))
(define (tst c b)
(define rslt (nonoblock c b))
(define rslt-l (length rslt))
(printf "~a cells, ~a blocks => ~a~%~a~%" c b
(match rslt-l
[0 "impossible"]
[1 "1 solution"]
[(app (curry format "~a solutions") r) r])
(neat rslt)))
(module+ test
(tst 5 '[2 1])
(tst 5 '[])
(tst 10 '[8])
(tst 15 '[2 3 2 3])
(tst 5 '[2 3])) |
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
| #Common_Lisp | Common Lisp | (defun all-subsequences (list)
(labels ((subsequences (tail &optional (acc '()) (result '()))
"Return a list of the subsequence designators of the
subsequences of tail. Each subsequence designator is a
list of tails of tail, the subsequence being the first
element of each tail."
(if (endp tail)
(list* (reverse acc) result)
(subsequences (rest tail) (list* tail acc)
(append (subsequences (rest tail) acc) result))))
(continuous-p (subsequence-d)
"True if the designated subsequence is continuous."
(loop for i in subsequence-d
for j on (first subsequence-d)
always (eq i j)))
(designated-sequence (subsequence-d)
"Destructively transforms a subsequence designator into
the designated subsequence."
(map-into subsequence-d 'first subsequence-d)))
(let ((nc-subsequences (delete-if #'continuous-p (subsequences list))))
(map-into nc-subsequences #'designated-sequence nc-subsequences)))) |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #AutoHotkey | AutoHotkey | MsgBox % number2base(200, 16) ; 12
MsgBox % parse(200, 16) ; 512
number2base(number, base)
{
While, base < digit := floor(number / base)
{
result := mod(number, base) . result
number := digit
}
result := digit . result
Return result
}
parse(number, base)
{
result = 0
pos := StrLen(number) - 1
Loop, Parse, number
{
result := ((base ** pos) * A_LoopField) + result
base -= 1
}
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.
| #Lua | Lua | print( tonumber("123") )
print( tonumber("a5b0", 16) )
print( tonumber("011101", 2) )
print( tonumber("za3r", 36) ) |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 19^^91g5dcg2h6da7260a9f3c4a
2^^11110001001000000 |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write("Non-decimal radices/Output")
every i := 255 | 2 | 5 | 16 do {
printf("%%d = %d\n",i) # integer format
printf("%%x = %x\n",i) # hex format
printf("%%o = %o\n",i) # octal format
printf("%%s = %s\n",i) # string format
printf("%%i = %i\n",i) # image format
}
end |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming language.
Note
This is distinct from Number base conversion as a user-defined conversion function is not asked for.)
The reverse operation is Common number base parsing.
| #J | J | 2 #.inv 12
1 1 0 0
3 #.inv 100
1 0 2 0 1
16 #.inv 180097588
10 11 12 1 2 3 4 |
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.
| #Rust | Rust | use std::io::{self, Write, stdout};
const SMALL: &[&str] = &[
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen",
];
const TENS: &[&str] = &[
"PANIC", "PANIC", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
];
const MAGNITUDE: &[&str] = &[
"PANIC", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion",
];
fn wordify<W: Write>(w: &mut W, mut number: i64) -> Result<(), io::Error> {
if number == 0 {
return write!(w, "zero");
}
if number < 0 {
write!(w, "negative ")?;
number = -number;
}
while number != 0 {
if number < 20 {
write!(w, "{}", SMALL[number as usize])?;
break;
} else if number < 100 {
write!(w, "{}", TENS[number as usize / 10])?;
number %= 10;
if number != 0 {
write!(w, "-")?;
}
} else if number < 1_000 {
write!(w, "{} hundred", SMALL[number as usize / 100])?;
number %= 100;
if number != 0 {
write!(w, " and ")?;
}
} else {
let mut top = number;
let mut magnitude = 0i64;
let mut magnitude_pow = 1i64;
while top >= 1_000 {
top /= 1_000;
magnitude += 1;
magnitude_pow *= 1_000;
}
wordify(w, top)?;
number %= magnitude_pow;
if number == 0 {
write!(w, " {}", MAGNITUDE[magnitude as usize])?;
} else if number > 100 {
write!(w, " {}, ", MAGNITUDE[magnitude as usize])?;
} else {
write!(w, " {} and ", MAGNITUDE[magnitude as usize])?;
}
}
}
Ok(())
}
fn main() {
let stdout = stdout();
let mut stdout = stdout.lock();
for &n in &[12, 1048576, 9_000_000_000_000_000_000, -2, 0, 5_000_000_000_000_000_001, -555_555_555_555] {
wordify(&mut stdout, n).unwrap();
write!(&mut stdout, "\n").unwrap();
}
} |
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
| #Scala | Scala | object NumberReversalGame extends App {
def play(n: Int, cur: List[Int], goal: List[Int]) {
readLine(s"""$n. ${cur mkString " "} How many to flip? """) match {
case null => println
case s => scala.util.Try(s.toInt) match {
case scala.util.Success(i) if i > 0 && i <= cur.length =>
(cur.take(i).reverse ++ cur.drop(i)) match {
case done if done == goal =>
println(s"Congratulations! You solved "+goal.mkString(" "))
println(s"Your score is $n (lower is better)")
case next => play(n + 1, next, goal)
}
case _ => println(s"Choose a number between 1 and ${cur.length}")
play(n + 1, cur, goal)
}
}
}
def play(size: Int) {
val goal = List.range(1, size + 1)
def init: List[Int] = scala.util.Random.shuffle(goal) match {
case repeat if repeat == goal => init
case done => done
}
play(1, init, goal)
}
play(9)
} |
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.
| #C | C |
#include <stdio.h>
int playerTurn(int numTokens, int take);
int computerTurn(int numTokens);
int main(void)
{
printf("Nim Game\n\n");
int Tokens = 12;
while(Tokens > 0)
{
printf("How many tokens would you like to take?: ");
int uin;
scanf("%i", &uin);
int nextTokens = playerTurn(Tokens, uin);
if (nextTokens == Tokens)
{
continue;
}
Tokens = nextTokens;
Tokens = computerTurn(Tokens);
}
printf("Computer wins.");
return 0;
}
int playerTurn(int numTokens, int take)
{
if (take < 1 || take > 3)
{
printf("\nTake must be between 1 and 3.\n\n");
return numTokens;
}
int remainingTokens = numTokens - take;
printf("\nPlayer takes %i tokens.\n", take);
printf("%i tokens remaining.\n\n", remainingTokens);
return remainingTokens;
}
int computerTurn(int numTokens)
{
int take = numTokens % 4;
int remainingTokens = numTokens - take;
printf("Computer takes %u tokens.\n", take);
printf("%i tokens remaining.\n\n", remainingTokens);
return remainingTokens;
}
|
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.
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
PROC NthRoot(REAL POINTER a,n REAL POINTER res)
REAL n1,eps,one,tmp1,tmp2,tmp3
ValR("0.0001",eps)
IntToReal(1,one)
RealSub(n,one,n1)
Sqrt(a,res) ;res=sqrt(a)
DO
Power(res,n,tmp1) ;tmp=res^n
RealSub(a,tmp1,tmp2) ;tmp2=a-res^n
RealAbs(tmp2,tmp1) ;tmp1=abs(a-res^n)
IF RealGreaterOrEqual(eps,tmp1) THEN
RETURN
FI
Power(res,n1,tmp1) ;tmp1=res^(n-1)
RealDiv(a,tmp1,tmp2) ;tmp2=a/(res^(n-1))
RealMult(n1,res,tmp1) ;tmp1=(n-1)*res
RealAdd(tmp1,tmp2,tmp3) ;tmp3=((n-1)*res + a/(res^(n-1)))
RealDiv(tmp3,n,res) ;res=((n-1)*res + a/(res^(n-1)))/n
OD
RETURN
PROC Test(CHAR ARRAY sa,sn)
REAL a,n,res
ValR(sa,a)
ValR(sn,n)
PrintR(n) Print(" root of ")
PrintR(a) Print(" is ")
NthRoot(a,n,res)
PrintRE(res)
RETURN
PROC Main()
Put(125) PutE() ;clear screen
MathInit()
Test("2","2")
Test("81","4")
Test("1024","10")
Test("7","0.5")
Test("12.34","56.78")
RETURN |
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
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
using integer = mpz_class;
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
return out.str();
}
integer next_highest(const integer& n) {
std::string str(to_string(n));
if (!std::next_permutation(str.begin(), str.end()))
return 0;
return integer(str);
}
int main() {
for (integer n : {0, 9, 12, 21, 12453, 738440, 45072010, 95322020})
std::cout << n << " -> " << next_highest(n) << '\n';
integer big("9589776899767587796600");
std::cout << big << " -> " << next_highest(big) << '\n';
return 0;
} |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #AppleScript | AppleScript | --------------------- NESTED FUNCTION --------------------
-- makeList :: String -> String
on makeList(separator)
set counter to 0
-- makeItem :: String -> String
script makeItem
on |λ|(x)
set counter to counter + 1
(counter & separator & x & linefeed) as string
end |λ|
end script
map(makeItem, ["first", "second", "third"]) as string
end makeList
--------------------------- TEST -------------------------
on run
makeList(". ")
end run
-------------------- GENERIC FUNCTIONS -------------------
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map |
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
| #Arturo | Arturo | makeList: function [separator][
counter: 1
makeItem: function [item] .export:[counter][
result: ~"|counter||separator||item|"
counter: counter+1
return result
]
@[
makeItem "first"
makeItem "second"
makeItem "third"
]
]
print join.with:"\n" 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
| #AppleScript | AppleScript | repeat
set {hours:h, minutes:m} to (current date)
if {0, 30} contains m then
set bells to (h mod 4) * 2 + (m div 30)
if bells is 0 then set bells to 4
set pairs to bells div 2
repeat pairs times
say "ding dong" using "Bells"
end repeat
if (bells mod 2) is 1 then
say "dong" using "Bells"
end if
end if
delay 60
end repeat |
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.
| #Julia | Julia | t = ([Any[Any[1, 2],
Any[3, 4, 1],
5]])
p = ["Payload#$x" for x in 0:6]
for (i, e) in enumerate(t)
if e isa Number
t[i] = p[e + 1]
else
for (j, f) in enumerate(e)
if f isa Number
e[j] = p[f + 1]
else
for (k, g) in enumerate(f)
if g isa Number
f[k] = p[g + 1]
end
end
end
end
end
end
show(t)
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | t = ToExpression[StringReplace["[[[1,2],[3,4,1],5]]", {"[" -> "{", "]" -> "}"}]];
p = "Payload#" <> ToString[#] & /@ Range[6];
Map[p[[#]] &, t, {-1}] |
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.
| #M2000_Interpreter | M2000 Interpreter | Font "Courier New"
cls
Module Checkit {
t=(((1,2), (3,4,1),5),) ' use (1,) for one item tuple
Tuple$ = lambda$ (a, feed$=" ") -> {
\\ we can pass a tuple of two arguments or two arguments
k=each(a)
lim=len(a)-1
res$="("
link a to a() ' to use type$()
while k {
if type$(a(k^))="mArray" then
res$+=Lambda$(array(a, k^),feed$+" ")
if k^<lim then
res$+={,
}+feed$
end if
else
res$+= trim$(str$(array(k)))
if k^<lim then res$+=", "
end if
}
=res$+")"
}
TotalPayload = lambda (a)->{
k=each(a)
link a to a()
res=0
while k {
if type$(a(k^))="mArray" then
res+=Lambda(a(k^))
else
res++
end if
}
=res
}
Payload = lambda (a,payloads as list)->{
misspayloads=List
used=list
inner=lambda misspayloads, p=1, payloads, used (a)-> {
k=each(a)
res=(,)
link a to a()
while k {
if type$(a(k^))="mArray" then
Append res, (Lambda(a(k^)),)
else
curpayload$="Payload#"+trim$(str$(array(k)))
if not exist(payloads, curpayload$) Then
if not exist(used, curpayload$) Then
Append res, ("missing#pos"+trim$(str$(p)),)
append misspayloads, p:=curpayload$
else
Append res, (curpayload$,)
End if
p++
else
Append res, (curpayload$,)
if exist(payloads, curpayload$) then
delete payloads, curpayload$
if not exist(used, curpayload$) then append used, curpayload$
end if
p++
end if
end if
}
=res
}
=inner(a), payloads, misspayloads
}
Expand$ =lambda$ (a as array, unused as list, misspayloads as list)-> {
Read ? space$
inner$= lambda$ (a, feed$=" ")->{
k=each(a)
lim=len(a)-1
res$="["
link a to a() ' to use type$()
while k {
if type$(a(k^))="mArray" then
res$+=Lambda$(array(a, k^),feed$+" ")
if k^<lim then
res$+={,
}+feed$
end if
else
res$+= "'"+array$(k)+"'"
if k^<lim then res$+=", "
end if
}
=res$+"]"
}
document unused$="Unused Payloads"+{
}
if len(unused)>0 then
un=each(unused)
while un {
unused$=" "+eval$(un)+{
}
}
else
unused$=" -"
end if
if len(misspayloads)>0 then
un=each(misspayloads)
lim=len(misspayloads)-1
document missing$="Missing in position: "+{
}
while un {
missing$=" "+eval$(un)+"-pos"+eval$(un,un^)+{
}
}
=inner$(a, space$)+{
}+unused$+missing$
Else
=inner$(a, space$)+{
} + unused$
End if
}
flush
Data t, (((1,10), (3,4,16),5),)
While not empty {
Read t
Document result$="Payloads:"+{
}
p=list
for i=0 to 6 {
Append p, "Payload#"+trim$(str$(i))
result$=" "+eval$(p, i)+{
}
}
result$="Template:"+{
}
result$=" "+Tuple$(t, " ")+{
}
result$="Template with Payloads:"+{
}
m=Payload(t, p)
result$=" "+Expand$(!m, " ")
clipboard result$
}
}
Checkit
Report clipboard$ |
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.
| #Nim | Nim | import macros,sugar,strformat
#macro to take a nested tuple and return a type
#e.g. (int,(int,int))=>(string,(string,string))
proc intstr(n: NimNode): NimNode =
if n.kind == nnkSym:
return ident("string")
result = nnkPar.newNimNode()
for i in 1..<n.len:
result.add(intstr(n[i]))
macro tuptype(t: typed): untyped = intstr(t.getType)
proc replace(t: tuple | int, p: openArray[string]): auto =
when t is int: (if t in 0..<p.len: p[t] else: "nil")
else:
var res: tuptype(t)
for k, v in t.fieldpairs:
#k will be 'Field0', so we convert to an integer index
res[k[^1].int - '0'.int] = replace(v, p)
return res
when isMainModule:
let p = collect(for i in 0..5: &"payload{i}")
let tplt1 = ((1,2),(3,4,1),5)
let tplt2 = ((1,2),(3,4,1),6)
echo replace(tplt1, p)
echo replace(tplt2, p) |
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)
| #Kotlin | Kotlin | // version 1.2.0
import java.util.BitSet
typealias BitSets = List<MutableList<BitSet>>
val rx = Regex("""\s""")
fun newPuzzle(data: List<String>) {
val rowData = data[0].split(rx)
val colData = data[1].split(rx)
val rows = getCandidates(rowData, colData.size)
val cols = getCandidates(colData, rowData.size)
do {
val numChanged = reduceMutual(cols, rows)
if (numChanged == -1) {
println("No solution")
return
}
}
while (numChanged > 0)
for (row in rows) {
for (i in 0 until cols.size) {
print(if (row[0][i]) "# " else ". ")
}
println()
}
println()
}
// collect all possible solutions for the given clues
fun getCandidates(data: List<String>, len: Int): BitSets {
val result = mutableListOf<MutableList<BitSet>>()
for (s in data) {
val lst = mutableListOf<BitSet>()
val a = s.toCharArray()
val sumChars = a.sumBy { it - 'A' + 1 }
val prep = a.map { "1".repeat(it - 'A' + 1) }
for (r in genSequence(prep, len - sumChars + 1)) {
val bits = r.substring(1).toCharArray()
val bitset = BitSet(bits.size)
for (i in 0 until bits.size) bitset[i] = bits[i] == '1'
lst.add(bitset)
}
result.add(lst)
}
return result
}
fun genSequence(ones: List<String>, numZeros: Int): List<String> {
if (ones.isEmpty()) return listOf("0".repeat(numZeros))
val result = mutableListOf<String>()
for (x in 1 until numZeros - ones.size + 2) {
val skipOne = ones.drop(1)
for (tail in genSequence(skipOne, numZeros - x)) {
result.add("0".repeat(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).
*/
fun reduceMutual(cols: BitSets, rows: BitSets): Int {
val countRemoved1 = reduce(cols, rows)
if (countRemoved1 == -1) return -1
val countRemoved2 = reduce(rows, cols)
if (countRemoved2 == -1) return -1
return countRemoved1 + countRemoved2
}
fun reduce(a: BitSets, b: BitSets): Int {
var countRemoved = 0
for (i in 0 until a.size) {
val commonOn = BitSet()
commonOn[0] = b.size
val commonOff = BitSet()
// determine which values all candidates of a[i] have in common
for (candidate in a[i]) {
commonOn.and(candidate)
commonOff.or(candidate)
}
// remove from b[j] all candidates that don't share the forced values
for (j in 0 until b.size) {
val fi = i
val fj = j
if (b[j].removeIf { cnd ->
(commonOn[fj] && !cnd[fi]) ||
(!commonOff[fj] && cnd[fi]) }) countRemoved++
if (b[j].isEmpty()) return -1
}
}
return countRemoved
}
val p1 = listOf("C BA CB BB F AE F A B", "AB CA AE GA E C D C")
val p2 = listOf(
"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"
)
val p3 = listOf(
"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"
)
val p4 = listOf(
"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"
)
fun main(args: Array<String>) {
for (puzzleData in listOf(p1, p2, p3, p4)) {
newPuzzle(puzzleData)
}
} |
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.
| #Raku | Raku | for (5, [2,1]), (5, []), (10, [8]), (5, [2,3]), (15, [2,3,2,3]) -> ($cells, @blocks) {
say $cells, ' cells with blocks: ', @blocks ?? join ', ', @blocks !! '∅';
my $letter = 'A';
my $row = join '.', map { $letter++ x $_ }, @blocks;
say "no solution\n" and next if $cells < $row.chars;
say $row ~= '.' x $cells - $row.chars;
say $row while $row ~~ s/^^ (\.*) <|w> (.*?) <|w> (\w+) \.<!|w> /$1$0.$2/;
say '';
} |
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
| #D | D | T[][] ncsub(T)(in T[] seq, in uint s=0) pure nothrow @safe {
if (seq.length) {
typeof(return) aux;
foreach (ys; ncsub(seq[1 .. $], s + !(s % 2)))
aux ~= seq[0] ~ ys;
return aux ~ ncsub(seq[1 .. $], s + s % 2);
} else
return new typeof(return)(s >= 3, 0);
}
void main() @safe {
import std.stdio;
[1, 2, 3].ncsub.writeln;
[1, 2, 3, 4].ncsub.writeln;
foreach (const nc; [1, 2, 3, 4, 5].ncsub)
nc.writeln;
} |
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.
| #AWK | AWK | function strtol(str, base)
{
symbols = "0123456789abcdefghijklmnopqrstuvwxyz"
res = 0
str = tolower(str)
for(i=1; i < length(str); i++) {
res += index(symbols, substr(str, i, 1)) - 1
res *= base
}
res += index(symbols, substr(str, length(str), 1)) - 1
return res
}
function ltostr(num, base)
{
symbols = "0123456789abcdefghijklmnopqrstuvwxyz"
res = ""
do {
res = substr(symbols, num%base + 1, 1) res
num = int(num/base)
} while ( num != 0 )
return res
}
BEGIN {
print strtol("7b", 16)
print ltostr(123, 16)
} |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | val = sscanf('11 11 11','%d %o %x') |
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.
| #Nanoquery | Nanoquery | println int("1234")
println int("1100", 2)
println int("abcd", 16)
println int("ghij", 22) |
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.
| #Java | Java | public static void main(String args[]){
for(int a= 0;a < 33;a++){
System.out.println(Integer.toBinaryString(a));
System.out.println(Integer.toOctalString(a));
System.out.println(Integer.toHexString(a));
//the above methods treat the integer as unsigned
//there are also corresponding Long.to***String() methods for long's.
System.out.printf("%3o %2d %2x\n",a ,a ,a); //printf like the other languages; binary not supported
}
} |
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.
| #11l | 11l | F encode_neg_base(=n, b)
I n == 0
R ‘0’
[Int] out
L n != 0
(n, V rem) = divmod(n, b)
I rem < 0
n++
rem -= b
out.append(rem)
R reversed(out).map(String).join(‘’)
F decode_neg_base(nstr, b)
I nstr == ‘0’
R 0
V total = 0
L(ch) reversed(nstr)
V i = L.index
total += Int(ch) * b ^ i
R total
print(‘Encode 10 as negabinary (expect 11110)’)
V result = encode_neg_base(10, -2)
print(result)
I decode_neg_base(result, -2) == 10
print(‘Converted back to decimal’)
E
print(‘Error converting back to decimal’)
print(‘Encode 146 as negaternary (expect 21102)’)
result = encode_neg_base(146, -3)
print(result)
I decode_neg_base(result, -3) == 146
print(‘Converted back to decimal’)
E
print(‘Error converting back to decimal’)
print(‘Encode 15 as negadecimal (expect 195)’)
result = encode_neg_base(15, -10)
print(result)
I decode_neg_base(result, -10) == 15
print(‘Converted back to decimal’)
E
print(‘Error converting back to decimal’) |
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.
| #Scala | Scala | import scala.annotation.tailrec
import scala.collection.parallel.ParSeq
/** Spells an English numeral longhand. The numbers are expressed using words.
*
* The implementation goes up to 10<sup>69</sup>-1 and also supports negative and zero inputs.
*
* @example longhand( 1234 ) // results in: "one thousand two hundred thirty-four".
*/
trait LongHand {
/** Spells a number longhand
*
* Done by recursively process the triplets of decimal numbers.
* @param numeral the numeric value to be converted
* @param showAnd flag the output extra and in output, default off
* @param zeroString the word for 0, default to "zero"
* @param showHyphen hyphenate all compound numbers e.g. twenty-four, default is on
* @return the numeric value expressed in words
*/
def longhand(numeral: BigInt,
showAnd: Boolean = false,
zeroString: String = "zero",
showHyphen: Boolean = true): String = {
val condAndString = if (showAnd) "and " else ""
val condHyphenString = if (showHyphen) "-" else " "
// 234 Becomes "two hundred [and] thirty-four"
def composeScale(nnn: String, isLSDgroup: Boolean, strE3: String): String = {
nnn match { // Rare exceptions confirms the rule
case "000" => ""
case "100" => onesAndTeens(1) + hundredString + strE3 // Solves the faulty hundred AND thousand problem
case _ => {
val eval = (nnn.par.map(_.toString.toInt).reverse zip ParSeq('units, 'tens, 'hundreds)).reverse
eval.map {
case (d, 'units) if eval.seq.contains(1, 'tens) => onesAndTeens(d + 10)
case (d, 'units) if (isLSDgroup && nnn == "0") => zeroString
case (d, 'units) => onesAndTeens(d)
case (d, 'hundreds) if d > 0 => onesAndTeens(d) + hundredString + condAndString
case (d, 'tens) if d > 1 && eval.seq.contains(0, 'units) => tens(d)
case (d, 'tens) if d > 1 => tens(d) + condHyphenString //'
case _ => ""
}.mkString + strE3
}
}
} // def composeScale(…
def compose(n: BigInt): String = {
// "1234" becomes List((1,"thousand"), (234, ""))
val decGroups = n.toString.reverse.grouped(3).map(_.reverse).toSeq.par // Group into powers of thousands
if (decGroups.size <= shortScale.size) // Detect overflow
{ // Send per group section to composeScale
@tailrec
def iter(elems: Seq[(String, String)], acc: String): String = {
elems match {
case (group, powers) :: tail => {
iter(tail, acc + composeScale(group, tail == Nil, powers))
}
case _ => acc
}
} // Group of decimals are accompanied with the short scale name.
iter(decGroups.zip(shortScale).reverse.toList, "").mkString.trim
} else "###.overflow.###"
} // def compose(…
// Here starts def longhand(…
if (numeral < 0) "minus " + compose(-numeral) else compose(numeral)
} // End def longhand(…
private val onesAndTeens = {
def dozen = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ").par
def teens = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ").par
ParSeq("") ++ dozen ++ teens
}
private val tens = ParSeq("", "") ++
("twen thir for fif six seven eigh nine".split(' ')).map(_ + "ty")
private final val hundredString = "hundred "
private val shortScale = {
def p1 = "m b tr quadr quint sext sept oct non dec".split(' ').map(_ + "illion ").par
def p2 = "un duo tre quattuor quin sex septen octo novem ".split(' ').map(_ + "decillion ").par
def p3 = "vigint cent".split(' ').map(_ + "illion ").par
ParSeq("", "thousand ") ++ p1 ++ p2 ++ p3
}
} // trait LongHand
object SpellNumber extends LongHand with App {
// Main entry A little test...
{ // Anonymous ordered list as test set
def testVal1 = BigInt("1" * 69)
def testVal9 = BigInt(10).pow(69) - 1
@tailrec // Series generator of 9, 98, 987, 9876 …
def inner(counter: Int, elem: BigInt, testList: ParSeq[BigInt]): ParSeq[BigInt] = {
if (counter < 20)
inner(counter + 1, elem * 10 + (9 - (counter % 10)), testList ++ ParSeq(elem))
else testList.par
}
inner(0, 0L, // Test values
ParSeq(-Long.MaxValue, -1000000000, 12, 13, 19, 20, 21, 112, 1001, 1012, 1013,
Long.MaxValue - 1, Long.MaxValue - 13, testVal1, testVal9)) ++
(for (z <- 0 to 69) yield BigInt(10).pow(z)) // powers of ten
}.seq.sorted.foreach(num => println(f"$num%+,80d -> ${longhand(numeral = num, showAnd = true)}"))
} // object SpellNumber @ line 110 |
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
| #Scheme | Scheme |
(import (scheme base)
(scheme read)
(scheme write)
(srfi 1) ; list functions
(srfi 27)) ; random numbers
(random-source-randomize! default-random-source)
(define (make-randomised-list)
(let ((vec (apply vector (iota 9 1))))
(do ((c 0 (+ 1 c)))
((and (>= c 20) ; at least 20 tries
(not (apply < (vector->list vec)))) ; ensures list not in order
(vector->list vec))
(let* ((i (random-integer 9)) ; swap two randomly chosen elements
(j (random-integer 9))
(tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)))))
(define (play-game lst plays)
(define (reverse-first n lst)
(let-values (((start tail) (split-at lst n)))
(append (reverse start) tail)))
;
(display "List: ") (display lst) (newline)
(display "How many numbers should be flipped? ")
(let* ((flip (string->number (read-line)))
(new-lst (reverse-first flip lst)))
(if (apply < new-lst)
(display (string-append "Finished in "
(number->string plays)
" attempts\n"))
(play-game new-lst (+ 1 plays)))))
(play-game (make-randomised-list) 1)
|
http://rosettacode.org/wiki/Nim_game | Nim game | Nim game
You are encouraged to solve this task according to the task description, using any language you may know.
Nim is a simple game where the second player ─── if they know the trick ─── will always win.
The game has only 3 rules:
start with 12 tokens
each player takes 1, 2, or 3 tokens in turn
the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3 ─── if the first player takes 2, the second should take 2 ─── and if the first player takes 3, the second player will take 1.
Task
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| #C.2B.2B | C++ | #include <iostream>
#include <limits>
using namespace std;
void showTokens(int tokens) {
cout << "Tokens remaining " << tokens << endl << endl;
}
int main() {
int tokens = 12;
while (true) {
showTokens(tokens);
cout << " How many tokens 1, 2 or 3? ";
int t;
cin >> t;
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << "Invalid input, try again." << endl << endl;
} else if (t < 1 || t > 3) {
cout << endl << "Must be a number between 1 and 3, try again." << endl << endl;
} else {
int ct = 4 - t;
string s = (ct > 1) ? "s" : "";
cout << " Computer takes " << ct << " token" << s << endl << endl;
tokens -= 4;
}
if (tokens == 0) {
showTokens(0);
cout << " Computer wins!" << endl;
return 0;
}
}
} |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Nth_Root is
generic
type Real is digits <>;
function Nth_Root (Value : Real; N : Positive) return Real;
function Nth_Root (Value : Real; N : Positive) return Real is
type Index is mod 2;
X : array (Index) of Real := (Value, Value);
K : Index := 0;
begin
loop
X (K + 1) := ( (Real (N) - 1.0) * X (K) + Value / X (K) ** (N-1) ) / Real (N);
exit when X (K + 1) >= X (K);
K := K + 1;
end loop;
return X (K + 1);
end Nth_Root;
function Long_Nth_Root is new Nth_Root (Long_Float);
begin
Put_Line ("1024.0 10th =" & Long_Float'Image (Long_Nth_Root (1024.0, 10)));
Put_Line (" 27.0 3rd =" & Long_Float'Image (Long_Nth_Root (27.0, 3)));
Put_Line (" 2.0 2nd =" & Long_Float'Image (Long_Nth_Root (2.0, 2)));
Put_Line ("5642.0 125th =" & Long_Float'Image (Long_Nth_Root (5642.0, 125)));
end Test_Nth_Root;
|
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
| #D | D | import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
string next(string s) {
auto sb = appender!string;
auto 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.
auto index2 = index;
foreach (i; index + 1 .. 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 ~= s[0 .. index - 1];
}
// Append found, place next
sb ~= s[index2];
// Get remaining characters
auto chars = [cast(dchar) s[index - 1]];
foreach (i; index .. s.length) {
if (i != index2) {
chars ~= s[i];
}
}
// Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right.
chars.sort;
sb ~= chars;
return sb.data;
}
long factorial(long n) {
long fact = 1;
foreach (num; 2 .. n + 1) {
fact *= num;
}
return fact;
}
void testAll(string s) {
writeln("Test all permutations of: ", s);
string sOrig = s;
string sPrev = s;
int count = 1;
// Check permutation order. Each is greater than the last
bool orderOk = true;
int[string] uniqueMap = [s: 1];
while (true) {
s = next(s);
if (s == "0") {
break;
}
count++;
if (s.to!long < sPrev.to!long) {
orderOk = false;
}
uniqueMap.update(s, {
return 1;
}, (int a) {
return a + 1;
});
sPrev = s;
}
writeln(" Order: OK = ", orderOk);
// Test last permutation
auto reverse = sOrig.dup.to!(dchar[]).reverse.to!string;
writefln(" Last permutation: Actual = %s, Expected = %s, OK = %s", sPrev, reverse, sPrev == reverse);
// Check permutations unique
bool unique = true;
foreach (k, v; uniqueMap) {
if (v > 1) {
unique = false;
break;
}
}
writeln(" Permutations unique: OK = ", unique);
// Check expected count.
int[char] charMap;
foreach (c; sOrig) {
charMap.update(c, {
return 1;
}, (int v) {
return v + 1;
});
}
long permCount = factorial(sOrig.length);
foreach (k, v; charMap) {
permCount /= factorial(v);
}
writefln(" Permutation count: Actual = %d, Expected = %d, OK = %s", count, permCount, count == permCount);
}
void main() {
foreach (s; ["0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600", "3345333"]) {
writeln(s, " -> ", next(s));
}
testAll("12345");
testAll("11122");
} |
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
| #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
fun
MakeList
(
sep: string
) : void = let
//
var count: int = 0
//
val count =
$UNSAFE.cast{ref(int)}(addr@count)
//
fun
MakeItem
(
item: string
) : void = let
val () = !count := !count+1
in
println! (!count, sep, item)
end // end of [MakeItem]
//
in
MakeItem"first"; MakeItem"second"; MakeItem"third"
end // end of [MakeList]
(* ****** ****** *)
implement main0() = { val () = 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
| #BQN | BQN | MakeList ← {
nl←@+10 ⋄ s←𝕩 ⋄ i←0
MakeItem ← {i+↩1 ⋄ (•Fmt i)∾s∾𝕩}
(⊣∾nl∾⊢)´MakeItem¨"first"‿"second"‿"third"
} |
http://rosettacode.org/wiki/Nested_function | Nested function | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
Task
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
References
Nested function
| #C | C |
#include<stdlib.h>
#include<stdio.h>
typedef struct{
char str[30];
}item;
item* makeList(char* separator){
int counter = 0,i;
item* list = (item*)malloc(3*sizeof(item));
item makeItem(){
item holder;
char names[5][10] = {"first","second","third","fourth","fifth"};
sprintf(holder.str,"%d%s%s",++counter,separator,names[counter]);
return holder;
}
for(i=0;i<3;i++)
list[i] = makeItem();
return list;
}
int main()
{
int i;
item* list = makeList(". ");
for(i=0;i<3;i++)
printf("\n%s",list[i].str);
return 0;
}
|
http://rosettacode.org/wiki/Nautical_bell | Nautical bell |
Task
Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.
The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.
It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type.
Related task
Sleep
| #AutoHotkey | AutoHotkey | NauticalBell(hh, mm){
Hr := 0, min := 30, Bells := [], pattern := []
Loop 8 ; genrate 8 patterns
{
num := A_Index , code := ""
while (num/2 >=1)
code .= "** ", num := num-2
code .= mod(A_Index, 2) ? "*" : ""
pattern[A_Index] := code
}
loop, 48 ; 24 hours * 2 for every half an hour
{
numBells := !mod(A_Index, 8) ? 8 : mod(A_Index, 8) , min := 30
if !Mod(A_Index, 2)
hr++ , min := 00
Bells[SubStr("0" hr, -1) ":" min] := numBells
}
Bells[00 ":" 00] := Bells[24 ":" 00] , numBells := Bells[hh ":" mm]
return {"bells": numBells, "pattern": Pattern[numBells]}
} |
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.
| #Perl | Perl | sub fulfill {
my @payloads;
push @payloads, 'Payload#' . $_ for 0..5;
my @result;
push @result, ref $_ eq 'ARRAY' ? [@payloads[@$_]] : @payloads[$_] for @{@_[0]};
return [@result];
}
sub formatted {
my $result;
$result .= ref $_ eq 'ARRAY' ? '[ "'. join('", "', @$_) . '" ], ' : qq{"$_"} for @{@_[0]};
return '[ ' . $result . " ]\n";
}
print formatted fulfill( [[1,2], [ 3,4,1], 5] );
print formatted fulfill( [[1,2], [10,4,1], 5] );
|
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)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[VisualizeGrid, Possibilities, TryRow, TryColumn]
VisualizeGrid[candgrid_List] := StringRiffle[StringJoin/@Replace[candgrid,{{0}->" ",{1}->"#",{0,1}|{1,0}->"."},{2}],"\n"]
Possibilities[clues_List, len_Integer] := Module[{spaces, numclue, spacecands, cands},
numclue = Length[clues];
spaces = len - Total[clues];
spacecands = IntegerPartitions[spaces, {numclue - 1}];
spacecands = DeleteDuplicates[Catenate[Permutations /@ spacecands]];
cands = Catenate[Riffle[ConstantArray[1, #] & /@ clues, ConstantArray[0, #] & /@ #]] & /@ spacecands;
spacecands = IntegerPartitions[spaces, {numclue}];
spacecands = DeleteDuplicates[Catenate[Permutations /@ spacecands]];
cands = Join[cands, Catenate[Riffle[ConstantArray[1, #] & /@ clues, ConstantArray[0, #] & /@ #]] & /@ spacecands];
cands = Join[cands, Catenate[Riffle[ConstantArray[0, #] & /@ #, ConstantArray[1, #] & /@ clues]] & /@ spacecands];
spacecands = IntegerPartitions[spaces, {numclue + 1}];
spacecands = DeleteDuplicates[Catenate[Permutations /@ spacecands]];
cands = Join[cands, Catenate[Riffle[ConstantArray[0, #] & /@ #, ConstantArray[1, #] & /@ clues]] & /@ spacecands];
cands
]
TryRow[candgrid_List, i_Integer, hclues_List] := Module[{row, clue, len, poss, newgrid},
row = candgrid[[i]];
clue = hclues[[i]];
len = Length[row];
poss = Possibilities[clue, len];
poss //= Select[MatchQ[Alternatives @@@ row]];
poss //= Transpose;
poss //= Map[Union];
newgrid = candgrid;
newgrid[[i]] = poss;
newgrid
]
TryColumn[candgrid_List, i_Integer, hclues_List] := Transpose[TryRow[Transpose[candgrid], i, hclues]]
puzzles = "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";
puzzles = StringSplit[puzzles, "\n\n"];
puzzles = StringSplit[#, "\n"] & /@ puzzles;
puzzles = Map[StringSplit[#, " "] &, puzzles, {2}];
puzzles = Map[Characters, puzzles, {3}];
puzzles = puzzles /. Thread[CharacterRange["A", "Z"] -> (ToString /@ Range[26])];
puzzles = Map[ToExpression, puzzles, {4}];
Do[
hclues = puzzles[[n, 1]];
vclues = puzzles[[n, 2]];
{hsize, vsize} = {vclues // Length, hclues // Length};
cand = ConstantArray[{0, 1}, {vsize, hsize}];
oldcand = {};
While[oldcand =!= cand,
oldcand = cand;
Do[cand = TryRow[cand, i, hclues], {i, Length[hclues]}];
Do[cand = TryColumn[cand, i, vclues], {i, Length[vclues]}];
];
Print@VisualizeGrid[cand]
,
{n, 4}
] |
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.
| #REXX | REXX | /*REXX program enumerates all possible configurations (or an error) for nonogram puzzles*/
$.=; $.1= 5 2 1
$.2= 5
$.3= 10 8
$.4= 15 2 3 2 3
$.5= 5 2 3
do i=1 while $.i\==''
parse var $.i N blocks /*obtain N and blocks from array. */
N= strip(N); blocks= space(blocks) /*assign stripped N and blocks. */
call nono /*incoke NONO subroutine for heavy work*/
end /*i*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
nono: say copies('=', 70) /*display seperator for title.*/
say 'For ' N " cells and blocks of: " blocks /*display the title for output*/
z= /*assign starter value for Z. */
do w=1 for words(blocks) /*process each of the blocks. */
z= z copies('#', word(blocks,w) ) /*build a string for 1st value*/
end /*w*/ /*Z now has a leading blank. */
#= 1 /*number of positions (so far)*/
z= translate( strip(z), ., ' '); L= length(z) /*change blanks to periods. */
if L>N then do; say '***error*** invalid blocks for number of cells.'; return
end
@.0=; @.1= z; !.=0 /*assign default and the first position*/
z= pad(z) /*fill─out (pad) the value with periods*/
do prepend=1 while words(blocks)\==0 /*process all the positions (leading .)*/
new= . || @.prepend /*create positions with leading dots. */
if length(new)>N then leave /*Length is too long? Then stop adding*/
call add /*add position that has a leading dot. */
end /*prepend*/ /* [↑] prepend positions with dots. */
do k=1 for N /*process each of the positions so far.*/
do c=1 for N /* " " " " position blocks. */
if @.c=='' then iterate /*if string is null, skip the string. */
p= loc(@.c, k) /*find location of block in position. */
if p==0 | p>=N then iterate /*Location zero or out─of─range? Skip.*/
new= strip( insert(., @.c, p),'T',.) /*insert a dot and strip trailing dots.*/
if strip(new,'T',.)=@.c then iterate /*Is it the same value? Then skip it. */
if length(new)<=N then call add /*Is length OK? Then add position. */
end /*k*/
end /*c*/
say
say '─position─' center("value", max(7, length(z) ), '─') /*show hdr for output.*/
do m=1 for #
say center(m, 10) pad(@.m) /*display the index count and position.*/
end /*m*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
loc: _=0; do arg(2); _=pos('#.',pad(arg(1)),_+1); if _==0 then return 0; end; return _+1
add: if !.new==1 then return; #= # + 1; @.#= new; !.new=1; return
pad: return left( arg(1), N, .) |
http://rosettacode.org/wiki/Non-continuous_subsequences | Non-continuous subsequences | Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.)
A subsequence contains some subset of the elements of this sequence, in the same order.
A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence.
Note: Subsequences are defined structurally, not by their contents.
So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value.
Task: Find all non-continuous subsequences for a given sequence.
Example
For the sequence 1,2,3,4, there are five non-continuous subsequences, namely:
1,3
1,4
2,4
1,3,4
1,2,4
Goal
There are different ways to calculate those subsequences.
Demonstrate algorithm(s) that are natural for the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Elixir | Elixir | defmodule RC do
defp masks(n) do
maxmask = trunc(:math.pow(2, n)) - 1
Enum.map(3..maxmask, &Integer.to_string(&1, 2))
|> Enum.filter_map(&contains_noncont(&1), &String.rjust(&1, n, ?0)) # padding
end
defp contains_noncont(n) do
Regex.match?(~r/10+1/, n)
end
defp apply_mask_to_list(mask, list) do
Enum.zip(to_char_list(mask), list)
|> Enum.filter_map(fn {include, _} -> include > ?0 end, fn {_, value} -> value end)
end
def ncs(list) do
Enum.map(masks(length(list)), fn mask -> apply_mask_to_list(mask, list) end)
end
end
IO.inspect RC.ncs([1,2,3])
IO.inspect RC.ncs([1,2,3,4])
IO.inspect RC.ncs('abcd') |
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.