task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be ass... | #C.2B.2B | C++ | #include <iostream>
#include <sstream>
int main()
{
int num;
std::istringstream("0123459") >> num;
std::cout << num << std::endl; // prints 123459
std::istringstream("0123459") >> std::dec >> num;
std::cout << num << std::endl; // prints 123459
std::istringstream("abcf123") >> std::hex >> num;
std... |
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 langu... | #Arturo | Arturo | loop 0..33 'i ->
print [
pad as.binary i 6
pad as.octal i 2
pad to :string i 2
pad as.hex i 2
] |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming langu... | #AWK | AWK | $ awk '{printf("%d 0%o 0x%x\n",$1,$1,$1)}'
10
10 012 0xa
16
16 020 0x10
255
255 0377 0xff |
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, negat... | #PowerShell | PowerShell |
function Get-NumberName
{
<#
.SYNOPSIS
Spells out a number in English.
.DESCRIPTION
Spells out a number in English in the range of 0 to 999,999,999.
.NOTES
The code for this function was copied (almost word for word) from the C#
example on this page to show how similar Po... |
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 reversa... | #Quackery | Quackery | [ 0 temp put
[] 9 times
[ i^ 1+ join ]
dup
[ shuffle 2dup != until ]
[ dup echo cr
2dup != while
[ $ "Reverse how many? "
input
$->n not iff
drop again ]
split dip reverse join
1 temp tally
again ]
drop cr
say "That took "
... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Vedit_macro_language | Vedit macro language | IT("Gen 0: ..###.##.#.#.#.#..#.....") // initial pattern
#9 = Cur_Col
for (#8 = 1; #8 < 10; #8++) { // 10 generations
Goto_Col(7)
Reg_Empty(20)
while (Cur_Col < #9-1) {
if (Match("|{##|!#,#.#,|!###}")==0) {
Reg_Set(20, "#", APPEND)
} else {
Reg_Set(... |
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. ... | #JavaScript | JavaScript | const compose = (...fn) => (...x) => fn.reduce((a, b) => c => a(b(c)))(...x);
const inv = b => !b;
const arrJoin = str => arr => arr.join(str);
const mkArr = (l, f) => Array(l).fill(f);
const sumArr = arr => arr.reduce((a, b) => a + b, 0);
const sumsTo = val => arr => sumArr(arr) === val;
const zipper = arr => (p, c, i... |
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
numb... | #J | J | NB. unique list of all y faced dice
udice=: {{ 1+~./:~"1 (#: ,@i.)y#y }}
NB. which dice are less than which other dice?
NB. y here is a result of udice
lthan=: {{ 0>*@(+/)@,@:*@(-/)"1/~ y}}
NB. "less than loops" length x, for y sided non-transitive dice
cycles=: {{
ud=. udice y
lt=. lthan ud
extend=. [:; lt{... |
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
numb... | #Java | Java | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
private static List<List<Integer>> fourFaceCombos() {
List<List<Integer>> res = new ArrayList<>();
Set<Integ... |
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 subseque... | #11l | 11l | F ncsub(seq, s = 0)
I seq.empty
R I s >= 3 {[[Int]()]} E [[Int]]()
E
V x = seq[0.<1]
V xs = seq[1..]
V p2 = s % 2
V p1 = !p2
R ncsub(xs, s + p1).map(ys -> @x + ys) [+] ncsub(xs, s + p2)
print(ncsub(Array(1..3)))
print(ncsub(Array(1..4)))
print(ncsub(Array(1..5))) |
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 ass... | #Common_Lisp | Common Lisp | (parse-integer "abc" :radix 20 :junk-allowed t) ; => 4232 |
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 ass... | #D | D | import std.stdio, std.conv;
void main() {
immutable text = "100";
foreach (base; 2 .. 21)
writefln("String '%s' in base %d is %d in base 10" ,
text, base, to!int(text, 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 langu... | #BBC_BASIC | BBC BASIC | REM STR$ converts to a decimal string:
PRINT STR$(0)
PRINT STR$(123456789)
PRINT STR$(-987654321)
REM STR$~ converts to a hexadecimal string:
PRINT STR$~(43981)
PRINT STR$~(-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 langu... | #Bc | Bc |
for(i=1;i<10;i++) {
obase=10; print i," "
obase=8; print i," "
obase=3; print i," "
obase=2; print i
print "\n"
} |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming langu... | #C | C | #include <stdio.h>
int main()
{
int i;
for(i=1; i <= 33; i++)
printf("%6d %6x %6o\n", i, i, i);
return 0;
} |
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, negat... | #Prolog | Prolog |
:- module(spell, [spell/2]).
%
% spell numbers up to the nonillions.
%
ones(1, "one"). ones(2, "two"). ones(3, "three"). ones(4, "four"). ones( 5, "five").
ones(6, "six"). ones(7, "seven"). ones(8, "eight"). ones(9, "nine"). ones(10, "ten").
ones(11, "eleven"). ones(12, "twelve"). ones(13, "thi... |
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 reversa... | #R | R | reversalGame <- function(){
cat("Welcome to the Number Reversal Game! \n")
cat("Sort the numbers into ascending order by repeatedly \n",
"reversing the first n digits, where you specify n. \n \n", sep="")
# Generate a list that's definitely not in ascending order, per instuctions
data <- sample(1:9, 9)
... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module CellularAutomata
Private Enum PetriStatus
Active
Stable
Dead
End Enum
Function Main(ByVal cmdArgs() As String) As Integer
If cmdArgs.Length = 0 Or cmdArgs.Length > 1 Then
Console.WriteLine("Command requires string of either 1s and ... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Wart | Wart | def (gens n l)
prn l
repeat n
zap! gen l
prn l
def (gen l)
with (a nil b nil c l.0)
collect nil # won't insert paren without second token
each x cdr.l
shift! a b c x
yield (next a b c)
yield (next b c nil)
def (next a b c) # next state of b given neighbors a and c
... |
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. ... | #Julia | Julia | minsized(arr) = join(map(x->"#"^x, arr), ".")
minlen(arr) = sum(arr) + length(arr) - 1
function sequences(blockseq, numblanks)
if isempty(blockseq)
return ["." ^ numblanks]
elseif minlen(blockseq) == numblanks
return minsized(blockseq)
else
result = Vector{String}()
all... |
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
numb... | #Julia | Julia | import Base.>, Base.<
using Memoize, Combinatorics
struct Die
name::String
faces::Vector{Int}
end
""" Compares two die returning 1, -1 or 0 for operators >, < == """
function cmpd(die1, die2)
# Numbers of times one die wins against the other for all combinations
# cmp(x, y) is `(x > y) - (y > x)` to... |
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
numb... | #Kotlin | Kotlin | fun fourFaceCombos(): List<Array<Int>> {
val res = mutableListOf<Array<Int>>()
val found = mutableSetOf<Int>()
for (i in 1..4) {
for (j in 1..4) {
for (k in 1..4) {
for (l in 1..4) {
val c = arrayOf(i, j, k, l)
c.sort()
... |
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 subseque... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Non_Continuous is
type Sequence is array (Positive range <>) of Integer;
procedure Put_NCS
( Tail : Sequence; -- To generate subsequences of
Head : Sequence := (1..0 => 1); -- Already generated
Contig... |
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 invisibl... | #11l | 11l | print(Int(‘1A’, radix' 16)) // prints the integer 26 |
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 ass... | #E | E | ? __makeInt("200", 16)
# value: 512
? __makeInt("200", 10)
# value: 200 |
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 ass... | #Elixir | Elixir | iex(1)> String.to_integer("1000")
1000
iex(2)> String.to_integer("1000",2)
8
iex(3)> String.to_integer("1000",8)
512
iex(4)> String.to_integer("1000",16)
4096
iex(5)> String.to_integer("ffff",16)
65535 |
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 langu... | #C.23 | C# |
using System;
namespace NonDecimalRadicesOutput
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 42; i++)
{
string binary = Convert.ToString(i, 2);
string octal = Convert.ToString(i, 8);
string hex... |
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, negat... | #PureBasic | PureBasic | DataSection
numberNames:
;small
Data.s "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"
Data.s "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
;tens
Data.s "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "... |
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 reversa... | #Racket | Racket | #lang racket
(let loop ([nums (range 1 10)] [n 0])
(cond [(apply < nums) (if (zero? n)
(loop (shuffle nums) 0)
(printf "Done in ~s steps.\n" n))]
[else (printf "Step #~s: ~s\nFlip how many? " n nums)
(define-values (l r) (split-at nums (rea... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Wren | Wren | var trans = "___#_##_"
var v = Fn.new { |cell, i| (cell[i] != "_") ? 1 : 0 }
var evolve = Fn.new { |cell, backup|
var len = cell.count - 2
var diff = 0
for (i in 1...len) {
/* use left, self, right as binary number bits for table index */
backup[i] = trans[v.call(cell, i - 1) * 4 + v.cal... |
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... | #11l | 11l | F gen_row(w, s)
‘Create all patterns of a row or col that match given runs.’
F gen_seg([[Int]] o, Int sp) -> [[Int]]
I o.empty
R [[2] * sp]
[[Int]] r
L(x) 1 .< sp - o.len + 2
L(tail) @gen_seg(o[1..], sp - x)
r [+]= [2] * x [+] o[0] [+] tail
R r
R gen_seg(... |
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. ... | #Kotlin | Kotlin | // version 1.2.0
fun printBlock(data: String, len: Int) {
val a = data.toCharArray()
val sumChars = a.map { it.toInt() - 48 }.sum()
println("\nblocks ${a.asList()}, cells $len")
if (len - sumChars <= 0) {
println("No solution")
return
}
val prep = a.map { "1".repeat(it.toInt() ... |
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
numb... | #MiniZinc | MiniZinc |
%Non transitive dice. Nigel Galloway, September 14th., 2020
int: die; int: faces; set of int: values;
predicate pN(array[1..faces] of var values: n, array[1..faces] of var values: g) = sum(i in 1..faces,j in 1..faces)(if n[i]<g[j] then 1 elseif n[i]>g[j] then -1 else 0 endif)>0;
predicate pG(array[1..faces] of var va... |
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
numb... | #Nim | Nim |
import algorithm, sequtils, sets, strformat
import itertools
type Die = object
name: string
faces: seq[int]
####################################################################################################
# Die functions.
func `$`(die: Die): string =
## Return the string representation of a Die.
... |
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 subseque... | #ALGOL_68 | ALGOL 68 | PROC test non continuous = VOID: BEGIN
MODE SEQMODE = CHAR;
MODE SEQ = [1:0]SEQMODE;
MODE YIELDSEQ = PROC(SEQ)VOID;
PROC gen ncs =
( SEQ tail, # To generate subsequences of #
SEQ head, # Already generated #
BOOL contiguous,# It is st... |
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 invisibl... | #8086_Assembly | 8086 Assembly | mov ah,02h
mov al,00h ;this is the unpacked encoding of octal "20" aka 10 in hexadecimal, 16 in decimal. Ignore the leading zeroes.
byte 0D5h,08h ;most assemblers don't allow you to encode a base so we have to inline the bytecode. |
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 ass... | #Erlang | Erlang | <12> erlang:list_to_integer("ffff", 17).
78300
|
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 ass... | #F.23 | F# | let value = "100"
let fromBases = [ 2; 8; 10; 16 ]
let values = Seq.initInfinite (fun i -> value)
Seq.zip fromBases (Seq.zip values fromBases |> Seq.map (System.Convert.ToInt32))
|> Seq.iter (
fun (fromBase, valueFromBaseX) ->
printfn "%s in base %i is %i in base 10" value fromBase valueFromBaseX) |
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 langu... | #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
int main()
{
for (int i = 0; i <= 33; i++)
std::cout << std::setw(6) << std::dec << i << " "
<< std::setw(6) << std::hex << i << " "
<< std::setw(6) << std::oct << i << std::endl;
return 0;
} |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming langu... | #Clojure | Clojure | (Integer/toBinaryString 25) ; returns "11001"
(Integer/toOctalString 25) ; returns "31"
(Integer/toHexString 25) ; returns "19"
(dotimes [i 20]
(println (Integer/toHexString i))) |
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, negat... | #Python | Python | TENS = [None, None, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", ... |
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 reversa... | #Raku | Raku | repeat while [<] my @jumbled-list {
@jumbled-list = (1..9).pick(*)
}
my $turn = 0;
repeat until [<] @jumbled-list {
my $d = prompt $turn.=succ.fmt('%2d: ') ~
@jumbled-list ~
" - Flip how many digits? "
or exit;
@jumbled-list[^$d] .= reverse;
}
say " @jumb... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #XPL0 | XPL0 | code ChOut=8, CrLf=9;
int Gen, Now, New, I;
[Now:= $076A_A400;
for Gen:= 1 to 10 do
[for I:= 31 downto 0 do ChOut(0, if Now & 1<<I then ^# else ^_);
CrLf(0);
New:= 0;
for I:= 30 downto 1 do
case Now>>(I-1) & 7 of %011, %101, %110: New:= New ! 1<<I other;
Now:= New;
];
] |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Yabasic | Yabasic | 10 n=10:READ w:DIM x(w+1),x2(w+1):FOR i=1 to w:READ x(i):NEXT
20 FOR k=1 TO n
30 FOR j=1 TO w
40 IF x(j) THEN PRINT "#"; ELSE PRINT "_"; END IF
50 IF x(j-1)+x(j)+x(j+1)=2 THEN x2(j)=1 ELSE x2(j)=0 END IF
60 NEXT:PRINT
70 FOR j=1 TO w:x(j)=x2(j):NEXT
80 NEXT
90 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,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... | #C.23 | C# | using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class NonogramSolver
{
public static void Main2() {
foreach (var (x, y) in new [] {
("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",
... |
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. ... | #Lua | Lua | local examples = {
{5, {2, 1}},
{5, {}},
{10, {8}},
{15, {2, 3, 2, 3}},
{5, {2, 3}},
}
function deep (blocks, iBlock, freedom, str)
if iBlock == #blocks then -- last
for takenFreedom = 0, freedom do
print (str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. string.rep("0", freedom - ta... |
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
numb... | #Perl | Perl | use strict;
use warnings;
sub fourFaceCombs {
my %found = ();
my @res = ();
for (my $i = 1; $i <= 4; $i++) {
for (my $j = 1; $j <= 4; $j++) {
for (my $k = 1; $k <= 4; $k++) {
for (my $l = 1; $l <= 4; $l++) {
my @c = sort ($i, $j, $k, $l);
... |
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 subseque... | #AutoHotkey | AutoHotkey | MsgBox % noncontinuous("a,b,c,d,e", ",")
MsgBox % noncontinuous("1,2,3,4", ",")
noncontinuous(list, delimiter)
{
stringsplit, seq, list, %delimiter%
n := seq0 ; sequence length
Loop % x := (1<<n) - 1 { ; try all 0-1 candidate sequences
If ... |
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 invisibl... | #ACL2 | ACL2 | (defun digit-value (chr)
(cond ((and (char>= chr #\0)
(char<= chr #\9))
(- (char-code chr) (char-code #\0)))
((and (char>= chr #\A)
(char<= chr #\Z))
(+ (- (char-code chr) (char-code #\A)) 10))
((and (char>= chr #\a)
(char<= chr #\z))... |
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 ass... | #Factor | Factor | ( scratchpad ) "ff" hex> . ! base 16
255
( scratchpad ) "777" oct> . ! base 8
511
( scratchpad ) "1111" bin> . ! base 2
15
( scratchpad ) "99" string>number . ! base 10
99
|
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 ass... | #Forth | Forth | : parse# ( str len -- u true | false )
0. 2SWAP DUP >R >NUMBER NIP NIP
R> <> DUP 0= IF NIP THEN ;
: base# ( str len base -- u true | false )
BASE @ >R BASE ! parse# R> 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 langu... | #Common_Lisp | Common Lisp | (loop for n from 0 to 33 do
(format t " ~6B ~3O ~2D ~2X~%" n n n n)) |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming langu... | #D | D | import std.stdio;
void main() {
writeln("Base: 2 8 10 16");
writeln("----------------------------");
foreach (i; 0 .. 34)
writefln(" %6b %6o %6d %6x", i, i, i, i);
} |
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, negat... | #Quackery | Quackery |
[ [ table
$ "zero" $ "one" $ "two"
$ "three" $ "four" $ "five"
$ "six" $ "seven" $ "eight"
$ "nine" $ "ten" $ "eleven"
$ "twelve" $ "thirteen"
$ "fourteen" $ "fifteen"
$ "sixteen" $ "seventeen"
$ "eighteen" $ "nineteen" ] do ] is units ( n --> $ )
[... |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversa... | #Rascal | Rascal | import Prelude;
import vis::Figure;
import vis::Render;
public void NumberReversalGame(){
//generate randomlist
L = [1..9];
score = 0;
randomlist = [];
while (L != []){
temp = takeOneFrom(L);
randomlist += temp[0];
L = temp[1];
}
// user interaction
score = 0;
text1 = "";
figure =
box(vcat([
b... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #zkl | zkl | fcn life1D(line){
right:=line[1,*] + False; // shift left, False fill
left :=T(False).extend(line[0,-1]); // shift right
left.zip(line,right).apply(fcn(hood){ hood.sum(0)==2 });
} |
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 tur... | #11l | 11l | V tokens = 12
F getTokens(curTokens) -> N
print(‘How many tokens would you like to take? ’, end' ‘’)
V take = Int(input())
I (take < 1 | take > 3)
print("Number must be between 1 and 3.\n")
getTokens(curTokens)
R
:tokens = curTokens - take
print(‘You take #. tokens.’.format(take))... |
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... | #C.2B.2B | C++ |
// A class to solve Nonogram (Hadje) Puzzles
// Nigel Galloway - January 23rd., 2017
template<uint _N, uint _G> class Nonogram {
enum class ng_val : char {X='#',B='.',V='?'};
template<uint _NG> struct N {
N() {}
N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}
std::bitset<_N... |
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. ... | #M2000_Interpreter | M2000 Interpreter |
Module NonoBlock {
Form 80,40
Flush
Print "Nonoblock"
Data 5, (2, 1)
Data 5, (,)
Data 10, (8,)
Data 15, (2,3,2,3)
Data 5, (2,3)
Def BLen(a$)=(Len(a$)-1)/2
Function UseLetter(arr) {
Dim Base 0, Res$(Len(arr))
Link Res$() to Res()
... |
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
numb... | #Phix | Phix | with javascript_semantics
requires("0.8.2") -- (added sq_cmp() builtin that returns nested -1/0/+1 compare() results, just like the existing sq_eq() does for equal().)
integer mx = 4, -- max number of a die side (later set to 6)
mn = 1 -- min number of a die side (later set to 0)
function possible_dice(int... |
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 subseque... | #BBC_BASIC | BBC BASIC | DIM list1$(3)
list1$() = "1", "2", "3", "4"
PRINT "For [1, 2, 3, 4] non-continuous subsequences are:"
PROCnon_continuous_subsequences(list1$())
DIM list2$(4)
list2$() = "1", "2", "3", "4", "5"
PRINT "For [1, 2, 3, 4, 5] non-continuous subsequences are:"
PROCnon_continuous... |
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 invisibl... | #Action.21 | Action! | CHAR ARRAY digits="0123456789abcdefghijklmnopqrstuvwxyz"
PROC CheckBase(BYTE b)
IF b<2 OR b>digits(0) THEN
PrintE("Base is out of range!")
Break()
FI
RETURN
PROC Encode(CARD v BYTE b CHAR ARRAY s)
CARD d
BYTE i,len
CHAR tmp
CheckBase(b)
len=0
DO
d=v MOD b
len==+1
s(len)=digits(... |
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 ass... | #Fortran | Fortran | program Example
implicit none
integer :: num
character(32) :: str
str = "0123459"
read(str, "(i10)") num ! Decimal
write(*,*) num ! Prints 123459
str = "abcf123"
read(str, "(z8)") num ! Hexadecimal
write(*,*) num ! Prints 180154659
str = "7651"
read(str, "(o11)"... |
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 ass... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim s(1 To 4) As String = {"&H1a", "26", "&O32", "&B11010"} '' 26 in various bases
For i As Integer = 1 To 4
Print s(i); Tab(9); "="; CInt(s(i))
Next
Sleep |
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 langu... | #Dc | Dc | [ dn [ ]P ]sp
[
2o lpx
8o lpx
10o lpx
16o lpx
17o lpx
AP
1+ d21>b
]sb
1 lbx |
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 langu... | #E | E | for value in 0..33 {
for base in [2, 8, 10, 12, 16, 36] {
def s := value.toString(base)
print(" " * (8 - s.size()), s)
}
println()
} |
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, negat... | #R | R | # Number Names
ones <- c("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen")
tens <- c("ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety")
m... |
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 reversa... | #REBOL | REBOL | rebol []
print "NUMBER REVERSAL GAME"
tries: 0
goal: [1 2 3 4 5 6 7 8 9]
random/seed now
until [
jumble: random goal
jumble != goal ; repeat in the unlikely case that jumble isn't jumbled
]
while [jumble != goal] [
prin jumble
prin " How many to flip? "
flip-index: to-integer input ; no vali... |
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 tur... | #8080_Assembly | 8080 Assembly | bdos: equ 5 ; CP/M syscalls
puts: equ 9
putch: equ 2
getch: equ 1
maxtokens: equ 12 ; you can change this for more tokens
org 100h
lxi d,nim
call outs
mvi b,maxtokens ; 12 tokens
gameloop: lxi d,tokens ; Show tokens
call outs
mov c,b
showtokens: dcr c
jm tokensdone
mvi a,'|'
call outa
jmp ... |
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 tur... | #8086_Assembly | 8086 Assembly | ;; MS-DOS Nim; assembles with nasm.
bits 16
cpu 8086
getch: equ 1
putch: equ 2
puts: equ 9 ; INT 21h calls
maxtokens: equ 12 ; Amount of tokens there are
section .text
org 100h
mov dx,nim ; Print sign-on
call outs
mov ch,maxtokens ; CH = amount of tokens we have
loop: mov dx,tokens ; Tokens: ... |
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... | #Common_Lisp | Common Lisp | (defpackage :ac3
(:use :cl)
(:export :var
:domain
:satisfies-p
:constraint-possible-p
:ac3)
(:documentation "Implements the AC3 algorithm. Extend VAR with the variable
types for your particular problem and implement SATISFIES-P and
CONSTRAINT-POSSIBLE-P for your variabl... |
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. ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[SpacesDistributeOverN, Possibilities]
SpacesDistributeOverN[s_, p_] :=
Flatten[
Permutations /@ (Join[#, ConstantArray[0, p - Length[#]]] & /@
IntegerPartitions[s, p]), 1]
Possibilities[hint_, len_] :=
Module[{p = hint, l = len, b = Length[hint], Spaces, out},
Spaces = # + (Prepend[Append[Constan... |
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. ... | #Nim | Nim | import math, sequtils, strformat, strutils
proc genSequence(ones: seq[string]; numZeroes: Natural): seq[string] =
if ones.len == 0: return @[repeat('0', numZeroes)]
for x in 1..(numZeroes - ones.len + 1):
let skipOne = ones[1..^1]
for tail in genSequence(skipOne, numZeroes - x):
result.add repeat(... |
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
numb... | #Python | Python | from collections import namedtuple
from itertools import permutations, product
from functools import lru_cache
Die = namedtuple('Die', 'name, faces')
@lru_cache(maxsize=None)
def cmpd(die1, die2):
'compares two die returning 1, -1 or 0 for >, < =='
# Numbers of times one die wins against the other for all... |
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 subseque... | #Bracmat | Bracmat | ( ( noncontinuous
= sub
. ( sub
= su a nc
. !arg:(?su.?nc)
& !su
: %
%?a
( %:[%(sub$(!sjt.!nc !a))
| ?
& !nc:~
& out$(!nc !a)
... |
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 subseque... | #C | C | #include <assert.h>
#include <stdio.h>
int main(int c, char **v)
{
unsigned int n = 1 << (c - 1), i = n, j, k;
assert(n);
while (i--) {
if (!(i & (i + (i & -(int)i)))) // consecutive 1s
continue;
for (j = n, k = 1; j >>= 1; k++)
if (i & j) printf("%s ", v[k]);
putchar('\n');
}
return 0;
} |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl... | #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
with Ada.Strings.Fixed;
With Ada.Strings.Unbounded;
procedure Number_Base_Conversion is
Max_Base : constant := 36;
subtype Base_Type is Integer range 2..Max_Base;
Num_Digits : constant String := "0123456789abcdefghijklmnopqrstuvwxyz";
Invalid_Digit : exception;
func... |
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 ass... | #Free_Pascal | Free Pascal |
program readIntegers(input, output);
var
i: aluSInt;
begin
while not EOF(input) do
begin
readLn(i);
writeLn(i:24);
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 ass... | #Go | Go | package main
import (
"fmt"
"math/big"
"strconv"
)
func main() {
// package strconv: the most common string to int conversion,
// base 10 only.
x, _ := strconv.Atoi("13")
fmt.Println(x)
// ParseInt handles arbitrary bases from 2 to 36, and returns
// a result of the requested ... |
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 langu... | #Elixir | Elixir | Enum.each(0..32, fn i -> :io.format "~2w :~6.2B, ~2.8B, ~2.16B~n", [i,i,i,i] 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 langu... | #Erlang | Erlang | 4> [io:fwrite("~s ", [erlang:integer_to_list(63, X)]) || X <- [3,8,16,26]].
2100 77 3F 2B
|
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 langu... | #Euphoria | Euphoria | for i = 1 to 33 do
printf(1,"%6d %6x %6o\n",{i,i,i})
end for |
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, negat... | #Racket | Racket |
#lang racket
(define smalls
(map symbol->string
'(zero one two three four five six seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen seventeen eighteen nineteen)))
(define tens
(map symbol->string
'(zero ten twenty thirty forty fifty sixty seventy eighty ninety)))
(... |
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 reversa... | #REXX | REXX | /*REXX program (a game): reverse a jumbled set of decimal digits 'til they're in order.*/
signal on halt /*allows the CBLF to HALT the program.*/
___= copies('─', 9); pad=left('', 9) /*a fence used for computer's messages.*/
say ___ "This game will show you nine random u... |
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 tur... | #Action.21 | Action! | BYTE FUNC PlayerTurn(BYTE tokens)
BYTE t,max
IF tokens<3 THEN
max=tokens
ELSE
max=3
FI
DO
PrintF("How many tokens would you like to take (1-%B)? ",max)
t=InputB()
UNTIL t>=1 AND t<=max
OD
PrintF("Player takes %B tokens.%E",t)
t=tokens-t
IF t=0 THEN
PrintE("Player wins.")
FI... |
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 tur... | #Ada | Ada | with Ada.Text_IO;
procedure Nim is
subtype Token_Range is Positive range 1 .. 3;
package TIO renames Ada.Text_IO;
package Token_IO is new TIO.Integer_IO(Token_Range);
procedure Get_Tokens(remaining : in Natural; how_many : out Token_Range) is
begin
loop
TIO.Put("How many tokens would... |
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 e... | #AutoHotkey | AutoHotkey | ;-----------------------------------------------------------
Nested_templated_data(template, Payload){
UsedP := [], UnusedP := [], UnusedI := []
result := template.Clone()
x := ArrMap(template, Payload, result, UsedP, UnusedI, [])
for i, v in Payload
if !UsedP[v]
UnusedP.Push(v)
return [x.1, x.2, UnusedP]
}
;... |
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... | #D | D | import std.stdio, std.range, std.file, std.algorithm, std.string;
/// Create all patterns of a row or col that match given runs.
auto genRow(in int w, in int[] s) pure nothrow @safe {
static int[][] genSeg(in int[][] o, in int sp) pure nothrow @safe {
if (o.empty)
return [[2].replicate(sp)];
... |
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. ... | #Pascal | Pascal |
program Nonoblock;
uses SysUtils;
// Working through solutions to the problem:
// Fill an array z[] with non-negative integers
// whose sum is the passed-in integer s.
function GetFirstSolution( var z : array of integer;
s : integer) : boolean;
var
j : integer;
begin
result := (s... |
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
numb... | #R | R | findNonTrans <- function()
{
diceSet <- unique(t(apply(expand.grid(1:4, 1:4, 1:4, 1:4), 1, sort))) #By construction, each row is a unique dice.
winningDice <- function(X, Y) #Recall 'Example 1' in the task.
{
comparisonTable <- data.frame(X = rep(X, each = length(X)), Y = rep(Y, times = length(Y)))
rowWin... |
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 subseque... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main() {
var sequence = new[] { "A", "B", "C", "D" };
foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {
Console.WriteLine(string.Join(" ", subset.Select(i... |
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 invisibl... | #Aime | Aime | o_text(bfxa(0, 0, 16, 1000000));
o_byte('\n');
o_text(bfxa(0, 0, 5, 1000000));
o_byte('\n');
o_text(bfxa(0, 0, 2, 1000000));
o_byte('\n');
o_integer(alpha("f4240", 16));
o_byte('\n');
o_integer(alpha("224000000", 5));
o_byte('\n');
o_integer(alpha("11110100001001000000", 2));
o_byte('\n'); |
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 invisibl... | #ALGOL_68 | ALGOL 68 | INT base = 16, from dec = 26;
BITS to bits;
FORMAT hex repr = $n(base)r2d$;
FILE f; STRING str;
associate(f, str);
putf(f, (hex repr, BIN from dec));
print(("Hex: ",str, new line));
reset(f);
getf(f, (hex repr, to bits));
print(("Int: ",ABS to bits, new line)) |
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 ass... | #Haskell | Haskell | Prelude> read "123459" :: Integer
123459
Prelude> read "0xabcf123" :: Integer
180154659
Prelude> read "0o7651" :: Integer
4009 |
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 ass... | #HicEst | HicEst | READ(Text="123459 ", Format="i10") dec ! 123459
READ(Text=" abcf123 ", Format="Z10") hex ! 180154659
READ(Text=" 7651 ", Format="o10") oct ! 4009
READ(Text=" 101011001", Format="B10.10") bin ! 345 |
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 langu... | #F.23 | F# | let ns = [30..33]
ns |> Seq.iter (fun n -> printfn " %3o %2d %2X" n n n) |
http://rosettacode.org/wiki/Non-decimal_radices/Output | Non-decimal radices/Output | Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal.
Task
Print a small range of integers in some different bases, as supported by standard routines of your programming langu... | #Factor | Factor | 1234567 2 36 [a,b] [ >base print ] with each |
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, negat... | #Raku | Raku | constant @I = <zero one two three four five six seven eight nine
ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen>;
constant @X = <0 X twenty thirty forty fifty sixty seventy eighty ninety>;
constant @C = @I X~ ' hundred';
co... |
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 reversa... | #Ring | Ring |
# Project : Number reversal game
rever = 1:9
leftrever = []
for n = 1 to len(rever)
rnd = random(8) + 1
temp = rever[n]
rever[n] = rever[rnd]
rever[rnd] = temp
next
see rever
see nl
while true
num = 0
leftrever = []
showarray(rever)
see " : Reverse how many = ... |
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 tur... | #ALGOL_68 | ALGOL 68 | BEGIN # play Nim #
# gets a single character answer from standin and returns it #
PROC answer = ( STRING prompt )CHAR:
BEGIN
STRING s;
INT left := 0;
WHILE print( ( prompt, "> " ) );
read( ( s, newline ) );
left := LWB s;... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.