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%2... | 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[Optio... | 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 e... | 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, c... | 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.ite... | 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 ... | 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 = [];
... | 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
... | 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 ),
... | 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 invalidPeri... | 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
... | 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... | 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] * $$L... | 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(x... | 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... | 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, tr... | 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... | 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... | 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,
... | 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 lin... | 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)
s... | 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 ... | 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()... | 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", ... | 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... | 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] - ... | 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
}
}
... | 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 {
... | 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... | 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.ar... | 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").getLine... | 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
... | 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 ... | 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)
... | 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: &Poi... | 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, BorderL... | 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 ... | 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 piper... | 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... | 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.... | 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... | 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... | 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 {
(p... | 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 (++) la... | 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.p... | 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 ... | 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) ... | 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)... | 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... | 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... | 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(numb... | 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 Mar... | 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].t... | 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)... | 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(', ', $... | 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 ... | 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*)mallo... | 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 = N... | 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(... | 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 dif... | 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... | 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, [])
... | 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.