code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
class Nim {
constructor(tokens, printFun) {
this.startTokens = tokens;
this.tokens = tokens;
this.printFun = printFun;
}
playerTurn(take) {
take = Math.round(take);
if (take < 1 || take > 3) {
this.printFun("take must be between 1 and 3.\n")
return false;
}
this.tokens -= take;
this.printFun("Player takes " + take + " tokens.");
this.printRemaining()
if (this.tokens === 0) {
this.printFun("Player wins!\n");
}
return true;
}
computerTurn() {
let take = this.tokens % 4;
this.tokens -= take;
this.printFun("Computer takes " + take + " tokens.");
this.printRemaining();
if (this.tokens === 0) {
this.printFun("Computer wins.\n");
}
}
printRemaining() {
this.printFun(this.tokens + " tokens remaining.\n");
}
}
let game = new Nim(12, console.log);
while (true) {
if (game.playerTurn(parseInt(prompt("How many tokens would you like to take?")))){
game.computerTurn();
}
if (game.tokens == 0) {
break;
}
} | 524Nim game
| 10javascript
| hz7jh |
main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q " | 529Narcissist
| 8haskell
| 2s3ll |
use strict;
use warnings;
use feature 'say';
use bigint;
use List::Util 'first';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub next_greatest_index {
my($str) = @_;
my @i = reverse split //, $str;
@i-1 - (1 + first { $i[$_] > $i[$_+1] } 0 .. @i-1);
}
sub next_greatest_integer {
my($num) = @_;
my $numr;
return 0 if length $num < 2;
return ($numr = 0 + reverse $num) > $num ? $numr : 0 if length $num == 2;
return 0 unless my $i = next_greatest_index( $num ) // 0;
my $digit = substr($num, $i, 1);
my @rest = sort split '', substr($num, $i);
my $next = first { $rest[$_] > $digit } 1..@rest;
join '', substr($num, 0, $i), (splice(@rest, $next, 1)), @rest;
}
say 'Next largest integer able to be made from these digits, or zero if no larger exists:';
for (0, 9, 12, 21, 12453, 738440, 45072010, 95322020, 9589776899767587796600, 3345333) {
printf "%30s -> %s\n", comma($_), comma next_greatest_integer $_;
} | 523Next highest int from digits
| 2perl
| pmpb0 |
function makeList(separator) {
var counter = 1;
function makeItem(item) {
return counter++ + separator + item + "\n";
}
return makeItem("first") + makeItem("second") + makeItem("third");
}
console.log(makeList(". ")); | 525Nested function
| 10javascript
| qvex8 |
null | 526Nautical bell
| 11kotlin
| ogq8z |
for n in range(34):
print % (n, n, n) | 519Non-decimal radices/Output
| 3python
| 7tbrm |
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class NegativeBaseNumbers {
private static final String DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static String encodeNegBase(long n, int b) {
if (b < -62 || b > -1) throw new IllegalArgumentException("Parameter b is out of bounds");
if (n == 0) return "0";
StringBuilder out = new StringBuilder();
long nn = n;
while (nn != 0) {
int rem = (int) (nn % b);
nn /= b;
if (rem < 0) {
nn++;
rem -= b;
}
out.append(DIGITS.charAt(rem));
}
out.reverse();
return out.toString();
}
private static long decodeNegBase(String ns, int b) {
if (b < -62 || b > -1) throw new IllegalArgumentException("Parameter b is out of bounds");
if (Objects.equals(ns, "0")) return 0;
long total = 0;
long bb = 1;
for (int i = ns.length() - 1; i >= 0; i--) {
char c = ns.charAt(i);
total += DIGITS.indexOf(c) * bb;
bb *= b;
}
return total;
}
public static void main(String[] args) {
List<Map.Entry<Long, Integer>> nbl = List.of(
Map.entry(10L, -2),
Map.entry(146L, -3),
Map.entry(15L, -10),
Map.entry(-4393346L, -62)
);
for (Map.Entry<Long, Integer> p : nbl) {
String ns = encodeNegBase(p.getKey(), p.getValue());
System.out.printf("%12d encoded in base%-3d =%s\n", p.getKey(), p.getValue(), ns);
long n = decodeNegBase(ns, p.getValue());
System.out.printf("%12s decoded in base%-3d =%d\n\n", ns, p.getValue(), n);
}
}
} | 527Negative base numbers
| 9java
| irqos |
null | 524Nim game
| 11kotlin
| lq9cp |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Narcissist {
private static final String SOURCE = "import java.io.BufferedReader;%nimport java.io.IOException;%nimport java.io.InputStreamReader;%n%npublic class Narcissist {%n private static final String SOURCE =%c%s%c;%n private static final char QUOTE = 0x22;%n%n public static void main(String[] args) throws IOException {%n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));%n StringBuilder sb = new StringBuilder();%n%n while (true) {%n String line = br.readLine();%n if (null == line) break;%n sb.append(line).append(System.lineSeparator());%n }%n%n String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);%n if (program.equals(sb.toString())) {%n System.out.println(%caccept%c);%n } else {%n System.out.println(%creject%c);%n }%n }%n}%n";
private static final char QUOTE = 0x22;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
while (true) {
String line = br.readLine();
if (null == line) break;
sb.append(line).append(System.lineSeparator());
}
String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);
if (program.equals(sb.toString())) {
System.out.println("accept");
} else {
System.out.println("reject");
}
}
} | 529Narcissist
| 9java
| 61i3z |
null | 525Nested function
| 11kotlin
| jtg7r |
dec1 =
hex2 =
oct3 =
bin4 =
p dec1.to_i
p hex2.hex
p oct3.oct | 518Non-decimal radices/Input
| 14ruby
| jz17x |
as.octmode(x)
as.hexmode(x)
as.integer(x)
as.numeric(x) | 519Non-decimal radices/Output
| 13r
| 5i7uy |
tokens = 12
print("Nim Game\n")
print("Starting with " .. tokens .. " tokens.\n\n")
function printRemaining()
print(tokens .. " tokens remaining.\n")
end
function playerTurn(take)
take = math.floor(take)
if (take < 1 or take > 3) then
print ("\nTake must be between 1 and 3.\n")
return false
end
tokens = tokens - take
print ("\nPlayer takes " .. take .. " tokens.")
printRemaining()
return true
end
function computerTurn()
take = tokens % 4
tokens = tokens - take
print("Computer takes " .. take .. " tokens.")
printRemaining()
end
while (tokens > 0) do
io.write("How many tokens would you like to take?: ")
if playerTurn(io.read("*n")) then
computerTurn()
end
end
print ("Computer wins.") | 524Nim game
| 1lua
| 2scl3 |
typedef struct wstr {
wchar_t *s;
int n, alloc;
} wstr;
wstr *w_new()
{
wstr *w = malloc(sizeof(wstr));
w->alloc = 1;
w->n = 0;
w->s = malloc(sizeof(wchar_t));
w->s[0] = 0;
return w;
}
void w_append(wstr *w, wchar_t c)
{
int n = w->n + 1;
if (n >= w->alloc) {
w->alloc *= 2;
w->s = realloc(w->s, w->alloc * sizeof(wchar_t));
}
w->s[w->n++] = c;
w->s[w->n] = 0;
}
wstr *w_make(wchar_t *s)
{
int i, len = wcslen(s);
wstr *w = w_new();
for (i = 0; i < len; i++) w_append(w, s[i]);
return w;
}
typedef void (*wtrans_func)(wstr *, wstr *);
void w_transform(wstr *in, wtrans_func f)
{
wstr t, *out = w_new();
f(in, out);
t = *in; *in = *out; *out = t;
w_del(out);
}
transfunc(nocase) {
int i;
wchar_t c;
forchars(i, c, in) w_append(out, towlower(c));
}
transfunc(despace) {
int i, gotspace = 0;
wchar_t c;
forchars(i, c, in) {
if (!iswspace(c)) {
if (gotspace && out->n)
w_append(out, L' ');
w_append(out, c);
gotspace = 0;
} else gotspace = 1;
}
}
static const wchar_t *const tbl_accent[] = {
L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L };
static const wchar_t *const tbl_ligature[] = {
L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L,
};
void w_char_repl(wstr *in, wstr *out, const wchar_t *const *tbl, int len)
{
int i, j, k;
wchar_t c;
forchars(i, c, in) {
for (j = k = 0; j < len; j += 2) {
if (c != tbl[j][0]) continue;
for (k = 0; tbl[j + 1][k]; k++)
w_append(out, tbl[j + 1][k]);
break;
}
if (!k) w_append(out, c);
}
}
transfunc(noaccent) {
w_char_repl(in, out, tbl_accent, sizeof(tbl_accent)/sizeof(wchar_t*));
}
transfunc(noligature) {
w_char_repl(in, out, tbl_ligature, sizeof(tbl_ligature)/sizeof(wchar_t*));
}
static const wchar_t *const tbl_article[] = {
L, L, L, L, L, L };
transfunc(noarticle) {
int i, j, n;
wchar_t c, c0 = 0;
forchars(i, c, in) {
if (!c0 || (iswalnum(c) && !iswalnum(c0))) {
for (j = N_ARTICLES - 1; j >= 0; j--) {
n = wcslen(tbl_article[j]);
if (wcsncasecmp(in->s + i, tbl_article[j], n))
continue;
if (iswalnum(in->s[i + n])) continue;
i += n;
break;
}
if (j < 0) w_append(out, c);
} else
w_append(out, c);
c0 = c;
}
}
enum { wi_space = 0, wi_case, wi_accent, wi_lig, wi_article, wi_numeric };
const wtrans_func trans_funcs[] = {
w_despace, w_nocase, w_noaccent, w_noligature, w_noarticle, 0
};
const char *const flagnames[] = {
,
,
,
,
,
,
};
typedef struct { wchar_t* s; wstr *w; } kw_t;
int w_numcmp(const void *a, const void *b)
{
wchar_t *pa = ((const kw_t*)a)->w->s, *pb = ((const kw_t*)b)->w->s;
int sa, sb, ea, eb;
while (*pa && *pb) {
if (iswdigit(*pa) && iswdigit(*pb)) {
sa = sb = 0;
while (pa[sa] == L'0') sa++;
while (pb[sb] == L'0') sb++;
ea = sa; eb = sb;
while (iswdigit(pa[ea])) ea++;
while (iswdigit(pb[eb])) eb++;
if (eb - sb > ea - sa) return -1;
if (eb - sb < ea - sa) return 1;
while (sb < eb) {
if (pa[sa] > pb[sb]) return 1;
if (pa[sa] < pb[sb]) return -1;
sa++; sb++;
}
pa += ea; pb += eb;
}
else if (iswdigit(*pa)) return 1;
else if (iswdigit(*pb)) return -1;
else {
if (*pa > *pb) return 1;
if (*pa < *pb) return -1;
pa++; pb++;
}
}
return (!*pa && !*pb) ? 0 : *pa ? 1 : -1;
}
int w_cmp(const void *a, const void *b)
{
return wcscmp(((const kw_t*)a)->w->s, ((const kw_t*)b)->w->s);
}
void natural_sort(wchar_t **strings, int len, int flags)
{
int i, j;
kw_t *kws = malloc(sizeof(kw_t) * len);
for (i = 0; i < len; i++) {
kws[i].s = strings[i];
kws[i].w = w_make(strings[i]);
for (j = 0; j < wi_numeric; j++)
if (flags & (1 << j) && trans_funcs[j])
w_transform(kws[i].w, trans_funcs[j]);
}
qsort(kws, len, sizeof(kw_t), (flags & WS_NUMERIC) ? w_numcmp : w_cmp);
for (i = 0; i < len; i++) {
w_del(kws[i].w);
strings[i] = kws[i].s;
}
free(kws);
}
const wchar_t *const test[] = {
L, L, L, L,
L,
L,
L,
};
void test_sort(int flags)
{
int i, j;
const wchar_t *str[N_STRINGS];
memcpy(str, test, sizeof(test));
printf();
for (i = 0, j = flags; j; i++, j >>= 1)
if ((j & 1))
printf(, flagnames[i], j > 1 ? :);
natural_sort((wchar_t **)str, N_STRINGS, flags);
for (i = 0; i < N_STRINGS; i++)
printf(, str[i]);
printf();
}
int main()
{
setlocale(LC_CTYPE, );
test_sort(WS_NOSPACE);
test_sort(WS_NOCASE);
test_sort(WS_NUMERIC);
test_sort(WS_NOARTICLE|WS_NOSPACE);
test_sort(WS_NOCASE|WS_NOSPACE|WS_ACCENT);
test_sort(WS_LIGATURE|WS_NOCASE|WS_NOSPACE|WS_NUMERIC|WS_ACCENT|WS_NOARTICLE);
return 0;
} | 530Natural sorting
| 5c
| 5oyuk |
var code='var q=String.fromCharCode(39);print("var code=" + q + code + q + "; eval(code)" == readline())'; eval(code) | 529Narcissist
| 10javascript
| lqzcf |
null | 529Narcissist
| 11kotlin
| djqnz |
def closest_more_than(n, lst):
large = max(lst) + 1
return lst.index(min(lst, key=lambda x: (large if x <= n else x)))
def nexthigh(n):
assert n == int(abs(n)),
this = list(int(digit) for digit in str(int(n)))[::-1]
mx = this[0]
for i, digit in enumerate(this[1:], 1):
if digit < mx:
mx_index = closest_more_than(digit, this[:i + 1])
this[mx_index], this[i] = this[i], this[mx_index]
this[:i] = sorted(this[:i], reverse=True)
return int(''.join(str(d) for d in this[::-1]))
elif digit > mx:
mx, mx_index = digit, i
return 0
if __name__ == '__main__':
for x in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020,
9589776899767587796600]:
print(f) | 523Next highest int from digits
| 3python
| 191pc |
function makeList (separator)
local counter = 0
local function makeItem(item)
counter = counter + 1
return counter .. separator .. item .. "\n"
end
return makeItem("first") .. makeItem("second") .. makeItem("third")
end
print(makeList(". ")) | 525Nested function
| 1lua
| hzrj8 |
fn main() {
println!(
"Parse from plain decimal: {}",
"123".parse::<u32>().unwrap()
);
println!(
"Parse with a given radix (2-36 supported): {}",
u32::from_str_radix("deadbeef", 16).unwrap()
);
} | 518Non-decimal radices/Input
| 15rust
| h3aj2 |
object Main extends App {
val (s, bases) = ("100", Seq(2, 8, 10, 16, 19, 36))
bases.foreach(base => println(f"String $s in base $base%2d is $BigInt(s, base)%5d"))
} | 518Non-decimal radices/Input
| 16scala
| pmxbj |
null | 527Negative base numbers
| 11kotlin
| qv1x1 |
double pow_ (double x, int e) {
int i;
double r = 1;
for (i = 0; i < e; i++) {
r *= x;
}
return r;
}
double root (int n, double x) {
double d, r = 1;
if (!x) {
return 0;
}
if (n < 1 || (x < 0 && !(n&1))) {
return 0.0 / 0.0;
}
do {
d = (x / pow_(r, n - 1) - r) / n;
r += d;
}
while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10);
return r;
}
int main () {
int n = 15;
double x = pow_(-3.14159, 15);
printf(, n, x, root(n, x));
return 0;
} | 531Nth root
| 5c
| qvhxc |
O_RDONLY, O_WRONLY, or O_RDWR. O_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC | 532Naming conventions
| 5c
| 3psza |
use utf8;
binmode STDOUT, ":utf8";
use DateTime;
$| = 1;
my @watch = <Middle Morning Forenoon Afternoon Dog First>;
my @ordinal = <One Two Three Four Five Six Seven Eight>;
my $thishour;
my $thisminute = '';
while () {
my $utc = DateTime->now( time_zone => 'UTC' );
if ($utc->minute =~ /^(00|30)$/ and $utc->minute != $thisminute) {
$thishour = $utc->hour;
$thisminute = $utc->minute;
bell($thishour, $thisminute);
}
printf "%s%02d:%02d:%02d", "\r", $utc->hour, $utc->minute, $utc->second;
sleep(1);
}
sub bell {
my($hour, $minute) = @_;
my $bells = (($hour % 4) * 2 + int $minute/30) || 8;
printf "%s%02d:%02d%9s watch,%6s Bell%s Gone: \t", "\b" x 9, $hour, $minute,
$watch[(int($hour/4) - (0==($minute + $hour % 4)) + 6) % 6],
$ordinal[$bells - 1], $bells == 1 ? '' : 's';
chime($bells);
}
sub chime {
my($count) = shift;
for (1..int($count/2)) {
print "\a "; sleep .25;
print "\a"; sleep .75;
}
if ($count % 2) {
print "\a"; sleep 1;
}
print "\n";
} | 526Nautical bell
| 2perl
| gnv4e |
local $/;
print do { open 0; <0> } eq <> ? "accept" : "reject"; | 529Narcissist
| 2perl
| jtv7f |
var xs = Array.Empty(10)
var ys = Array(1, 2, 3)
var str = xs.ToString()
type Maybe = Some(x) or None()
var x = Maybe.Some(42) | 532Naming conventions
| 6clojure
| cxn9b |
my ($max, @current);
sub non_continuous {
my ($idx, $has_gap) = @_;
my $found;
for ($idx .. $max) {
push @current, $_;
$found ++ if $has_gap;
$found += non_continuous($_ + 1, $has_gap) if $_ < $max;
pop @current;
$has_gap = @current;
}
$found;
}
$max = 20;
print "found ", non_continuous(1), " sequences\n"; | 520Non-continuous subsequences
| 2perl
| h3pjl |
for n in 0..33
puts % [n, n, n, n]
end
puts
[2,8,10,16,36].each {|i| puts } | 519Non-decimal radices/Output
| 14ruby
| h31jx |
fn main() { | 519Non-decimal radices/Output
| 15rust
| k6ah5 |
use strict;
use warnings;
use feature 'say';
my $tokens = 12;
say "$tokens tokens remaining.\n";
while (1) {
print "How many tokens do you want to remove; 1, 2 or 3?: ";
(my $player = <>) =~ s/\s//g;
say "Nice try. $tokens tokens remaining.\n" and next
unless $player =~ /^[123]$/;
$tokens -= 4;
say "Computer takes @{[4 - $player]}.\n$tokens tokens remaining.\n";
say "Computer wins." and last
if $tokens <= 0;
} | 524Nim game
| 2perl
| qvwx6 |
import sys
with open(sys.argv[0]) as quine:
code = raw_input()
if code == quine.read():
print()
else:
print() | 529Narcissist
| 3python
| hzujw |
fn next_permutation<T: PartialOrd>(array: &mut [T]) -> bool {
let len = array.len();
if len < 2 {
return false;
}
let mut i = len - 1;
while i > 0 {
let j = i;
i -= 1;
if array[i] < array[j] {
let mut k = len - 1;
while array[i] >= array[k] {
k -= 1;
}
array.swap(i, k);
array[j..len].reverse();
return true;
}
}
false
}
fn next_highest_int(n: u128) -> u128 {
use std::iter::FromIterator;
let mut chars: Vec<char> = n.to_string().chars().collect();
if!next_permutation(&mut chars) {
return 0;
}
String::from_iter(chars).parse::<u128>().unwrap()
}
fn main() {
for n in &[0, 9, 12, 21, 12453, 738440, 45072010, 95322020, 9589776899767587796600] {
println!("{} -> {}", n, next_highest_int(*n));
}
} | 523Next highest int from digits
| 15rust
| w2we4 |
sub makeList {
my $separator = shift;
my $counter = 1;
sub makeItem { $counter++ . $separator . shift . "\n" }
makeItem("first") . makeItem("second") . makeItem("third")
}
print makeList(". "); | 525Nested function
| 2perl
| tknfg |
object Main extends App {
val radices = List(2, 8, 10, 16, 19, 36)
for (base <- radices) print(f"$base%6d")
println(s"""\n${"-" * (6 * radices.length)}""")
for (i <- BigInt(0) to 35; | 519Non-decimal radices/Output
| 16scala
| 19xpf |
use strict;
use feature 'say';
use POSIX qw(floor);
use ntheory qw/fromdigits todigits/;
sub encode {
my($n, $b) = @_;
my @out;
my $r = 0;
while ($n) {
$r = $n % $b;
$n = floor $n/$b;
$n += 1, $r -= $b if $r < 0;
push @out, todigits($r, -$b) || 0;
}
join '', reverse @out;
}
sub decode {
my($s, $b) = @_;
my $total = 0;
my $i = 0;
for my $c (reverse split '', $s) {
$total += (fromdigits($c, -$b) * $b**$i);
$i++;
}
$total
}
say ' 10 in base -2: ', encode(10, -2);
say ' 15 in base -10: ', encode(15, -10);
say '146 in base -3: ', encode(146, -3);
say '';
say '11110 from base -2: ', decode("11110", -2);
say '21102 from base -3: ', decode("21102", -3);
say ' 195 from base -10: ', decode("195", -10); | 527Negative base numbers
| 2perl
| v0m20 |
(ns test-project-intellij.core
(:gen-class))
(defn abs [x]
" Absolute value"
(if (< x 0) (- x) x))
(defn power [x n]
" x to power n, where n = 0, 1, 2, ... "
(apply * (repeat n x)))
(defn calc-delta [A x n]
" nth rooth algorithm delta calculation "
(/ (- (/ A (power x (- n 1))) x) n))
(defn nth-root
" nth root of algorithm: A = numer, n = root"
([A n] (nth-root A n 0.5 1.0))
([A n guess-prev guess-current]
(if (< (abs (- guess-prev guess-current)) 1e-6)
guess-current
(recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) | 531Nth root
| 6clojure
| iraom |
package main
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
)
var tests = []struct {
descr string
list []string
}{
{"Ignoring leading spaces", []string{
"ignore leading spaces: 2-2",
" ignore leading spaces: 2-1",
" ignore leading spaces: 2+0",
" ignore leading spaces: 2+1",
}},
{"Ignoring multiple adjacent spaces", []string{
"ignore m.a.s spaces: 2-2",
"ignore m.a.s spaces: 2-1",
"ignore m.a.s spaces: 2+0",
"ignore m.a.s spaces: 2+1",
}},
{"Equivalent whitespace characters", []string{
"Equiv. spaces: 3-3",
"Equiv.\rspaces: 3-2",
"Equiv.\fspaces: 3-1",
"Equiv.\bspaces: 3+0",
"Equiv.\nspaces: 3+1",
"Equiv.\tspaces: 3+2",
}},
{"Case Indepenent sort", []string{
"cASE INDEPENENT: 3-2",
"caSE INDEPENENT: 3-1",
"casE INDEPENENT: 3+0",
"case INDEPENENT: 3+1",
}},
{"Numeric fields as numerics", []string{
"foo100bar99baz0.txt",
"foo100bar10baz0.txt",
"foo1000bar99baz10.txt",
"foo1000bar99baz9.txt",
}},
}
func main() {
for _, test := range tests {
fmt.Println(test.descr)
fmt.Println("Input order:")
for _, s := range test.list {
fmt.Printf(" %q\n", s)
}
fmt.Println("Natural order:")
l := make(list, len(test.list))
for i, s := range test.list {
l[i] = newNatStr(s)
}
sort.Sort(l)
for _, s := range l {
fmt.Printf(" %q\n", s.s)
}
fmt.Println()
}
} | 530Natural sorting
| 0go
| 8410g |
null | 532Naming conventions
| 0go
| b6vkh |
<?
function makeList($separator) {
$counter = 1;
$makeItem = function ($item) use ($separator, &$counter) {
return $counter++ . $separator . $item . ;
};
return $makeItem() . $makeItem() . $makeItem();
}
echo makeList();
?> | 525Nested function
| 12php
| k37hv |
import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar =
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); off(0.5)
def bongs(m):
for i in range(m):
print(bellchar, end=' ')
bong()
if i% 2:
print(' ', end='')
off(0.5)
print('')
scheds = sched.scheduler(time.time, time.sleep)
def ships_bell(now=None):
def adjust_to_half_hour(atime):
atime[4] = (atime[4]
atime[5] = 0
return atime
debug = now is not None
rightnow = time.gmtime()
if not debug:
now = adjust_to_half_hour( list(rightnow) )
then = now[::]
then[4] += 30
hr, mn = now[3:5]
watch, b = divmod(int(2 * hr + mn
b += 1
bells = '%i bell%s'% (b, 's' if b > 1 else ' ')
if debug:
print(% (now[3], now[4], watches[watch] + ' watch', bells), end=' ')
else:
print(% (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')
bongs(b)
if not debug:
scheds.enterabs(calendar.timegm(then), 0, ships_bell)
scheds.run()
def dbg_tester():
for h in range(24):
for m in (0, 30):
if (h,m) == (24,30): break
ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )
if __name__ == '__main__':
ships_bell() | 526Nautical bell
| 3python
| rdugq |
int main() {
const int MU_MAX = 1000000;
int i, j;
int *mu;
int sqroot;
sqroot = (int)sqrt(MU_MAX);
mu = malloc((MU_MAX + 1) * sizeof(int));
for (i = 0; i < MU_MAX;i++) {
mu[i] = 1;
}
for (i = 2; i <= sqroot; i++) {
if (mu[i] == 1) {
for (j = i; j <= MU_MAX; j += i) {
mu[j] *= -i;
}
for (j = i * i; j <= MU_MAX; j += i * i) {
mu[j] = 0;
}
}
}
for (i = 2; i <= MU_MAX; i++) {
if (mu[i] == i) {
mu[i] = 1;
} else if (mu[i] == -i) {
mu[i] = -1;
} else if (mu[i] < 0) {
mu[i] = 1;
} else if (mu[i] > 0) {
mu[i] = -1;
}
}
printf();
for (i = 1; i < 200; i++) {
printf(, mu[i]);
if ((i + 1) % 20 == 0) {
printf();
}
}
free(mu);
return 0;
} | 533Möbius function
| 5c
| rdyg7 |
import Data.List
import Data.Char
import Data.String.Utils
import Data.List.Utils
import Data.Function (on)
printOutput = do
putStrLn "# Ignoring leading spaces \n"
printBlockOfMessages sample1Rule ignoringStartEndSpaces
putStrLn "\n # Ignoring multiple adjacent spaces (m.a.s) \n"
printBlockOfMessages sample2Rule ignoringMultipleAdjacentSpaces
putStrLn "\n # Equivalent whitespace characters \n"
printBlockOfMessages sample3Rule ignoringMultipleAdjacentSpaces
putStrLn "\n # Case Indepenent sorts \n"
printBlockOfMessages sample4Rule caseIndependent
putStrLn "\n # Numeric fields as numerics \n"
printBlockOfMessages sample5Rule numericFieldsAsNumbers
putStrLn "\n # Title sorts \n"
printBlockOfMessages sample6Rule removeLeadCommonWords
printMessage message content = do
putStrLn message
mapM_ print content
printBlockOfMessages list function = do
printMessage "Text strings:" list
printMessage "Normally sorted:" (sort list)
printMessage "Naturally sorted:" (sortListWith list function)
sample1Rule = ["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1"]
sample2Rule = ["ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1"]
sample3Rule = ["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"]
sample4Rule = ["cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"]
sample5Rule = ["foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"]
sample6Rule = ["The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"]
sortListWith l f = sort $ f l
ignoringStartEndSpaces :: [String] -> [String]
ignoringStartEndSpaces = map strip
ignoringMultipleAdjacentSpaces :: [String] -> [String]
ignoringMultipleAdjacentSpaces = map (unwords . words)
caseIndependent :: [String] -> [String]
caseIndependent = map (map toLower)
numericFieldsAsNumbers :: [String] -> [[Int]]
numericFieldsAsNumbers = map findOnlyNumerics
findOnlyNumerics :: String -> [Int]
findOnlyNumerics s = convertDigitAsStringToInt $ makeListOfDigitsAsString $ extractDigitsAsString s
extractDigitsAsString :: String -> [String]
extractDigitsAsString s = map (filter isNumber) $ groupBy ((==) `on` isNumber ) s
makeListOfDigitsAsString :: [String] -> [String]
makeListOfDigitsAsString l = tail $ nub l
convertDigitAsStringToInt :: [String] -> [Int]
convertDigitAsStringToInt = map (joiner . map digitToInt)
joiner :: [Int] -> Int
joiner = read . concatMap show
removeLeadCommonWords l = map removeLeadCommonWord $ splitList l
splitList = map words
removeLeadCommonWord a = unwords $ if f a commonWords then tail a else a
where f l1 = elem (map toLower (head l1))
commonWords = ["the","a","an","of"] | 530Natural sorting
| 8haskell
| lqtch |
s = ; puts(gets.chomp == (s % [34.chr, s, 34.chr])? 'accept': 'reject') | 529Narcissist
| 14ruby
| b64kq |
use std::io::{stdin, prelude::*};
fn main() {
let src = include_str!("main.rs");
let mut input = String::new();
stdin()
.lock()
.read_to_string(&mut input)
.expect("Could not read from STDIN");
println!("{}", src == input);
} | 529Narcissist
| 15rust
| pygbu |
import scala.io.StdIn
object Narcissist extends App {
val text = scala.io.Source.fromFile("Narcissist.scala", "UTF-8").toStream
println("Enter the number of lines to be input followed by those lines:\n")
val n = StdIn.readInt()
val lines = Stream {
StdIn.readLine()
}
if (lines.mkString("\r\n") == text) println("\naccept") else println("\nreject")
} | 529Narcissist
| 16scala
| ecjab |
// version 1.0.6
const val SOLAR_DIAMETER = 864938
enum class Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } // Yeah, Pluto!
class Star(val name: String) {
fun showDiameter() {
println("The diameter of the $name is ${"%,d".format(SOLAR_DIAMETER)} miles")
}
}
class SolarSystem(val star: Star) {
private val planets = mutableListOf<Planet>() // some people might prefer _planets
init {
for (planet in Planet.values()) planets.add(planet)
}
fun listPlanets() {
println(planets)
}
}
fun main(args: Array<String>) {
val sun = Star("sun")
val ss = SolarSystem(sun)
sun.showDiameter()
println("\nIts planetary system comprises: ")
ss.listPlanets()
} | 532Naming conventions
| 8haskell
| djen4 |
def makeList(separator):
counter = 1
def makeItem(item):
nonlocal counter
result = str(counter) + separator + item +
counter += 1
return result
return makeItem() + makeItem() + makeItem()
print(makeList()) | 525Nested function
| 3python
| zbdtt |
MakeList <- function(sep)
{
counter <- 0
MakeItem <- function() paste0(counter <<- counter + 1, sep, c("first", "second", "third")[counter])
cat(replicate(3, MakeItem()), sep = "\n")
}
MakeList(". ") | 525Nested function
| 13r
| n78i2 |
from __future__ import print_function
def EncodeNegBase(n, b):
if n == 0:
return
out = []
while n != 0:
n, rem = divmod(n, b)
if rem < 0:
n += 1
rem -= b
out.append(rem)
return .join(map(str, out[::-1]))
def DecodeNegBase(nstr, b):
if nstr == :
return 0
total = 0
for i, ch in enumerate(nstr[::-1]):
total += int(ch) * b**i
return total
if __name__==:
print ()
result = EncodeNegBase(10, -2)
print (result)
if DecodeNegBase(result, -2) == 10: print ()
else: print ()
print ()
result = EncodeNegBase(146, -3)
print (result)
if DecodeNegBase(result, -3) == 146: print ()
else: print ()
print ()
result = EncodeNegBase(15, -10)
print (result)
if DecodeNegBase(result, -10) == 15: print ()
else: print () | 527Negative base numbers
| 3python
| u89vd |
print()
def getTokens(curTokens):
global tokens
print(, end='')
take = int(input())
if (take < 1 or take > 3):
print()
getTokens(curTokens)
return
tokens = curTokens - take
print(f'You take {take} tokens.')
print(f'{tokens} tokens remaining.\n')
def compTurn(curTokens):
global tokens
take = curTokens% 4
tokens = curTokens - take
print (f'Computer takes {take} tokens.')
print (f'{tokens} tokens remaining.\n')
tokens = 12
while (tokens > 0):
getTokens(tokens)
compTurn(tokens)
print() | 524Nim game
| 3python
| suxq9 |
tokens <- 12
while(tokens > 0) {
print(paste("Tokens remaining:",tokens))
playertaken <- 0
while(playertaken == 0) {
playeropts <- c(1:min(c(tokens,3)))
playertaken <- menu(playeropts, title = "Your go, how many tokens will you take? ")
tokens <- tokens - playertaken
if(tokens == 0) {print("Well done you won, that shouldn't be possible!")}
}
cputaken <- 4 - playertaken
tokens <- tokens - cputaken
print(paste("I take",cputaken,"tokens,",tokens,"remain"))
if(tokens == 0) {print("I win!")}
} | 524Nim game
| 13r
| ec1ad |
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL) {
fprintf(stderr, );
exit(1);
}
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL) {
fprintf(stderr, );
exit(1);
}
return ptr;
}
bool is_prime(uint32_t n) {
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
for (uint32_t p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return false;
}
return true;
}
uint32_t find_primes(uint32_t from, uint32_t to, uint32_t** primes) {
uint32_t count = 0, buffer_length = 16;
uint32_t* buffer = xmalloc(sizeof(uint32_t) * buffer_length);
for (uint32_t p = from; p <= to; ++p) {
if (is_prime(p)) {
if (count >= buffer_length) {
uint32_t new_length = buffer_length * 2;
if (new_length < count + 1)
new_length = count + 1;
buffer = xrealloc(buffer, sizeof(uint32_t) * new_length);
buffer_length = new_length;
}
buffer[count++] = p;
}
}
*primes = buffer;
return count;
}
void free_numbers(mpz_t* numbers, size_t count) {
for (size_t i = 0; i < count; ++i)
mpz_clear(numbers[i]);
free(numbers);
}
mpz_t* find_nsmooth_numbers(uint32_t n, uint32_t count) {
uint32_t* primes = NULL;
uint32_t num_primes = find_primes(2, n, &primes);
mpz_t* numbers = xmalloc(sizeof(mpz_t) * count);
mpz_t* queue = xmalloc(sizeof(mpz_t) * num_primes);
uint32_t* index = xmalloc(sizeof(uint32_t) * num_primes);
for (uint32_t i = 0; i < num_primes; ++i) {
index[i] = 0;
mpz_init_set_ui(queue[i], primes[i]);
}
for (uint32_t i = 0; i < count; ++i)
mpz_init(numbers[i]);
mpz_set_ui(numbers[0], 1);
for (uint32_t i = 1; i < count; ++i) {
for (uint32_t p = 0; p < num_primes; ++p) {
if (mpz_cmp(queue[p], numbers[i - 1]) == 0)
mpz_mul_ui(queue[p], numbers[++index[p]], primes[p]);
}
uint32_t min_index = 0;
for (uint32_t p = 1; p < num_primes; ++p) {
if (mpz_cmp(queue[min_index], queue[p]) > 0)
min_index = p;
}
mpz_set(numbers[i], queue[min_index]);
}
free_numbers(queue, num_primes);
free(primes);
free(index);
return numbers;
}
void print_nsmooth_numbers(uint32_t n, uint32_t begin, uint32_t count) {
uint32_t num = begin + count;
mpz_t* numbers = find_nsmooth_numbers(n, num);
printf(, n);
mpz_out_str(stdout, 10, numbers[begin]);
for (uint32_t i = 1; i < count; ++i) {
printf();
mpz_out_str(stdout, 10, numbers[begin + i]);
}
printf();
free_numbers(numbers, num);
}
int main() {
printf();
for (uint32_t n = 2; n <= 29; ++n) {
if (is_prime(n))
print_nsmooth_numbers(n, 0, 25);
}
printf();
for (uint32_t n = 3; n <= 29; ++n) {
if (is_prime(n))
print_nsmooth_numbers(n, 2999, 3);
}
printf();
for (uint32_t n = 503; n <= 521; ++n) {
if (is_prime(n))
print_nsmooth_numbers(n, 29999, 20);
}
return 0;
} | 534N-smooth numbers
| 5c
| 84h04 |
typedef struct { int x, y, z; } FTest_args;
void FTest (FTest_args args) {
printf(, args.x, args.y, args.z);
}
void FTest2 (int x, int y, int z) {
printf(, x, y, z);
}
static inline void FTest2_default_wrapper (FTest_args args) {
return FTest2(args.x, args.y, args.z);
}
int main(int argc, char **argv)
{
FTest((FTest_args){ .y = 10 });
FTest((FTest_args){ .y = 10, .z = 42 });
FT( .z = 47, .y = 10, .x = 42 );
DFT();
DFT( .z = 99 );
DF2();
DF2( .z = 99 );
return 0;
} | 535Named parameters
| 5c
| surq5 |
#! /usr/bin/swift
import Foundation
let script = CommandLine.arguments[0]
print(script)
let mytext = try? String.init(contentsOfFile: script, encoding: .utf8)
var enteredtext = readLine()
if mytext == enteredtext {
print("Accept")
} else {
print("Reject")
} | 529Narcissist
| 17swift
| k35hx |
package main
import (
"fmt"
"math/big"
"strconv"
)
func main () {
s := strconv.FormatInt(26, 16) | 528Non-decimal radices/Convert
| 0go
| a9j1f |
var nsort = function(input) {
var e = function(s) {
return (' ' + s + ' ').replace(/[\s]+/g, ' ').toLowerCase().replace(/[\d]+/, function(d) {
d = '' + 1e20 + d;
return d.substring(d.length - 20);
});
};
return input.sort(function(a, b) {
return e(a).localeCompare(e(b));
});
};
console.log(nsort([
"file10.txt",
"\nfile9.txt",
"File11.TXT",
"file12.txt"
])); | 530Natural sorting
| 10javascript
| cxf9j |
null | 532Naming conventions
| 11kotlin
| a9413 |
def makeList(separator)
counter = 1
makeItem = lambda {|item|
result =
counter += 1
result
}
makeItem[] + makeItem[] + makeItem[]
end
print makeList() | 525Nested function
| 14ruby
| 61t3t |
fn make_list(sep: &str) -> String {
let mut counter = 0;
let mut make_item = |label| {
counter += 1;
format!("{}{}{}", counter, sep, label)
};
format!(
"{}\n{}\n{}",
make_item("First"),
make_item("Second"),
make_item("Third")
)
}
fn main() {
println!("{}", make_list(". "))
} | 525Nested function
| 15rust
| yaz68 |
watches = [ , , , , , , , ]
watch_ends = [ , , , , , , , ]
words = [,,,,,,,]
sound =
loop do
time = Time.now
if time.sec == 0 and time.min % 30 == 0
num = (time.hour * 60 + time.min) / 30 % 8
num = 8 if num == 0
hr_min = time.strftime
idx = watch_ends.find_index {|t| hr_min <= t}
text = % [
hr_min,
watches[idx],
words[num-1],
num==1? :
]
bells = (sound * num).gsub(sound + sound) {|dd| dd + ' '}
puts % [text, bells]
end
sleep 1
end | 526Nautical bell
| 14ruby
| jt47x |
def ncsub(seq, s=0):
if seq:
x = seq[:1]
xs = seq[1:]
p2 = s% 2
p1 = not p2
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else [] | 520Non-continuous subsequences
| 3python
| k61hf |
def radixParse = { s, radix -> Integer.parseInt(s, radix) }
def radixFormat = { i, radix -> Integer.toString(i, radix) } | 528Non-decimal radices/Convert
| 7groovy
| hz5j9 |
(defn foo [& opts]
(let [opts (merge {:bar 1:baz 2} (apply hash-map opts))
{:keys [bar baz]} opts]
[bar baz])) | 535Named parameters
| 6clojure
| n7bik |
- constants use UPCASE_SNAKE
- variable names use lower_case_snake
- class-like structures use CamelCase
- other functions use smallCamelCase
- Use _ for unneeded variables
- Don't use Hungarian Notation | 532Naming conventions
| 1lua
| ecgac |
def main(args: Array[String]) {
val sep: String=". "
var c:Int=1;
def go(s: String):Unit={
println(c+sep+s)
c=c+1
}
go("first")
go("second")
go("third")
} | 525Nested function
| 16scala
| cxy93 |
ncsub <- function(x)
{
n <- length(x)
a <- seq_len(n)
seqlist <- list()
for(i in 2:(n-1))
{
seqs <- combn(a, i)
ok <- apply(seqs, 2, function(x) any(diff(x)!=1))
newseqs <- unlist(apply(seqs[,ok], 2, function(x) list(x)), recursive=FALSE)
seqlist <- c(seqlist, newseqs)
}
lapply(seqlist, function(index) x[index])
}
ncsub(1:4)
ncsub(letters[1:5]) | 520Non-continuous subsequences
| 13r
| rfhgj |
Prelude> Numeric.showIntAtBase 16 Char.intToDigit 42 ""
"2a"
Prelude> fst $ head $ Numeric.readInt 16 Char.isHexDigit Char.digitToInt "2a"
42 | 528Non-decimal radices/Convert
| 8haskell
| zbot0 |
[12, 8, 4].each do |remaining|
puts
unless (num=gets.to_i).between?(1, 3)
puts
redo
end
puts
end
puts | 524Nim game
| 14ruby
| 84s01 |
$ALL_CAPS_HERE constants
$Some_Caps_Here package-wide global/static
$no_caps_here function scope my/our/local variables
$_internal_use private | 532Naming conventions
| 2perl
| 9wimn |
DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
def negative_base_encode(n, b)
raise 'base out of range' if (b < -62) || (b > -2)
return '0' if n == 0
revdigs = []
while n!= 0 do
n, r = n.divmod(b)
if r < 0
n += 1
r -= b
end
revdigs << r
end
return revdigs.reduce('') { |digstr, digit| DIGITS[digit] + digstr }
end
def negative_base_decode(n, b)
raise 'base out of range' if (b < -62) || (b > -2)
value = 0
n.reverse.each_char.with_index do |ch, inx|
value += DIGITS.index(ch) * b**inx
end
return value
end
[ [10, -2], [146, -3], [15, -10], [0, -31], [-6221826, -62] ].each do |pair|
decimal, base = pair
encoded = negative_base_encode(decimal, base)
decoded = negative_base_decode(encoded, base)
puts( %
[decimal, 10, encoded, base, encoded, base, decoded, 10])
end | 527Negative base numbers
| 14ruby
| 4il5p |
fn main() {
let mut tokens = 12;
println!("Nim game");
println!("Starting with {} tokens.", tokens);
println!("");
loop {
tokens = p_turn(&tokens);
print_remaining(&tokens);
tokens = c_turn(&tokens);
print_remaining(&tokens);
if tokens == 0 {
println!("Computer wins!");
break;
}
}
}
fn p_turn(tokens: &i32) -> i32 {
loop { | 524Nim game
| 15rust
| og083 |
var tokens = 12
def playerTurn(curTokens: Int): Unit =
{
val take = readLine("How many tokens would you like to take? ").toInt
if (take < 1 || take > 3) {
println("Number must be between 1 and 3.")
playerTurn(curTokens)
}
else {
tokens = curTokens - take
println(s"You take $take tokens. $tokens tokens remaining.\n")
}
}
def compTurn(curTokens: Int): Unit =
{
val take = curTokens % 4
tokens = curTokens - take
println(s"Computer takes $take tokens. $tokens remaining.\n")
}
def main(args: Array[String]): Unit =
{
while (tokens > 0)
{
playerTurn(tokens)
compTurn(tokens)
}
println("Computer wins!")
} | 524Nim game
| 16scala
| djing |
null | 530Natural sorting
| 11kotlin
| n7wij |
render-game-state
send-message-to-client
traverse-forest | 532Naming conventions
| 3python
| cxn9q |
func makeList(_ separator: String) -> String {
var counter = 1
func makeItem(_ item: String) -> String {
let result = String(counter) + separator + item + "\n"
counter += 1
return result
}
return makeItem("first") + makeItem("second") + makeItem("third")
}
print(makeList(". ")) | 525Nested function
| 17swift
| 3pfz2 |
const DIGITS: [char;62] = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
fn main() {
let nums_and_bases: [(i64,i64);5] = [(10,-2),(146,-3),(15,-10),(-6222885,-62),(1488588316238,-62)];
for (n,b) in nums_and_bases.iter() {
let ns = encode_neg_base(*n, *b);
println!("{} encoded in base {} = {}", *n, *b, &ns);
let nn = decode_neg_base(&ns, *b);
println!("{} decoded in base {} = {}\n", &ns, *b, nn);
}
}
fn decode_neg_base(ns: &str, b: i64) -> i64 {
if b < -62 || b > -1 {
panic!("base must be between -62 and -1 inclusive")
}
if ns == "0" {
return 0
}
let mut total: i64 = 0;
let mut bb: i64 = 1;
for c in ns.chars().rev() {
total += (DIGITS.iter().position(|&d| d==c).unwrap() as i64) * bb;
bb *= b;
}
return total;
}
fn encode_neg_base(mut n: i64, b: i64) -> String {
if b < -62 || b > -1 {
panic!("base must be between -62 and -1 inclusive");
}
if n == 0 {
return "0".to_string();
}
let mut out = String::new();
while n!= 0 {
let mut rem = n% b;
n /= b;
if rem < 0 {
n+=1;
rem -= b;
}
out.push(DIGITS[rem as usize]);
}
return out.chars().rev().collect();
} | 527Negative base numbers
| 15rust
| gn24o |
object NegativeBase {
val digits = ('0' to '9') ++ ('a' to 'z') ++ ('A' to 'Z')
def intToStr(n: Int, b: Int): String = {
def _fromInt(n: Int): List[Int] = {
if (n == 0) {
Nil
} else {
val r = n % b
val rp = if (r < 0) r + b else r
val m = -(n - rp)/b
rp :: _fromInt(m)
}
}
_fromInt(n).map(digits).reverse.mkString
}
def strToInt(s: String, b: Int): Int = {
s.map(digits.indexOf).foldRight((0, 1)){ case (x, (sum, pow)) =>
(sum + x * pow, pow * -b)
}._1
}
} | 527Negative base numbers
| 16scala
| jt57i |
package main
import "fmt"
func mbius(to int) []int {
if to < 1 {
to = 1
}
mobs := make([]int, to+1) | 533Möbius function
| 0go
| n71i1 |
test_variable = [1, 9, 8, 3]
test_variable.sort
test_variable
test_variable.sort!
test_variable | 532Naming conventions
| 14ruby
| 2sflw |
Dim dblDistance as Double | 532Naming conventions
| 15rust
| v0t2t |
Dim dblDistance as Double | 532Naming conventions
| 16scala
| 4i650 |
class Array
def func_power_set
inject([[]]) { |ps,item|
ps +
ps.map { |e| e + [item] }
}
end
def non_continuous_subsequences
func_power_set.reject {|seq| continuous?(seq)}
end
def continuous?(seq)
seq.each_cons(2) {|a, b| return false if a.succ!= b}
true
end
end
p (1..3).to_a.non_continuous_subsequences
p (1..4).to_a.non_continuous_subsequences
p (1..5).to_a.non_continuous_subsequences
p (..).to_a.non_continuous_subsequences | 520Non-continuous subsequences
| 14ruby
| pmebh |
public static long backToTen(String num, int oldBase){
return Long.parseLong(num, oldBase); | 528Non-decimal radices/Convert
| 9java
| ogw8d |
var tokens = 12
while tokens!= 0 {
print("Tokens remaining: \(tokens)\nPlease enter a number between 1 and 3: ", terminator: "")
guard let input = readLine(), let n = Int(input), n >= 1 && n <= 3 else {
fatalError("Invalid input")
}
tokens -= n
if tokens == 0 {
print("You win!")
break
}
print("I'll remove \(4 - n) tokens.")
tokens -= 4 - n
if tokens == 0 {
print("I win!")
}
print()
} | 524Nim game
| 17swift
| 05qs6 |
mpz_t power[10];
mpz_t dsum[MAX_LEN + 1];
int cnt[10], len;
void check_perm(void)
{
char s[MAX_LEN + 1];
int i, c, out[10] = { 0 };
mpz_get_str(s, 10, dsum[0]);
for (i = 0; s[i]; i++) {
c = s[i]-'0';
if (++out[c] > cnt[c]) return;
}
if (i == len)
gmp_printf(, dsum[0]);
}
void narc_(int pos, int d)
{
if (!pos) {
check_perm();
return;
}
do {
mpz_add(dsum[pos-1], dsum[pos], power[d]);
++cnt[d];
narc_(pos - 1, d);
--cnt[d];
} while (d--);
}
void narc(int n)
{
int i;
len = n;
for (i = 0; i < 10; i++)
mpz_ui_pow_ui(power[i], i, n);
mpz_init_set_ui(dsum[n], 0);
printf(, n);
narc_(n, 9);
putchar('\n');
}
int main(void)
{
int i;
for (i = 0; i <= 10; i++)
mpz_init(power[i]);
for (i = 1; i <= MAX_LEN; i++) narc(i);
return 0;
} | 536Narcissistic decimal number
| 5c
| ogj80 |
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{,0},{,2},{,4},{,5},{,7},{,9},{,11},{,12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf(,sequence[i].str);
sound(261.63*pow(2,sequence[i].key/12.0));
delay(sequence[i].key%12==0?500:1000);
i = (i+1)%8;
i==0?printf():printf();
}
nosound();
return 0;
} | 537Musical scale
| 5c
| 1mcpj |
package main
import (
"fmt"
"log"
"math/big"
)
var (
primes []*big.Int
smallPrimes []int
) | 534N-smooth numbers
| 0go
| 5otul |
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Data.Vector.Unboxed (toList)
import Math.NumberTheory.ArithmeticFunctions.Moebius (Moebius(..),
sieveBlockMoebius)
import System.Environment (getArgs, getProgName)
import System.IO (hPutStrLn, stderr)
import Text.Read (readMaybe)
moebiusBlock :: Word -> [Moebius]
moebiusBlock = toList . sieveBlockMoebius 1
showMoebiusBlock :: Word -> [Moebius] -> String
showMoebiusBlock cols = intercalate "\n" . map (concatMap showMoebius) .
chunksOf (fromIntegral cols)
where showMoebius MoebiusN = " -1"
showMoebius MoebiusZ = " 0"
showMoebius MoebiusP = " 1"
main :: IO ()
main = do
prog <- getProgName
args <- map readMaybe <$> getArgs
case args of
[Just cols, Just n] ->
putStrLn ("(n) for 1 n " ++ show n ++ ":\n") >>
putStrLn (showMoebiusBlock cols $ moebiusBlock n)
_ -> hPutStrLn stderr $ "Usage: " ++ prog ++ " num-columns maximum-number" | 533Möbius function
| 8haskell
| u8tv2 |
object NonContinuousSubSequences extends App {
private def seqR(s: String, c: String, i: Int, added: Int): Unit = {
if (i == s.length) {
if (c.trim.length > added) println(c)
} else {
seqR(s, c + s(i), i + 1, added + 1)
seqR(s, c + " ", i + 1, added)
}
}
seqR("1234", "", 0, 0)
} | 520Non-continuous subsequences
| 16scala
| w2ses |
k = 26
s = k.toString(16) | 528Non-decimal radices/Convert
| 10javascript
| tk8fm |
void hue_to_rgb(double hue, double sat, unsigned char *p)
{
double x;
int c = 255 * sat;
hue /= 60;
x = (1 - fabs(fmod(hue, 2) - 1)) * 255;
switch((int)hue) {
case 0: p[0] = c; p[1] = x; p[2] = 0; return;
case 1: p[0] = x; p[1] = c; p[2] = 0; return;
case 2: p[0] = 0; p[1] = c; p[2] = x; return;
case 3: p[0] = 0; p[1] = x; p[2] = c; return;
case 4: p[0] = x; p[1] = 0; p[2] = c; return;
case 5: p[0] = c; p[1] = 0; p[2] = x; return;
}
}
int main(void)
{
const int size = 512;
int i, j;
unsigned char *colors = malloc(size * 3);
unsigned char *pix = malloc(size * size * 3), *p;
FILE *fp;
for (i = 0; i < size; i++)
hue_to_rgb(i * 240. / size, i * 1. / size, colors + 3 * i);
for (i = 0, p = pix; i < size; i++)
for (j = 0; j < size; j++, p += 3)
memcpy(p, colors + (i ^ j) * 3, 3);
fp = fopen(, );
fprintf(fp, , size, size);
fwrite(pix, size * size * 3, 1, fp);
fclose(fp);
return 0;
} | 538Munching squares
| 5c
| tkbf4 |
import Data.Numbers.Primes (primes)
import Text.Printf (printf)
merge :: Ord a => [a] -> [a] -> [a]
merge [] b = b
merge a@(x:xs) b@(y:ys) | x < y = x: merge xs b
| otherwise = y: merge a ys
nSmooth :: Integer -> [Integer]
nSmooth p = 1: foldr u [] factors
where
factors = takeWhile (<=p) primes
u n s = r
where r = merge s (map (n*) (1:r))
main :: IO ()
main = do
mapM_ (printf "First 25%d-smooth:\n%s\n\n" <*> showTwentyFive) firstTenPrimes
mapM_
(printf "The 3,000 to 3,202%d-smooth numbers are:\n%s\n\n" <*> showRange1)
firstTenPrimes
mapM_
(printf "The 30,000 to 30,019%d-smooth numbers are:\n%s\n\n" <*> showRange2)
[503, 509, 521]
where
firstTenPrimes = take 10 primes
showTwentyFive = show . take 25 . nSmooth
showRange1 = show . ((<$> [2999 .. 3001]) . (!!) . nSmooth)
showRange2 = show . ((<$> [29999 .. 30018]) . (!!) . nSmooth) | 534N-smooth numbers
| 8haskell
| x2gw4 |
public class MbiusFunction {
public static void main(String[] args) {
System.out.printf("First 199 terms of the mbius function are as follows:%n ");
for ( int n = 1 ; n < 200 ; n++ ) {
System.out.printf("%2d ", mbiusFunction(n));
if ( (n+1) % 20 == 0 ) {
System.out.printf("%n");
}
}
}
private static int MU_MAX = 1_000_000;
private static int[] MU = null; | 533Möbius function
| 9java
| me8ym |
use feature 'fc';
use Unicode::Normalize;
sub natural_sort {
my @items = map {
my $str = fc(NFKD($_));
$str =~ s/\s+/ /;
$str =~ s/|^(?:the|a|an) \b|\p{Nonspacing_Mark}| $//g;
my @fields = $str =~ /(?!\z) ([^0-9]*+) ([0-9]*+)/gx;
[$_, \@fields]
} @_;
return map { $_->[0] } sort {
my @x = @{$a->[1]};
my @y = @{$b->[1]};
my $numeric;
while (@x && @y) {
my ($x, $y) = (shift @x, shift @y);
return (($numeric = !$numeric) ? $x cmp $y : $x <=> $y or next);
}
return @x <=> @y;
} @items;
} | 530Natural sorting
| 2perl
| 7flrh |
(use 'overtone.live)
(definst saw-wave [freq 440 attack 0.01 sustain 0.4 release 0.1 vol 0.4]
(* (env-gen (env-lin attack sustain release) 1 1 0 1 FREE)
(saw freq)
vol))
(defn play [note ms]
(saw-wave (midi->hz note))
(Thread/sleep ms))
(doseq [note (scale:c4:major)] (play note 500)) | 537Musical scale
| 6clojure
| qv5xt |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class NSmoothNumbers {
public static void main(String[] args) {
System.out.printf("show the first 25 n-smooth numbers for n = 2 through n = 29%n");
int max = 25;
List<BigInteger> primes = new ArrayList<>();
for ( int n = 2 ; n <= 29 ; n++ ) {
if ( isPrime(n) ) {
primes.add(BigInteger.valueOf(n));
System.out.printf("The first%d%d-smooth numbers:%n", max, n);
BigInteger[] humble = nSmooth(max, primes.toArray(new BigInteger[0]));
for ( int i = 0 ; i < max ; i++ ) {
System.out.printf("%s ", humble[i]);
}
System.out.printf("%n%n");
}
}
System.out.printf("show three numbers starting with 3,000 for n-smooth numbers for n = 3 through n = 29%n");
int count = 3;
max = 3000 + count - 1;
primes = new ArrayList<>();
primes.add(BigInteger.valueOf(2));
for ( int n = 3 ; n <= 29 ; n++ ) {
if ( isPrime(n) ) {
primes.add(BigInteger.valueOf(n));
System.out.printf("The%d through%d%d-smooth numbers:%n", max-count+1, max, n);
BigInteger[] nSmooth = nSmooth(max, primes.toArray(new BigInteger[0]));
for ( int i = max-count ; i < max ; i++ ) {
System.out.printf("%s ", nSmooth[i]);
}
System.out.printf("%n%n");
}
}
System.out.printf("Show twenty numbers starting with 30,000 n-smooth numbers for n=503 through n=521%n");
count = 20;
max = 30000 + count - 1;
primes = new ArrayList<>();
for ( int n = 2 ; n <= 521 ; n++ ) {
if ( isPrime(n) ) {
primes.add(BigInteger.valueOf(n));
if ( n >= 503 && n <= 521 ) {
System.out.printf("The%d through%d%d-smooth numbers:%n", max-count+1, max, n);
BigInteger[] nSmooth = nSmooth(max, primes.toArray(new BigInteger[0]));
for ( int i = max-count ; i < max ; i++ ) {
System.out.printf("%s ", nSmooth[i]);
}
System.out.printf("%n%n");
}
}
}
}
private static final boolean isPrime(long test) {
if ( test == 2 ) {
return true;
}
if ( test % 2 == 0 ) return false;
for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
if ( test % i == 0 ) {
return false;
}
}
return true;
}
private static BigInteger[] nSmooth(int n, BigInteger[] primes) {
int size = primes.length;
BigInteger[] test = new BigInteger[size];
for ( int i = 0 ; i < size ; i++ ) {
test[i] = primes[i];
}
BigInteger[] results = new BigInteger[n];
results[0] = BigInteger.ONE;
int[] indexes = new int[size];
for ( int i = 0 ; i < size ; i++ ) {
indexes[i] = 0;
}
for ( int index = 1 ; index < n ; index++ ) {
BigInteger min = test[0];
for ( int i = 1 ; i < size ; i++ ) {
min = min.min(test[i]);
}
results[index] = min;
for ( int i = 0 ; i < size ; i++ ) {
if ( results[index].compareTo(test[i]) == 0 ) {
indexes[i] = indexes[i] + 1;
test[i] = primes[i].multiply(results[indexes[i]]);
}
}
}
return results;
}
} | 534N-smooth numbers
| 9java
| b6lk3 |
package main
import (
"fmt"
)
type params struct {x, y, z int}
func myFunc(p params) int {
return p.x + p.y + p.z
}
func main() {
r := myFunc(params{x: 1, y: 2, z: 3}) | 535Named parameters
| 0go
| v0n2m |
import kotlin.math.sqrt
fun main() {
println("First 199 terms of the mbius function are as follows:")
print(" ")
for (n in 1..199) {
print("%2d ".format(mobiusFunction(n)))
if ((n + 1) % 20 == 0) {
println()
}
}
}
private const val MU_MAX = 1000000
private var MU: IntArray? = null | 533Möbius function
| 11kotlin
| tkwf0 |
(ns narcissistic.core
(:require [clojure.math.numeric-tower:as math]))
(defn digits [n]
(->> n str (map (comp read-string str))))
(defn narcissistic? [n]
(let [d (digits n)
s (count d)]
(= n (reduce + (map #(math/expt % s) d)))))
(defn firstNnarc [n]
(take n (filter narcissistic? (range)))) | 536Narcissistic decimal number
| 6clojure
| tk1fv |
function isPrime(n){
var x = Math.floor(Math.sqrt(n)), i = 2
while ((i <= x) && (n % i != 0)) i++
return (x < i)
}
function smooth(n, s, k){
var p = []
for (let i = 2; i <= n; i++){
if (isPrime(i)){
p.push([BigInt(i), [1n], 0])
}
}
var res = []
for (let i = 0; i < s + k; i++){
var m = p[0][1][p[0][2]]
for (let j = 1; j < p.length; j++){
if (p[j][1][p[j][2]] < m) m = p[j][1][p[j][2]]
}
for (let j = 0; j < p.length; j++){
p[j][1].push(p[j][0]*m)
if (p[j][1][p[j][2]] == m) p[j][2]++
}
res.push(m)
}
return res.slice(s-1, s-1+k);
} | 534N-smooth numbers
| 10javascript
| wl4e2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.