code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use List::Util qw(shuffle);
my $turn = 0;
my @jumble = shuffle 1..9;
while ( join('', @jumble) eq '123456789' ) {
@jumble = shuffle 1..9;
}
until ( join('', @jumble) eq '123456789' ) {
$turn++;
printf "%2d: @jumble - Flip how many digits? ", $turn;
my $d = <>;
@jumble[0..$d-1] = reverse @jumble[0..$d-1];
}
print " @jumble\n";
print "You won in $turn turns.\n"; | 514Number reversal game
| 2perl
| 31uzs |
def evolve(ary)
([0]+ary+[0]).each_cons(3).map{|a,b,c| a+b+c == 2? 1: 0}
end
def printit(ary)
puts ary.join.tr(,)
end
ary = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]
printit ary
until ary == (new = evolve(ary))
printit ary = new
end | 512One-dimensional cellular automata
| 14ruby
| 9xjmz |
void nb(int cells, int total_block_size, int* blocks, int block_count,
char* output, int offset, int* count) {
if (block_count == 0) {
printf(, ++*count, output);
return;
}
int block_size = blocks[0];
int max_pos = cells - (total_block_size + block_count - 1);
total_block_size -= block_size;
cells -= block_size + 1;
++blocks;
--block_count;
for (int i = 0; i <= max_pos; ++i, --cells) {
memset(output + offset, '.', max_pos + block_size);
memset(output + offset + i, '
nb(cells, total_block_size, blocks, block_count, output,
offset + block_size + i + 1, count);
}
}
void nonoblock(int cells, int* blocks, int block_count) {
printf(, cells);
for (int i = 0; i < block_count; ++i)
printf(i == 0 ? : , blocks[i]);
printf();
int total_block_size = 0;
for (int i = 0; i < block_count; ++i)
total_block_size += blocks[i];
if (cells < total_block_size + block_count - 1) {
printf();
return;
}
char output[cells + 1];
memset(output, '.', cells);
output[cells] = '\0';
int count = 0;
nb(cells, total_block_size, blocks, block_count, output, 0, &count);
}
int main() {
int blocks1[] = {2, 1};
nonoblock(5, blocks1, 2);
printf();
nonoblock(5, NULL, 0);
printf();
int blocks2[] = {8};
nonoblock(10, blocks2, 1);
printf();
int blocks3[] = {2, 3, 2, 3};
nonoblock(15, blocks3, 4);
printf();
int blocks4[] = {2, 3};
nonoblock(5, blocks4, 2);
return 0;
} | 516Nonoblock
| 5c
| xvnwu |
use Lingua::EN::Numbers 'num2en';
print num2en(123456789), "\n"; | 515Number names
| 2perl
| s5tq3 |
class ReversalGame {
private $numbers;
public function __construct() {
$this->initialize();
}
public function play() {
$i = 0;
$moveCount = 0;
while (true) {
echo json_encode($this->numbers) . ;
echo ;
$i = intval(rtrim(fgets(STDIN), ));
if ($i == 99) {
break;
}
if ($i < 2 || $i > 9) {
echo ;
} else {
$moveCount++;
$this->reverse($i);
if ($this->isSorted()) {
echo ;
break;
}
}
}
}
private function reverse($position) {
array_splice($this->numbers, 0, $position, array_reverse(array_slice($this->numbers, 0, $position)));
}
private function isSorted() {
for ($i = 0; $i < count($this->numbers) - 1; ++$i) {
if ($this->numbers[$i] > $this->numbers[$i + 1]) {
return false;
}
}
return true;
}
private function initialize() {
$this->numbers = range(1, 9);
while ($this->isSorted()) {
shuffle($this->numbers);
}
}
}
$game = new ReversalGame();
$game->play(); | 514Number reversal game
| 12php
| pm8ba |
fn get_new_state(windowed: &[bool]) -> bool {
match windowed {
[false, true, true] | [true, true, false] => true,
_ => false
}
}
fn next_gen(cell: &mut [bool]) {
let mut v = Vec::with_capacity(cell.len());
v.push(cell[0]);
for i in cell.windows(3) {
v.push(get_new_state(i));
}
v.push(cell[cell.len() - 1]);
cell.copy_from_slice(&v);
}
fn print_cell(cell: &[bool]) {
for v in cell {
print!("{} ", if *v {'#'} else {' '});
}
println!();
}
fn main() {
const MAX_GENERATION: usize = 10;
const CELLS_LENGTH: usize = 30;
let mut cell: [bool; CELLS_LENGTH] = rand::random();
for i in 1..=MAX_GENERATION {
print!("Gen {:2}: ", i);
print_cell(&cell);
next_gen(&mut cell);
}
} | 512One-dimensional cellular automata
| 15rust
| cqh9z |
def cellularAutomata(s: String) = {
def it = Iterator.iterate(s) ( generation =>
("_%s_" format generation).iterator
sliding 3
map (_ count (_ == '#'))
map Map(2 -> "#").withDefaultValue("_")
mkString
)
(it drop 1) zip it takeWhile Function.tupled(_ != _) map (_._2) foreach println
} | 512One-dimensional cellular automata
| 16scala
| v8p2s |
$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,');
$smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');
$decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');
function NumberToEnglish($num, $count = 0){
global $orderOfMag, $smallNumbers, $decades;
$isLast = true;
$str = '';
if ($num < 0){
$str = 'Negative ';
$num = abs($num);
}
(int) $thisPart = substr((string) $num, -3);
if (strlen((string) $num) > 3){
$str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1);
$isLast = false;
}
if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative '))
$and = '';
else
$and = ' and ';
if ($thisPart > 99){
$str .= ($isLast? '' : ' ') . ;
if(($thisPart %= 100) == 0){
$str .= ;
return $str;
}
$and = ' and ';
}
if ($thisPart >= 20){
$str .= ;
$and = ' ';
if(($thisPart %= 10) == 0)
return $str . ($count != 0? : '');
}
if ($thisPart < 20 && $thisPart > 0)
return $str . . ($count != 0? $orderOfMag[$count] : '');
elseif ($thisPart == 0 && strlen($thisPart) == 1)
return $str . ;
} | 515Number names
| 12php
| uokv5 |
package main
import (
"fmt"
"strings"
)
func printBlock(data string, le int) {
a := []byte(data)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 48)
}
fmt.Printf("\nblocks%c, cells%d\n", a, le)
if le-sumBytes <= 0 {
fmt.Println("No solution")
return
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-48))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
fmt.Println(r[1:])
}
}
func genSequence(ones []string, numZeros int) []string {
if len(ones) == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-len(ones)+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func main() {
printBlock("21", 5)
printBlock("", 5)
printBlock("8", 10)
printBlock("2323", 15)
printBlock("23", 5)
} | 516Nonoblock
| 0go
| lsrcw |
package main
import (
"fmt"
"sort"
)
func fourFaceCombs() (res [][4]int) {
found := make([]bool, 256)
for i := 1; i <= 4; i++ {
for j := 1; j <= 4; j++ {
for k := 1; k <= 4; k++ {
for l := 1; l <= 4; l++ {
c := [4]int{i, j, k, l}
sort.Ints(c[:])
key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)
if !found[key] {
found[key] = true
res = append(res, c)
}
}
}
}
}
return
}
func cmp(x, y [4]int) int {
xw := 0
yw := 0
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
if x[i] > y[j] {
xw++
} else if y[j] > x[i] {
yw++
}
}
}
if xw < yw {
return -1
} else if xw > yw {
return 1
}
return 0
}
func findIntransitive3(cs [][4]int) (res [][3][4]int) {
var c = len(cs)
for i := 0; i < c; i++ {
for j := 0; j < c; j++ {
for k := 0; k < c; k++ {
first := cmp(cs[i], cs[j])
if first == -1 {
second := cmp(cs[j], cs[k])
if second == -1 {
third := cmp(cs[i], cs[k])
if third == 1 {
res = append(res, [3][4]int{cs[i], cs[j], cs[k]})
}
}
}
}
}
}
return
}
func findIntransitive4(cs [][4]int) (res [][4][4]int) {
c := len(cs)
for i := 0; i < c; i++ {
for j := 0; j < c; j++ {
for k := 0; k < c; k++ {
for l := 0; l < c; l++ {
first := cmp(cs[i], cs[j])
if first == -1 {
second := cmp(cs[j], cs[k])
if second == -1 {
third := cmp(cs[k], cs[l])
if third == -1 {
fourth := cmp(cs[i], cs[l])
if fourth == 1 {
res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})
}
}
}
}
}
}
}
}
return
}
func main() {
combs := fourFaceCombs()
fmt.Println("Number of eligible 4-faced dice", len(combs))
it3 := findIntransitive3(combs)
fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3))
for _, a := range it3 {
fmt.Println(a)
}
it4 := findIntransitive4(combs)
fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4))
for _, a := range it4 {
fmt.Println(a)
}
} | 517Non-transitive dice
| 0go
| 19sp5 |
int main()
{
int num;
sscanf(, , &num);
printf(, num);
sscanf(, , &num);
printf(, num);
sscanf(, , &num);
printf(, num);
return 0;
} | 518Non-decimal radices/Input
| 5c
| v8r2o |
'''
number reversal game
Given a jumbled list of the numbers 1 to 9
Show the list.
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.
'''
import random
print(__doc__)
data, trials = list('123456789'), 0
while data == sorted(data):
random.shuffle(data)
while data != sorted(data):
trials += 1
flip = int(input('
data[:flip] = reversed(data[:flip])
print('\nYou took%2i attempts to put the digits in order!'% trials) | 514Number reversal game
| 3python
| 6a53w |
import java.util.*;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
public class Nonoblock {
public static void main(String[] args) {
printBlock("21", 5);
printBlock("", 5);
printBlock("8", 10);
printBlock("2323", 15);
printBlock("23", 5);
}
static void printBlock(String data, int len) {
int sumChars = data.chars().map(c -> Character.digit(c, 10)).sum();
String[] a = data.split("");
System.out.printf("%nblocks%s, cells%s%n", Arrays.toString(a), len);
if (len - sumChars <= 0) {
System.out.println("No solution");
return;
}
List<String> prep = stream(a).filter(x -> !"".equals(x))
.map(x -> repeat(Character.digit(x.charAt(0), 10), "1"))
.collect(toList());
for (String r : genSequence(prep, len - sumChars + 1))
System.out.println(r.substring(1));
} | 516Nonoblock
| 9java
| 7tarj |
import Data.List
import Control.Monad
newtype Dice = Dice [Int]
instance Show Dice where
show (Dice s) = "(" ++ unwords (show <$> s) ++ ")"
instance Eq Dice where
d1 == d2 = d1 `compare` d2 == EQ
instance Ord Dice where
Dice d1 `compare` Dice d2 = (add $ compare <$> d1 <*> d2) `compare` 0
where
add = sum . map (\case {LT -> -1; EQ -> 0; GT -> 1})
dices n = Dice <$> (nub $ sort <$> replicateM n [1..n])
nonTrans dice = filter (\x -> last x < head x) . go
where
go 0 = []
go 1 = sequence [dice]
go n = do
(a:as) <- go (n-1)
b <- filter (< a) dice
return (b:a:as) | 517Non-transitive dice
| 8haskell
| tb9f7 |
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) => arr[i] ? [...p, c, arr[i]] : [...p, c];
const zip = (a, b) => a.reduce(zipper(b), []);
const zipArr = arr => a => zip(a, arr);
const hasInner = v => arr => arr.slice(1, -1).indexOf(v) >= 0;
const choose = (even, odd) => n => n % 2 === 0 ? even : odd;
const toBin = f => arr => arr.reduce(
(p, c, i) => [...p, ...mkArr(c, f(i))], []);
const looper = (arr, max, acc = [[...arr]], idx = 0) => {
if (idx !== arr.length) {
const b = looper([...arr], max, acc, idx + 1)[0];
if (b[idx] !== max) {
b[idx] = b[idx] + 1;
acc.push(looper([...b], max, acc, idx)[0]);
}
}
return [arr, acc];
};
const gapPerms = (grpSize, numGaps, minVal = 0) => {
const maxVal = numGaps - grpSize * minVal + minVal;
return maxVal <= 0
? (grpSize === 2 ? [[0]] : [])
: looper(mkArr(grpSize, minVal), maxVal)[1];
}
const test = (cells, ...blocks) => {
const grpSize = blocks.length + 1;
const numGaps = cells - sumArr(blocks); | 516Nonoblock
| 10javascript
| pmsb7 |
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<Integer> found = new HashSet<>();
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
for (int k = 1; k <= 4; k++) {
for (int l = 1; l <= 4; l++) {
List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());
int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1);
if (found.add(key)) {
res.add(c);
}
}
}
}
}
return res;
}
private static int cmp(List<Integer> x, List<Integer> y) {
int xw = 0;
int yw = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (x.get(i) > y.get(j)) {
xw++;
} else if (x.get(i) < y.get(j)) {
yw++;
}
}
}
return Integer.compare(xw, yw);
}
private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) {
int c = cs.size();
List<List<List<Integer>>> res = new ArrayList<>();
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
if (cmp(cs.get(i), cs.get(j)) == -1) {
for (List<Integer> kl : cs) {
if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) {
res.add(List.of(cs.get(i), cs.get(j), kl));
}
}
}
}
}
return res;
}
private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) {
int c = cs.size();
List<List<List<Integer>>> res = new ArrayList<>();
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
if (cmp(cs.get(i), cs.get(j)) == -1) {
for (int k = 0; k < cs.size(); k++) {
if (cmp(cs.get(j), cs.get(k)) == -1) {
for (List<Integer> ll : cs) {
if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) {
res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll));
}
}
}
}
}
}
}
return res;
}
public static void main(String[] args) {
List<List<Integer>> combos = fourFaceCombos();
System.out.printf("Number of eligible 4-faced dice:%d%n", combos.size());
System.out.println();
List<List<List<Integer>>> it3 = findIntransitive3(combos);
System.out.printf("%d ordered lists of 3 non-transitive dice found, namely:%n", it3.size());
for (List<List<Integer>> a : it3) {
System.out.println(a);
}
System.out.println();
List<List<List<Integer>>> it4 = findIntransitive4(combos);
System.out.printf("%d ordered lists of 4 non-transitive dice found, namely:%n", it4.size());
for (List<List<Integer>> a : it4) {
System.out.println(a);
}
}
} | 517Non-transitive dice
| 9java
| 8gt06 |
int main()
{
int i;
for(i=1; i <= 33; i++)
printf(, i, i, i);
return 0;
} | 519Non-decimal radices/Output
| 5c
| uorv4 |
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="")
data <- sample(1:9, 9)
while (all(data == 1:9)){
cat("What were the chances...? \n")
data <- sample(1:9, 9)
}
trials <- 0
while (any(data!= 1:9)){
trials <- trials + 1
cat("Trial", sprintf("%02d", trials), "
answer <- readline(paste("Flip how many? "))
data[1:answer] <- data[answer:1]
}
cat("Well done. You needed", trials, "flips. \n")
} | 514Number reversal game
| 13r
| fkldc |
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()
val key = 64 * (c[0] - 1) + 16 * (c[1] - 1) + 4 * (c[2] - 1) + (c[3] - 1)
if (!found.contains(key)) {
found.add(key)
res.add(c)
}
}
}
}
}
return res
}
fun cmp(x: Array<Int>, y: Array<Int>): Int {
var xw = 0
var yw = 0
for (i in 0 until 4) {
for (j in 0 until 4) {
if (x[i] > y[j]) {
xw++
} else if (y[j] > x[i]) {
yw++
}
}
}
if (xw < yw) {
return -1
}
if (xw > yw) {
return 1
}
return 0
}
fun findIntransitive3(cs: List<Array<Int>>): List<Array<Array<Int>>> {
val c = cs.size
val res = mutableListOf<Array<Array<Int>>>()
for (i in 0 until c) {
for (j in 0 until c) {
if (cmp(cs[i], cs[j]) == -1) {
for (k in 0 until c) {
if (cmp(cs[j], cs[k]) == -1 && cmp(cs[k], cs[i]) == -1) {
res.add(arrayOf(cs[i], cs[j], cs[k]))
}
}
}
}
}
return res
}
fun findIntransitive4(cs: List<Array<Int>>): List<Array<Array<Int>>> {
val c = cs.size
val res = mutableListOf<Array<Array<Int>>>()
for (i in 0 until c) {
for (j in 0 until c) {
if (cmp(cs[i], cs[j]) == -1) {
for (k in 0 until c) {
if (cmp(cs[j], cs[k]) == -1) {
for (l in 0 until c) {
if (cmp(cs[k], cs[l]) == -1 && cmp(cs[l], cs[i]) == -1) {
res.add(arrayOf(cs[i], cs[j], cs[k], cs[l]))
}
}
}
}
}
}
}
return res
}
fun main() {
val combos = fourFaceCombos()
println("Number of eligible 4-faced dice: ${combos.size}")
println()
val it3 = findIntransitive3(combos)
println("${it3.size} ordered lists of 3 non-transitive dice found, namely:")
for (a in it3) {
println(a.joinToString(", ", "[", "]") { it.joinToString(", ", "[", "]") })
}
println()
val it4 = findIntransitive4(combos)
println("${it4.size} ordered lists of 4 non-transitive dice found, namely:")
for (a in it4) {
println(a.joinToString(", ", "[", "]") { it.joinToString(", ", "[", "]") })
}
} | 517Non-transitive dice
| 11kotlin
| w2oek |
null | 516Nonoblock
| 11kotlin
| uohvc |
(Integer/toBinaryString 25)
(Integer/toOctalString 25)
(Integer/toHexString 25)
(dotimes [i 20]
(println (Integer/toHexString i))) | 519Non-decimal radices/Output
| 6clojure
| 7tbr0 |
TENS = [None, None, , , ,
, , , , ]
SMALL = [, , , , , ,
, , , , , ,
, , , ,
, , , ]
HUGE = [None, None] + [h +
for h in (, , , , , ,
, , , )]
def nonzero(c, n, connect=''):
return if n == 0 else connect + c + spell_integer(n)
def last_and(num):
if ',' in num:
pre, last = num.rsplit(',', 1)
if ' and ' not in last:
last = ' and' + last
num = ''.join([pre, ',', last])
return num
def big(e, n):
if e == 0:
return spell_integer(n)
elif e == 1:
return spell_integer(n) +
else:
return spell_integer(n) + + HUGE[e]
def base1000_rev(n):
while n != 0:
n, r = divmod(n, 1000)
yield r
def spell_integer(n):
if n < 0:
return + spell_integer(-n)
elif n < 20:
return SMALL[n]
elif n < 100:
a, b = divmod(n, 10)
return TENS[a] + nonzero(, b)
elif n < 1000:
a, b = divmod(n, 100)
return SMALL[a] + + nonzero(, b, ' and')
else:
num = .join([big(e, x) for e, x in
enumerate(base1000_rev(n)) if x][::-1])
return last_and(num)
if __name__ == '__main__':
for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):
print('%+4i ->%s'% (n, spell_integer(n)))
print('')
n = 201021002001
while n:
print('%-12i ->%s'% (n, spell_integer(n)))
n
print('%-12i ->%s'% (n, spell_integer(n)))
print('') | 515Number names
| 3python
| 04zsq |
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 | 516Nonoblock
| 1lua
| 5iku6 |
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);
my $key = 0;
for my $p (@c) {
$key = 10 * $key + $p;
}
if (not exists $found{$key}) {
$found{$key} = 1;
push @res, \@c;
}
}
}
}
}
return @res;
}
sub compare {
my $xref = shift;
my $yref = shift;
my @x = @$xref;
my $xw = 0;
my @y = @$yref;
my $yw = 0;
for my $i (@x) {
for my $j (@y) {
if ($i < $j) {
$yw++;
}
if ($j < $i) {
$xw++;
}
}
}
if ($xw < $yw) {
return -1;
}
if ($yw < $xw) {
return 1;
}
return 0;
}
sub findIntransitive3 {
my $dice_ref = shift;
my @dice = @$dice_ref;
my $len = scalar @dice;
my @res = ();
for (my $i = 0; $i < $len; $i++) {
for (my $j = 0; $j < $len; $j++) {
my $first = compare($dice[$i], $dice[$j]);
if ($first == 1) {
for (my $k = 0; $k < $len; $k++) {
my $second = compare($dice[$j], $dice[$k]);
if ($second == 1) {
my $third = compare($dice[$k], $dice[$i]);
if ($third == 1) {
my $d1r = $dice[$i];
my $d2r = $dice[$j];
my $d3r = $dice[$k];
my @itd = ($d1r, $d2r, $d3r);
push @res, \@itd;
}
}
}
}
}
}
return @res;
}
sub findIntransitive4 {
my $dice_ref = shift;
my @dice = @$dice_ref;
my $len = scalar @dice;
my @res = ();
for (my $i = 0; $i < $len; $i++) {
for (my $j = 0; $j < $len; $j++) {
for (my $k = 0; $k < $len; $k++) {
for (my $l = 0; $l < $len; $l++) {
my $first = compare($dice[$i], $dice[$j]);
if ($first == 1) {
my $second = compare($dice[$j], $dice[$k]);
if ($second == 1) {
my $third = compare($dice[$k], $dice[$l]);
if ($third == 1) {
my $fourth = compare($dice[$l], $dice[$i]);
if ($fourth == 1) {
my $d1r = $dice[$i];
my $d2r = $dice[$j];
my $d3r = $dice[$k];
my $d4r = $dice[$l];
my @itd = ($d1r, $d2r, $d3r, $d4r);
push @res, \@itd;
}
}
}
}
}
}
}
}
return @res;
}
sub main {
my @dice = fourFaceCombs();
my $len = scalar @dice;
print "Number of eligible 4-faced dice: $len\n\n";
my @it3 = findIntransitive3(\@dice);
my $count3 = scalar @it3;
print "$count3 ordered lists of 3 non-transitive dice found, namely:\n";
for my $itref (@it3) {
print "[ ";
for my $r (@$itref) {
print "[@$r] ";
}
print "]\n";
}
print "\n";
my @it4 = findIntransitive4(\@dice);
my $count = scalar @it4;
print "$count ordered lists of 4 non-transitive dice found, namely:\n";
for my $itref (@it4) {
print "[ ";
for my $r (@$itref) {
print "[@$r] ";
}
print "]\n";
}
}
main(); | 517Non-transitive dice
| 2perl
| lsgc5 |
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")
mags <- c("", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion")
return_hund <- function(input_number){
if (input_number == 0) return("")
num_text <- as.character()
input_hund <- trunc(input_number / 100)
input_ten <- trunc((input_number - input_hund * 100) / 10)
input_one <- input_number%% 10
if (input_number > 99) num_text <- paste0(ones[trunc(input_number / 100) + 1], "-hundred")
if (input_ten < 2){
if (input_ten == 0 & input_one == 0) return(num_text)
if (input_hund > 0) return(paste0(num_text, " ", ones[input_ten * 10 + input_one + 1]))
return(paste0(ones[input_ten * 10 + input_one + 1]))
}
ifelse(input_hund > 0,
num_text <- paste0(num_text, " ", tens[input_ten]),
num_text <- paste0(tens[input_ten])
)
if (input_one!= 0) num_text <- paste0(num_text, "-", ones[input_one + 1])
return(num_text)
}
make_number <- function(number){
if (number == 0) return("zero")
a <- abs(number)
num_text <- as.character()
g <- trunc(log(a, 10)) + 1
for (i in c(seq(g, 1))){
b <- floor(a / 1000 ^ (i - 1))
x <- return_hund(b)
if (x!= "") num_text <- paste0(num_text, return_hund(b), " ", mags[i], " ")
a <- a - b * 1000 ^ (i - 1)
}
return(ifelse(sign(number) > 0, num_text, paste("negative", num_text)))
}
my_num <- data.frame(nums = c(
0, 1, -11, 13, 99, 100, -101, 113, -120, 450, -999, 1000, 1001, 1017, 3000, 3001,
9999, 10000, 10001, 10100, 10101, 19000, 20001, 25467, 99999, 100000, 1056012,
-200000, 200001, -200012, 2012567, -5685436, 5000201, -11627389, 100067652, 456000342)
)
my_num$text <- as.character(lapply(my_num$nums, make_number))
print(my_num, right=F) | 515Number names
| 13r
| w2ne5 |
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 >, < =='
tot = [0, 0, 0]
for d1, d2 in product(die1.faces, die2.faces):
tot[1 + (d1 > d2) - (d2 > d1)] += 1
win2, _, win1 = tot
return (win1 > win2) - (win2 > win1)
def is_non_trans(dice):
check = (all(cmpd(c1, c2) == -1
for c1, c2 in zip(dice, dice[1:]))
and cmpd(dice[0], dice[-1]) == 1)
return dice if check else False
def find_non_trans(alldice, n=3):
return [perm for perm in permutations(alldice, n)
if is_non_trans(perm)]
def possible_dice(sides, mx):
print(f)
dice = [Die(f, faces)
for n, faces in enumerate(product(range(1, mx+1), repeat=sides))]
print(f' Created {len(dice)} dice')
print(' Remove duplicate with same bag of numbers on different faces')
found = set()
filtered = []
for d in dice:
count = tuple(sorted(d.faces))
if count not in found:
found.add(count)
filtered.append(d)
l = len(filtered)
print(f' Return {l} filtered dice')
return filtered
def verbose_cmp(die1, die2):
'compares two die returning their relationship of their names as a string'
win1 = sum(d1 > d2 for d1, d2 in product(die1.faces, die2.faces))
win2 = sum(d2 > d1 for d1, d2 in product(die1.faces, die2.faces))
n1, n2 = die1.name, die2.name
return f'{n1} > {n2}' if win1 > win2 else (f'{n1} < {n2}' if win1 < win2 else f'{n1} = {n2}')
def verbose_dice_cmp(dice):
c = [verbose_cmp(x, y) for x, y in zip(dice, dice[1:])]
c += [verbose_cmp(dice[0], dice[-1])]
return ', '.join(c)
if __name__ == '__main__':
dice = possible_dice(sides=4, mx=4)
for N in (3, 4):
non_trans = find_non_trans(dice, N)
print(f'\n Non_transitive length-{N} combinations found: {len(non_trans)}')
for lst in non_trans:
print()
for i, die in enumerate(lst):
print(f)
if non_trans:
print('\n More verbose comparison of last non_transitive result:')
print(' ', verbose_dice_cmp(non_trans[-1]))
print('\n ====') | 517Non-transitive dice
| 3python
| 20rlz |
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))))
continue;
for (j = n, k = 1; j >>= 1; k++)
if (i & j) printf(, v[k]);
putchar('\n');
}
return 0;
} | 520Non-continuous subsequences
| 5c
| gdj45 |
package main
import (
"fmt"
"math/big"
"strconv"
)
func main() { | 518Non-decimal radices/Input
| 0go
| s5nqa |
findNonTrans <- function()
{
diceSet <- unique(t(apply(expand.grid(1:4, 1:4, 1:4, 1:4), 1, sort)))
winningDice <- function(X, Y)
{
comparisonTable <- data.frame(X = rep(X, each = length(X)), Y = rep(Y, times = length(Y)))
rowWinner <- ifelse(comparisonTable["X"] > comparisonTable["Y"], "X",
ifelse(comparisonTable["X"] == comparisonTable["Y"], "-", "Y"))
netXWins <- sum(rowWinner == "X") - sum(rowWinner == "Y")
if(netXWins > 0) "X" else if(netXWins == 0) "Draw" else "Y"
}
rows <- seq_len(nrow(diceSet))
XvsAllY <- function(X) sapply(rows, function(i) winningDice(X, diceSet[i, ]))
winners <- as.data.frame(lapply(rows, function(i) XvsAllY(diceSet[i, ])),
row.names = paste("Y=Dice", rows), col.names = paste("X=Dice", rows), check.names = FALSE)
solutionCount <- 0
for(S in rows)
{
beatsS <- which(winners[paste("X=Dice", S)] == "Y")
beatsT <- lapply(beatsS, function(X) which(winners[paste("X=Dice", X)] == "Y"))
beatenByS <- which(winners[paste("X=Dice", S)] == "X")
potentialU <- lapply(beatsT, function(X) intersect(X, beatenByS))
nonEmptyIndices <- lengths(potentialU) != 0
if(any(nonEmptyIndices))
{
solutionCount <- solutionCount + 1
diceUIndex <- potentialU[nonEmptyIndices][[1]]
diceTIndex <- beatsS[nonEmptyIndices][[1]]
cat("Solution", solutionCount, "is:\n")
output <- rbind(S = diceSet[S,], T = diceSet[diceTIndex,], U = diceSet[diceUIndex,])
colnames(output) <- paste("Dice", 1:4)
print(output)
}
}
}
findNonTrans() | 517Non-transitive dice
| 13r
| mwuy4 |
Prelude> read "123459" :: Integer
123459
Prelude> read "0xabcf123" :: Integer
180154659
Prelude> read "0o7651" :: Integer
4009 | 518Non-decimal radices/Input
| 8haskell
| 9xumo |
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 | 516Nonoblock
| 2perl
| 8gz0w |
ary = (1..9).to_a
ary.shuffle! while ary == ary.sort
score = 0
until ary == ary.sort
print
num = gets.to_i
ary[0, num] = ary[0, num].reverse
score += 1
end
p ary
puts | 514Number reversal game
| 14ruby
| mwgyj |
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()
} | 521Nonogram solver
| 0go
| qu0xz |
(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])) | 520Non-continuous subsequences
| 6clojure
| k61hs |
Scanner sc = new Scanner(System.in); | 518Non-decimal radices/Input
| 9java
| tbmf9 |
+"0123459"; | 518Non-decimal radices/Input
| 10javascript
| mwvyv |
package main
import (
"fmt"
"math/big"
"strconv"
)
func main() { | 519Non-decimal radices/Output
| 0go
| 04nsk |
{{index .P n}} | 522Nested templated data
| 0go
| rf7gm |
data Template a = Val a | List [Template a]
deriving ( Show
, Functor
, Foldable
, Traversable ) | 522Nested templated data
| 8haskell
| 048s7 |
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();
} | 521Nonogram solver
| 9java
| fkzdv |
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:]
minspace4rest = sum(1+b for b in brest)
for bpos in range(0, cells - minspace4rest - blength + 1):
if not brest:
yield [(bpos, blength)]
else:
offset = bpos + blength +1
nonoargs = (brest, cells - offset)
for subpos in nonoblocks(*nonoargs):
rest = [(offset + bp, bl) for bp, bl in subpos]
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),
([2, 3], 5),
):
print('\nConfiguration:\n %s
print(' Possibilities:')
for i, vector in enumerate(nonoblocks(blocks, cells)):
print(' ', pblock(vector, cells))
print(' A total of%i Possible configurations.'% (i+1)) | 516Nonoblock
| 3python
| or381 |
null | 518Non-decimal radices/Input
| 11kotlin
| ort8z |
import Text.Printf
main :: IO ()
main = mapM_ f [0..33] where
f :: Int -> IO ()
f n = printf "%3o%2d%2X\n" n n n | 519Non-decimal radices/Output
| 8haskell
| cqu94 |
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, ] +
%w( m b tr quadr quint sext sept oct non dec).map{ |p| }
def wordify number
case
when number < 0
when number < 20
SMALL[number]
when number < 100
div, mod = number.divmod(10)
TENS[div] + (mod==0? : )
when number < 1000
div, mod = number.divmod(100)
+ (mod==0? : )
else
chunks = []
div = number
while div!= 0
div, mod = div.divmod(1000)
chunks << mod
end
raise ArgumentError, if chunks.size > BIG.size
chunks.map{ |c| wordify c }.
zip(BIG).
find_all { |c| c[0]!= 'zero' }.
map{ |c| c.join ' '}.
reverse.
join(', ').
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
begin
puts
rescue => e
puts
end
end | 515Number names
| 14ruby
| or68v |
use rand::prelude::*;
use std::io::stdin;
fn is_sorted(seq: &[impl PartialOrd]) -> bool {
if seq.len() < 2 {
return true;
} | 514Number reversal game
| 15rust
| 9xrmm |
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), , 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(, numbers[i], next_highest_int(numbers[i]));
const char big[] = ;
char next[sizeof(big)];
memcpy(next, big, sizeof(big));
next_permutation(next);
printf(, big, next);
return 0;
} | 523Next highest int from digits
| 5c
| jzj70 |
print( tonumber("123") )
print( tonumber("a5b0", 16) )
print( tonumber("011101", 2) )
print( tonumber("za3r", 36) ) | 518Non-decimal radices/Input
| 1lua
| i7zot |
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();
}
} | 515Number names
| 15rust
| i7yod |
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)
} | 514Number reversal game
| 16scala
| 20hlb |
int playerTurn(int numTokens, int take);
int computerTurn(int numTokens);
int main(void)
{
printf();
int Tokens = 12;
while(Tokens > 0)
{
printf();
int uin;
scanf(, &uin);
int nextTokens = playerTurn(Tokens, uin);
if (nextTokens == Tokens)
{
continue;
}
Tokens = nextTokens;
Tokens = computerTurn(Tokens);
}
printf();
return 0;
}
int playerTurn(int numTokens, int take)
{
if (take < 1 || take > 3)
{
printf();
return numTokens;
}
int remainingTokens = numTokens - take;
printf(, take);
printf(, remainingTokens);
return remainingTokens;
}
int computerTurn(int numTokens)
{
int take = numTokens % 4;
int remainingTokens = numTokens - take;
printf(, take);
printf(, remainingTokens);
return remainingTokens;
} | 524Nim game
| 5c
| a9p11 |
null | 521Nonogram solver
| 11kotlin
| 8gi0q |
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)); | 519Non-decimal radices/Output
| 9java
| zpmtq |
import scala.annotation.tailrec
import scala.collection.parallel.ParSeq
trait LongHand {
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 " " | 515Number names
| 16scala
| fkcd4 |
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] = {,,,,};
sprintf(holder.str,,++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(,list[i].str);
return 0;
} | 525Nested function
| 5c
| ir0o2 |
sub fulfill {
my @payloads;
push @payloads, 'Payload
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] ); | 522Nested templated data
| 2perl
| zp3tb |
var bases = [2, 8, 10, 16, 24];
for (var n = 0; n <= 33; n++) {
var row = [];
for (var i = 0; i < bases.length; i++)
row.push( n.toString(bases[i]) );
print(row.join(', '));
} | 519Non-decimal radices/Output
| 10javascript
| 9xvml |
def nonoblocks(cell, blocks)
raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1
nblock(cell, blocks, '', [])
end
def nblock(cell, blocks, position, result)
if cell <= 0
result << position[0..cell-1]
elsif blocks.empty? or blocks[0].zero?
result << position + '.' * cell
else
rest = cell - blocks.inject(:+) - blocks.size + 2
bl, *brest = blocks
rest.times.inject(result) do |res, i|
nblock(cell-i-bl-1, brest, position + '.'*i + '
end
end
end
conf = [[ 5, [2, 1]],
[ 5, []],
[10, [8]],
[15, [2, 3, 2, 3]],
[ 5, [2, 3]], ]
conf.each do |cell, blocks|
begin
puts
result = nonoblocks(cell, blocks)
puts result, result.size,
rescue => e
p e
end
end | 516Nonoblock
| 14ruby
| njyit |
null | 519Non-decimal radices/Output
| 11kotlin
| i7to4 |
package main
import (
"fmt"
"sort"
)
func permute(s string) []string {
var res []string
if len(s) == 0 {
return res
}
b := []byte(s)
var rc func(int) | 523Next highest int from digits
| 0go
| fkfd0 |
(defn make-list [separator]
(let [x (atom 0)]
(letfn [(make-item [item] (swap! x inc) (println (format "%s%s%s" @x separator item)))]
(make-item "first")
(make-item "second")
(make-item "third"))))
(make-list ". ") | 525Nested function
| 6clojure
| zbdtj |
int main(){
int i,times,hour,min,sec,min1,min2;
time_t t;
struct tm* currentTime;
while(1){
time(&t);
currentTime = localtime(&t);
hour = currentTime->tm_hour;
min = currentTime->tm_min;
sec = currentTime->tm_sec;
hour = 12;
min = 0;
sec = 0;
if((min==0 || min==30) && sec==0)
times = ((hour*60 + min)%240)%8;
if(times==0){
times = 8;
}
if(min==0){
min1 = 0;
min2 = 0;
}
else{
min1 = 3;
min2 = 0;
}
if((min==0 || min==30) && sec==0){
printf(,hour,min1,min2,(hour>11)?:,times);
for(i=1;i<=times;i++){
printf();
(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);
}
}
}
return 0;
} | 526Nautical bell
| 5c
| v092o |
from pprint import pprint as pp
class Template():
def __init__(self, structure):
self.structure = structure
self.used_payloads, self.missed_payloads = [], []
def inject_payload(self, id2data):
def _inject_payload(substruct, i2d, used, missed):
used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)
missed.extend(f'??
for x in substruct if type(x) is not tuple and x not in i2d)
return tuple(_inject_payload(x, i2d, used, missed)
if type(x) is tuple
else i2d.get(x, f'??
for x in substruct)
ans = _inject_payload(self.structure, id2data,
self.used_payloads, self.missed_payloads)
self.unused_payloads = sorted(set(id2data.values())
- set(self.used_payloads))
self.missed_payloads = sorted(set(self.missed_payloads))
return ans
if __name__ == '__main__':
index2data = {p: f'Payload
print(, end='')
print('\n '.join(list(index2data.values())))
for structure in [
(((1, 2),
(3, 4, 1),
5),),
(((1, 2),
(10, 4, 1),
5),)]:
print()
pp(structure, width=13)
print()
t = Template(structure)
out = t.inject_payload(index2data)
pp(out)
print(, end='')
unused = t.unused_payloads
print('\n '.join(unused) if unused else '-')
print(, end='')
missed = t.missed_payloads
print('\n '.join(missed) if missed else '-') | 522Nested templated data
| 3python
| 316zc |
struct Nonoblock {
width: usize,
config: Vec<usize>,
spaces: Vec<usize>,
}
impl Nonoblock {
pub fn new(width: usize, config: Vec<usize>) -> Nonoblock {
Nonoblock {
width: width,
config: config,
spaces: Vec::new(),
}
}
pub fn solve(&mut self) -> Vec<Vec<i32>> {
let mut output: Vec<Vec<i32>> = Vec::new();
self.spaces = (0..self.config.len()).fold(Vec::new(), |mut s, i| {
s.push(match i {
0 => 0,
_ => 1,
});
s
});
if self.spaces.iter().sum::<usize>() + self.config.iter().sum::<usize>() <= self.width {
'finished: loop {
match self.spaces.iter().enumerate().fold((0, vec![0; self.width]), |mut a, (i, s)| {
(0..self.config[i]).for_each(|j| a.1[a.0 + j + *s] = 1 + i as i32);
return (a.0 + self.config[i] + *s, a.1);
}) {
(_, out) => output.push(out),
}
let mut i: usize = 1;
'calc: loop {
let len = self.spaces.len();
if i > len {
break 'finished;
} else {
self.spaces[len - i] += 1
}
if self.spaces.iter().sum::<usize>() + self.config.iter().sum::<usize>() > self.width {
self.spaces[len - i] = 1;
i += 1;
} else {
break 'calc;
}
}
}
}
output
}
}
fn main() {
let mut blocks = [
Nonoblock::new(5, vec![2, 1]),
Nonoblock::new(5, vec![]),
Nonoblock::new(10, vec![8]),
Nonoblock::new(15, vec![2, 3, 2, 3]),
Nonoblock::new(5, vec![2, 3]),
];
for block in blocks.iter_mut() {
println!("{} cells and {:?} blocks", block.width, block.config);
println!("{}",(0..block.width).fold(String::from("="), |a, _| a + "=="));
let solutions = block.solve();
if solutions.len() > 0 {
for solution in solutions.iter() {
println!("{}", solution.iter().fold(String::from("|"), |s, f| s + &match f {
i if *i > 0 => (('A' as u8 + ((*i - 1) as u8)% 26) as char).to_string(),
_ => String::from("_"),
}+ "|"));
}
} else {
println!("No solutions. ");
}
println!();
}
} | 516Nonoblock
| 15rust
| dhmny |
for i = 1, 33 do
print( string.format( "%o \t%d \t%x", i, i, i ) )
end | 519Non-decimal radices/Output
| 1lua
| njzi8 |
const char DIGITS[] = ;
const int DIGITS_LEN = 64;
void encodeNegativeBase(long n, long base, char *out) {
char *ptr = out;
if (base > -1 || base < -62) {
out = ;
return;
}
if (n == 0) {
out = ;
return;
}
while (n != 0) {
long rem = n % base;
n = n / base;
if (rem < 0) {
n++;
rem = rem - base;
}
*ptr = DIGITS[rem];
ptr++;
}
*ptr = 0;
ptr--;
while (out < ptr) {
char t = *out;
*out = *ptr;
*ptr = t;
out++;
ptr--;
}
return;
}
long decodeNegativeBase(const char* ns, long base) {
long value, bb;
int i;
const char *ptr;
if (base < -62 || base > -1) {
return 0;
}
if (ns[0] == 0 || (ns[0] == '0' && ns[1] == 0)) {
return 0;
}
ptr = ns;
while (*ptr != 0) {
ptr++;
}
value = 0;
bb = 1;
ptr--;
while (ptr >= ns) {
for (i = 0; i < DIGITS_LEN; i++) {
if (*ptr == DIGITS[i]) {
value = value + i * bb;
bb = bb * base;
break;
}
}
ptr--;
}
return value;
}
void driver(long n, long b) {
char buf[64];
long value;
encodeNegativeBase(n, b, buf);
printf(, n, b, buf);
value = decodeNegativeBase(buf, b);
printf(, buf, b, value);
printf();
}
int main() {
driver(10, -2);
driver(146, -3);
driver(15, -10);
driver(12, -62);
return 0;
} | 527Negative base numbers
| 5c
| 9wzm1 |
import Data.List (nub, permutations, sort)
digitShuffleSuccessors :: Integer -> [Integer]
digitShuffleSuccessors n =
(fmap . (+) <*> (nub . sort . concatMap go . permutations . show)) n
where
go ds
| 0 >= delta = []
| otherwise = [delta]
where
delta = (read ds :: Integer) - n
main :: IO ()
main =
putStrLn $
fTable
"Taking up to 5 digit-shuffle successors of a positive integer:\n"
show
(\xs ->
let harvest = take 5 xs
in rjust
12
' '
(show (length harvest) <> " of " <> show (length xs) <> ": ") <>
show harvest)
digitShuffleSuccessors
[0, 9, 12, 21, 12453, 738440, 45072010, 95322020]
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
fTable s xShow fxShow f xs =
unlines $
s: fmap (((<>) . rjust w ' ' . xShow) <*> ((" -> " <>) . fxShow . f)) xs
where
w = maximum (length . xShow <$> xs)
rjust :: Int -> Char -> String -> String
rjust n c = drop . length <*> (replicate n c <>) | 523Next highest int from digits
| 8haskell
| 4n45s |
fill_template <- function(x, template, prefix = "Payload
for (i in seq_along(template)) {
temp_slice <- template[[i]]
if (is.list(temp_slice)) {
template[[i]] <- fill_template(x, temp_slice, prefix)
} else {
temp_slice <- paste0(prefix, temp_slice)
template[[i]] <- x[match(temp_slice, x)]
}
}
return(template)
}
library("jsonlite")
template <- list(list(c(1, 2), c(3, 4), 5))
payload <- paste0("Payload
result <- fill_template(payload, template)
cat(sprintf(
"Template\t%s\nPayload\t%s\nResult\t%s",
toJSON(template, auto_unbox = TRUE),
toJSON(payload, auto_unbox = TRUE),
toJSON(result, auto_unbox = TRUE)
)) | 522Nested templated data
| 13r
| dhfnt |
use strict;
use warnings;
my $file = 'nonogram_problems.txt';
open my $fd, '<', $file or die "$! opening $file";
while(my $row = <$fd> )
{
$row =~ /\S/ or next;
my $column = <$fd>;
my @rpats = makepatterns($row);
my @cpats = makepatterns($column);
my @rows = ( '.' x @cpats ) x @rpats;
for( my $prev = ''; $prev ne "@rows"; )
{
$prev = "@rows";
try(\@rows, \@rpats);
my @cols = map { join '', map { s/.//; $& } @rows } 0..$
try(\@cols, \@cpats);
@rows = map { join '', map { s/.//; $& } @cols } 0..$
}
print "\n", "@rows" =~ /\./ ? "Failed\n" : map { tr/01/.
}
sub try
{
my ($lines, $patterns) = @_;
for my $i ( 0 .. $
{
while( $lines->[$i] =~ /\./g )
{
for my $try ( 0, 1 )
{
$lines->[$i] =~ s/.\G/$try/r =~ $patterns->[$i] or
$lines->[$i] =~ s// 1 - $try /e;
}
}
}
}
sub makepatterns {
map { qr/^$_$/
} map { '[0.]*'
. join('[0.]+',
map { "[1.]{$_}"
} map { -64+ord
} split //
)
. '[0.]*'
} split ' ', shift;
} | 521Nonogram solver
| 2perl
| 4nr5d |
import Foundation
func nonoblock(cells: Int, blocks: [Int]) {
print("\(cells) cells and blocks \(blocks):")
let totalBlockSize = blocks.reduce(0, +)
if cells < totalBlockSize + blocks.count - 1 {
print("no solution")
return
}
func solve(cells: Int, index: Int, totalBlockSize: Int, offset: Int) {
if index == blocks.count {
count += 1
print("\(String(format: "%2d", count)) \(String(output))")
return
}
let blockSize = blocks[index]
let maxPos = cells - (totalBlockSize + blocks.count - index - 1)
let t = totalBlockSize - blockSize
var c = cells - (blockSize + 1)
for pos in 0...maxPos {
fill(value: ".", offset: offset, count: maxPos + blockSize)
fill(value: "#", offset: offset + pos, count: blockSize)
solve(cells: c, index: index + 1, totalBlockSize: t,
offset: offset + blockSize + pos + 1)
c -= 1
}
}
func fill(value: Character, offset: Int, count: Int) {
output.replaceSubrange(offset..<offset+count,
with: repeatElement(value, count: count))
}
var output: [Character] = Array(repeating: ".", count: cells)
var count = 0
solve(cells: cells, index: 0, totalBlockSize: totalBlockSize, offset: 0)
}
nonoblock(cells: 5, blocks: [2, 1])
print()
nonoblock(cells: 5, blocks: [])
print()
nonoblock(cells: 10, blocks: [8])
print()
nonoblock(cells: 15, blocks: [2, 3, 2, 3])
print()
nonoblock(cells: 5, blocks: [2, 3]) | 516Nonoblock
| 17swift
| i76o0 |
package main
import "fmt"
const ( | 520Non-continuous subsequences
| 0go
| i7fog |
char *to_base(int64_t num, int base)
{
char *tbl = ;
char buf[66] = {'\0'};
char *out;
uint64_t n;
int i, len = 0, neg = 0;
if (base > 36) {
fprintf(stderr, , base);
return 0;
}
n = ((neg = num < 0)) ? (~num) + 1 : num;
do { buf[len++] = tbl[n % base]; } while(n /= base);
out = malloc(len + neg + 1);
for (i = neg; len > 0; i++) out[i] = buf[--len];
if (neg) out[0] = '-';
return out;
}
long from_base(const char *num_str, int base)
{
char *endptr;
int result = strtol(num_str, &endptr, base);
return result;
}
int main()
{
int64_t x;
x = ~(1LL << 63) + 1;
printf(, x, to_base(x, 2));
x = 383;
printf(, x, to_base(x, 16));
return 0;
} | 528Non-decimal radices/Convert
| 5c
| mefys |
my $dec = "0123459";
my $hex_noprefix = "abcf123";
my $hex_withprefix = "0xabcf123";
my $oct_noprefix = "7651";
my $oct_withprefix = "07651";
my $bin_withprefix = "0b101011001";
print 0 + $dec, "\n";
print hex($hex_noprefix), "\n";
print hex($hex_withprefix), "\n";
print oct($hex_withprefix), "\n";
print oct($oct_noprefix), "\n";
print oct($oct_withprefix), "\n";
print oct($bin_withprefix), "\n"; | 518Non-decimal radices/Input
| 2perl
| gdk4e |
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NextHighestIntFromDigits {
public static void main(String[] args) {
for ( String s : new String[] {"0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600", "3345333"} ) {
System.out.printf("%s ->%s%n", format(s), format(next(s)));
}
testAll("12345");
testAll("11122");
}
private static NumberFormat FORMAT = NumberFormat.getNumberInstance();
private static String format(String s) {
return FORMAT.format(new BigInteger(s));
}
private static void testAll(String s) {
System.out.printf("Test all permutations of: %s%n", s);
String sOrig = s;
String sPrev = s;
int count = 1; | 523Next highest int from digits
| 9java
| cqc9h |
action p x = if p x then succ x else x
fenceM p q s [] = guard (q s) >> return []
fenceM p q s (x:xs) = do
(f,g) <- p
ys <- fenceM p q (g s) xs
return $ f x ys
ncsubseq = fenceM [((:), action even), (flip const, action odd)] (>= 3) 0 | 520Non-continuous subsequences
| 8haskell
| v842k |
<?php
echo +, ;
echo intval(), ;
echo hexdec(), ;
echo octdec(), ;
echo bindec(), ;
?> | 518Non-decimal radices/Input
| 12php
| nj3ig |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func showTokens(tokens int) {
fmt.Println("Tokens remaining", tokens, "\n")
}
func main() {
tokens := 12
scanner := bufio.NewScanner(os.Stdin)
for {
showTokens(tokens)
fmt.Print(" How many tokens 1, 2 or 3? ")
scanner.Scan()
if scerr := scanner.Err(); scerr != nil {
fmt.Println("Error reading standard input:", scerr)
return
}
t, err := strconv.Atoi(scanner.Text())
if err != nil || t < 1 || t > 3 {
fmt.Println("\nMust be a number between 1 and 3, try again.\n")
} else {
ct := 4 - t
s := "s"
if ct == 1 {
s = ""
}
fmt.Print(" Computer takes ", ct, " token", s, "\n\n")
tokens -= 4
}
if tokens == 0 {
showTokens(0)
fmt.Println(" Computer wins!")
return
}
}
} | 524Nim game
| 0go
| me6yi |
const compose = (...fn) => (...x) => fn.reduce((a, b) => c => a(b(c)))(...x);
const toString = x => x + '';
const reverse = x => Array.from(x).reduce((p, c) => [c, ...p], []);
const minBiggerThanN = (arr, n) => arr.filter(e => e > n).sort()[0];
const remEl = (arr, e) => {
const r = arr.indexOf(e);
return arr.filter((e,i) => i !== r);
}
const nextHighest = itr => {
const seen = [];
let result = 0;
for (const [i,v] of itr.entries()) {
const n = +v;
if (Math.max(n, ...seen) !== n) {
const right = itr.slice(i + 1);
const swap = minBiggerThanN(seen, n);
const rem = remEl(seen, swap);
const rest = [n, ...rem].sort();
result = [...reverse(right), swap, ...rest].join('');
break;
} else {
seen.push(n);
}
}
return result;
};
const check = compose(nextHighest, reverse, toString);
const test = v => {
console.log(v, '=>', check(v));
}
test(0);
test(9);
test(12);
test(21);
test(12453);
test(738440);
test(45072010);
test(95322020);
test('9589776899767587796600'); | 523Next highest int from digits
| 10javascript
| 5i5ur |
package main
import (
"fmt"
"strings"
"time"
)
func main() {
watches := []string{
"First", "Middle", "Morning", "Forenoon",
"Afternoon", "Dog", "First",
}
for {
t := time.Now()
h := t.Hour()
m := t.Minute()
s := t.Second()
if (m == 0 || m == 30) && s == 0 {
bell := 0
if m == 30 {
bell = 1
}
bells := (h*2 + bell) % 8
watch := h/4 + 1
if bells == 0 {
bells = 8
watch--
}
sound := strings.Repeat("\a", bells)
pl := "s"
if bells == 1 {
pl = " "
}
w := watches[watch] + " watch"
if watch == 5 {
if bells < 5 {
w = "First " + w
} else {
w = "Last " + w
}
}
fmt.Printf("%s%02d:%02d =%d bell%s:%s\n", sound, h, m, bells, pl, w)
}
time.Sleep(1 * time.Second)
}
} | 526Nautical bell
| 0go
| sueqa |
public class NonContinuousSubsequences {
public static void main(String args[]) {
seqR("1234", "", 0, 0);
}
private static void seqR(String s, String c, int i, int added) {
if (i == s.length()) {
if (c.trim().length() > added)
System.out.println(c);
} else {
seqR(s, c + s.charAt(i), i + 1, added + 1);
seqR(s, c + ' ', i + 1, added);
}
}
} | 520Non-continuous subsequences
| 9java
| yec6g |
SELECT val, to_char(to_date(val,'j'),'jsp') name
FROM
(
SELECT
round( dbms_random.VALUE(1, 5373484)) val
FROM dual
CONNECT BY level <= 5
);
SELECT to_char(to_date(5373485,'j'),'jsp') FROM dual; | 515Number names
| 19sql
| 31vz1 |
import Data.Char (isDigit, digitToInt)
import System.IO
prompt :: String
prompt = "How many do you take? 1, 2 or 3? "
getPlayerSelection :: IO Int
getPlayerSelection = do
hSetBuffering stdin NoBuffering
c <- getChar
putChar '\n'
if isDigit c && digitToInt c <= 3 then
pure (digitToInt c)
else do
putStrLn "Invalid input"
putStr prompt
getPlayerSelection
play :: Int -> IO ()
play n = do
putStrLn $ show n ++ token n ++ " remain."
if n == 0 then putStrLn "Computer Wins!"
else do
putStr prompt
playerSelection <- getPlayerSelection
let computerSelection
| playerSelection > 4 = playerSelection - 4
| otherwise = 4 - playerSelection
putStrLn $ "Computer takes " ++ show computerSelection ++ token computerSelection ++ ".\n"
play (n - computerSelection - playerSelection)
where token 1 = " token"
token _ = " tokens"
main :: IO ()
main = play 12 | 524Nim game
| 8haskell
| k3jh0 |
extern void*stdin;main(){ char*p = ,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); } | 529Narcissist
| 5c
| 4i95t |
import Control.Concurrent
import Control.Monad
import Data.Time
import Text.Printf
type Microsecond = Int
type Scheduler = TimeOfDay -> Microsecond
getTime :: TimeZone -> IO TimeOfDay
getTime tz = do
t <- getCurrentTime
return $ localTimeOfDay $ utcToLocalTime tz t
getGMTTime = getTime utc
getLocalTime = getCurrentTimeZone >>= getTime
nextInterval x y
| x > y = x - y
| mod y x > 0 = x - mod y x
| otherwise = 0
onInterval :: Int -> Scheduler
onInterval interval time = toNext dMS
where
toNext = nextInterval (1000000 * interval)
tDelta = timeOfDayToTime time
dMS = truncate $ 1000000 * tDelta
doWithScheduler :: Scheduler -> (Int -> IO ()) -> IO ThreadId
doWithScheduler sched task = forkIO $ forM_ [0..] exec
where
exec n = do
t <- getLocalTime
threadDelay $ sched t
task n
watchNames = words "Middle Morning Forenoon Afternoon Dog First"
countWords = words "One Two Three Four Five Six Seven Eight"
postDelay n fn = fn >> threadDelay n
termBell = putStr "\a"
termBells n = replicateM_ n $ postDelay 100000 termBell
termBellSeq seq = forM_ seq $ postDelay 500000 . termBells
toNoteGlyph 1 = ""
toNoteGlyph 2 = ""
toNoteGlyph _ = ""
ringBells :: Int -> IO ()
ringBells n = do
t <- getLocalTime
let numBells = 1 + (mod n 8)
watch = watchNames!!(mod (div n 8) 8)
count = countWords!!(numBells - 1)
(twos,ones) = quotRem numBells 2
pattern = (replicate twos 2) ++ (replicate ones 1)
notes = unwords $ map toNoteGlyph pattern
plural = if numBells > 1 then "s" else ""
strFMT = show t ++ ":%s watch,%5s bell%s: " ++ notes ++ "\n"
printf strFMT watch count plural
termBellSeq pattern
bellRinger :: IO ThreadId
bellRinger = doWithScheduler (onInterval (30*60)) ringBells | 526Nautical bell
| 8haskell
| 9w3mo |
function non_continuous_subsequences(ary) {
var non_continuous = new Array();
for (var i = 0; i < ary.length; i++) {
if (! is_array_continuous(ary[i])) {
non_continuous.push(ary[i]);
}
}
return non_continuous;
}
function is_array_continuous(ary) {
if (ary.length < 2)
return true;
for (var j = 1; j < ary.length; j++) {
if (ary[j] - ary[j-1] != 1) {
return false;
}
}
return true;
}
load('json2.js');
print(JSON.stringify( non_continuous_subsequences( powerset([1,2,3,4])))); | 520Non-continuous subsequences
| 10javascript
| 205lr |
foreach my $n (0..33) {
printf "%6b%3o%2d%2X\n", $n, $n, $n, $n;
} | 519Non-decimal radices/Output
| 2perl
| rfkgd |
extension Int {
private static let bigNames = [
1_000: "thousand",
1_000_000: "million",
1_000_000_000: "billion",
1_000_000_000_000: "trillion",
1_000_000_000_000_000: "quadrillion",
1_000_000_000_000_000_000: "quintillion"
]
private static let names = [
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "fourteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen",
20: "twenty",
30: "thirty",
40: "forty",
50: "fifty",
60: "sixty",
70: "seventy",
80: "eighty",
90: "ninety"
]
public var numberName: String {
guard self!= 0 else {
return "zero"
}
let neg = self < 0
let maxNeg = self == Int.min
var nn: Int
if maxNeg {
nn = -(self + 1)
} else if neg {
nn = -self
} else {
nn = self
}
var digits3 = [Int](repeating: 0, count: 7)
for i in 0..<7 {
digits3[i] = (nn% 1000)
nn /= 1000
}
func threeDigitsToText(n: Int) -> String {
guard n!= 0 else {
return ""
}
var ret = ""
let hundreds = n / 100
let remainder = n% 100
if hundreds > 0 {
ret += "\(Int.names[hundreds]!) hundred"
if remainder > 0 {
ret += " "
}
}
if remainder > 0 {
let tens = remainder / 10
let units = remainder% 10
if tens > 1 {
ret += Int.names[tens * 10]!
if units > 0 {
ret += "-\(Int.names[units]!)"
}
} else {
ret += Int.names[remainder]!
}
}
return ret
}
let strings = (0..<7).map({ threeDigitsToText(n: digits3[$0]) })
var name = strings[0]
var big = 1000
for i in 1...6 {
if digits3[i] > 0 {
var name2 = "\(strings[i]) \(Int.bigNames[big]!)"
if name.count > 0 {
name2 += ", "
}
name = name2 + name
}
big &*= 1000
}
if maxNeg {
name = String(name.dropLast(5) + "eight")
}
return neg? "minus \(name)": name
}
}
let nums = [
0, 1, 7, 10, 18, 22, 67, 99, 100, 105, 999, -1056, 1000005000,
2074000000, 1234000000745003, Int.min
]
for number in nums {
print("\(number) => \(number.numberName)")
} | 515Number names
| 17swift
| 8g30v |
import java.math.BigInteger
import java.text.NumberFormat
fun main() {
for (s in arrayOf(
"0",
"9",
"12",
"21",
"12453",
"738440",
"45072010",
"95322020",
"9589776899767587796600",
"3345333"
)) {
println("${format(s)} -> ${format(next(s))}")
}
testAll("12345")
testAll("11122")
}
private val FORMAT = NumberFormat.getNumberInstance()
private fun format(s: String): String {
return FORMAT.format(BigInteger(s))
}
private fun testAll(str: String) {
var s = str
println("Test all permutations of: $s")
val sOrig = s
var sPrev = s
var count = 1 | 523Next highest int from digits
| 11kotlin
| 313z5 |
package main
import "fmt"
func makeList(separator string) string {
counter := 1
makeItem := func(item string) string {
result := fmt.Sprintf("%d%s%s\n", counter, separator, item)
counter += 1
return result
}
return makeItem("first") + makeItem("second") + makeItem("third")
}
func main() {
fmt.Print(makeList(". "))
} | 525Nested function
| 0go
| gnu4n |
import Control.Monad.ST
import Data.STRef
makeList :: String -> String
makeList separator = concat $ runST $ do
counter <- newSTRef 1
let makeItem item = do
x <- readSTRef counter
let result = show x ++ separator ++ item ++ "\n"
modifySTRef counter (+ 1)
return result
mapM makeItem ["first", "second", "third"]
main :: IO ()
main = putStr $ makeList ". " | 525Nested function
| 8haskell
| suwqk |
from itertools import izip
def gen_row(w, s):
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]
def deduce(hr, vr):
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
for x in m:
print .join([i] for i in x)
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print
else:
print
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print
elif n == 1:
print
else:
print n,
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print , s[0]
print , s[1]
deduce(s[0], s[1])
def main():
fn =
for p in (x for x in open(fn).read().split() if x):
solve(p)
print
solve()
print
solve()
main() | 521Nonogram solver
| 3python
| gd74h |
>>> text = '100'
>>> for base in range(2,21):
print (
% (text, base, int(text, base)))
String '100' in base 2 is 4 in base 10
String '100' in base 3 is 9 in base 10
String '100' in base 4 is 16 in base 10
String '100' in base 5 is 25 in base 10
String '100' in base 6 is 36 in base 10
String '100' in base 7 is 49 in base 10
String '100' in base 8 is 64 in base 10
String '100' in base 9 is 81 in base 10
String '100' in base 10 is 100 in base 10
String '100' in base 11 is 121 in base 10
String '100' in base 12 is 144 in base 10
String '100' in base 13 is 169 in base 10
String '100' in base 14 is 196 in base 10
String '100' in base 15 is 225 in base 10
String '100' in base 16 is 256 in base 10
String '100' in base 17 is 289 in base 10
String '100' in base 18 is 324 in base 10
String '100' in base 19 is 361 in base 10
String '100' in base 20 is 400 in base 10 | 518Non-decimal radices/Input
| 3python
| rfbgq |
<?php
foreach (range(0, 33) as $n) {
echo decbin($n), , decoct($n), , $n, , dechex($n), ;
}
?> | 519Non-decimal radices/Output
| 12php
| dh3n8 |
package main
import (
"fmt"
"log"
"strings"
)
const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
func reverse(bs []byte) []byte {
for i, j := 0, len(bs)-1; i < len(bs)/2; i, j = i+1, j-1 {
bs[i], bs[j] = bs[j], bs[i]
}
return bs
}
func encodeNegBase(n, b int64) (string, error) {
if b < -62 || b > -1 {
return "", fmt.Errorf("base must be between -62 and -1 inclusive")
}
if n == 0 {
return "0", nil
}
var out []byte
for n != 0 {
rem := n % b
n /= b
if rem < 0 {
n++
rem -= b
}
out = append(out, digits[int(rem)])
}
reverse(out)
return string(out), nil
}
func decodeNegBase(ns string, b int64) (int64, error) {
if b < -62 || b > -1 {
return 0, fmt.Errorf("base must be between -62 and -1 inclusive")
}
if ns == "0" {
return 0, nil
}
total := int64(0)
bb := int64(1)
bs := []byte(ns)
reverse(bs)
for _, c := range bs {
total += int64(strings.IndexByte(digits, c)) * bb
bb *= b
}
return total, nil
}
func main() {
numbers := []int64{10, 146, 15, -942, 1488588316238}
bases := []int64{-2, -3, -10, -62, -62}
for i := 0; i < len(numbers); i++ {
n := numbers[i]
b := bases[i]
ns, err := encodeNegBase(n, b)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%13d encoded in base%-3d =%s\n", n, b, ns)
n, err = decodeNegBase(ns, b)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%13s decoded in base%-3d =%d\n\n", ns, b, n)
}
} | 527Negative base numbers
| 0go
| ecka6 |
import java.util.Scanner;
public class NimGame {
public static void main(String[] args) {
runGame(12);
}
private static void runGame(int tokens) {
System.out.printf("Nim game.%n%n");
Scanner in = new Scanner(System.in);;
do {
boolean humanInputOk = false;
int humanTokens = 0;
while ( ! humanInputOk ) {
System.out.printf("Human takes how many tokens? ");
String input = in.next();
try {
humanTokens = Integer.parseInt(input);
if ( humanTokens >= 1 && humanTokens <= 3 ) {
humanInputOk = true;
}
else {
System.out.printf("Try a number between 1 and 3.%n");
}
}
catch (NumberFormatException e) {
System.out.printf("Invalid input. Try a number between 1 and 3.%n");
}
}
tokens -= humanTokens;
System.out.printf("You take%d token%s.%n%d token%s remaining.%n%n", humanTokens, humanTokens > 1 ? "s" : "", tokens, tokens != 1 ? "s" : "");
if ( tokens == 0 ) {
System.out.printf("You win!!.%n%n");
break;
}
int computerTokens = 4 - humanTokens;
tokens -= computerTokens;
System.out.printf("Computer takes%d token%s.%n%d token%s remaining.%n%n", computerTokens, computerTokens != 1 ? "s" : "", tokens, tokens != 1 ? "s" : "");
if ( tokens == 0 ) {
System.out.printf("Computer wins!!.%n%n");
}
} while (tokens > 0);
in.close();
}
} | 524Nim game
| 9java
| 4iu58 |
package main; import "os"; import "fmt"; import "bytes"; import "io/ioutil"; func main() {ios := "os"; ifmt := "fmt"; ibytes := "bytes"; iioutil := "io/ioutil"; zero := "Reject"; one := "Accept"; x := "package main; import%q; import%q; import%q; import%q; func main() {ios:=%q; ifmt:=%q; ibytes:=%q; iioutil:=%q; zero:=%q; one:=%q; x:=%q; s:= fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _:= ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}\n"; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};} | 529Narcissist
| 0go
| oge8q |
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class NestedFunctionsDemo {
static String makeList(String separator) {
AtomicInteger counter = new AtomicInteger(1);
Function<String, String> makeItem = item -> counter.getAndIncrement() + separator + item + "\n";
return makeItem.apply("first") + makeItem.apply("second") + makeItem.apply("third");
}
public static void main(String[] args) {
System.out.println(makeList(". "));
}
} | 525Nested function
| 9java
| 1mkp2 |
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class NauticalBell extends Thread {
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000)); | 526Nautical bell
| 9java
| tkif9 |
null | 520Non-continuous subsequences
| 11kotlin
| fk3do |
as.numeric("20")
as.numeric("0x20")
as.hexmode(as.numeric("32"))
as.octmode(as.numeric("20")) | 518Non-decimal radices/Input
| 13r
| uo7vx |
import Data.Char (chr, ord)
import Numeric (showIntAtBase)
quotRemP :: Integral a => a -> a -> (a, a)
quotRemP n d = let (q, r) = quotRem n d
in if r < 0 then (q+1, r-d) else (q, r)
toNegBase :: Integral a => a -> a -> a
toNegBase b n = let (q, r) = quotRemP n b
in if q == 0 then r else negate b * toNegBase b q + r
showAtBase :: (Integral a, Show a) => a -> a -> String
showAtBase b n = showIntAtBase (abs b) charOf n ""
where charOf m | m < 10 = chr $ m + ord '0'
| m < 36 = chr $ m + ord 'a' - 10
| otherwise = '?'
printAtBase :: (Integral a, Show a) => a -> a -> IO ()
printAtBase b = putStrLn . showAtBase b . toNegBase b
main :: IO ()
main = do
printAtBase (-2) 10
printAtBase (-3) 146
printAtBase (-10) 15
printAtBase (-16) 107
printAtBase (-36) 41371458 | 527Negative base numbers
| 8haskell
| 3pnzj |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.