code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
l = []
(1..6).each{|e|
a, i = [], e-2
(0..l.length-e+1).each{|g|
if not (n = l[g..g+e-2]).uniq!
a.concat(n[(a[0]? i: 0)..-1]).push(e).concat(n)
i = e-2
else
i -= 1
end
}
a.each{|n| print n}; puts
l = a
} | 152Superpermutation minimisation
| 14ruby
| 9tqmz |
object SuperpermutationMinimisation extends App {
val nMax = 12
@annotation.tailrec
def factorial(number: Int, acc: Long = 1): Long =
if (number == 0) acc else factorial(number - 1, acc * number)
def factSum(n: Int): Long = (1 to n).map(factorial(_)).sum
for (n <- 0 until nMax) println(f"superPerm($n%2d) len = ${factSum(n)}%d")
} | 152Superpermutation minimisation
| 16scala
| vyo2s |
object DataMunging {
import scala.io.Source
def spans[A](list: List[A]) = list.tail.foldLeft(List((list.head, 1))) {
case ((a, n) :: tail, b) if a == b => (a, n + 1) :: tail
case (l, b) => (b, 1) :: l
}
type Flag = ((Boolean, Int), String)
type Flags = List[Flag]
type LineIterator = Iterator[Option[(Double, Int, Flags)]]
val pattern = """^(\d+-\d+-\d+)""" + """\s+(\d+\.\d+)\s+(-?\d+)""" * 24 + "$" r;
def linesIterator(file: java.io.File) = Source.fromFile(file).getLines().map(
pattern findFirstMatchIn _ map (
_.subgroups match {
case List(date, rawData @ _*) =>
val dataset = (rawData map (_ toDouble) iterator) grouped 2 toList;
val valid = dataset filter (_.last > 0) map (_.head)
val validSize = valid length;
val validSum = valid sum;
val flags = spans(dataset map (_.last > 0)) map ((_, date))
println("Line:%11s Reject:%2d Accept:%2d Line_tot:%10.3f Line_avg:%10.3f" format
(date, 24 - validSize, validSize, validSum, validSum / validSize))
(validSum, validSize, flags)
}
)
)
def totalizeLines(fileIterator: LineIterator) =
fileIterator.foldLeft(0.0, 0, List[Flag]()) {
case ((totalSum, totalSize, ((flag, size), date) :: tail), Some((validSum, validSize, flags))) =>
val ((firstFlag, firstSize), _) = flags.last
if (firstFlag == flag) {
(totalSum + validSum, totalSize + validSize, flags.init ::: ((flag, size + firstSize), date) :: tail)
} else {
(totalSum + validSum, totalSize + validSize, flags ::: ((flag, size), date) :: tail)
}
case ((_, _, Nil), Some(partials)) => partials
case (totals, None) => totals
}
def main(args: Array[String]) {
val files = args map (new java.io.File(_)) filter (file => file.isFile && file.canRead)
val lines = files.iterator flatMap linesIterator
val (totalSum, totalSize, flags) = totalizeLines(lines)
val ((_, invalidCount), startDate) = flags.filter(!_._1._1).max
val report = """|
|File(s) =%s
|Total =%10.3f
|Readings =%6d
|Average =%10.3f
|
|Maximum run(s) of%d consecutive false readings began at%s""".stripMargin
println(report format (files mkString " ", totalSum, totalSize, totalSum / totalSize, invalidCount, startDate))
}
} | 136Text processing/1
| 16scala
| 4lr50 |
'''Prime sums of primes up to 1000'''
from itertools import accumulate, chain, takewhile
def primeSums():
'''Non finite stream of enumerated tuples,
in which the first value is a prime,
and the second the sum of that prime and all
preceding primes.
'''
return (
x for x in enumerate(
accumulate(
chain([(0, 0)], primes()),
lambda a, p: (p, p + a[1])
)
) if isPrime(x[1][1])
)
def main():
'''Prime sums of primes below 1000'''
for x in takewhile(
lambda t: 1000 > t[1][0],
primeSums()
):
print(f'{x[0]} -> {x[1][1]}')
def isPrime(n):
'''True if n is prime.'''
if n in (2, 3):
return True
if 2 > n or 0 == n% 2:
return False
if 9 > n:
return True
if 0 == n% 3:
return False
def p(x):
return 0 == n% x or 0 == n% (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def primes():
''' Non finite sequence of prime numbers.
'''
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
if __name__ == '__main__':
main() | 158Summarize primes
| 3python
| r28gq |
subjectPolygon = {
{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}
}
clipPolygon = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}
function inside(p, cp1, cp2)
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
end
function intersection(cp1, cp2, s, e)
local dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y
local dpx, dpy = s.x-e.x, s.y-e.y
local n1 = cp1.x*cp2.y - cp1.y*cp2.x
local n2 = s.x*e.y - s.y*e.x
local n3 = 1 / (dcx*dpy - dcy*dpx)
local x = (n1*dpx - n2*dcx) * n3
local y = (n1*dpy - n2*dcy) * n3
return {x=x, y=y}
end
function clip(subjectPolygon, clipPolygon)
local outputList = subjectPolygon
local cp1 = clipPolygon[#clipPolygon]
for _, cp2 in ipairs(clipPolygon) do | 154Sutherland-Hodgman polygon clipping
| 1lua
| bg6ka |
null | 150Take notes on the command line
| 11kotlin
| 0a7sf |
from collections import defaultdict
from itertools import product
from pprint import pprint as pp
cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
taxied = sorted((k, v) for k,v in sum2cubes.items() if len(v) >= 2)
for t in enumerate(taxied[:25], 1):
pp(t)
print('...')
for t in enumerate(taxied[2000-1:2000+6], 2000):
pp(t) | 144Taxicab numbers
| 3python
| xbkwr |
class Trit(int):
def __new__(cls, value):
if value == 'TRUE':
value = 1
elif value == 'FALSE':
value = 0
elif value == 'MAYBE':
value = -1
return super(Trit, cls).__new__(cls, value
def __repr__(self):
if self > 0:
return 'TRUE'
elif self == 0:
return 'FALSE'
return 'MAYBE'
def __str__(self):
return repr(self)
def __bool__(self):
if self > 0:
return True
elif self == 0:
return False
else:
raise ValueError(% self)
def __or__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][1]
else:
try:
return _ttable[(self, Trit(bool(other)))][1]
except:
return NotImplemented
def __ror__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][1]
else:
try:
return _ttable[(self, Trit(bool(other)))][1]
except:
return NotImplemented
def __and__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][0]
else:
try:
return _ttable[(self, Trit(bool(other)))][0]
except:
return NotImplemented
def __rand__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][0]
else:
try:
return _ttable[(self, Trit(bool(other)))][0]
except:
return NotImplemented
def __xor__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][2]
else:
try:
return _ttable[(self, Trit(bool(other)))][2]
except:
return NotImplemented
def __rxor__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][2]
else:
try:
return _ttable[(self, Trit(bool(other)))][2]
except:
return NotImplemented
def __invert__(self):
return _ttable[self]
def __getattr__(self, name):
if name in ('_n', 'flip'):
return _ttable[self]
else:
raise AttributeError
TRUE, FALSE, MAYBE = Trit(1), Trit(0), Trit(-1)
_ttable = {
TRUE: FALSE,
FALSE: TRUE,
MAYBE: MAYBE,
(MAYBE, MAYBE): (MAYBE, MAYBE, MAYBE),
(MAYBE, FALSE): (FALSE, MAYBE, MAYBE),
(MAYBE, TRUE): (MAYBE, TRUE, MAYBE),
(FALSE, MAYBE): (FALSE, MAYBE, MAYBE),
(FALSE, FALSE): (FALSE, FALSE, FALSE),
(FALSE, TRUE): (FALSE, TRUE, TRUE),
( TRUE, MAYBE): (MAYBE, TRUE, MAYBE),
( TRUE, FALSE): (FALSE, TRUE, TRUE),
( TRUE, TRUE): ( TRUE, TRUE, FALSE),
}
values = ('FALSE', 'TRUE ', 'MAYBE')
print()
for a in values:
expr = '~%s'% a
print(' %s =%s'% (expr, eval(expr)))
for op, ophelp in (('&', 'and'), ('|', 'or'), ('^', 'exclusive-or')):
print(% (ophelp, op))
for a in values:
for b in values:
expr = '%s%s%s'% (a, op, b)
print(' %s =%s'% (expr, eval(expr))) | 138Ternary logic
| 3python
| f8fde |
<?php
header();
$days = array(
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth',
);
$gifts = array(
,
,
,
,
,
,
,
,
,
,
,
);
$verses = [];
for ( $i = 0; $i < 12; $i++ ) {
$lines = [];
$lines[0] = ;
$j = $i;
$k = 0;
while ( $j >= 0 ) {
$lines[++$k] = $gifts[$j];
$j--;
}
$verses[$i] = implode(PHP_EOL, $lines);
if ( $i == 0 )
$gifts[0] = ;
}
echo implode(PHP_EOL . PHP_EOL, $verses);
?> | 139The Twelve Days of Christmas
| 12php
| r24ge |
filename = "NOTES.TXT"
if #arg == 0 then
fp = io.open( filename, "r" )
if fp ~= nil then
print( fp:read( "*all*" ) )
fp:close()
end
else
fp = io.open( filename, "a+" )
fp:write( os.date( "%x%X\n" ) )
fp:write( "\t" )
for i = 1, #arg do
fp:write( arg[i], " " )
end
fp:write( "\n" )
fp:close()
end | 150Take notes on the command line
| 1lua
| 8ej0e |
my $a = 200;
my $b = 200;
my $n = 2.5;
sub y_from_x {
my($x) = @_;
int $b * abs(1 - ($x / $a) ** $n ) ** (1/$n)
}
push @q, $_, y_from_x($_) for 0..200;
open $fh, '>', 'superellipse.svg';
print $fh
qq|<svg height="@{[2*$b]}" width="@{[2*$a]}" xmlns="http://www.w3.org/2000/svg">\n|,
pline( 1, 1, @q ),
pline( 1,-1, @q ),
pline(-1,-1, @q ),
pline(-1, 1, @q ),
'</svg>';
sub pline {
my($sx,$sy,@q) = @_;
for (0..$
$q[ 2*$_] *= $sx;
$q[1+2*$_] *= $sy;
}
qq|<polyline points="@{[join ' ',@q]}"
style="fill:none;stroke:black;stroke-width:3"
transform="translate($a, $b)" />\n|
} | 156Superellipse
| 2perl
| 8eu0w |
import Foundation
let fmtDbl = { String(format: "%10.3f", $0) }
Task.detached {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let (data, _) = try await URLSession.shared.bytes(from: URL(fileURLWithPath: CommandLine.arguments[1]))
var rowStats = [(Date, Double, Int)]()
var invalidPeriods = 0
var invalidStart: Date?
var sumFile = 0.0
var readings = 0
var longestInvalid = 0
var longestInvalidStart: Date?
var longestInvalidEnd: Date?
for try await line in data.lines {
let lineSplit = line.components(separatedBy: "\t")
guard!lineSplit.isEmpty, let date = formatter.date(from: lineSplit[0]) else {
fatalError("Invalid date \(lineSplit[0])")
}
let data = Array(lineSplit.dropFirst())
let parsed = stride(from: 0, to: data.endIndex, by: 2).map({idx -> (Double, Int) in
let slice = data[idx..<idx+2]
return (Double(slice[idx])?? 0, Int(slice[idx+1])?? 0)
})
var sum = 0.0
var numValid = 0
for (val, flag) in parsed {
if flag <= 0 {
if invalidStart == nil {
invalidStart = date
}
invalidPeriods += 1
} else {
if invalidPeriods > longestInvalid {
longestInvalid = invalidPeriods
longestInvalidStart = invalidStart
longestInvalidEnd = date
}
sumFile += val
sum += val
numValid += 1
readings += 1
invalidPeriods = 0
invalidStart = nil
}
}
if numValid!= 0 {
rowStats.append((date, sum / Double(numValid), parsed.count - numValid))
}
}
for stat in rowStats.lazy.reversed().prefix(5) {
print("\(stat.0): Average: \(fmtDbl(stat.1)); Valid Readings: \(24 - stat.2); Invalid Readings: \(stat.2)")
}
print("""
Sum File: \(fmtDbl(sumFile))
Average: \(fmtDbl(sumFile / Double(readings)))
Readings: \(readings)
Longest Invalid: \(longestInvalid) (\(longestInvalidStart!) - \(longestInvalidEnd!))
""")
exit(0)
}
dispatchMain() | 136Text processing/1
| 17swift
| l6vc2 |
int main(){
time_t my_time = time(NULL);
printf(, ctime(&my_time));
return 0;
} | 161System time
| 5c
| 26plo |
def isPrime(n)
if n < 2 then
return false
end
if n % 2 == 0 then
return n == 2
end
if n % 3 == 0 then
return n == 3
end
i = 5
while i * i <= n
if n % i == 0 then
return false
end
i += 2
if n % i == 0 then
return false
end
i += 4
end
return true
end
START = 1
STOP = 1000
sum = 0
count = 0
sc = 0
for p in START .. STOP
if isPrime(p) then
count += 1
sum += p
if isPrime(sum) then
print % [count, p, sum]
sc += 1
end
end
end
print % [sc, START, STOP] | 158Summarize primes
| 14ruby
| jui7x |
null | 158Summarize primes
| 15rust
| h5nj2 |
use threads;
use Thread::Queue qw();
my $q1 = Thread::Queue->new;
my $q2 = Thread::Queue->new;
my $reader = threads->create(sub {
my $q1 = shift;
my $q2 = shift;
open my $fh, '<', 'input.txt';
$q1->enqueue($_) while <$fh>;
close $fh;
$q1->enqueue(undef);
print $q2->dequeue;
}, $q1, $q2);
my $printer = threads->create(sub {
my $q1 = shift;
my $q2 = shift;
my $count;
while (my $line = $q1->dequeue) {
print $line;
$count++;
};
$q2->enqueue($count);
}, $q1, $q2);
$reader->join;
$printer->join; | 149Synchronous concurrency
| 2perl
| czo9a |
def taxicab_number(nmax=1200)
[*1..nmax].repeated_combination(2).group_by{|x,y| x**3 + y**3}.select{|k,v| v.size>1}.sort
end
t = [0] + taxicab_number
[*1..25, *2000...2007].each do |i|
puts % [i, t[i][0]] + t[i][1].map{|a| % a}.join
end | 144Taxicab numbers
| 14ruby
| s1pqw |
(import '[java.util Date])
(print (new Date))
(print (. (new Date) getTime))
(print (System/currentTimeMillis)) | 161System time
| 6clojure
| glx4f |
use strict;
use warnings;
sub intersection {
my($L11, $L12, $L21, $L22) = @_;
my ($d1x, $d1y) = ($$L11[0] - $$L12[0], $$L11[1] - $$L12[1]);
my ($d2x, $d2y) = ($$L21[0] - $$L22[0], $$L21[1] - $$L22[1]);
my $n1 = $$L11[0] * $$L12[1] - $$L11[1] * $$L12[0];
my $n2 = $$L21[0] * $$L22[1] - $$L21[1] * $$L22[0];
my $n3 = 1 / ($d1x * $d2y - $d2x * $d1y);
[($n1 * $d2x - $n2 * $d1x) * $n3, ($n1 * $d2y - $n2 * $d1y) * $n3]
}
sub is_inside {
my($p1, $p2, $p3) = @_;
($$p2[0] - $$p1[0]) * ($$p3[1] - $$p1[1]) > ($$p2[1] - $$p1[1]) * ($$p3[0] - $$p1[0])
}
sub sutherland_hodgman {
my($polygon, $clip) = @_;
my @output = @$polygon;
my $clip_point1 = $$clip[-1];
for my $clip_point2 (@$clip) {
my @input = @output;
@output = ();
my $start = $input[-1];
for my $end (@input) {
if (is_inside($clip_point1, $clip_point2, $end)) {
push @output, intersection($clip_point1, $clip_point2, $start, $end)
unless is_inside($clip_point1, $clip_point2, $start);
push @output, $end;
} elsif (is_inside($clip_point1, $clip_point2, $start)) {
push @output, intersection($clip_point1, $clip_point2, $start, $end);
}
$start = $end;
}
$clip_point1 = $clip_point2;
}
@output
}
my @polygon = ([50, 150], [200, 50], [350, 150], [350, 300], [250, 300],
[200, 250], [150, 350], [100, 250], [100, 200]);
my @clip = ([100, 100], [300, 100], [300, 300], [100, 300]);
my @clipped = sutherland_hodgman(\@polygon, \@clip);
print "Clipped polygon:\n";
print '(' . join(' ', @$_) . ') ' for @clipped; | 154Sutherland-Hodgman polygon clipping
| 2perl
| 3ipzs |
import matplotlib.pyplot as plt
from math import sin, cos, pi
def sgn(x):
return ((x>0)-(x<0))*1
a,b,n=200,200,2.5
na=2/n
step=100
piece=(pi*2)/step
xp=[];yp=[]
t=0
for t1 in range(step+1):
x=(abs((cos(t)))**na)*a*sgn(cos(t))
y=(abs((sin(t)))**na)*b*sgn(sin(t))
xp.append(x);yp.append(y)
t+=piece
plt.plot(xp,yp)
plt.title(+str(n))
plt.show() | 156Superellipse
| 3python
| ow581 |
use std::collections::HashMap;
use itertools::Itertools;
fn cubes(n: u64) -> Vec<u64> {
let mut cube_vector = Vec::new();
for i in 1..=n {
cube_vector.push(i.pow(3));
}
cube_vector
}
fn main() {
let c = cubes(1201);
let it = c.iter().combinations(2);
let mut m = HashMap::new();
for x in it {
let sum = x[0] + x[1];
m.entry(sum).or_insert(Vec::new()).push(x)
}
let mut result = Vec::new();
for (k,v) in m.iter() {
if v.len() > 1 {
result.push((k,v));
}
}
result.sort();
for f in result {
println!("{:?}", f);
}
} | 144Taxicab numbers
| 15rust
| 0a1sl |
import scala.collection.MapView
import scala.math.pow
implicit class Pairs[A, B]( p:List[(A, B)]) {
def collectPairs: MapView[A, List[B]] = p.groupBy(_._1).view.mapValues(_.map(_._2)).filterNot(_._2.size<2)
} | 144Taxicab numbers
| 16scala
| ixwox |
my $file = 'notes.txt';
if ( @ARGV ) {
open NOTES, '>>', $file or die "Can't append to file $file: $!";
print NOTES scalar localtime, "\n\t@ARGV\n";
} else {
open NOTES, '<', $file or die "Can't read file $file: $!";
print <NOTES>;
}
close NOTES; | 150Take notes on the command line
| 2perl
| 59fu2 |
require 'singleton'
class MaybeClass
include Singleton
def to_s; ; end
end
MAYBE = MaybeClass.instance
class TrueClass
TritMagic = Object.new
class << TritMagic
def index; 0; end
def!; false; end
def & other; other; end
def | other; true; end
def ^ other; [false, MAYBE, true][other.trit.index]; end
def == other; other; end
end
def trit; TritMagic; end
end
class MaybeClass
TritMagic = Object.new
class << TritMagic
def index; 1; end
def!; MAYBE; end
def & other; [MAYBE, MAYBE, false][other.trit.index]; end
def | other; [true, MAYBE, MAYBE][other.trit.index]; end
def ^ other; MAYBE; end
def == other; MAYBE; end
end
def trit; TritMagic; end
end
class FalseClass
TritMagic = Object.new
class << TritMagic
def index; 2; end
def!; true; end
def & other; false; end
def | other; other; end
def ^ other; other; end
def == other; [false, MAYBE, true][other.trit.index]; end
end
def trit; TritMagic; end
end | 138Ternary logic
| 14ruby
| ziztw |
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'''.split('\n')
days = '''first second third fourth fifth
sixth seventh eighth ninth tenth
eleventh twelfth'''.split()
for n, day in enumerate(days, 1):
g = gifts[:n][::-1]
print(('\nOn the%s day of Christmas\nMy true love gave to me:\n'% day) +
'\n'.join(g[:-1]) +
(' and\n' + g[-1] if n > 1 else g[-1].capitalize())) | 139The Twelve Days of Christmas
| 3python
| nqoiz |
<?php
function clip ($subjectPolygon, $clipPolygon) {
function inside ($p, $cp1, $cp2) {
return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);
}
function intersection ($cp1, $cp2, $e, $s) {
$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];
}
$outputList = $subjectPolygon;
$cp1 = end($clipPolygon);
foreach ($clipPolygon as $cp2) {
$inputList = $outputList;
$outputList = [];
$s = end($inputList);
foreach ($inputList as $e) {
if (inside($e, $cp1, $cp2)) {
if (!inside($s, $cp1, $cp2)) {
$outputList[] = intersection($cp1, $cp2, $e, $s);
}
$outputList[] = $e;
}
else if (inside($s, $cp1, $cp2)) {
$outputList[] = intersection($cp1, $cp2, $e, $s);
}
$s = $e;
}
$cp1 = $cp2;
}
return $outputList;
}
$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];
$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];
$clippedPolygon = clip($subjectPolygon, $clipPolygon);
echo json_encode($clippedPolygon);
echo ;
?> | 154Sutherland-Hodgman polygon clipping
| 12php
| pryba |
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')..implode(' ', array_slice($argv, 1)).,
FILE_APPEND
);
else
@readfile('notes.txt'); | 150Take notes on the command line
| 12php
| owh85 |
use std::{ops, fmt};
#[derive(Copy, Clone, Debug)]
enum Trit {
True,
Maybe,
False,
}
impl ops::Not for Trit {
type Output = Self;
fn not(self) -> Self {
match self {
Trit::True => Trit::False,
Trit::Maybe => Trit::Maybe,
Trit::False => Trit::True,
}
}
}
impl ops::BitAnd for Trit {
type Output = Self;
fn bitand(self, other: Self) -> Self {
match (self, other) {
(Trit::True, Trit::True) => Trit::True,
(Trit::False, _) | (_, Trit::False) => Trit::False,
_ => Trit::Maybe,
}
}
}
impl ops::BitOr for Trit {
type Output = Self;
fn bitor(self, other: Self) -> Self {
match (self, other) {
(Trit::True, _) | (_, Trit::True) => Trit::True,
(Trit::False, Trit::False) => Trit::False,
_ => Trit::Maybe,
}
}
}
impl Trit {
fn imp(self, other: Self) -> Self {
match self {
Trit::True => other,
Trit::Maybe => {
if let Trit::True = other {
Trit::True
} else {
Trit::Maybe
}
}
Trit::False => Trit::True,
}
}
fn eqv(self, other: Self) -> Self {
match self {
Trit::True => other,
Trit::Maybe => Trit::Maybe,
Trit::False =>!other,
}
}
}
impl fmt::Display for Trit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Trit::True => 'T',
Trit::Maybe => 'M',
Trit::False => 'F',
}
)
}
}
static TRITS: [Trit; 3] = [Trit::True, Trit::Maybe, Trit::False];
fn main() {
println!("not");
println!("-------");
for &t in &TRITS {
println!(" {} | {}", t,!t);
}
table("and", |a, b| a & b);
table("or", |a, b| a | b);
table("imp", |a, b| a.imp(b));
table("eqv", |a, b| a.eqv(b));
}
fn table(title: &str, f: impl Fn(Trit, Trit) -> Trit) {
println!();
println!("{:3} | T M F", title);
println!("-------------");
for &t1 in &TRITS {
print!(" {} | ", t1);
for &t2 in &TRITS {
print!("{} ", f(t1, t2));
}
println!();
}
} | 138Ternary logic
| 15rust
| 3n3z8 |
import sys
from Queue import Queue
from threading import Thread
lines = Queue(1)
count = Queue(1)
def read(file):
try:
for line in file:
lines.put(line)
finally:
lines.put(None)
print count.get()
def write(file):
n = 0
while 1:
line = lines.get()
if line is None:
break
file.write(line)
n += 1
count.put(n)
reader = Thread(target=read, args=(open('input.txt'),))
writer = Thread(target=write, args=(sys.stdout,))
reader.start()
writer.start()
reader.join()
writer.join() | 149Synchronous concurrency
| 3python
| l3icv |
package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
seqMaxLen = [][]string{s}
}
}
fmt.Println("Max sequence length:", maxLen)
fmt.Println("Sequences:", len(seqMaxLen))
for _, seq := range seqMaxLen {
fmt.Println("Sequence:")
for _, t := range seq {
fmt.Println(t)
}
}
}
func seq(n int) []string {
s := strconv.Itoa(n)
ss := []string{s}
for {
dSeq := sortD(s)
d := dSeq[0]
nd := 1
s = ""
for i := 1; ; i++ {
if i == len(dSeq) {
s = fmt.Sprintf("%s%d%c", s, nd, d)
break
}
if dSeq[i] == d {
nd++
} else {
s = fmt.Sprintf("%s%d%c", s, nd, d)
d = dSeq[i]
nd = 1
}
}
for _, s0 := range ss {
if s == s0 {
return ss
}
}
ss = append(ss, s)
}
panic("unreachable")
}
func sortD(s string) []rune {
r := make([]rune, len(s))
for i, d := range s {
j := 0
for ; j < i; j++ {
if d > r[j] {
copy(r[j+1:], r[j:i])
break
}
}
r[j] = d
}
return r
} | 160Summarize and say sequence
| 0go
| ix2og |
extension Array {
func combinations(_ k: Int) -> [[Element]] {
return Self._combinations(slice: self[startIndex...], k)
}
static func _combinations(slice: Self.SubSequence, _ k: Int) -> [[Element]] {
guard k!= 1 else {
return slice.map({ [$0] })
}
guard k!= slice.count else {
return [slice.map({ $0 })]
}
let chopped = slice[slice.index(after: slice.startIndex)...]
var res = _combinations(slice: chopped, k - 1).map({ [[slice.first!], $0].flatMap({ $0 }) })
res += _combinations(slice: chopped, k)
return res
}
}
let cubes = (1...).lazy.map({ $0 * $0 * $0 })
let taxis =
Array(cubes.prefix(1201))
.combinations(2)
.reduce(into: [Int: [[Int]]](), { $0[$1[0] + $1[1], default: []].append($1) })
let res =
taxis
.lazy
.filter({ $0.value.count > 1 })
.sorted(by: { $0.key < $1.key })
.map({ ($0.key, $0.value) })
.prefix(2006)
print("First 25 taxicab numbers:")
for taxi in res[..<25] {
print(taxi)
}
print("\n2000th through 2006th taxicab numbers:")
for taxi in res[1999..<2006] {
print(taxi)
} | 144Taxicab numbers
| 17swift
| qpbxg |
sealed trait Trit { self =>
def nand(that:Trit):Trit=(this,that) match {
case (TFalse, _) => TTrue
case (_, TFalse) => TTrue
case (TMaybe, _) => TMaybe
case (_, TMaybe) => TMaybe
case _ => TFalse
}
def nor(that:Trit):Trit = this.or(that).not()
def and(that:Trit):Trit = this.nand(that).not()
def or(that:Trit):Trit = this.not().nand(that.not())
def not():Trit = this.nand(this)
def imply(that:Trit):Trit = this.nand(that.not())
def equiv(that:Trit):Trit = this.and(that).or(this.nor(that))
}
case object TTrue extends Trit
case object TMaybe extends Trit
case object TFalse extends Trit
object TernaryLogic extends App {
val v=List(TTrue, TMaybe, TFalse)
println("- NOT -")
for(a<-v) println("%6s =>%6s".format(a, a.not))
println("\n- AND -")
for(a<-v; b<-v) println("%6s:%6s =>%6s".format(a, b, a and b))
println("\n- OR -")
for(a<-v; b<-v) println("%6s:%6s =>%6s".format(a, b, a or b))
println("\n- Imply -")
for(a<-v; b<-v) println("%6s:%6s =>%6s".format(a, b, a imply b))
println("\n- Equiv -")
for(a<-v; b<-v) println("%6s:%6s =>%6s".format(a, b, a equiv b))
} | 138Ternary logic
| 16scala
| mtmyc |
gifts <- c("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")
days <- c("first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth")
for (i in seq_along(days)) {
cat("On the", days[i], "day of Christmas\n")
cat("My true love gave to me:\n")
cat(paste(gifts[i:1], collapse = "\n"), "\n\n")
} | 139The Twelve Days of Christmas
| 13r
| 0aqsg |
Number.metaClass.getSelfReferentialSequence = {
def number = delegate as String; def sequence = []
while (!sequence.contains(number)) {
sequence << number
def encoded = new StringBuilder()
((number as List).sort().join('').reverse() =~ /(([0-9])\2*)/).each { matcher, text, digit ->
encoded.append(text.size()).append(digit)
}
number = encoded.toString()
}
sequence
}
def maxSeqSize = { List values ->
values.inject([seqSize: 0, seeds: []]) { max, n ->
if (n % 100000 == 99999) println 'HT'
else if (n % 10000 == 9999) print '.'
def seqSize = n.selfReferentialSequence.size()
switch (seqSize) {
case max.seqSize: max.seeds << n
case { it < max.seqSize }: return max
default: return [seqSize: seqSize, seeds: [n]]
}
}
} | 160Summarize and say sequence
| 7groovy
| qpyxp |
def clip(subjectPolygon, clipPolygon):
def inside(p):
return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
def computeIntersection():
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]
outputList = subjectPolygon
cp1 = clipPolygon[-1]
for clipVertex in clipPolygon:
cp2 = clipVertex
inputList = outputList
outputList = []
s = inputList[-1]
for subjectVertex in inputList:
e = subjectVertex
if inside(e):
if not inside(s):
outputList.append(computeIntersection())
outputList.append(e)
elif inside(s):
outputList.append(computeIntersection())
s = e
cp1 = cp2
return(outputList) | 154Sutherland-Hodgman polygon clipping
| 3python
| 6n13w |
package main
import "fmt"
var a = map[string]bool{"John": true, "Bob": true, "Mary": true, "Serena": true}
var b = map[string]bool{"Jim": true, "Mary": true, "John": true, "Bob": true}
func main() {
sd := make(map[string]bool)
for e := range a {
if !b[e] {
sd[e] = true
}
}
for e := range b {
if !a[e] {
sd[e] = true
}
}
fmt.Println(sd)
} | 159Symmetric difference
| 0go
| 0acsk |
import java.awt._
import java.awt.geom.Path2D
import java.util
import javax.swing._
import javax.swing.event.{ChangeEvent, ChangeListener}
object SuperEllipse extends App {
SwingUtilities.invokeLater(() => {
new JFrame("Super Ellipse") {
class SuperEllipse extends JPanel with ChangeListener {
setPreferredSize(new Dimension(650, 650))
setBackground(Color.white)
setFont(new Font("Serif", Font.PLAIN, 18))
private var exp = 2.5
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawGrid(g: Graphics2D): Unit = {
g.setStroke(new BasicStroke(2))
g.setColor(new Color(0xEEEEEE))
val w = getWidth
val h = getHeight
val spacing = 25
for (i <- 0 until (w / spacing)) {
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)
}
def drawLegend(g: Graphics2D): Unit = {
g.setColor(Color.black)
g.setFont(getFont)
g.drawString("n = " + String.valueOf(exp), getWidth - 150, 45)
g.drawString("a = b = 200", getWidth - 150, 75)
}
def drawEllipse(g: Graphics2D): Unit = {
val a = 200 | 156Superellipse
| 16scala
| zohtr |
count = 0
IO.foreach() { |line| print line; count += 1 }
puts | 149Synchronous concurrency
| 14ruby
| vyd2n |
import Data.Set (Set, member, insert, empty)
import Data.List (group, sort)
step :: String -> String
step = concatMap (\list -> show (length list) ++ [head list]) . group . sort
findCycle :: (Ord a) => [a] -> [a]
findCycle = aux empty where
aux set (x: xs)
| x `member` set = []
| otherwise = x: aux (insert x set) xs
select :: [[a]] -> [[a]]
select = snd . foldl (\(len, acc) xs -> case len `compare` length xs of
LT -> (length xs, [xs])
EQ -> (len, xs: acc)
GT -> (len, acc)) (0, [])
main :: IO ()
main = mapM_ (mapM_ print) $
select $
map findCycle $
map (iterate step) $
map show
[1..1000000] | 160Summarize and say sequence
| 8haskell
| vya2k |
def symDiff = { Set s1, Set s2 ->
assert s1 != null
assert s2 != null
(s1 + s2) - (s1.intersect(s2))
} | 159Symmetric difference
| 7groovy
| eh3al |
import Data.Set
a = fromList ["John", "Bob", "Mary", "Serena"]
b = fromList ["Jim", "Mary", "John", "Bob"]
(-|-) :: Ord a => Set a -> Set a -> Set a
x -|- y = (x \\ y) `union` (y \\ x) | 159Symmetric difference
| 8haskell
| czp94 |
import sys, datetime, shutil
if len(sys.argv) == 1:
try:
with open('notes.txt', 'r') as f:
shutil.copyfileobj(f, sys.stdout)
except IOError:
pass
else:
with open('notes.txt', 'a') as f:
f.write(datetime.datetime.now().isoformat() + '\n')
f.write(% ' '.join(sys.argv[1:])) | 150Take notes on the command line
| 3python
| 4ct5k |
args <- commandArgs(trailingOnly=TRUE)
if (length(args) == 0) {
conn <- file("notes.txt", 'r')
cat(readLines(conn), sep="\n")
} else {
conn <- file("notes.txt", 'a')
cat(file=conn, date(), "\n\t", paste(args, collapse=" "), "\n", sep="")
}
close(conn) | 150Take notes on the command line
| 13r
| 26ilg |
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::sync::mpsc::{channel, sync_channel};
use std::thread;
fn main() { | 149Synchronous concurrency
| 15rust
| umfvj |
case class HowMany(asker: Actor)
val printer = actor {
var count = 0
while (true) {
receive {
case line: String =>
print(line); count = count + 1
case HowMany(asker: Actor) => asker ! count; exit()
}
}
}
def reader(printer: Actor) {
scala.io.Source.fromFile("c:\\input.txt").getLines foreach { printer ! _ }
printer ! HowMany(
actor {
receive {
case count: Int => println("line count = " + count)
}
})
}
reader(printer) | 149Synchronous concurrency
| 16scala
| gl34i |
gifts = .split()
days = %w(first second third fourth fifth sixth
seventh eighth ninth tenth eleventh twelfth)
days.each_with_index do |day, i|
puts
puts
puts gifts[0, i+1].reverse
puts
end | 139The Twelve Days of Christmas
| 14ruby
| f0ndr |
null | 149Synchronous concurrency
| 17swift
| 26nlj |
Point = Struct.new(:x,:y) do
def to_s; end
end
def sutherland_hodgman(subjectPolygon, clipPolygon)
cp1, cp2, s, e = nil
inside = proc do |p|
(cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
end
intersection = proc do
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.0 / (dcx*dpy - dcy*dpx)
Point[(n1*dpx - n2*dcx) * n3, (n1*dpy - n2*dcy) * n3]
end
outputList = subjectPolygon
cp1 = clipPolygon.last
for cp2 in clipPolygon
inputList = outputList
outputList = []
s = inputList.last
for e in inputList
if inside[e]
outputList << intersection[] unless inside[s]
outputList << e
elsif inside[s]
outputList << intersection[]
end
s = e
end
cp1 = cp2
end
outputList
end
subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300],
[250, 300], [200, 250], [150, 350], [100, 250],
[100, 200]].collect{|pnt| Point[*pnt]}
clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]].collect{|pnt| Point[*pnt]}
puts sutherland_hodgman(subjectPolygon, clipPolygon) | 154Sutherland-Hodgman polygon clipping
| 14ruby
| mfeyj |
fn main() {
let days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth",
"ninth", "tenth", "eleventh", "twelfth"];
let gifts = ["A Patridge 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"];
for i in 0..12 {
println!("On the {} day of Christmas,", days[i]);
println!("My true love gave to me:");
for j in (0..i + 1).rev() {
println!("{}", gifts[j]);
}
println!()
}
} | 139The Twelve Days of Christmas
| 15rust
| t8dfd |
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class SelfReferentialSequence {
static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);
public static void main(String[] args) {
Seeds res = IntStream.range(0, 1000_000)
.parallel()
.mapToObj(n -> summarize(n, false))
.collect(Seeds::new, Seeds::accept, Seeds::combine);
System.out.println("Seeds:");
res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));
System.out.println("\nSequence:");
summarize(res.seeds.get(0)[0], true);
}
static int[] summarize(int seed, boolean display) {
String n = String.valueOf(seed);
String k = Arrays.toString(n.chars().sorted().toArray());
if (!display && cache.get(k) != null)
return new int[]{seed, cache.get(k)};
Set<String> seen = new HashSet<>();
StringBuilder sb = new StringBuilder();
int[] freq = new int[10];
while (!seen.contains(n)) {
seen.add(n);
int len = n.length();
for (int i = 0; i < len; i++)
freq[n.charAt(i) - '0']++;
sb.setLength(0);
for (int i = 9; i >= 0; i--) {
if (freq[i] != 0) {
sb.append(freq[i]).append(i);
freq[i] = 0;
}
}
if (display)
System.out.println(n);
n = sb.toString();
}
cache.put(k, seen.size());
return new int[]{seed, seen.size()};
}
static class Seeds {
int largest = Integer.MIN_VALUE;
List<int[]> seeds = new ArrayList<>();
void accept(int[] s) {
int size = s[1];
if (size >= largest) {
if (size > largest) {
largest = size;
seeds.clear();
}
seeds.add(s);
}
}
void combine(Seeds acc) {
acc.seeds.forEach(this::accept);
}
}
} | 160Summarize and say sequence
| 9java
| ydj6g |
#[derive(Debug, Clone)]
struct Point {
x: f64,
y: f64,
}
#[derive(Debug, Clone)]
struct Polygon(Vec<Point>);
fn is_inside(p: &Point, cp1: &Point, cp2: &Point) -> bool {
(cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x)
}
fn compute_intersection(cp1: &Point, cp2: &Point, s: &Point, e: &Point) -> Point {
let dc = Point {
x: cp1.x - cp2.x,
y: cp1.y - cp2.y,
};
let dp = Point {
x: s.x - e.x,
y: s.y - e.y,
};
let n1 = cp1.x * cp2.y - cp1.y * cp2.x;
let n2 = s.x * e.y - s.y * e.x;
let n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x);
Point {
x: (n1 * dp.x - n2 * dc.x) * n3,
y: (n1 * dp.y - n2 * dc.y) * n3,
}
}
fn sutherland_hodgman_clip(subject_polygon: &Polygon, clip_polygon: &Polygon) -> Polygon {
let mut result_ring = subject_polygon.0.clone();
let mut cp1 = clip_polygon.0.last().unwrap();
for cp2 in &clip_polygon.0 {
let input = result_ring;
let mut s = input.last().unwrap();
result_ring = vec![];
for e in &input {
if is_inside(e, cp1, cp2) {
if!is_inside(s, cp1, cp2) {
result_ring.push(compute_intersection(cp1, cp2, s, e));
}
result_ring.push(e.clone());
} else if is_inside(s, cp1, cp2) {
result_ring.push(compute_intersection(cp1, cp2, s, e));
}
s = e;
}
cp1 = cp2;
}
Polygon(result_ring)
}
fn main() {
let _p = |x: f64, y: f64| Point { x, y };
let subject_polygon = Polygon(vec![
_p(50.0, 150.0), _p(200.0, 50.0), _p(350.0, 150.0), _p(350.0, 300.0), _p(250.0, 300.0),
_p(200.0, 250.0), _p(150.0, 350.0), _p(100.0, 250.0), _p(100.0, 200.0),
]);
let clip_polygon = Polygon(vec![
_p(100.0, 100.0),_p(300.0, 100.0),_p(300.0, 300.0),_p(100.0, 300.0),
]);
let result = sutherland_hodgman_clip(&subject_polygon, &clip_polygon);
println!("{:?}", result);
} | 154Sutherland-Hodgman polygon clipping
| 15rust
| 9twmm |
import javax.swing.{ JFrame, JPanel }
object SutherlandHodgman extends JFrame with App {
import java.awt.BorderLayout
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setVisible(true)
val content = getContentPane()
content.setLayout(new BorderLayout())
content.add(SutherlandHodgmanPanel, BorderLayout.CENTER)
setTitle("SutherlandHodgman")
pack()
setLocationRelativeTo(null)
}
object SutherlandHodgmanPanel extends JPanel {
import java.awt.{ Color, Graphics, Graphics2D }
setPreferredSize(new java.awt.Dimension(600, 500)) | 154Sutherland-Hodgman polygon clipping
| 16scala
| 26slb |
notes = 'NOTES.TXT'
if ARGV.empty?
File.copy_stream(notes, $stdout) rescue nil
else
File.open(notes, 'a') {|file| file.puts % [Time.now, ARGV.join(' ')]}
end | 150Take notes on the command line
| 14ruby
| r23gs |
extern crate chrono;
use std::fs::OpenOptions;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::env;
const FILENAME: &str = "NOTES.TXT";
fn show_notes() -> Result<(), io::Error> {
let file = OpenOptions::new()
.read(true)
.create(true) | 150Take notes on the command line
| 15rust
| 7v6rc |
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: k <Kelvin>")
return
}
k, err := strconv.ParseFloat(os.Args[1], 64)
if err != nil {
fmt.Println(err)
return
}
if k < 0 {
fmt.Println("Kelvin must be >= 0.")
return
}
fmt.Printf("K %.2f\n", k)
fmt.Printf("C %.2f\n", k-273.15)
fmt.Printf("F %.2f\n", k*9/5-459.67)
fmt.Printf("R %.2f\n", k*9/5)
} | 157Temperature conversion
| 0go
| 173p5 |
val gifts = Array(
"A partridge in a pear tree.",
"Two turtle doves and",
"Three French hens,",
"Four calling birds,",
"Five gold 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,"
)
val days = Array(
"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"
)
val giftsForDay = (day: Int) =>
"On the%s day of Christmas, my true love sent to me:\n".format(days(day)) +
gifts.take(day+1).reverse.mkString("\n") + "\n"
(0 until 12).map(giftsForDay andThen println) | 139The Twelve Days of Christmas
| 16scala
| 6nz31 |
function selfReferential(n) {
n = n.toString();
let res = [n];
const makeNext = (n) => {
let matchs = {
'9':0,'8':0,'7':0,'6':0,'5':0,'4':0,'3':0,'2':0,'1':0,'0':0}, res = [];
for(let index=0;index<n.length;index++)
matchs[n[index].toString()]++;
for(let index=9;index>=0;index--)
if(matchs[index]>0)
res.push(matchs[index],index);
return res.join("").toString();
}
for(let i=0;i<10;i++)
res.push(makeNext(res[res.length-1]));
return [...new Set(res)];
} | 160Summarize and say sequence
| 10javascript
| 261lr |
interface XYCoords {
x: number;
y: number;
}
const inside = ( cp1: XYCoords, cp2: XYCoords, p: XYCoords): boolean => {
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x);
};
const intersection = ( cp1: XYCoords ,cp2: XYCoords ,s: XYCoords, e: XYCoords ): XYCoords => {
const dc = {
x: cp1.x - cp2.x,
y: cp1.y - cp2.y
},
dp = { x: s.x - e.x,
y: s.y - e.y
},
n1 = cp1.x * cp2.y - cp1.y * cp2.x,
n2 = s.x * e.y - s.y * e.x,
n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x);
return { x: (n1*dp.x - n2*dc.x) * n3,
y: (n1*dp.y - n2*dc.y) * n3
};
};
export const sutherland_hodgman = ( subjectPolygon: Array<XYCoords>,
clipPolygon: Array<XYCoords> ): Array<XYCoords> => {
let cp1: XYCoords = clipPolygon[clipPolygon.length-1];
let cp2: XYCoords;
let s: XYCoords;
let e: XYCoords;
let outputList: Array<XYCoords> = subjectPolygon;
for( var j in clipPolygon ) {
cp2 = clipPolygon[j];
var inputList = outputList;
outputList = [];
s = inputList[inputList.length - 1]; | 154Sutherland-Hodgman polygon clipping
| 20typescript
| h5zjt |
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SymmetricDifference {
public static void main(String[] args) {
Set<String> setA = new HashSet<String>(Arrays.asList("John", "Serena", "Bob", "Mary", "Serena"));
Set<String> setB = new HashSet<String>(Arrays.asList("Jim", "Mary", "John", "Jim", "Bob")); | 159Symmetric difference
| 9java
| zortq |
import java.io.{ FileNotFoundException, FileOutputStream, PrintStream }
import java.time.LocalDateTime
object TakeNotes extends App {
val notesFileName = "notes.txt"
if (args.length > 0) {
val ps = new PrintStream(new FileOutputStream(notesFileName, true))
ps.println(LocalDateTime.now() + args.mkString("\n\t", " ", "."))
ps.close()
} else try {
io.Source.fromFile(notesFileName).getLines().foreach(println)
} catch {
case e: FileNotFoundException => println(e.getLocalizedMessage())
case e: Throwable => {
println("Some other exception type:")
e.printStackTrace()
}
}
} | 150Take notes on the command line
| 16scala
| k49hk |
class Convert{
static void main(String[] args){
def c=21.0;
println("K "+c)
println("C "+k_to_c(c));
println("F "+k_to_f(k_to_c(c)));
println("R "+k_to_r(c));
}
static def k_to_c(def k=21.0){return k-273.15;}
static def k_to_f(def k=21.0){return ((k*9)/5)+32;}
static def k_to_r(def k=21.0){return k*1.8;}
} | 157Temperature conversion
| 7groovy
| jun7o |
struct Point {
var x: Double
var y: Double
}
struct Polygon {
var points: [Point]
init(points: [Point]) {
self.points = points
}
init(points: [(Double, Double)]) {
self.init(points: points.map({ Point(x: $0.0, y: $0.1) }))
}
}
func isInside(_ p1: Point, _ p2: Point, _ p3: Point) -> Bool {
(p3.x - p2.x) * (p1.y - p2.y) > (p3.y - p2.y) * (p1.x - p2.x)
}
func computeIntersection(_ p1: Point, _ p2: Point, _ s: Point, _ e: Point) -> Point {
let dc = Point(x: p1.x - p2.x, y: p1.y - p2.y)
let dp = Point(x: s.x - e.x, y: s.y - e.y)
let n1 = p1.x * p2.y - p1.y * p2.x
let n2 = s.x * e.y - s.y * e.x
let n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x)
return Point(x: (n1 * dp.x - n2 * dc.x) * n3, y: (n1 * dp.y - n2 * dc.y) * n3)
}
func sutherlandHodgmanClip(subjPoly: Polygon, clipPoly: Polygon) -> Polygon {
var ring = subjPoly.points
var p1 = clipPoly.points.last!
for p2 in clipPoly.points {
let input = ring
var s = input.last!
ring = []
for e in input {
if isInside(e, p1, p2) {
if!isInside(s, p1, p2) {
ring.append(computeIntersection(p1, p2, s, e))
}
ring.append(e)
} else if isInside(s, p1, p2) {
ring.append(computeIntersection(p1, p2, s, e))
}
s = e
}
p1 = p2
}
return Polygon(points: ring)
}
let subj = Polygon(points: [
(50.0, 150.0),
(200.0, 50.0),
(350.0, 150.0),
(350.0, 300.0),
(250.0, 300.0),
(200.0, 250.0),
(150.0, 350.0),
(100.0, 250.0),
(100.0, 200.0)
])
let clip = Polygon(points: [
(100.0, 100.0),
(300.0, 100.0),
(300.0, 300.0),
(100.0, 300.0)
])
print(sutherlandHodgmanClip(subjPoly: subj, clipPoly: clip)) | 154Sutherland-Hodgman polygon clipping
| 17swift
| yda6e |
null | 159Symmetric difference
| 10javascript
| 9tbml |
import System.Exit (die)
import Control.Monad (mapM_)
main = do
putStrLn "Please enter temperature in kelvin: "
input <- getLine
let kelvin = read input
if kelvin < 0.0
then die "Temp cannot be negative"
else mapM_ putStrLn $ convert kelvin
convert :: Double -> [String]
convert n = zipWith (++) labels nums
where labels = ["kelvin: ", "celcius: ", "farenheit: ", "rankine: "]
conversions = [id, subtract 273, subtract 459.67 . (1.8 *), (*1.8)]
nums = (show . ($n)) <$> conversions | 157Temperature conversion
| 8haskell
| t87f7 |
import Foundation
let args = Process.arguments
let manager = NSFileManager()
let currentPath = manager.currentDirectoryPath
var err:NSError? | 150Take notes on the command line
| 17swift
| glz49 |
null | 160Summarize and say sequence
| 11kotlin
| f05do |
null | 159Symmetric difference
| 11kotlin
| ixvo4 |
null | 160Summarize and say sequence
| 1lua
| t84fn |
public class TemperatureConversion {
public static void main(String args[]) {
if (args.length == 1) {
try {
double kelvin = Double.parseDouble(args[0]);
if (kelvin >= 0) {
System.out.printf("K %2.2f\n", kelvin);
System.out.printf("C %2.2f\n", kelvinToCelsius(kelvin));
System.out.printf("F %2.2f\n", kelvinToFahrenheit(kelvin));
System.out.printf("R %2.2f\n", kelvinToRankine(kelvin));
} else {
System.out.printf("%2.2f K is below absolute zero", kelvin);
}
} catch (NumberFormatException e) {
System.out.println(e);
}
}
}
public static double kelvinToCelsius(double k) {
return k - 273.15;
}
public static double kelvinToFahrenheit(double k) {
return k * 1.8 - 459.67;
}
public static double kelvinToRankine(double k) {
return k * 1.8;
}
} | 157Temperature conversion
| 9java
| 8ev06 |
WITH
FUNCTION nl ( s IN varchar2 )
RETURN varchar2
IS
BEGIN
RETURN chr(10) || s;
END nl;
FUNCTION v ( d NUMBER, x NUMBER, g IN varchar2 )
RETURN varchar2
IS
BEGIN
RETURN
CASE WHEN d >= x THEN nl (g) END;
END v;
SELECT 'On the '
|| to_char(to_date(level,'j'),'jspth' )
|| ' day of Christmas,'
|| nl( 'my true love sent to me:')
|| v ( level, 12, 'Twelve drummers drumming,' )
|| v ( level, 11, 'Eleven pipers piping,' )
|| v ( level, 10, 'Ten lords a-leaping,' )
|| v ( level, 9, 'Nine ladies dancing,' )
|| v ( level, 8, 'Eight maids a-milking,' )
|| v ( level, 7, 'Seven swans a-swimming,' )
|| v ( level, 6, 'Six geese a-laying,' )
|| v ( level, 5, 'Five golden rings!' )
|| v ( level, 4, 'Four calling birds,' )
|| v ( level, 3, 'Three French hens,' )
|| v ( level, 2, 'Two turtle doves,' )
|| v ( level, 1, CASE level WHEN 1 THEN 'A' ELSE 'And a' END || ' partridge in a pear tree.' )
|| nl(NULL)
FROM dual
CONNECT BY level <= 12
/ | 139The Twelve Days of Christmas
| 19sql
| 9tym6 |
A = { ["John"] = true, ["Bob"] = true, ["Mary"] = true, ["Serena"] = true }
B = { ["Jim"] = true, ["Mary"] = true, ["John"] = true, ["Bob"] = true }
A_B = {}
for a in pairs(A) do
if not B[a] then A_B[a] = true end
end
B_A = {}
for b in pairs(B) do
if not A[b] then B_A[b] = true end
end
for a_b in pairs(A_B) do
print( a_b )
end
for b_a in pairs(B_A) do
print( b_a )
end | 159Symmetric difference
| 1lua
| nqui8 |
var k2c = k => k - 273.15
var k2r = k => k * 1.8
var k2f = k => k2r(k) - 459.67
Number.prototype.toMaxDecimal = function (d) {
return +this.toFixed(d) + ''
}
function kCnv(k) {
document.write( k,'K = ', k2c(k).toMaxDecimal(2),'C = ', k2r(k).toMaxDecimal(2),'R = ', k2f(k).toMaxDecimal(2),'F<br>' )
}
kCnv(21)
kCnv(295) | 157Temperature conversion
| 10javascript
| f0rdg |
let gifts = [ "partridge in a pear tree", "Two turtle doves",
"Three French hens", "Four calling birds",
"Five gold 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" ]
let nth = [ "first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ]
func giftsForDay(day: Int) -> String {
var result = "On the \(nth[day-1]) day of Christmas, my true love sent to me:\n"
if day > 1 {
for again in 1...day-1 {
let n = day - again
result += gifts[n]
if n > 1 { result += "," }
result += "\n"
}
result += "And a "
} else {
result += "A "
}
return result + gifts[0] + ".\n";
}
for day in 1...12 {
print(giftsForDay(day))
} | 139The Twelve Days of Christmas
| 17swift
| dsinh |
package main
import "time"
import "fmt"
func main() {
t := time.Now()
fmt.Println(t) | 161System time
| 0go
| qp6xz |
def nowMillis = new Date().time
println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis | 161System time
| 7groovy
| 17dp6 |
import System.Time
(getClockTime, toCalendarTime, formatCalendarTime)
import System.Locale (defaultTimeLocale)
main :: IO ()
main = do
ct <- getClockTime
print ct
cal <- toCalendarTime ct
putStrLn $ formatCalendarTime defaultTimeLocale "%a%b%e%H:%M:%S%Y" cal | 161System time
| 8haskell
| mfjyf |
sub next_num {
my @a;
$a[$_]++ for split '', shift;
join('', map(exists $a[$_] ? $a[$_].$_ : "", reverse 0 .. 9));
}
my %cache;
sub seq {
my $a = shift;
my (%seen, @s);
until ($seen{$a}) {
$seen{$a} = 1;
push(@s, $a);
last if !wantarray && $cache{$a};
$a = next_num($a);
}
return (@s) if wantarray;
my $l = $cache{$a};
if ($l) { $cache{$s[$_]} = $
else {
$l++ while ($s[-$l] != $a);
$cache{pop @s} = $l for (1 .. $l);
$cache{pop @s} = ++$l while @s;
}
$cache{$s[0]}
}
my (@mlist, $mlen);
for (1 .. 100_000) {
my $l = seq($_);
next if $l < $mlen;
if ($l > $mlen) { $mlen = $l; @mlist = (); }
push @mlist, $_;
}
print "longest ($mlen): @mlist\n";
print join("\n", seq($_)), "\n\n" for @mlist; | 160Summarize and say sequence
| 2perl
| h5ojl |
null | 157Temperature conversion
| 11kotlin
| wkmek |
from itertools import groupby, permutations
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(sorted(str(number), reverse=True)) )
def A036058_length(numberstring='0', printit=False):
iterations, last_three, queue_index = 1, ([None] * 3), 0
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(number) )
while True:
if printit:
print(% (iterations, numberstring))
numberstring = ''.join(sorted(numberstring, reverse=True))
if numberstring in last_three:
break
assert iterations < 1000000
last_three[queue_index], numberstring = numberstring, A036058(numberstring)
iterations += 1
queue_index +=1
queue_index%=3
return iterations
def max_A036058_length( start_range=range(11) ):
already_done = set()
max_len = (-1, [])
for n in start_range:
sn = str(n)
sns = tuple(sorted(sn, reverse=True))
if sns not in already_done:
already_done.add(sns)
size = A036058_length(sns)
if size > max_len[0]:
max_len = (size, [n])
elif size == max_len[0]:
max_len[1].append(n)
return max_len
lenmax, starts = max_A036058_length( range(1000000) )
allstarts = []
for n in starts:
allstarts += [int(''.join(x))
for x in set(k
for k in permutations(str(n), 4)
if k[0] != '0')]
allstarts = [x for x in sorted(allstarts) if x < 1000000]
print ( '''\
The longest length, followed by the number(s) with the longest sequence length
for starting sequence numbers below 1000000 are:
Iterations =%i and sequence-starts =%s.'''% (lenmax, allstarts) )
print ( '''
Note that only the first of any sequences with the same digits is printed below.
(The others will differ only in their first term)''' )
for n in starts:
print()
A036058_length(str(n), printit=True) | 160Summarize and say sequence
| 3python
| k4ihf |
function convert_temp(k)
local c = k - 273.15
local r = k * 1.8
local f = r - 459.67
return k, c, r, f
end
print(string.format([[
Kelvin: %.2f K
Celcius: %.2f C
Rankine: %.2f R
Fahrenheit: %.2f F
]],convert_temp(21.0))) | 157Temperature conversion
| 1lua
| xb9wz |
public class SystemTime{
public static void main(String[] args){
System.out.format("%tc%n", System.currentTimeMillis());
}
} | 161System time
| 9java
| f0udv |
console.log(new Date()) | 161System time
| 10javascript
| yd76r |
null | 161System time
| 11kotlin
| 8e90q |
sub symm_diff {
my %in_a = map(($_=>1), @{+shift});
my %in_b = map(($_=>1), @{+shift});
my @a = grep { !$in_b{$_} } keys %in_a;
my @b = grep { !$in_a{$_} } keys %in_b;
return \@a, \@b, [ @a, @b ]
}
my @a = qw(John Serena Bob Mary Serena);
my @b = qw(Jim Mary John Jim Bob );
my ($a, $b, $s) = symm_diff(\@a, \@b);
print "A\\B: @$a\nB\\A: @$b\nSymm: @$s\n"; | 159Symmetric difference
| 2perl
| r20gd |
$cache = {}
def selfReferentialSequence_cached(n, seen = [])
return $cache[n] if $cache.include? n
return [] if seen.include? n
digit_count = Array.new(10, 0)
n.to_s.chars.collect {|char| digit_count[char.to_i] += 1}
term = ''
9.downto(0).each do |d|
if digit_count[d] > 0
term += digit_count[d].to_s + d.to_s
end
end
term = term.to_i
$cache[n] = [n] + selfReferentialSequence_cached(term, [n] + seen)
end
limit = 1_000_000
max_len = 0
max_vals = []
1.upto(limit - 1) do |n|
seq = selfReferentialSequence_cached(n)
if seq.length > max_len
max_len = seq.length
max_vals = [n]
elsif seq.length == max_len
max_vals << n
end
end
puts
puts
puts
selfReferentialSequence_cached(max_vals[0]).each_with_index do |val, idx|
puts % [idx + 1, val]
end | 160Summarize and say sequence
| 14ruby
| prdbh |
import spire.math.SafeLong
import scala.annotation.tailrec
import scala.collection.parallel.immutable.ParVector
object SelfReferentialSequence {
def main(args: Array[String]): Unit = {
val nums = ParVector.range(1, 1000001).map(SafeLong(_))
val seqs = nums.map{ n => val seq = genSeq(n); (n, seq, seq.length) }.toVector.sortWith((a, b) => a._3 > b._3)
val maxes = seqs.takeWhile(t => t._3 == seqs.head._3)
println(s"Seeds: ${maxes.map(_._1).mkString(", ")}\nIterations: ${maxes.head._3}")
for(e <- maxes.distinctBy(a => nextTerm(a._1.toString))){
println(s"\nSeed: ${e._1}\n${e._2.mkString("\n")}")
}
}
def genSeq(seed: SafeLong): Vector[String] = {
@tailrec
def gTrec(seq: Vector[String], n: String): Vector[String] = {
if(seq.contains(n)) seq
else gTrec(seq :+ n, nextTerm(n))
}
gTrec(Vector[String](), seed.toString)
}
def nextTerm(num: String): String = {
@tailrec
def dTrec(digits: Vector[(Int, Int)], src: String): String = src.headOption match{
case Some(n) => dTrec(digits :+ ((n.asDigit, src.count(_ == n))), src.filter(_ != n))
case None => digits.sortWith((a, b) => a._1 > b._1).map(p => p._2.toString + p._1.toString).mkString
}
dTrec(Vector[(Int, Int)](), num)
}
} | 160Summarize and say sequence
| 16scala
| wk3es |
<?php
$a = array('John', 'Bob', 'Mary', 'Serena');
$b = array('Jim', 'Mary', 'John', 'Bob');
$a = array_unique($a);
$b = array_unique($b);
$a_minus_b = array_diff($a, $b);
$b_minus_a = array_diff($b, $a);
$symmetric_difference = array_merge($a_minus_b, $b_minus_a);
echo 'List A: ', implode(', ', $a),
, implode(', ', $b),
, implode(', ', $a_minus_b),
, implode(', ', $b_minus_a),
, implode(', ', $symmetric_difference), ;
?> | 159Symmetric difference
| 12php
| ds5n8 |
print(os.date()) | 161System time
| 1lua
| owc8h |
>>> setA = {, , , }
>>> setB = {, , , }
>>> setA ^ setB
{'Jim', 'Serena'}
>>> setA - setB
{'Serena'}
>>> setB - setA
{'Jim'}
>>> setA | setB
{'John', 'Bob', 'Jim', 'Serena', 'Mary'}
>>> setA & setB
{'Bob', 'John', 'Mary'} | 159Symmetric difference
| 3python
| 7v8rm |
a <- c( "John", "Bob", "Mary", "Serena" )
b <- c( "Jim", "Mary", "John", "Bob" )
c(setdiff(b, a), setdiff(a, b))
a <- c("John", "Serena", "Bob", "Mary", "Serena")
b <- c("Jim", "Mary", "John", "Jim", "Bob")
c(setdiff(b, a), setdiff(a, b)) | 159Symmetric difference
| 13r
| 59xuy |
my %scale = (
Celcius => { factor => 1 , offset => -273.15 },
Rankine => { factor => 1.8, offset => 0 },
Fahrenheit => { factor => 1.8, offset => -459.67 },
);
print "Enter a temperature in Kelvin: ";
chomp(my $kelvin = <STDIN>);
die "No such temperature!\n" unless $kelvin > 0;
foreach (sort keys %scale) {
printf "%12s:%8.2f\n", $_, $kelvin * $scale{$_}{factor} + $scale{$_}{offset};
} | 157Temperature conversion
| 2perl
| l3ec5 |
typedef struct{
int rows,cols;
int** dataSet;
}matrix;
matrix readMatrix(char* dataFile){
FILE* fp = fopen(dataFile,);
matrix rosetta;
int i,j;
fscanf(fp,,&rosetta.rows,&rosetta.cols);
rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));
for(i=0;i<rosetta.rows;i++){
rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));
for(j=0;j<rosetta.cols;j++)
fscanf(fp,,&rosetta.dataSet[i][j]);
}
fclose(fp);
return rosetta;
}
void printMatrix(matrix rosetta){
int i,j;
for(i=0;i<rosetta.rows;i++){
printf();
for(j=0;j<rosetta.cols;j++)
printf(,rosetta.dataSet[i][j]);
}
}
int findSum(matrix rosetta){
int i,j,sum = 0;
for(i=1;i<rosetta.rows;i++){
for(j=0;j<i;j++){
sum += rosetta.dataSet[i][j];
}
}
return sum;
}
int main(int argC,char* argV[])
{
if(argC!=2)
return printf(,argV[0]);
matrix data = readMatrix(argV[1]);
printf();
printMatrix(data);
printf(,findSum(data));
return 0;
} | 162Sum of elements below main diagonal of matrix
| 5c
| nqli6 |
a = [, , , , ]
b = [, , , , ]
p sym_diff = (a | b)-(a & b) | 159Symmetric difference
| 14ruby
| h5ijx |
typedef struct node_t {
int x, y;
struct node_t *prev, *next;
} node;
node *new_node(int x, int y) {
node *n = malloc(sizeof(node));
n->x = x;
n->y = y;
n->next = NULL;
n->prev = NULL;
return n;
}
void free_node(node **n) {
if (n == NULL) {
return;
}
(*n)->prev = NULL;
(*n)->next = NULL;
free(*n);
*n = NULL;
}
typedef struct list_t {
node *head;
node *tail;
} list;
list make_list() {
list lst = { NULL, NULL };
return lst;
}
void append_node(list *const lst, int x, int y) {
if (lst == NULL) {
return;
}
node *n = new_node(x, y);
if (lst->head == NULL) {
lst->head = n;
lst->tail = n;
} else {
n->prev = lst->tail;
lst->tail->next = n;
lst->tail = n;
}
}
void remove_node(list *const lst, const node *const n) {
if (lst == NULL || n == NULL) {
return;
}
if (n->prev != NULL) {
n->prev->next = n->next;
if (n->next != NULL) {
n->next->prev = n->prev;
} else {
lst->tail = n->prev;
}
} else {
if (n->next != NULL) {
n->next->prev = NULL;
lst->head = n->next;
}
}
free_node(&n);
}
void free_list(list *const lst) {
node *ptr;
if (lst == NULL) {
return;
}
ptr = lst->head;
while (ptr != NULL) {
node *nxt = ptr->next;
free_node(&ptr);
ptr = nxt;
}
lst->head = NULL;
lst->tail = NULL;
}
void print_list(const list *lst) {
node *it;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
int prod = it->x * it->y;
printf(, it->x, it->y, sum, prod);
}
}
void print_count(const list *const lst) {
node *it;
int c = 0;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
c++;
}
if (c == 0) {
printf();
} else if (c == 1) {
printf();
} else {
printf(, c);
}
}
void setup(list *const lst) {
int x, y;
if (lst == NULL) {
return;
}
for (x = 2; x <= 98; x++) {
for (y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
append_node(lst, x, y);
}
}
}
}
void remove_by_sum(list *const lst, const int sum) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int s = it->x + it->y;
if (s == sum) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void remove_by_prod(list *const lst, const int prod) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int p = it->x * it->y;
if (p == prod) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void statement1(list *const lst) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = lst->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = lst->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] == 1) {
remove_by_sum(lst, it->x + it->y);
it = lst->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement2(list *const candidates) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = candidates->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] > 1) {
remove_by_prod(candidates, prod);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement3(list *const candidates) {
short *unique = calloc(100, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
unique[sum]++;
}
it = candidates->head;
while (it != NULL) {
int sum = it->x + it->y;
nxt = it->next;
if (unique[sum] > 1) {
remove_by_sum(candidates, sum);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
int main() {
list candidates = make_list();
setup(&candidates);
print_count(&candidates);
statement1(&candidates);
print_count(&candidates);
statement2(&candidates);
print_count(&candidates);
statement3(&candidates);
print_count(&candidates);
print_list(&candidates);
free_list(&candidates);
return 0;
} | 163Sum and product puzzle
| 5c
| juq70 |
use std::collections::HashSet;
fn main() {
let a: HashSet<_> = ["John", "Bob", "Mary", "Serena"]
.iter()
.collect();
let b = ["Jim", "Mary", "John", "Bob"]
.iter()
.collect();
let diff = a.symmetric_difference(&b);
println!("{:?}", diff);
} | 159Symmetric difference
| 15rust
| k4nh5 |
while (true) {
echo ;
if ($kelvin = trim(fgets(STDIN))) {
if ($kelvin == 'q') {
echo 'quitting';
break;
}
if (is_numeric($kelvin)) {
$kelvin = floatVal($kelvin);
if ($kelvin >= 0) {
printf(, $kelvin);
printf(, $kelvin - 273.15);
printf(, $kelvin * 1.8 - 459.67);
printf(, $kelvin * 1.8);
} else printf(, $kelvin);
}
}
} | 157Temperature conversion
| 12php
| qpcx3 |
scala> val s1 = Set("John", "Serena", "Bob", "Mary", "Serena")
s1: scala.collection.immutable.Set[java.lang.String] = Set(John, Serena, Bob, Mary)
scala> val s2 = Set("Jim", "Mary", "John", "Jim", "Bob")
s2: scala.collection.immutable.Set[java.lang.String] = Set(Jim, Mary, John, Bob)
scala> (s1 diff s2) union (s2 diff s1)
res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim) | 159Symmetric difference
| 16scala
| 17tpf |
package main
import (
"fmt"
"log"
)
func main() {
m := [][]int{
{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5},
}
if len(m) != len(m[0]) {
log.Fatal("Matrix must be square.")
}
sum := 0
for i := 1; i < len(m); i++ {
for j := 0; j < i; j++ {
sum = sum + m[i][j]
}
}
fmt.Println("Sum of elements below main diagonal is", sum)
} | 162Sum of elements below main diagonal of matrix
| 0go
| r2xgm |
print scalar localtime, "\n"; | 161System time
| 2perl
| 4cw5d |
matrixTriangle :: Bool -> [[a]] -> Either String [[a]]
matrixTriangle upper matrix
| upper = go drop id
| otherwise = go take pred
where
go f g
| isSquare matrix =
(Right . snd) $
foldr
(\xs (n, rows) -> (pred n, f n xs: rows))
(g $ length matrix, [])
matrix
| otherwise = Left "Defined only for a square matrix."
isSquare :: [[a]] -> Bool
isSquare rows = all ((n ==) . length) rows
where
n = length rows
main :: IO ()
main =
mapM_ putStrLn $
zipWith
( flip ((<>) . (<> " triangle:\n\t"))
. either id (show . sum . concat)
)
( [matrixTriangle] <*> [False, True]
<*> [ [ [1, 3, 7, 8, 10],
[2, 4, 16, 14, 4],
[3, 1, 9, 18, 11],
[12, 14, 17, 18, 20],
[7, 1, 3, 9, 5]
]
]
)
["Lower", "Upper"] | 162Sum of elements below main diagonal of matrix
| 8haskell
| 0ays7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.