code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
object LinePLaneIntersection extends App { val (rv, rp, pn, pp) = (Vector3D(0.0, -1.0, -1.0), Vector3D(0.0, 0.0, 10.0), Vector3D(0.0, 0.0, 1.0), Vector3D(0.0, 0.0, 5.0)) val ip = intersectPoint(rv, rp, pn, pp) def intersectPoint(rayVector: Vector3D, rayPoint: Vector3D, ...
832Find the intersection of a line with a plane
16scala
5ahut
extern crate rand; extern crate ansi_term; #[derive(Copy, Clone, PartialEq)] enum Tile { Empty, Tree, Burning, Heating, } impl fmt::Display for Tile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let output = match *self { Empty => Black.paint(" "), Tree =...
821Forest fire
15rust
ady14
def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() } def missingPerms missingPerms = {List elts, List perms -> perms.empty ? elts.permutations(): elts.collect { e -> def ePerms = perms.findAll { e == it[0] }.collect { it[1..-1] } ePerms.size() == fact(elts.size() - 1) ? [] \ ...
834Find the missing permutation
7groovy
piwbo
function lastSundayOfEachMonths(year) { var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var sundays = []; var date, month; if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) { lastDay[2] = 29; } for (date = new Date(), month = 0; month < 12; month += 1) { date.setFullYear(year, mont...
833Find the last Sunday of each month
10javascript
d26nu
null
830Five weekends
11kotlin
s6tq7
import Data.List ((\\), permutations, nub) import Control.Monad (join) missingPerm :: Eq a => [[a]] -> [[a]] missingPerm = (\\) =<< permutations . nub . join deficientPermsList :: [String] deficientPermsList = [ "ABCD" , "CABD" , "ACDB" , "DACB" , "BCDA" , "ACBD" , "ADCB" , "CDAB" , "DABC" , "...
834Find the missing permutation
8haskell
yrl66
Point = Struct.new(:x, :y) class Line attr_reader :a, :b def initialize(point1, point2) @a = (point1.y - point2.y).fdiv(point1.x - point2.x) @b = point1.y - @a*point1.x end def intersect(other) return nil if @a == other.a x = (other.b - @b).fdiv(@a - other.a) y = @a*x + @b Point.new(x...
831Find the intersection of two lines
14ruby
rx1gs
local months={"JAN","MAR","MAY","JUL","AUG","OCT","DEC"} local daysPerMonth={31+28,31+30,31+30,31,31+30,31+30,0} function find5weMonths(year) local list={} local startday=((year-1)*365+math.floor((year-1)/4)-math.floor((year-1)/100)+math.floor((year-1)/400))%7 for i,v in ipairs(daysPerMonth) do if startday=...
830Five weekends
1lua
0yzsd
import scala.util.Random class Forest(matrix:Array[Array[Char]]){ import Forest._ val f=0.01;
821Forest fire
16scala
xzcwg
import java.util.LinkedList; import java.util.List; public final class FlattenUtil { public static List<Object> flatten(List<?> list) { List<Object> retVal = new LinkedList<Object>(); flatten(list, retVal); return retVal; } public static void flatten(List<?> fromTreeList, List<Object> toFlatList) { for (...
827Flatten a list
9java
fvvdv
null
833Find the last Sunday of each month
11kotlin
ef0a4
#[derive(Copy, Clone, Debug)] struct Point { x: f64, y: f64, } impl Point { pub fn new(x: f64, y: f64) -> Self { Point { x, y } } } #[derive(Copy, Clone, Debug)] struct Line(Point, Point); impl Line { pub fn intersect(self, other: Self) -> Option<Point> { let a1 = self.1.y - self....
831Find the intersection of two lines
15rust
7qarc
object Intersection extends App { val (l1, l2) = (LineF(PointF(4, 0), PointF(6, 10)), LineF(PointF(0, 3), PointF(10, 7))) def findIntersection(l1: LineF, l2: LineF): PointF = { val a1 = l1.e.y - l1.s.y val b1 = l1.s.x - l1.e.x val c1 = a1 * l1.s.x + b1 * l1.s.y val a2 = l2.e.y - l2.s.y val b2 ...
831Find the intersection of two lines
16scala
k8xhk
for n in {1..100}; do ((( n % 15 == 0 )) && echo 'FizzBuzz') || ((( n % 5 == 0 )) && echo 'Buzz') || ((( n % 3 == 0 )) && echo 'Fizz') || echo $n; done
835FizzBuzz
4bash
gwj4x
function flatten(list) { return list.reduce(function (acc, val) { return acc.concat(val.constructor === Array ? flatten(val) : val); }, []); }
827Flatten a list
10javascript
yrr6r
>>> def floyd(rowcount=5): rows = [[1]] while len(rows) < rowcount: n = rows[-1][-1] + 1 rows.append(list(range(n, n + len(rows[-1]) + 1))) return rows >>> floyd() [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]] >>> def pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]): colspace = [len(str(n))...
824Floyd's triangle
3python
tugfw
import java.util.ArrayList; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; public class FindMissingPermutation { public static void main(String[] args) { Joiner joiner = Joiner.on("").skipNulls(); ImmutableSet<String> s = ImmutableSet....
834Find the missing permutation
9java
d23n9
function isLeapYear (y) return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0 end function dayOfWeek (y, m, d) local t = os.time({year = y, month = m, day = d}) return os.date("%A", t) end function lastWeekdays (wday, year) local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} if...
833Find the last Sunday of each month
1lua
wt8ea
struct Point { var x: Double var y: Double } struct Line { var p1: Point var p2: Point var slope: Double { guard p1.x - p2.x!= 0.0 else { return .nan } return (p1.y-p2.y) / (p1.x-p2.x) } func intersection(of other: Line) -> Point? { let ourSlope = slope let theirSlope = other.slope ...
831Find the intersection of two lines
17swift
gwp49
permute = function(v, m){
834Find the missing permutation
10javascript
6gc38
use Math::Complex ':trig'; sub compose { my ($f, $g) = @_; sub { $f -> ($g -> (@_)); }; } my $cube = sub { $_[0] ** (3) }; my $croot = sub { $_[0] ** (1/3) }; my @flist1 = ( \&Math::Complex::sin, \&Math::Complex::cos, $cube ); my @flist2 = ( \&asin, \&acos, $croot...
829First-class functions
2perl
0y3s4
Floyd <- function(n) { out <- t(sapply(seq_len(n), function(i) c(seq(to = 0.5 * (i * (i + 1)), by = 1, length.out = i), rep(NA, times = n - i)))) dimnames(out) <- list(rep("", times = nrow(out)), rep("", times = ncol(out))) print(out, na.print = "") } Floyd(5) Floyd(14)
824Floyd's triangle
13r
icvo5
$compose = function ($f, $g) { return function ($x) use ($f, $g) { return $f($g($x)); }; }; $fn = array('sin', 'cos', function ($x) { return pow($x, 3); }); $inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); }); for ($i = 0; $i < 3; $i++) { $f = $compose($inv[$i], $fn[$i]); ech...
829First-class functions
12php
5apus
null
834Find the missing permutation
11kotlin
0ynsf
use strict ; use warnings ; use DateTime ; for my $i( 1..12 ) { my $date = DateTime->last_day_of_month( year => $ARGV[ 0 ] , month => $i ) ; while ( $date->dow != 7 ) { $date = $date->subtract( days => 1 ) ; } my $ymd = $date->ymd ; print "$ymd\n" ; }
833Find the last Sunday of each month
2perl
ch59a
null
827Flatten a list
11kotlin
8mm0q
def floyd(rows) max = (rows * (rows + 1)) / 2 widths = ((max - rows + 1)..max).map {|n| n.to_s.length + 1} n = 0 rows.times do |r| puts (0..r).map {|i| n += 1; % n}.join end end floyd(5) floyd(14)
824Floyd's triangle
14ruby
347z7
local permute, tablex = require("pl.permute"), require("pl.tablex") local permList, pStr = { "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB" } for perm in permute.iter({"A",...
834Find the missing permutation
1lua
8md0e
fn main() { floyds_triangle(5); floyds_triangle(14); } fn floyds_triangle(n: u32) { let mut triangle: Vec<Vec<String>> = Vec::new(); let mut current = 0; for i in 1..=n { let mut v = Vec::new(); for _ in 0..i { current += 1; v.push(current); } ...
824Floyd's triangle
15rust
6gj3l
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
833Find the last Sunday of each month
12php
xzow5
use DateTime ; my @happymonths ; my @workhardyears ; my @longmonths = ( 1 , 3 , 5 , 7 , 8 , 10 , 12 ) ; my @years = 1900..2100 ; foreach my $year ( @years ) { my $countmonths = 0 ; foreach my $month ( @longmonths ) { my $dt = DateTime->new( year => $year , month => $month , ...
830Five weekends
2perl
u1kvr
>>> >>> from math import sin, cos, acos, asin >>> >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> >>> >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist...
829First-class functions
3python
8m60o
def floydstriangle( n:Int ) = { val s = (1 to n) val t = s map {i => (s.take(i-1).sum) + 1} (s zip t) foreach { n => var m = n._2; for( i <- 0 until n._1 ) { val w = (t.last + i).toString.length + 1
824Floyd's triangle
16scala
9jbm5
cube <- function(x) x^3 croot <- function(x) x^(1/3) compose <- function(f, g) function(x){f(g(x))} f1 <- c(sin, cos, cube) f2 <- c(asin, acos, croot) for(i in 1:3) { print(compose(f1[[i]], f2[[i]])(.5)) }
829First-class functions
13r
xzfw2
import sys import calendar year = 2013 if len(sys.argv) > 1: try: year = int(sys.argv[-1]) except ValueError: pass for month in range(1, 13): last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month)) print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun...
833Find the last Sunday of each month
3python
lk4cv
last_sundays <- function(year) { for (month in 1:12) { if (month == 12) { date <- as.Date(paste0(year,"-",12,"-",31)) } else { date <- as.Date(paste0(year,"-",month+1,"-",1))-1 } while (weekdays(date) != "Sunday") { date <- date - 1 } print(date) } } last_sundays(2004)
833Find the last Sunday of each month
13r
yr26h
cube = proc{|x| x ** 3} croot = proc{|x| x ** (1.quo 3)} compose = proc {|f,g| proc {|x| f[g[x]]}} funclist = [Math.method(:sin), Math.method(:cos), cube] invlist = [Math.method(:asin), Math.method(:acos), croot] puts funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]}
829First-class functions
14ruby
icmoh
#![feature(conservative_impl_trait)] fn main() { let cube = |x: f64| x.powi(3); let cube_root = |x: f64| x.powf(1.0 / 3.0); let flist : [&Fn(f64) -> f64; 3] = [&cube , &f64::sin , &f64::cos ]; let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos]; let result = flist.ite...
829First-class functions
15rust
nl9i4
function flatten(list) if type(list) ~= "table" then return {list} end local flat_list = {} for _, elem in ipairs(list) do for _, val in ipairs(flatten(elem)) do flat_list[#flat_list + 1] = val end end return flat_list end test_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}} print(table...
827Flatten a list
1lua
o998h
import math._
829First-class functions
16scala
tu2fb
sub check_perm { my %hash; @hash{@_} = (); for my $s (@_) { exists $hash{$_} or return $_ for map substr($s,1) . substr($s,0,1), (1..length $s); } } @perms = qw(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB); print check_...
834Find the missing permutation
2perl
5a7u2
require 'date' def last_sundays_of_year(year = Date.today.year) (1..12).map do |month| d = Date.new(year, month, -1) d - d.wday end end puts last_sundays_of_year(2013)
833Find the last Sunday of each month
14ruby
vpr2n
from datetime import timedelta, date DAY = timedelta(days=1) START, STOP = date(1900, 1, 1), date(2101, 1, 1) WEEKEND = {6, 5, 4} FMT = '%Y%m(%B)' def fiveweekendspermonth(start=START, stop=STOP): 'Compute months with five weekends between dates' when = start lastmonth = weekenddays = 0 ...
830Five weekends
3python
5abux
use std::env::args; use time::{Date, Duration}; fn main() { let year = args().nth(1).unwrap().parse::<i32>().unwrap(); (1..=12) .map(|month| Date::try_from_ymd(year + month / 12, ((month% 12) + 1) as u8, 1)) .filter_map(|date| date.ok()) .for_each(|date| { let days_back = ...
833Find the last Sunday of each month
15rust
u17vj
int i = 0 ; char B[88] ; while ( i++ < 100 ) !sprintf( B, , i%3 ? :, i%5 ? : ) ? sprintf( B, , i ):0, printf( , B );
835FizzBuzz
5c
7qkrg
ms = as.Date(sapply(c(1, 3, 5, 7, 8, 10, 12), function(month) paste(1900:2100, month, 1, sep = "-"))) ms = format(sort(ms[weekdays(ms) == "Friday"]), "%b%Y") message("There are ", length(ms), " months with five weekends.") message("The first five: ", paste(ms[1:5], collapse = ", ")) message("The last five: ", paste...
830Five weekends
13r
lk7ce
<?php $finalres = Array(); function permut($arr,$result=array()){ global $finalres; if(empty($arr)){ $finalres[] = implode(,$result); }else{ foreach($arr as $key => $val){ $newArr = $arr; $newres = $result; $newres[] = $val; unset($newArr[$key]); permut($newArr,$newres); } } } $givenPerms = ...
834Find the missing permutation
12php
o9f85
object FindTheLastSundayOfEachMonth extends App { import java.util.Calendar._ val cal = getInstance def lastSundaysOf(year: Int) = (JANUARY to DECEMBER).map{month => cal.set(year, month + 1, 1)
833Find the last Sunday of each month
16scala
gwk4i
import Darwin func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C { return { f(g($0)) } } let funclist = [ { (x: Double) in sin(x) }, { (x: Double) in cos(x) }, { (x: Double) in pow(x, 3) } ] let funclisti = [ { (x: Double) in asin(x) }, { (x: Double) in acos(x) }, { (x: Double) in cbrt(x) } ] println(map(zip(f...
829First-class functions
17swift
o9y8k
import Foundation func lastSundays(of year: Int) -> [Date] { let calendar = Calendar.current var dates = [Date]() for month in 1...12 { var dateComponents = DateComponents(calendar: calendar, year: year, month: month + 1, ...
833Find the last Sunday of each month
17swift
2bglj
require 'date' LONG_MONTHS = [1,3,5,7,8,10,12] YEARS = (1900..2100).to_a dates = YEARS.product(LONG_MONTHS).map{|y, m| Date.new(y,m,31)}.select(&:sunday?) years_4w = YEARS - dates.map(&:year) puts puts dates.first(5).map {|d| d.strftime() }, puts dates.last(5).map {|d| d.strftime() } puts puts years_4w...
830Five weekends
14ruby
gw14q
from itertools import permutations given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''.split() allPerms = [''.join(x) for x in permutations(given[0])] missing = list(set(allPerms) - set(given))
834Find the missing permutation
3python
4ej5k
extern crate chrono; use chrono::prelude::*;
830Five weekends
15rust
rxag5
library(combinat) permute.me <- c("A", "B", "C", "D") perms <- permn(permute.me) perms2 <- matrix(unlist(perms), ncol=length(permute.me), byrow=T) perms3 <- apply(perms2, 1, paste, collapse="") incomplete <- c("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CAD...
834Find the missing permutation
13r
2b4lg
import java.util.Calendar._ import java.util.GregorianCalendar import org.scalatest.{FlatSpec, Matchers} class FiveWeekends extends FlatSpec with Matchers { case class YearMonth[T](year: T, month: T) implicit class CartesianProd[T](val seq: Seq[T]) { def x(other: Seq[T]) = for(s1 <- seq; s2 <- other) yield Y...
830Five weekends
16scala
h0xja
given = %w{ ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB } all = given[0].chars.permutation.collect(&:join) puts
834Find the missing permutation
14ruby
rxkgs
(doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz"))))
835FizzBuzz
6clojure
piebd
sub flatten { map { ref eq 'ARRAY' ? flatten(@$_) : $_ } @_ } my @lst = ([1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []); print flatten(@lst), "\n";
827Flatten a list
2perl
4ee5d
const GIVEN_PERMUTATIONS: [&str; 23] = [ "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB" ]; ...
834Find the missing permutation
15rust
7qbrc
def fat(n: Int) = (2 to n).foldLeft(1)(_*_) def perm[A](x: Int, a: Seq[A]): Seq[A] = if (x == 0) a else { val n = a.size val fatN1 = fat(n - 1) val fatN = fatN1 * n val p = x / fatN1 % fatN val (before, Seq(el, after @ _*)) = a splitAt p el +: perm(x % fatN1, before ++ after) } def findMissingPerm(start: St...
834Find the missing permutation
16scala
k8ahk
while (array_filter($lst, 'is_array')) $lst = call_user_func_array('array_merge', $lst);
827Flatten a list
12php
iccov
package main import ( "fmt" "crypto/md5" "io/ioutil" "log" "os" "path/filepath" "sort" "time" ) type fileData struct { filePath string info os.FileInfo } type hash [16]byte func check(err error) { if err != nil { log.Fatal(err) } } func checksum(filePath ...
836Find duplicate files
0go
jsk7d
>>> def flatten(lst): return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] ) >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] >>> flatten(lst) [1, 2, 3, 4, 5, 6, 7, 8]
827Flatten a list
3python
gww4h
- checks for wrong command line input (not existing directory / negative size) - works on Windows as well as Unix Systems (tested with Mint 17 / Windows 7)
836Find duplicate files
8haskell
o9n8p
import java.io.*; import java.nio.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.security.*; import java.util.*; public class DuplicateFiles { public static void main(String[] args) { if (args.length != 2) { System.err.println("Directory name and minimum file size are ...
836Find duplicate files
9java
wtqej
package main import ( "fmt" "log" "strings" ) var glyphs = []rune("") var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"} var g2lMap = map[rune]string{ '': "R", '': "N", '': "B", '': "Q", '': "K", '': "R", '': "N", '': "B", '': "Q", '': "K", } var nta...
837Find Chess960 starting position identifier
0go
u15vt
use strict; use warnings; use feature 'say'; use List::AllUtils 'indexes'; sub sp_id { my $setup = shift // 'RNBQKBNR'; 8 == length $setup or die 'Illegal position: should have exactly eight pieces'; 1 == @{[ $setup =~ /$_/g ]} or die "Illegal position: should have...
837Find Chess960 starting position identifier
2perl
nldiw
typedef unsigned long ulong; ulong small_primes[] = {2,3,5,7,11,13,17,19,23,29,31,37,41, 43,47,53,59,61,67,71,73,79,83,89,97}; mpz_t tens[MAX_STACK], value[MAX_STACK], answer; ulong base, seen_depth; void add_digit(ulong i) { ulong d; for (d = 1; d < base; d++) { mpz_set(value[i], value[i-1]); mpz_addmul_...
838Find largest left truncatable prime in a given base
5c
d2dnv
use File::Find qw(find); use File::Compare qw(compare); use Sort::Naturally; use Getopt::Std qw(getopts); my %opts; $opts{s} = 1; getopts("s:", \%opts); sub find_dups { my($dir) = @_; my @results; my %files; find { no_chdir => 1, wanted => sub { lstat; -f _ && (-s >= $opt{s} ) && push...
836Find duplicate files
2perl
6gm36
def validate_position(candidate: str): assert ( len(candidate) == 8 ), f valid_pieces = {: 2, : 2, : 2, : 1, : 1} assert { piece for piece in candidate } == valid_pieces.keys(), f for piece_type in valid_pieces.keys(): assert ( candidate.count(piece_type) == ...
837Find Chess960 starting position identifier
3python
d2fn1
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list()) unlist(x)
827Flatten a list
13r
vpp27
main() { for (int i = 1; i <= 100; i++) { List<String> out = []; if (i% 3 == 0) out.add("Fizz"); if (i% 5 == 0) out.add("Buzz"); print(out.length > 0? out.join(""): i); } }
835FizzBuzz
18dart
vp42j
from __future__ import print_function import os import hashlib import datetime def FindDuplicateFiles(pth, minSize = 0, hashName = ): knownFiles = {} for root, dirs, files in os.walk(pth): for fina in files: fullFina = os.path.join(root, fina) isSymLink = os.path.islink(fu...
836Find duplicate files
3python
yr96q
def chess960_to_spid(pos) start_str = pos.tr(, ) s = start_str.delete() n = [0,1,2,3,4].combination(2).to_a.index( [s.index(), s.rindex()] ) q = start_str.delete().index() bs = start_str.index(), start_str.rindex() d = bs.detect(&:even?).div(2) l = bs.detect(&:odd? ).div(2) 96*n + 16*q + 4*d +...
837Find Chess960 starting position identifier
14ruby
tuzf2
require 'digest/md5' def find_duplicate_files(dir) puts Dir.chdir(dir) do file_size = Dir.foreach('.').select{|f| FileTest.file?(f)}.group_by{|f| File.size(f)} file_size.each do |size, files| next if files.size==1 files.group_by{|f| Digest::MD5.file(f).to_s}.each do |md5,fs| next if fs...
836Find duplicate files
14ruby
9jlmz
flat = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten p flat
827Flatten a list
14ruby
7qqri
package main import ( "fmt" "math/big" ) var smallPrimes = [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} const maxStack = 128 var ( tens, values [maxStack]big.Int bigTemp, answer = new(big.Int), new(big.Int) base, seenDepth int ) func addDigit(i int) { for d := 1; d < base; d++ { ...
838Find largest left truncatable prime in a given base
0go
7q7r2
use std::{ collections::BTreeMap, fs::{read_dir, File}, hash::Hasher, io::Read, path::{Path, PathBuf}, }; type Duplicates = BTreeMap<(u64, u64), Vec<PathBuf>>; struct DuplicateFinder { found: Duplicates, min_size: u64, } impl DuplicateFinder { fn search(path: impl AsRef<Path>, min_siz...
836Find duplicate files
15rust
ch29z
primesTo100 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] find2km :: Integral a => a -> (Int,a) find2km n = f 0 n where f k m | r == 1 = (k,m) | otherwise = f (k+1) q where (q,r) = quotRem m 2 millerRabinPrimality :: Integer -> Integer -> Bool miller...
838Find largest left truncatable prime in a given base
8haskell
8m80z
use std::{vec, mem, iter}; enum List<T> { Node(Vec<List<T>>), Leaf(T), } impl<T> IntoIterator for List<T> { type Item = List<T>; type IntoIter = ListIter<T>; fn into_iter(self) -> Self::IntoIter { match self { List::Node(vec) => ListIter::NodeIter(vec.into_iter()), ...
827Flatten a list
15rust
jss72
import java.math.BigInteger; import java.util.*; class LeftTruncatablePrime { private static List<BigInteger> getNextLeftTruncatablePrimes(BigInteger n, int radix, int millerRabinCertainty) { List<BigInteger> probablePrimes = new ArrayList<BigInteger>(); String baseString = n.equals(BigInteger.ZERO) ? "" :...
838Find largest left truncatable prime in a given base
9java
efea5
null
838Find largest left truncatable prime in a given base
11kotlin
k8kh3
const double EPS = 0.001; const double EPS_SQUARE = 0.000001; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { d...
839Find if a point is within a triangle
5c
ed1av
def flatList(l: List[_]): List[Any] = l match { case Nil => Nil case (head: List[_]) :: tail => flatList(head) ::: flatList(tail) case head :: tail => head :: flatList(tail) }
827Flatten a list
16scala
book6
typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' '); do { putchar('...
840Find palindromic numbers in both binary and ternary bases
5c
xtawu
void recurse(unsigned int i) { printf(, i); recurse(i+1); } int main() { recurse(0); return 0; }
841Find limit of recursion
5c
ygt6f
use ntheory qw/:all/; use Math::GMPz; sub lltp { my($n, $b, $best) = (shift, Math::GMPz->new(1)); my @v = map { Math::GMPz->new($_) } @{primes($n-1)}; while (@v) { $best = vecmax(@v); $b *= $n; my @u; foreach my $vi (@v) { push @u, grep { is_prob_prime($_) } map { $vi + $_*$b } 1 .. $n-1; ...
838Find largest left truncatable prime in a given base
2perl
343zs
=> (def *stack* 0) => ((fn overflow [] ((def *stack* (inc *stack*))(overflow)))) java.lang.StackOverflowError (NO_SOURCE_FILE:0) => *stack* 10498
841Find limit of recursion
6clojure
2kml1
import random def is_probable_prime(n,k): if n==0 or n==1: return False if n==2: return True if n% 2 == 0: return False s = 0 d = n-1 while True: quotient, remainder = divmod(d, 2) if remainder == 1: break s += 1 d = quot...
838Find largest left truncatable prime in a given base
3python
6g63w
package main import ( "fmt" "math" ) const EPS = 0.001 const EPS_SQUARE = EPS * EPS func side(x1, y1, x2, y2, x, y float64) float64 { return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1) } func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool { checkSide1 := side(x1, y1, x2, y2, x, y) >= 0 che...
839Find if a point is within a triangle
0go
97ymt
require 'prime' BASE = 3 MAX = 500 stems = Prime.each(BASE-1).to_a (1..MAX-1).each {|i| print t = [] b = BASE ** i stems.each {|z| (1..BASE-1).each {|n| c = n*b+z t.push(c) if c.prime? }} break if t.empty? stems = t } puts less than
838Find largest left truncatable prime in a given base
14ruby
m7myj
import scala.collection.parallel.immutable.ParSeq object LeftTruncatablePrime extends App { private def leftTruncatablePrime(maxRadix: Int, millerRabinCertainty: Int) { def getLargestLeftTruncatablePrime(radix: Int, millerRabinCertainty: Int): BigInt = { def getNextLeftTruncatablePrimes(n: BigInt, radix: I...
838Find largest left truncatable prime in a given base
16scala
2b2lb
int main(int argC, char* argV[]) { char str[MAXORDER],commandString[1000],*startPath; long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max; int i,j,len; double scale; FILE* fp; if(argC==1) printf(,argV[0]); else{ if(strchr(argV[1],' ')!=NULL){ len = strlen(argV[1]); startPath = (char...
842File size distribution
5c
vbm2o
package main import ( "fmt" "strconv" "time" ) func isPalindrome2(n uint64) bool { x := uint64(0) if (n & 1) == 0 { return n == 0 } for x < n { x = (x << 1) | (n & 1) n >>= 1 } return n == x || n == (x>>1) } func reverse3(n uint64) uint64 { x := uint64(...
840Find palindromic numbers in both binary and ternary bases
0go
lhmcw
import BigInt func largestLeftTruncatablePrime(_ base: Int) -> BigInt { var radix = 0 var candidates = [BigInt(0)] while true { let multiplier = BigInt(base).power(radix) var newCandidates = [BigInt]() for i in 1..<BigInt(base) { newCandidates += candidates.map({ ($0+i*multiplier, ($0+i*multi...
838Find largest left truncatable prime in a given base
17swift
yry6e
type Pt a = (a, a) data Overlapping = Inside | Outside | Boundary deriving (Show, Eq) data Triangle a = Triangle (Pt a) (Pt a) (Pt a) deriving Show vertices (Triangle a b c) = [a, b, c] toTriangle :: Num a => Triangle a -> Pt a -> (a, Pt a) toTriangle t (x,y) = let [(x0,y0), (x1,y1), (x2,y2)] = vertices t ...
839Find if a point is within a triangle
8haskell
b8hk2
func list(s: Any...) -> [Any] { return s } func flatten<T>(s: [Any]) -> [T] { var r = [T]() for e in s { switch e { case let a as [Any]: r += flatten(a) case let x as T: r.append(x) default: assert(false, "value of wrong type") } } return r } let s = list(list(1), 2, ...
827Flatten a list
17swift
rxxgg
import Data.Char (digitToInt, intToDigit, isDigit) import Data.List (transpose, unwords) import Numeric (readInt, showIntAtBase) dualPalindromics :: [Integer] dualPalindromics = 0: 1: take 4 ( filter isBinPal (readBase3 . base3Palindrome <$> [1 ..]) ) base3Palindrome :: Integer -> ...
840Find palindromic numbers in both binary and ternary bases
8haskell
1ikps
import java.util.Objects; public class FindTriangle { private static final double EPS = 0.001; private static final double EPS_SQUARE = EPS * EPS; public static class Point { private final double x, y; public Point(double x, double y) { this.x = x; this.y = y; ...
839Find if a point is within a triangle
9java
ge54m
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue;
840Find palindromic numbers in both binary and ternary bases
9java
7x4rj