code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use strict;
use warnings;
use feature 'say';
use ntheory 'divisors';
my(@x,$n);
do { push(@x,$n) unless $n % scalar(divisors(++$n)) } until 100 == @x;
say "Tau numbers - first 100:\n" .
((sprintf "@{['%5d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr); | 145Tau number
| 2perl
| 0aps4 |
tau :: Integral a => a -> a
tau n | n <= 0 = error "Not a positive integer"
tau n = go 0 (1, 1)
where
yo i = (i, i * i)
go r (i, ii)
| n < ii = r
| n == ii = r + 1
| 0 == mod n i = go (r + 2) (yo $ i + 1)
| otherwise = go r (yo $ i + 1)
main = print $ map tau [1..100] | 147Tau function
| 8haskell
| yd866 |
os.execute( "clear" ) | 151Terminal control/Clear the screen
| 1lua
| 3iezo |
null | 138Ternary logic
| 11kotlin
| rvrgo |
from colorama import init, Fore, Back, Style
init(autoreset=True)
print Fore.RED +
print Back.BLUE + Fore.YELLOW +
print % (Style.BRIGHT, Style.NORMAL)
print Fore.YELLOW +
print Fore.CYAN +
print Fore.GREEN +
print Fore.MAGENTA +
print Back.YELLOW + Fore.BLUE + Style.BRIGHT + * 40 + | 142Terminal control/Coloured text
| 3python
| mftyh |
typedef struct { double x, y; } vec_t, *vec;
inline double dot(vec a, vec b)
{
return a->x * b->x + a->y * b->y;
}
inline double cross(vec a, vec b)
{
return a->x * b->y - a->y * b->x;
}
inline vec vsub(vec a, vec b, vec res)
{
res->x = a->x - b->x;
res->y = a->y - b->y;
return res;
}
int left_of(vec a, vec b, vec c)
{
vec_t tmp1, tmp2;
double x;
vsub(b, a, &tmp1);
vsub(c, b, &tmp2);
x = cross(&tmp1, &tmp2);
return x < 0 ? -1 : x > 0;
}
int line_sect(vec x0, vec x1, vec y0, vec y1, vec res)
{
vec_t dx, dy, d;
vsub(x1, x0, &dx);
vsub(y1, y0, &dy);
vsub(x0, y0, &d);
double dyx = cross(&dy, &dx);
if (!dyx) return 0;
dyx = cross(&d, &dx) / dyx;
if (dyx <= 0 || dyx >= 1) return 0;
res->x = y0->x + dyx * dy.x;
res->y = y0->y + dyx * dy.y;
return 1;
}
typedef struct { int len, alloc; vec v; } poly_t, *poly;
poly poly_new()
{
return (poly)calloc(1, sizeof(poly_t));
}
void poly_free(poly p)
{
free(p->v);
free(p);
}
void poly_append(poly p, vec v)
{
if (p->len >= p->alloc) {
p->alloc *= 2;
if (!p->alloc) p->alloc = 4;
p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);
}
p->v[p->len++] = *v;
}
int poly_winding(poly p)
{
return left_of(p->v, p->v + 1, p->v + 2);
}
void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)
{
int i, side0, side1;
vec_t tmp;
vec v0 = sub->v + sub->len - 1, v1;
res->len = 0;
side0 = left_of(x0, x1, v0);
if (side0 != -left) poly_append(res, v0);
for (i = 0; i < sub->len; i++) {
v1 = sub->v + i;
side1 = left_of(x0, x1, v1);
if (side0 + side1 == 0 && side0)
if (line_sect(x0, x1, v0, v1, &tmp))
poly_append(res, &tmp);
if (i == sub->len - 1) break;
if (side1 != -left) poly_append(res, v1);
v0 = v1;
side0 = side1;
}
}
poly poly_clip(poly sub, poly clip)
{
int i;
poly p1 = poly_new(), p2 = poly_new(), tmp;
int dir = poly_winding(clip);
poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);
for (i = 0; i < clip->len - 1; i++) {
tmp = p2; p2 = p1; p1 = tmp;
if(p1->len == 0) {
p2->len = 0;
break;
}
poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);
}
poly_free(p1);
return p2;
}
int main()
{
int i;
vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};
vec_t s[] = { {50,150}, {200,50}, {350,150},
{350,300},{250,300},{200,250},
{150,350},{100,250},{100,200}};
poly_t clipper = {clen, 0, c};
poly_t subject = {slen, 0, s};
poly res = poly_clip(&subject, &clipper);
for (i = 0; i < res->len; i++)
printf(, res->v[i].x, res->v[i].y);
FILE * eps = fopen(, );
fprintf(eps,
);
fprintf(eps, , c[0].x, c[0].y);
for (i = 1; i < clen; i++)
fprintf(eps, , c[i].x, c[i].y);
fprintf(eps, );
fprintf(eps, , s[0].x, s[0].y);
for (i = 1; i < slen; i++)
fprintf(eps, , s[i].x, s[i].y);
fprintf(eps, );
fprintf(eps, ,
res->v[0].x, res->v[0].y);
for (i = 1; i < res->len; i++)
fprintf(eps, , res->v[i].x, res->v[i].y);
fprintf(eps, );
fprintf(eps, );
fclose(eps);
printf();
return 0;
} | 154Sutherland-Hodgman polygon clipping
| 5c
| dsjnv |
package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
two := big.NewInt(2)
next := new(big.Int)
sylvester := []*big.Int{two}
prod := new(big.Int).Set(two)
count := 1
for count < 10 {
next.Add(prod, one)
sylvester = append(sylvester, new(big.Int).Set(next))
count++
prod.Mul(prod, next)
}
fmt.Println("The first 10 terms in the Sylvester sequence are:")
for i := 0; i < 10; i++ {
fmt.Println(sylvester[i])
}
sumRecip := new(big.Rat)
for _, s := range sylvester {
sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))
}
fmt.Println("\nThe sum of their reciprocals as a rational number is:")
fmt.Println(sumRecip)
fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
fmt.Println(sumRecip.FloatString(211))
} | 155Sylvester's sequence
| 0go
| 9temt |
sylvester :: [Integer]
sylvester = map s [0 ..]
where
s 0 = 2
s n = succ $ foldr ((*) . s) 1 [0 .. pred n]
main :: IO ()
main = do
putStrLn "First 10 elements of Sylvester's sequence:"
putStr $ unlines $ map show $ take 10 sylvester
putStr "\nSum of reciprocals by sum over map: "
print $ sum $ map ((1 /) . fromInteger) $ take 10 sylvester
putStr "Sum of reciprocals by fold: "
print $ foldr ((+) . (1 /) . fromInteger) 0 $ take 10 sylvester | 155Sylvester's sequence
| 8haskell
| bg3k2 |
use std::collections::BTreeSet;
use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
use std::iter::FromIterator;
fn load_dictionary(filename: &str) -> std::io::Result<BTreeSet<String>> {
let file = File::open(filename)?;
let mut dict = BTreeSet::new();
for line in io::BufReader::new(file).lines() {
let word = line?;
dict.insert(word);
}
Ok(dict)
}
fn find_teacup_words(dict: &BTreeSet<String>) {
let mut teacup_words: Vec<&String> = Vec::new();
let mut found: HashSet<&String> = HashSet::new();
for word in dict {
let len = word.len();
if len < 3 || found.contains(word) {
continue;
}
teacup_words.clear();
let mut is_teacup_word = true;
let mut chars: Vec<char> = word.chars().collect();
for _ in 1..len {
chars.rotate_left(1);
if let Some(w) = dict.get(&String::from_iter(&chars)) {
if!w.eq(word) &&!teacup_words.contains(&w) {
teacup_words.push(w);
}
} else {
is_teacup_word = false;
break;
}
}
if!is_teacup_word || teacup_words.is_empty() {
continue;
}
print!("{}", word);
found.insert(word);
for w in &teacup_words {
found.insert(w);
print!(" {}", w);
}
println!();
}
}
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len()!= 2 {
eprintln!("Usage: teacup dictionary");
std::process::exit(1);
}
let dict = load_dictionary(&args[1]);
match dict {
Ok(dict) => find_teacup_words(&dict),
Err(error) => eprintln!("Cannot open file {}: {}", &args[1], error),
}
} | 143Teacup rim text
| 15rust
| juu72 |
import Foundation
func loadDictionary(_ path: String) throws -> Set<String> {
let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
return Set<String>(contents.components(separatedBy: "\n").filter{!$0.isEmpty})
}
func rotate<T>(_ array: inout [T]) {
guard array.count > 1 else {
return
}
let first = array[0]
array.replaceSubrange(0..<array.count-1, with: array[1...])
array[array.count - 1] = first
}
func findTeacupWords(_ dictionary: Set<String>) {
var teacupWords: [String] = []
var found = Set<String>()
for word in dictionary {
if word.count < 3 || found.contains(word) {
continue
}
teacupWords.removeAll()
var isTeacupWord = true
var chars = Array(word)
for _ in 1..<word.count {
rotate(&chars)
let w = String(chars)
if (!dictionary.contains(w)) {
isTeacupWord = false
break
}
if w!= word &&!teacupWords.contains(w) {
teacupWords.append(w)
}
}
if!isTeacupWord || teacupWords.isEmpty {
continue
}
print(word, terminator: "")
found.insert(word)
for w in teacupWords {
found.insert(w)
print(" \(w)", terminator: "")
}
print()
}
}
do {
let dictionary = try loadDictionary("unixdict.txt")
findTeacupWords(dictionary)
} catch {
print(error)
} | 143Teacup rim text
| 17swift
| r22gg |
public class TauFunction {
private static long divisorCount(long n) {
long total = 1; | 147Tau function
| 9java
| dsen9 |
enum class Day {
first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth;
val header = "On the " + this + " day of Christmas, my true love sent to me\n\t"
}
fun main(x: Array<String>) {
val gifts = listOf("A partridge in a pear tree",
"Two turtle doves and",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming")
Day.values().forEachIndexed { i, d -> println(d.header + gifts.slice(0..i).asReversed().joinToString("\n\t")) }
} | 139The Twelve Days of Christmas
| 11kotlin
| 4cu57 |
(defn super [d]
(let [run (apply str (repeat d (str d)))]
(filter #(clojure.string/includes? (str (* d (Math/pow % d ))) run) (range))))
(doseq [d (range 2 9)]
(println (str d ": ") (take 10 (super d)))) | 153Super-d numbers
| 6clojure
| dshnb |
int main(){
double a,b,n,i,incr = 0.0001;
printf();
scanf(,&a,&b);
printf();
scanf(,&n);
initwindow(500,500,);
for(i=0;i<2*pi;i+=incr){
putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);
}
printf(,i);
getch();
closegraph();
} | 156Superellipse
| 5c
| xbcwu |
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
class CubeSum implements Comparable<CubeSum> {
public long x, y, value;
public CubeSum(long x, long y) {
this.x = x;
this.y = y;
this.value = x*x*x + y*y*y;
}
public String toString() {
return String.format("%4d^3 +%4d^3", x, y);
}
public int compareTo(CubeSum that) {
return value < that.value ? -1 : value > that.value ? 1 : 0;
}
}
class SumIterator implements Iterator<CubeSum> {
PriorityQueue<CubeSum> pq = new PriorityQueue<CubeSum>();
long n = 0;
public boolean hasNext() { return true; }
public CubeSum next() {
while (pq.size() == 0 || pq.peek().value >= n*n*n)
pq.add(new CubeSum(++n, 1));
CubeSum s = pq.remove();
if (s.x > s.y + 1) pq.add(new CubeSum(s.x, s.y+1));
return s;
}
}
class TaxiIterator implements Iterator<List<CubeSum>> {
Iterator<CubeSum> sumIterator = new SumIterator();
CubeSum last = sumIterator.next();
public boolean hasNext() { return true; }
public List<CubeSum> next() {
CubeSum s;
List<CubeSum> train = new ArrayList<CubeSum>();
while ((s = sumIterator.next()).value != last.value)
last = s;
train.add(last);
do { train.add(s); } while ((s = sumIterator.next()).value == last.value);
last = s;
return train;
}
}
public class Taxi {
public static final void main(String[] args) {
Iterator<List<CubeSum>> taxi = new TaxiIterator();
for (int i = 1; i <= 2006; i++) {
List<CubeSum> t = taxi.next();
if (i > 25 && i < 2000) continue;
System.out.printf("%4d:%10d", i, t.get(0).value);
for (CubeSum s: t)
System.out.print(" = " + s);
System.out.println();
}
}
} | 144Taxicab numbers
| 9java
| umyvv |
package main
import "fmt"
const max = 12
var (
super []byte
pos int
cnt [max]int
) | 152Superpermutation minimisation
| 0go
| ju37d |
def tau(n):
assert(isinstance(n, int) and 0 < n)
ans, i, j = 0, 1, 1
while i*i <= n:
if 0 == n%i:
ans += 1
j = n
if j != i:
ans += 1
i += 1
return ans
def is_tau_number(n):
assert(isinstance(n, int))
if n <= 0:
return False
return 0 == n%tau(n)
if __name__ == :
n = 1
ans = []
while len(ans) < 100:
if is_tau_number(n):
ans.append(n)
n += 1
print(ans) | 145Tau number
| 3python
| 8e10o |
function divisorCount(n)
local total = 1 | 147Tau function
| 1lua
| 8eb0e |
require 'rubygems'
require 'colored'
print 'Colors are'.bold
print ' black'.black
print ' blue'.blue
print ' cyan'.cyan
print ' green'.green
print ' magenta'.magenta
print ' red'.red
print ' white '.white
print 'and'.underline, ' yellow'.yellow,
puts 'black on blue'.black_on_blue
puts 'black on cyan'.black_on_cyan
puts 'black on green'.black_on_green
puts 'black on magenta'.black_on_magenta
puts 'black on red'.black_on_red
puts 'white on black'.white_on_black
puts 'white on blue'.white_on_blue
puts 'white on cyan'.white_on_cyan
puts 'white on green'.white_on_green
puts 'white on magenta'.white_on_magenta
puts 'white on red'.white_on_red | 142Terminal control/Coloured text
| 14ruby
| cz39k |
use strict;
use warnings;
use feature 'say';
use List::Util 'reduce';
use Math::AnyNum ':overload';
local $Math::AnyNum::PREC = 845;
my(@S,$sum);
push @S, 1 + reduce { $a * $b } @S for 0..10;
shift @S;
$sum += 1/$_ for @S;
say "First 10 elements of Sylvester's sequence: @S";
say "\nSum of the reciprocals of first 10 elements: " . float $sum; | 155Sylvester's sequence
| 2perl
| s1vq3 |
var n3s = [],
s3s = {}
for (var n = 1, e = 1200; n < e; n += 1) n3s[n] = n * n * n
for (var a = 1; a < e - 1; a += 1) {
var a3 = n3s[a]
for (var b = a; b < e; b += 1) {
var b3 = n3s[b]
var s3 = a3 + b3,
abs = s3s[s3]
if (!abs) s3s[s3] = abs = []
abs.push([a, b])
}
}
var i = 0
for (var s3 in s3s) {
var abs = s3s[s3]
if (abs.length < 2) continue
i += 1
if (abs.length == 2 && i > 25 && i < 2000) continue
if (i > 2006) break
document.write(i, ': ', s3)
for (var ab of abs) {
document.write(' = ', ab[0], '<sup>3</sup>+', ab[1], '<sup>3</sup>')
}
document.write('<br>')
} | 144Taxicab numbers
| 10javascript
| 7v2rd |
import static java.util.stream.IntStream.rangeClosed
class Superpermutation {
final static int nMax = 12
static char[] superperm
static int pos
static int[] count = new int[nMax]
static int factSum(int n) {
return rangeClosed(1, n)
.map({ m -> rangeClosed(1, m).reduce(1, { a, b -> a * b }) }).sum()
}
static boolean r(int n) {
if (n == 0) {
return false
}
char c = superperm[pos - n]
if (--count[n] == 0) {
count[n] = n
if (!r(n - 1)) {
return false
}
}
superperm[pos++] = c
return true
}
static void superPerm(int n) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
pos = n
superperm = new char[factSum(n)]
for (int i = 0; i < n + 1; i++) {
count[i] = i
}
for (int i = 1; i < n + 1; i++) {
superperm[i - 1] = chars.charAt(i)
}
while (r(n)) {
}
}
static void main(String[] args) {
for (int n = 0; n < nMax; n++) {
superPerm(n)
printf("superPerm(%2d) len =%d", n, superperm.length)
println()
}
}
} | 152Superpermutation minimisation
| 7groovy
| 59nuv |
tau <- function(t)
{
results <- integer(0)
resultsCount <- 0
n <- 1
while(resultsCount != t)
{
condition <- function(n) (n %% length(c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n))) == 0
if(condition(n))
{
resultsCount <- resultsCount + 1
results[resultsCount] <- n
}
n <- n + 1
}
results
}
tau(100) | 145Tau number
| 13r
| xbhw2 |
system('clear') | 151Terminal control/Clear the screen
| 2perl
| bg9k4 |
const ESC: &str = "\x1B[";
const RESET: &str = "\x1B[0m";
fn main() {
println!("ForegroundBackground--------------------------------------------------------------");
print!(" ");
for i in 40..48 {
print!(" ESC[{}m ", i);
}
println!("\n----------------------------------------------------------------------------------");
for i in 30..38 {
print!("{}ESC[{}m {}{1}m", RESET, i, ESC);
for j in 40..48 {
print!("{}{}m Rosetta ", ESC, j);
}
println!("{}", RESET);
print!("{}ESC[{};1m {}{1};1m", RESET, i, ESC);
for j in 40..48 {
print!("{}{}m Rosetta ", ESC, j);
}
println!("{}", RESET);
}
} | 142Terminal control/Coloured text
| 15rust
| l36cc |
object ColouredText extends App {
val ESC = "\u001B"
val (normal, bold, blink, black, white) =
(ESC + "[0", ESC + "[1"
, ESC + "[5" | 142Terminal control/Coloured text
| 16scala
| um9v8 |
require 'pstore'
require 'set'
Address = Struct.new :id, :street, :city, :state, :zip
db = PStore.new()
db.transaction do
db[:next] ||= 0
db[:ids] ||= Set[]
end | 148Table creation/Postal addresses
| 14ruby
| l3ncl |
package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) {
fmt.Printf("First 10 super-%d numbers:\n", i)
ii := i.Uint64()
k := new(big.Int)
count := 0
inner:
for j := big.NewInt(3); ; j.Add(j, one) {
k.Exp(j, i, nil)
k.Mul(i, k)
ix := strings.Index(k.String(), rd[ii-2])
if ix >= 0 {
count++
fmt.Printf("%d ", j)
if count == 10 {
fmt.Printf("\nfound in%d ms\n\n", time.Since(start).Milliseconds())
break inner
}
}
}
}
} | 153Super-d numbers
| 0go
| umovt |
import Data.List (isInfixOf)
import Data.Char (intToDigit)
isSuperd :: (Show a, Integral a) => a -> a -> Bool
isSuperd p n =
(replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p)
findSuperd :: (Show a, Integral a) => a -> [a]
findSuperd p = filter (isSuperd p) [1 ..]
main :: IO ()
main =
mapM_
(putStrLn .
("First 10 super-" ++) .
((++) . show <*> ((": " ++) . show . take 10 . findSuperd)))
[2 .. 6] | 153Super-d numbers
| 8haskell
| wk2ed |
'''Sylvester's sequence'''
from functools import reduce
from itertools import count, islice
def sylvester():
'''Non-finite stream of the terms
of Sylvester's sequence.
(OEIS A000058)
'''
def go(n):
return 1 + reduce(
lambda a, x: a * go(x),
range(0, n),
1
) if 0 != n else 2
return map(go, count(0))
def main():
'''First terms, and sum of reciprocals.'''
print()
xs = list(islice(sylvester(), 10))
print('\n'.join([
str(x) for x in xs
]))
print()
print(
reduce(lambda a, x: a + 1 / x, xs, 0)
)
if __name__ == '__main__':
main() | 155Sylvester's sequence
| 3python
| 0ausq |
import static java.util.stream.IntStream.rangeClosed;
public class Test {
final static int nMax = 12;
static char[] superperm;
static int pos;
static int[] count = new int[nMax];
static int factSum(int n) {
return rangeClosed(1, n)
.map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();
}
static boolean r(int n) {
if (n == 0)
return false;
char c = superperm[pos - n];
if (--count[n] == 0) {
count[n] = n;
if (!r(n - 1))
return false;
}
superperm[pos++] = c;
return true;
}
static void superPerm(int n) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pos = n;
superperm = new char[factSum(n)];
for (int i = 0; i < n + 1; i++)
count[i] = i;
for (int i = 1; i < n + 1; i++)
superperm[i - 1] = chars.charAt(i);
while (r(n)) {
}
}
public static void main(String[] args) {
for (int n = 0; n < nMax; n++) {
superPerm(n);
System.out.printf("superPerm(%2d) len =%d", n, superperm.length);
System.out.println();
}
}
} | 152Superpermutation minimisation
| 9java
| wkvej |
double kelvinToCelsius(double k){
return k - 273.15;
}
double kelvinToFahrenheit(double k){
return k * 1.8 - 459.67;
}
double kelvinToRankine(double k){
return k * 1.8;
}
void convertKelvin(double kelvin) {
printf(, kelvin);
printf(, kelvinToCelsius(kelvin));
printf(, kelvinToFahrenheit(kelvin));
printf(, kelvinToRankine(kelvin));
}
int main(int argc, const char * argv[])
{
if (argc > 1) {
double kelvin = atof(argv[1]);
convertKelvin(kelvin);
}
return 0;
} | 157Temperature conversion
| 5c
| ydb6f |
local days = {
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth',
}
local gifts = {
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming",
}
local verses = {}
for i = 1, 12 do
local lines = {}
lines[1] = "On the " .. days[i] .. " day of Christmas, my true love gave to me"
local j = i
local k = 2
repeat
lines[k] = gifts[j]
k = k + 1
j = j - 1
until j == 0
verses[i] = table.concat(lines, '\n')
end
print(table.concat(verses, '\n\n')) | 139The Twelve Days of Christmas
| 1lua
| gl54j |
import java.math.BigInteger;
public class SuperDNumbers {
public static void main(String[] args) {
for ( int i = 2 ; i <= 9 ; i++ ) {
superD(i, 10);
}
}
private static final void superD(int d, int max) {
long start = System.currentTimeMillis();
String test = "";
for ( int i = 0 ; i < d ; i++ ) {
test += (""+d);
}
int n = 0;
int i = 0;
System.out.printf("First%d super-%d numbers:%n", max, d);
while ( n < max ) {
i++;
BigInteger val = BigInteger.valueOf(d).multiply(BigInteger.valueOf(i).pow(d));
if ( val.toString().contains(test) ) {
n++;
System.out.printf("%d ", i);
}
}
long end = System.currentTimeMillis();
System.out.printf("%nRun time%d ms%n%n", end-start);
}
} | 153Super-d numbers
| 9java
| k46hm |
package main
import (
"github.com/fogleman/gg"
"math"
)
func superEllipse(dc *gg.Context, n float64, a int) {
hw := float64(dc.Width() / 2)
hh := float64(dc.Height() / 2) | 156Superellipse
| 0go
| l3wcw |
null | 144Taxicab numbers
| 11kotlin
| 9tfmh |
null | 152Superpermutation minimisation
| 11kotlin
| bgmkb |
require 'prime'
taus = Enumerator.new do |y|
(1..).each do |n|
num_divisors = n.prime_division.inject(1){|prod, n| prod *= n[1] + 1 }
y << n if n % num_divisors == 0
end
end
p taus.take(100) | 145Tau number
| 14ruby
| ixeoh |
use strict;
use warnings;
use feature 'say';
use ntheory 'divisors';
my @x;
push @x, scalar divisors($_) for 1..100;
say "Tau function - first 100:\n" .
((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr); | 147Tau function
| 2perl
| 593u2 |
import os
os.system() | 151Terminal control/Clear the screen
| 3python
| prcbm |
cat("\33[2J") | 151Terminal control/Clear the screen
| 13r
| ju678 |
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
lines := make(chan string)
count := make(chan int)
go func() {
c := 0
for l := range lines {
fmt.Println(l)
c++
}
count <- c
}()
f, err := os.Open("input.txt")
if err != nil {
log.Fatal(err)
}
for s := bufio.NewScanner(f); s.Scan(); {
lines <- s.Text()
}
f.Close()
close(lines)
fmt.Println("Number of lines:", <-count)
} | 149Synchronous concurrency
| 0go
| pr2bg |
bool is_prime(int n) {
int i = 5;
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
if (n % i == 0) {
return false;
}
i += 4;
}
return true;
}
int main() {
const int start = 1;
const int stop = 1000;
int sum = 0;
int count = 0;
int sc = 0;
int p;
for (p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf(, count, p, sum);
sc++;
}
}
}
printf(, sc, start, stop);
return 0;
} | 158Summarize primes
| 5c
| vyw2o |
import java.math.BigInteger
fun superD(d: Int, max: Int) {
val start = System.currentTimeMillis()
var test = ""
for (i in 0 until d) {
test += d
}
var n = 0
var i = 0
println("First $max super-$d numbers:")
while (n < max) {
i++
val value: Any = BigInteger.valueOf(d.toLong()) * BigInteger.valueOf(i.toLong()).pow(d)
if (value.toString().contains(test)) {
n++
print("$i ")
}
}
val end = System.currentTimeMillis()
println("\nRun time ${end - start} ms\n")
}
fun main() {
for (i in 2..9) {
superD(i, 10)
}
} | 153Super-d numbers
| 11kotlin
| gld4d |
import Reflex
import Reflex.Dom
import Data.Text (Text, pack, unpack)
import Data.Map (Map, fromList, empty)
import Text.Read (readMaybe)
width = 600
height = 500
type Point = (Float,Float)
type Segment = (Point,Point)
data Ellipse = Ellipse {a :: Float, b :: Float, n :: Float}
toFloat :: Text -> Maybe Float
toFloat = readMaybe.unpack
toEllipse :: Maybe Float -> Maybe Float -> Maybe Float -> Maybe Ellipse
toEllipse (Just a) (Just b) (Just n) =
if a < 1.0 || b <= 1.0 || n <= 0.0
then Nothing
else Just $ Ellipse a b n
toEllipse _ _ _ = Nothing
showError :: Maybe a -> String
showError Nothing = "invalid input"
showError _ = ""
reflect45 pts = pts ++ fmap (\(x,y) -> ( y, x)) (reverse pts)
rotate90 pts = pts ++ fmap (\(x,y) -> ( y, -x)) pts
rotate180 pts = pts ++ fmap (\(x,y) -> (-x, -y)) pts
scale a b = fmap (\(x,y) -> ( a*x, b*y ))
segments pts = zip pts $ tail pts
toLineMap :: Maybe Ellipse -> Map Int ((Float,Float),(Float,Float))
toLineMap (Just (Ellipse a b n)) =
let f p = (1 - p**n)**(1/n)
dp = iterate (*0.9) 1.0
ip = map (\p -> 1.0 -p) dp
points s =
if n > 1.0
then (\p -> zip p (map f p)) ip
else (\p -> zip (map f p) p) dp
in fromList $
zip [0..] $
segments $
scale a b $
rotate180 $
rotate90 $
reflect45 $
takeWhile (\(x,y) -> x < y ) $
points 0.9
toLineMap Nothing = empty
lineAttrs :: Segment -> Map Text Text
lineAttrs ((x1,y1), (x2,y2)) =
fromList [ ( "x1", pack $ show (width/2+x1))
, ( "y1", pack $ show (height/2+y1))
, ( "x2", pack $ show (width/2+x2))
, ( "y2", pack $ show (height/2+y2))
, ( "style", "stroke:brown;stroke-width:2")
]
showLine :: MonadWidget t m => Int -> Dynamic t Segment -> m ()
showLine _ dSegment = do
elSvgns "line" (lineAttrs <$> dSegment) $ return ()
return ()
main = mainWidget $ do
elAttr "h1" ("style" =: "color:brown") $ text "Superellipse"
ta <- el "div" $ do
text "a: "
textInput def { _textInputConfig_initialValue = "200"}
tb <- el "div" $ do
text "b: "
textInput def { _textInputConfig_initialValue = "200"}
tn <- el "div" $ do
text "n: "
textInput def { _textInputConfig_initialValue = "2.5"}
let
ab = zipDynWith toEllipse (toFloat <$> value ta) (toFloat <$> value tb)
dEllipse = zipDynWith ($) ab (toFloat <$> value tn)
dLines = fmap toLineMap dEllipse
dAttrs = constDyn $ fromList
[ ("width" , pack $ show width)
, ("height", pack $ show height)
]
elAttr "div" ("style" =: "color:red") $ dynText $ fmap (pack.showError) dEllipse
el "div" $ elSvgns "svg" dAttrs $ listWithKey dLines showLine
return ()
elSvgns :: forall t m a. MonadWidget t m => Text -> Dynamic t (Map Text Text) -> m a -> m (El t, a)
elSvgns = elDynAttrNS' (Just "http://www.w3.org/2000/svg") | 156Superellipse
| 8haskell
| 176ps |
def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 }
(0..9).each {|n| puts }
puts | 155Sylvester's sequence
| 14ruby
| ow48v |
sums, taxis, limit = {}, {}, 1200
for i = 1, limit do
for j = 1, i-1 do
sum = i^3 + j^3
sums[sum] = sums[sum] or {}
table.insert(sums[sum], i.."^3 + "..j.."^3")
end
end
for k,v in pairs(sums) do
if #v > 1 then table.insert(taxis, { sum=k, num=#v, terms=table.concat(v," = ") }) end
end
table.sort(taxis, function(a,b) return a.sum<b.sum end)
for i=1,2006 do
if i<=25 or i>=2000 or taxis[i].num==3 then
print(string.format("%4d%s:%10d =%s", i, taxis[i].num==3 and "*" or " ", taxis[i].sum, taxis[i].terms))
end
end
print("* n=3") | 144Taxicab numbers
| 1lua
| czt92 |
null | 145Tau number
| 15rust
| nqwi4 |
import Foundation | 145Tau number
| 17swift
| owa8k |
import fileinput
import sys
nodata = 0;
nodata_max=-1;
nodata_maxline=[];
tot_file = 0
num_file = 0
infiles = sys.argv[1:]
for line in fileinput.input():
tot_line=0;
num_line=0;
field = line.split()
date = field[0]
data = [float(f) for f in field[1::2]]
flags = [int(f) for f in field[2::2]]
for datum, flag in zip(data, flags):
if flag<1:
nodata += 1
else:
if nodata_max==nodata and nodata>0:
nodata_maxline.append(date)
if nodata_max<nodata and nodata>0:
nodata_max=nodata
nodata_maxline=[date]
nodata=0;
tot_line += datum
num_line += 1
tot_file += tot_line
num_file += num_line
print % (
date,
len(data) -num_line,
num_line, tot_line,
tot_line/num_line if (num_line>0) else 0)
print
print % (.join(infiles),)
print % (tot_file,)
print % (num_file,)
print % (tot_file / num_file,)
print % (
nodata_max, .join(nodata_maxline)) | 136Text processing/1
| 3python
| c329q |
import Control.Concurrent
import Control.Concurrent.MVar
main =
do lineVar <- newEmptyMVar
countVar <- newEmptyMVar
let takeLine = takeMVar lineVar
putLine = putMVar lineVar . Just
putEOF = putMVar lineVar Nothing
takeCount = takeMVar countVar
putCount = putMVar countVar
forkIO $ writer takeLine putCount
reader putLine putEOF takeCount | 149Synchronous concurrency
| 8haskell
| f0ad1 |
package main
import "fmt"
type point struct {
x, y float32
}
var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}
var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}
func main() {
var cp1, cp2, s, e point
inside := func(p point) bool {
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
}
intersection := func() (p point) {
dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y
dpx, dpy := s.x-e.x, s.y-e.y
n1 := cp1.x*cp2.y - cp1.y*cp2.x
n2 := s.x*e.y - s.y*e.x
n3 := 1 / (dcx*dpy - dcy*dpx)
p.x = (n1*dpx - n2*dcx) * n3
p.y = (n1*dpy - n2*dcy) * n3
return
}
outputList := subjectPolygon
cp1 = clipPolygon[len(clipPolygon)-1]
for _, cp2 = range clipPolygon { | 154Sutherland-Hodgman polygon clipping
| 0go
| 7vfr2 |
const char *A[] = { , , , , };
const char *B[] = { , , , , };
void uniq(const char *x[], int len)
{
int i, j;
for (i = 0; i < len; i++)
for (j = i + 1; j < len; j++)
if (x[j] && x[i] && !strcmp(x[i], x[j])) x[j] = 0;
}
int in_set(const char *const x[], int len, const char *match)
{
int i;
for (i = 0; i < len; i++)
if (x[i] && !strcmp(x[i], match))
return 1;
return 0;
}
void show_diff(const char *const x[], int lenx, const char *const y[], int leny)
{
int i;
for (i = 0; i < lenx; i++)
if (x[i] && !in_set(y, leny, x[i]))
printf(, x[i]);
}
void show_sym_diff(const char *const x[], int lenx, const char *const y[], int leny)
{
show_diff(x, lenx, y, leny);
show_diff(y, leny, x, lenx);
}
int main()
{
uniq(A, LEN(A));
uniq(B, LEN(B));
printf(); show_diff(A, LEN(A), B, LEN(B));
printf(); show_diff(B, LEN(B), A, LEN(A));
printf(); show_sym_diff(A, LEN(A), B, LEN(B));
return 0;
} | 159Symmetric difference
| 5c
| umwv4 |
for d = 2, 5 do
local n, found = 0, {}
local dds = string.rep(d, d)
while #found < 10 do
local dnd = string.format("%15.f", d * n ^ d)
if string.find(dnd, dds) then found[#found+1] = n end
n = n + 1
end
print("super-" .. d .. ": " .. table.concat(found,", "))
end | 153Super-d numbers
| 1lua
| r2fga |
import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new Dimension(650, 650));
setBackground(Color.white);
setFont(new Font("Serif", Font.PLAIN, 18));
}
void drawGrid(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0xEEEEEE));
int w = getWidth();
int h = getHeight();
int spacing = 25;
for (int i = 0; i < w / spacing; i++) {
g.drawLine(0, i * spacing, w, i * spacing);
g.drawLine(i * spacing, 0, i * spacing, w);
}
g.drawLine(0, h - 1, w, h - 1);
g.setColor(new Color(0xAAAAAA));
g.drawLine(0, w / 2, w, w / 2);
g.drawLine(w / 2, 0, w / 2, w);
}
void drawLegend(Graphics2D g) {
g.setColor(Color.black);
g.setFont(getFont());
g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45);
g.drawString("a = b = 200", getWidth() - 150, 75);
}
void drawEllipse(Graphics2D g) {
final int a = 200; | 156Superellipse
| 9java
| 7vnrj |
import BigNumber
func sylvester(n: Int) -> BInt {
var a = BInt(2)
for _ in 0..<n {
a = a * a - a + 1
}
return a
}
var sum = BDouble(0)
for n in 0..<10 {
let syl = sylvester(n: n)
sum += BDouble(1) / BDouble(syl)
print(syl)
}
print("Sum of the reciprocals of first ten in sequence: \(sum)") | 155Sylvester's sequence
| 17swift
| 8e50v |
use ntheory qw/forperm/;
for my $len (1..8) {
my($pre, $post, $t) = ("","");
forperm {
$t = join "",@_;
$post .= $t unless index($post ,$t) >= 0;
$pre = $t . $pre unless index($pre, $t) >= 0;
} $len;
printf "%2d:%8d%8d\n", $len, length($pre), length($post);
} | 152Superpermutation minimisation
| 2perl
| 6ne36 |
def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == :
print([tau(n) for n in range(1,101)]) | 147Tau function
| 3python
| 4c65k |
package Trit;
use Exporter 'import';
our @EXPORT_OK = qw(TRUE FALSE MAYBE is_true is_false is_maybe);
our %EXPORT_TAGS = (
all => \@EXPORT_OK,
const => [qw(TRUE FALSE MAYBE)],
bool => [qw(is_true is_false is_maybe)],
);
use List::Util qw(min max);
use overload
'=' => sub { $_[0]->clone() },
'<=>'=> sub { $_[0]->cmp($_[1]) },
'cmp'=> sub { $_[0]->cmp($_[1]) },
'==' => sub { ${$_[0]} == ${$_[1]} },
'eq' => sub { $_[0]->equiv($_[1]) },
'>' => sub { ${$_[0]} > ${$_[1]} },
'<' => sub { ${$_[0]} < ${$_[1]} },
'>=' => sub { ${$_[0]} >= ${$_[1]} },
'<=' => sub { ${$_[0]} <= ${$_[1]} },
'|' => sub { $_[0]->or($_[1]) },
'&' => sub { $_[0]->and($_[1]) },
'!' => sub { $_[0]->not() },
'~' => sub { $_[0]->not() },
'""' => sub { $_[0]->tostr() },
'0+' => sub { $_[0]->tonum() },
;
sub new
{
my ($class, $v) = @_;
my $ret =
!defined($v) ? 0 :
$v eq 'true' ? 1 :
$v eq 'false'? -1 :
$v eq 'maybe'? 0 :
$v > 0 ? 1 :
$v < 0 ? -1 :
0;
return bless \$ret, $class;
}
sub TRUE() { new Trit( 1) }
sub FALSE() { new Trit(-1) }
sub MAYBE() { new Trit( 0) }
sub clone
{
my $ret = ${$_[0]};
return bless \$ret, ref($_[0]);
}
sub tostr { ${$_[0]} > 0 ? "true" : ${$_[0]} < 0 ? "false" : "maybe" }
sub tonum { ${$_[0]} }
sub is_true { ${$_[0]} > 0 }
sub is_false { ${$_[0]} < 0 }
sub is_maybe { ${$_[0]} == 0 }
sub cmp { ${$_[0]} <=> ${$_[1]} }
sub not { new Trit(-${$_[0]}) }
sub and { new Trit(min(${$_[0]}, ${$_[1]}) ) }
sub or { new Trit(max(${$_[0]}, ${$_[1]}) ) }
sub equiv { new Trit( ${$_[0]} * ${$_[1]} ) } | 138Ternary logic
| 2perl
| d0dnw |
dfr <- read.delim("readings.txt")
flags <- as.matrix(dfr[,seq(3,49,2)])>0
vals <- as.matrix(dfr[,seq(2,49,2)])
daily.means <- rowSums(ifelse(flags, vals, 0))/rowSums(flags)
times <- strptime(dfr[1,1], "%Y-%m-%d", tz="GMT") + 3600*seq(1,24*nrow(dfr),1)
hours.between.good.measurements <- diff(times[t(flags)])/3600 | 136Text processing/1
| 13r
| 6dm3e |
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
class SynchronousConcurrency
{
public static void main(String[] args) throws Exception
{
final AtomicLong lineCount = new AtomicLong(0);
final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
final String EOF = new String();
final Thread writerThread = new Thread(new Runnable() {
public void run()
{
long linesWrote = 0;
while (true)
{
try
{
String line = queue.take(); | 149Synchronous concurrency
| 9java
| 0ajse |
module SuthHodgClip (clipTo) where
import Data.List
type Pt a = (a, a)
type Ln a = (Pt a, Pt a)
type Poly a = [Pt a]
polyFrom ps = last ps: ps
linesFrom pps@(_:ps) = zip pps ps
(.|) :: (Num a, Ord a) => Pt a -> Ln a -> Bool
(x,y) .| ((px,py),(qx,qy)) = (qx-px)*(y-py) >= (qy-py)*(x-px)
(><) :: Fractional a => Ln a -> Ln a -> Pt a
((x1,y1),(x2,y2)) >< ((x3,y3),(x4,y4)) =
let (r,s) = (x1*y2-y1*x2, x3*y4-y3*x4)
(t,u,v,w) = (x1-x2, y3-y4, y1-y2, x3-x4)
d = t*u-v*w
in ((r*w-t*s)/d, (r*u-v*s)/d)
(-|) :: (Fractional a, Ord a) => Ln a -> Ln a -> [Pt a]
ln@(p0, p1) -| clipLn =
case (p0 .| clipLn, p1 .| clipLn) of
(False, False) -> []
(False, True) -> [isect, p1]
(True, False) -> [isect]
(True, True) -> [p1]
where isect = ln >< clipLn
(<|) :: (Fractional a, Ord a) => Poly a -> Ln a -> Poly a
poly <| clipLn = polyFrom $ concatMap (-| clipLn) (linesFrom poly)
clipTo :: (Fractional a, Ord a) => [Pt a] -> [Pt a] -> [Pt a]
targPts `clipTo` clipPts =
let targPoly = polyFrom targPts
clipLines = linesFrom (polyFrom clipPts)
in foldl' (<|) targPoly clipLines | 154Sutherland-Hodgman polygon clipping
| 8haskell
| 8e40z |
package main
import (
"fmt"
"io"
"os"
"strings"
"time"
)
func addNote(fn string, note string) error {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") | 150Take notes on the command line
| 0go
| xb4wf |
var n = 2.5, a = 200, b = 200, ctx;
function point( x, y ) {
ctx.fillRect( x, y, 1, 1);
}
function start() {
var can = document.createElement('canvas');
can.width = can.height = 600;
ctx = can.getContext( "2d" );
ctx.rect( 0, 0, can.width, can.height );
ctx.fillStyle = "#000000"; ctx.fill();
document.body.appendChild( can );
ctx.fillStyle = "#ffffff";
for( var t = 0; t < 1000; t += .1 ) {
x = Math.pow( Math.abs( Math.cos( t ) ), 2 / n ) * a * Math.sign( Math.cos( t ) );
y = Math.pow( Math.abs( Math.sin( t ) ), 2 / n ) * b * Math.sign( Math.sin( t ) );
point( x + ( can.width >> 1 ), y + ( can.height >> 1 ) );
}
} | 156Superellipse
| 10javascript
| pr3b7 |
(defn to-celsius [k]
(- k 273.15))
(defn to-fahrenheit [k]
(- (* k 1.8) 459.67))
(defn to-rankine [k]
(* k 1.8))
(defn temperature-conversion [k]
(if (number? k)
(format "Celsius:%.2f Fahrenheit:%.2f Rankine:%.2f"
(to-celsius k) (to-fahrenheit k) (to-rankine k))
(format "Error: Non-numeric value entered."))) | 157Temperature conversion
| 6clojure
| 26wl1 |
lengths(sapply(1:100, function(n) c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n))) | 147Tau function
| 13r
| 26flg |
system 'clear' | 151Terminal control/Clear the screen
| 14ruby
| aj21s |
print!("\x1B[2J"); | 151Terminal control/Clear the screen
| 15rust
| ehvaj |
object Cls extends App {print("\033[2J")} | 151Terminal control/Clear the screen
| 16scala
| qp4xw |
import java.util.concurrent.SynchronousQueue
import kotlin.concurrent.thread
import java.io.File
const val EOT = "\u0004" | 149Synchronous concurrency
| 11kotlin
| eh5a4 |
typedef struct rec_t rec_t;
struct rec_t {
int depth;
rec_t * p[10];
};
rec_t root = {0, {0}};
rec_t *tail = 0, *head = 0;
inline rec_t *new_rec()
{
if (head == tail) {
head = calloc(sizeof(rec_t), POOL_SIZE);
tail = head + POOL_SIZE;
}
return head++;
}
rec_t *find_rec(char *s)
{
int i;
rec_t *r = &root;
while (*s) {
i = *s++ - '0';
if (!r->p[i]) r->p[i] = new_rec();
r = r->p[i];
}
return r;
}
char number[100][4];
void init()
{
int i;
for (i = 0; i < 100; i++)
sprintf(number[i], , i);
}
void count(char *buf)
{
int i, c[10] = {0};
char *s;
for (s = buf; *s; c[*s++ - '0']++);
for (i = 9; i >= 0; i--) {
if (!c[i]) continue;
s = number[c[i]];
*buf++ = s[0];
if ((*buf = s[1])) buf++;
*buf++ = i + '0';
}
*buf = '\0';
}
int depth(char *in, int d)
{
rec_t *r = find_rec(in);
if (r->depth > 0)
return r->depth;
d++;
if (!r->depth) r->depth = -d;
else r->depth += d;
count(in);
d = depth(in, d);
if (r->depth <= 0) r->depth = d + 1;
return r->depth;
}
int main(void)
{
char a[100];
int i, d, best_len = 0, n_best = 0;
int best_ints[32];
rec_t *r;
init();
for (i = 0; i < 1000000; i++) {
sprintf(a, , i);
d = depth(a, 0);
if (d < best_len) continue;
if (d > best_len) {
n_best = 0;
best_len = d;
}
if (d == best_len)
best_ints[n_best++] = i;
}
printf(, best_len);
for (i = 0; i < n_best; i++) {
printf(, best_ints[i]);
sprintf(a, , best_ints[i]);
for (d = 0; d <= best_len; d++) {
r = find_rec(a);
printf(, r->depth, a);
count(a);
}
putchar('\n');
}
return 0;
} | 160Summarize and say sequence
| 5c
| glq45 |
use strict;
use warnings;
use bigint;
use feature 'say';
sub super {
my $d = shift;
my $run = $d x $d;
my @super;
my $i = 0;
my $n = 0;
while ( $i < 10 ) {
if (index($n ** $d * $d, $run) > -1) {
push @super, $n;
++$i;
}
++$n;
}
@super;
}
say "\nFirst 10 super-$_ numbers:\n", join ' ', super($_) for 2..6; | 153Super-d numbers
| 2perl
| nqjiw |
def notes = new File('./notes.txt')
if (args) {
notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n"
} else {
println notes.text
} | 150Take notes on the command line
| 7groovy
| prlbo |
import System.Environment (getArgs)
import System.Time (getClockTime)
main :: IO ()
main = do
args <- getArgs
if null args
then catch (readFile "notes.txt" >>= putStr)
(\_ -> return ())
else
do ct <- getClockTime
appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "\n" | 150Take notes on the command line
| 8haskell
| ydq66 |
null | 156Superellipse
| 11kotlin
| umsvc |
from __future__ import print_function, division
from itertools import permutations
from math import factorial
import string
import datetime
import gc
MAXN = 7
def s_perm0(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in permutations(allchars)]
sp, tofind = allperms[0], set(allperms[1:])
while tofind:
for skip in range(1, n):
for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):
trial_perm = (sp + trial_add)[-n:]
if trial_perm in tofind:
sp += trial_add
tofind.discard(trial_perm)
trial_add = None
break
if trial_add is None:
break
assert all(perm in sp for perm in allperms)
return sp
def s_perm1(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
nxt = perms.pop()
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def s_perm2(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
nxt = perms.pop(0)
if nxt not in sp:
sp += nxt
if perms:
nxt = perms.pop(-1)
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def _s_perm3(n, cmp):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
lastn = sp[-n:]
nxt = cmp(perms,
key=lambda pm:
sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))
perms.remove(nxt)
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def s_perm3_max(n):
return _s_perm3(n, max)
def s_perm3_min(n):
return _s_perm3(n, min)
longest = [factorial(n) * n for n in range(MAXN + 1)]
weight, runtime = {}, {}
print(__doc__)
for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:
print('\n
print(algo.__doc__)
weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)
for n in range(1, MAXN + 1):
gc.collect()
gc.disable()
t = datetime.datetime.now()
sp = algo(n)
t = datetime.datetime.now() - t
gc.enable()
runtime[algo.__name__] += t
lensp = len(sp)
wt = (lensp / longest[n]) ** 2
print(' For N=%i: SP length%5i Max:%5i Weight:%5.2f'
% (n, lensp, longest[n], wt))
weight[algo.__name__] *= wt
weight[algo.__name__] **= 1 / n
weight[algo.__name__] = 1 / weight[algo.__name__]
print('%*s Overall Weight:%5.2f in%.1f seconds.'
% (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))
print('\n
print('\n'.join('%12s (%.3f)'% kv for kv in
sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))
print('\n
print('\n'.join('%12s (%.3f)'% (k, v.total_seconds()) for k, v in
sorted(runtime.items(), key=lambda keyvalue: keyvalue[1]))) | 152Superpermutation minimisation
| 3python
| ydw6q |
<?php
if (! define('triFalse',0)) trigger_error('Unknown error defining!', E_USER_ERROR);
if (! define('triMaybe',1)) trigger_error('Unknown error defining!', E_USER_ERROR);
if (! define('triTrue', 2)) trigger_error('Unknown error defining!', E_USER_ERROR);
$triNotarray = array(triFalse=>triTrue, triMaybe=>triMaybe, triTrue=>triFalse);
function triString ($tri) {
if ($tri===triFalse) return 'false ';
if ($tri===triMaybe) return 'unknown';
if ($tri===triTrue) return 'true ';
trigger_error('triString: parameter not a tri value', E_USER_ERROR);
}
function triAnd() {
if (func_num_args() < 2)
trigger_error('triAnd needs 2 or more parameters', E_USER_ERROR);
return min(func_get_args());
}
function triOr() {
if (func_num_args() < 2)
trigger_error('triOr needs 2 or more parameters', E_USER_ERROR);
return max(func_get_args());
}
function triNot($t) {
global $triNotarray;
if (in_array($t, $triNotarray)) return $triNotarray[$t];
trigger_error('triNot: Parameter is not a tri value', E_USER_ERROR);
}
function triImplies($a, $b) {
if ($a===triFalse || $b===triTrue) return triTrue;
if ($a===triMaybe || $b===triMaybe) return triMaybe;
if ($a===triTrue && $b===triFalse) return triFalse;
trigger_error('triImplies: parameter type error', E_USER_ERROR);
}
function triEquiv($a, $b) {
if ($a===triTrue) return $b;
if ($a===triMaybe) return $a;
if ($a===triFalse) return triNot($b);
trigger_error('triEquiv: parameter type error', E_USER_ERROR);
}
printf();
foreach ([triTrue,triMaybe,triFalse] as $a) {
foreach ([triTrue,triMaybe,triFalse] as $b) {
printf(,
triString($a), triString($b), triString(triEquiv($a, $b)));
}
} | 138Ternary logic
| 12php
| j5j7z |
function ReadFile()
local fp = io.open( "input.txt" )
assert( fp ~= nil )
for line in fp:lines() do
coroutine.yield( line )
end
fp:close()
end
co = coroutine.create( ReadFile )
while true do
local status, val = coroutine.resume( co )
if coroutine.status( co ) == "dead" then break end
print( val )
end | 149Synchronous concurrency
| 1lua
| wk4ea |
package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum, n, c := 0, 0, 0
fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:")
fmt.Println(" n cumulative sum")
for _, p := range primes {
n++
sum += p
if rcu.IsPrime(sum) {
c++
fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum))
}
}
fmt.Println()
fmt.Println(c, "such prime sums found")
} | 158Summarize primes
| 0go
| s1cqa |
import Data.List (scanl)
import Data.Numbers.Primes (isPrime, primes)
indexedPrimeSums :: [(Integer, Integer, Integer)]
indexedPrimeSums =
filter (\(_, _, n) -> isPrime n) $
scanl
(\(i, _, m) p -> (succ i, p, p + m))
(0, 0, 0)
primes
main :: IO ()
main =
mapM_ print $
takeWhile (\(_, p, _) -> 1000 > p) indexedPrimeSums | 158Summarize primes
| 8haskell
| 9tpmo |
import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class SutherlandHodgman extends JFrame {
SutherlandHodgmanPanel panel;
public static void main(String[] args) {
JFrame f = new SutherlandHodgman();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public SutherlandHodgman() {
Container content = getContentPane();
content.setLayout(new BorderLayout());
panel = new SutherlandHodgmanPanel();
content.add(panel, BorderLayout.CENTER);
setTitle("SutherlandHodgman");
pack();
setLocationRelativeTo(null);
}
}
class SutherlandHodgmanPanel extends JPanel {
List<double[]> subject, clipper, result;
public SutherlandHodgmanPanel() {
setPreferredSize(new Dimension(600, 500)); | 154Sutherland-Hodgman polygon clipping
| 9java
| ehca5 |
(use '[clojure.set])
(defn symmetric-difference [s1 s2]
(union (difference s1 s2) (difference s2 s1)))
(symmetric-difference #{:john:bob:mary:serena} #{:jim:mary:john:bob}) | 159Symmetric difference
| 6clojure
| 7v8r0 |
from itertools import islice, count
def superd(d):
if d != int(d) or not 2 <= d <= 9:
raise ValueError()
tofind = str(d) * d
for n in count(2):
if tofind in str(d * n ** d):
yield n
if __name__ == '__main__':
for d in range(2, 9):
print(f, ', '.join(str(n) for n in islice(superd(d), 10))) | 153Super-d numbers
| 3python
| dshn1 |
library(Rmpfr)
options(scipen = 999)
find_super_d_number <- function(d, N = 10){
super_number <- c(NA)
n = 0
n_found = 0
while(length(super_number) < N){
n = n + 1
test = d * mpfr(n, precBits = 200) ** d
test_formatted = .mpfr2str(test)$str
iterable = strsplit(test_formatted, "")[[1]]
if (length(iterable) < d) next
for(i in d:length(iterable)){
if (iterable[i]!= d) next
equalities = 0
for(j in 1:d) {
if (i == j) break
if(iterable[i] == iterable[i-j])
equalities = equalities + 1
else break
}
if (equalities >= (d-1)) {
n_found = n_found + 1
super_number[n_found] = n
break
}
}
}
message(paste0("First ", N, " super-", d, " numbers:"))
print((super_number))
return(super_number)
}
for(d in 2:6){find_super_d_number(d, N = 10)} | 153Super-d numbers
| 13r
| 8eg0x |
my($beg, $end) = (@ARGV==0) ? (1,25) : (@ARGV==1) ? (1,shift) : (shift,shift);
my $lim = 1e14;
my @basis = map { $_*$_*$_ } (1 .. int($lim ** (1.0/3.0) + 1));
my $paira = 2;
my ($segsize, $low, $high, $i) = (500_000_000, 0, 0, 0);
while ($i < $end) {
$low = $high+1;
die "lim too low" if $low > $lim;
$high = $low + $segsize - 1;
$high = $lim if $high > $lim;
foreach my $p (_find_pairs_segment(\@basis, $paira, $low, $high,
sub { sprintf("%4d^3 +%4d^3", $_[0], $_[1]) }) ) {
$i++;
next if $i < $beg;
last if $i > $end;
my $n = shift @$p;
printf "%4d:%10d =%s\n", $i, $n, join(" = ", @$p);
}
}
sub _find_pairs_segment {
my($p, $len, $start, $end, $formatsub) = @_;
my $plen = $
my %allpairs;
foreach my $i (0 .. $plen) {
my $pi = $p->[$i];
next if ($pi+$p->[$plen]) < $start;
last if (2*$pi) > $end;
foreach my $j ($i .. $plen) {
my $sum = $pi + $p->[$j];
next if $sum < $start;
last if $sum > $end;
push @{ $allpairs{$sum} }, $i, $j;
}
}
my @retlist;
foreach my $list (grep { scalar @$_ >= $len*2 } values %allpairs) {
my $n = $p->[$list->[0]] + $p->[$list->[1]];
my @pairlist;
while (@$list) {
push @pairlist, $formatsub->(1 + shift @$list, 1 + shift @$list);
}
push @retlist, [$n, @pairlist];
}
@retlist = sort { $a->[0] <=> $b->[0] } @retlist;
return @retlist;
} | 144Taxicab numbers
| 2perl
| wkhe6 |
require 'prime'
def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1}
(1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join} | 147Tau function
| 14ruby
| r2mgs |
null | 147Tau function
| 15rust
| 7v9rc |
(defmacro reduce-with
"simplifies form of reduce calls"
[bindings & body]
(assert (and (vector? bindings) (= 4 (count bindings))))
(let [[acc init, item sequence] bindings]
`(reduce (fn [~acc ~item] ~@body) ~init ~sequence)))
(defn digits
"maps e.g. 2345 => [2 3 4 5]"
[n] (->> n str seq (map #(- (int %) (int \0))) vec))
(defn dcount
"handles case (probably impossible in this range) of digit count > 9"
[ds] (let [c (count ds)] (if (< c 10) c (digits c))))
(defn summarize-prev
"produces the summary sequence for a digit sequence"
[ds]
(->> ds (sort >) (partition-by identity) (map (juxt dcount first)) flatten vec)
(defn convergent-sequence
"iterates summarize-prev until a duplicate is found
[ds]
(reduce-with [cur-seq [], ds (iterate summarize-prev ds)]
(if (some #{ds} cur-seq)
(reduced cur-seq)
(conj cur-seq ds))))
(defn candidate-seq
"only try an already sorted digit sequence, so we only try equivalent seeds once
e.g. 23 => []
[n]
(let [ds (digits n)]
(if (apply >= ds) (convergent-sequence ds) [])))
(defn find-longest
"the meat of the task
[limit]
(reduce-with [max-seqs [[]], new-seq (map candidate-seq (range 1 limit))]
(let [cmp (compare (-> max-seqs first count) (count new-seq))]
(cond
(pos? cmp) max-seqs
(neg? cmp) [new-seq]
(zero? cmp) (conj max-seqs new-seq)))))
(def results (find-longest 1000000)) | 160Summarize and say sequence
| 6clojure
| k4ihs |
<html>
<head>
<script>
function clip (subjectPolygon, clipPolygon) {
var cp1, cp2, s, e;
var inside = function (p) {
return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]);
};
var intersection = function () {
var dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ],
dp = [ s[0] - e[0], s[1] - e[1] ],
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0],
n2 = s[0] * e[1] - s[1] * e[0],
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]);
return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3];
};
var outputList = subjectPolygon;
cp1 = clipPolygon[clipPolygon.length-1];
for (var j in clipPolygon) {
cp2 = clipPolygon[j];
var inputList = outputList;
outputList = [];
s = inputList[inputList.length - 1]; | 154Sutherland-Hodgman polygon clipping
| 10javascript
| 0a5sz |
(2..8).each do |d|
rep = d.to_s * d
print
puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join()
end | 153Super-d numbers
| 14ruby
| t8bf2 |
import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
ps.print("\t" + args[0]);
for (int i = 1; i < args.length; i++)
ps.print(" " + args[i]);
ps.println();
ps.close();
} else {
FileChannel fc = new FileInputStream("notes.txt").getChannel();
fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
fc.close();
}
}
} | 150Take notes on the command line
| 9java
| dspn9 |
local abs,cos,floor,pi,pow,sin = math.abs,math.cos,math.floor,math.pi,math.pow,math.sin
local bitmap = {
init = function(self, w, h, value)
self.w, self.h, self.pixels = w, h, {}
for y=1,h do self.pixels[y]={} end
self:clear(value)
end,
clear = function(self, value)
for y=1,self.h do
for x=1,self.w do
self.pixels[y][x] = value or " "
end
end
end,
set = function(self, x, y, value)
x,y = floor(x+0.5),floor(y+0.5)
if x>0 and y>0 and x<=self.w and y<=self.h then
self.pixels[y][x] = value or "#"
end
end,
superellipse = function(self, ox, oy, n, a, b, c)
local function sgn(n) return n>=0 and 1 or -1 end
for t = 0, 1, 0.002 do
local theta = t * 2 * pi
local x = ox + a * pow(abs(cos(theta)), 2/n) * sgn(cos(theta))
local y = oy + b * pow(abs(sin(theta)), 2/n) * sgn(sin(theta))
self:set(x, y, c)
end
end,
render = function(self)
for y=1,self.h do
print(table.concat(self.pixels[y]))
end
end,
}
bitmap:init(80, 60, "..")
bitmap:superellipse(40, 30, 2.5, 38, 28, "[]")
bitmap:render() | 156Superellipse
| 1lua
| 590u6 |
import Foundation | 147Tau function
| 17swift
| gly49 |
filename =
total = { => 0, => 0, => 0.0 }
invalid_count = 0
max_invalid_count = 0
invalid_run_end =
File.new(filename).each do |line|
num_readings = 0
num_good_readings = 0
sum_readings = 0.0
fields = line.split
fields[1..-1].each_slice(2) do |reading, flag|
num_readings += 1
if Integer(flag) > 0
num_good_readings += 1
sum_readings += Float(reading)
invalid_count = 0
else
invalid_count += 1
if invalid_count > max_invalid_count
max_invalid_count = invalid_count
invalid_run_end = fields[0]
end
end
end
printf ,
fields[0], num_readings - num_good_readings, num_good_readings, sum_readings,
num_good_readings > 0? sum_readings/num_good_readings: 0.0
total[] += num_readings
total[] += num_good_readings
total[] += sum_readings
end
puts
puts
printf , total['sum_readings']
puts
printf , total['sum_readings']/total['num_good_readings']
puts
puts | 136Text processing/1
| 14ruby
| 2yulw |
use v5.10;
my @days = qw{ first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth };
chomp ( my @gifts = grep { /\S/ } <DATA> );
while ( my $day = shift @days ) {
say "On the $day day of Christmas,\nMy true love gave to me:";
say for map { $day eq 'first' ? s/And a/A/r : $_ } @gifts[@days .. @gifts-1];
say "";
}
__DATA__
Twelve drummers drumming
Eleven pipers piping
Ten lords a-leaping
Nine ladies dancing
Eight maids a-milking
Seven swans a-swimming
Six geese a-laying
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree. | 139The Twelve Days of Christmas
| 2perl
| ix8o3 |
use strict;
use warnings;
use ntheory <nth_prime is_prime>;
my($n, $s, $limit, @sums) = (0, 0, 1000);
do {
push @sums, sprintf '%3d%8d', $n, $s if is_prime($s += nth_prime ++$n)
} until $n >= $limit;
print "Of the first $limit primes: @{[scalar @sums]} cumulative prime sums:\n", join "\n", @sums; | 158Summarize primes
| 2perl
| gl04e |
null | 154Sutherland-Hodgman polygon clipping
| 11kotlin
| k43h3 |
null | 153Super-d numbers
| 15rust
| zopto |
import BigInt
import Foundation
let rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]
for d in 2...9 {
print("First 10 super-\(d) numbers:")
var count = 0
var n = BigInt(3)
var k = BigInt(0)
while true {
k = n.power(d)
k *= BigInt(d)
if let _ = String(k).range(of: rd[d - 2]) {
count += 1
print(n, terminator: " ")
fflush(stdout)
guard count < 10 else {
break
}
}
n += 1
}
print()
print()
} | 153Super-d numbers
| 17swift
| f0kdk |
var notes = 'NOTES.TXT';
var args = WScript.Arguments;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2, ForAppending = 8;
if (args.length == 0) {
if (fso.FileExists(notes)) {
var f = fso.OpenTextFile(notes, ForReading);
WScript.Echo(f.ReadAll());
f.Close();
}
}
else {
var f = fso.OpenTextFile(notes, ForAppending, true);
var d = new Date();
f.WriteLine(d.toLocaleString());
f.Write("\t"); | 150Take notes on the command line
| 10javascript
| 6nx38 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.