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, planeNormal: Vector3D, planePoint: Vector3D): Vector3D = { val diff = rayPoint - planePoint val prod1 = diff dot planeNormal val prod2 = rayVector dot planeNormal val prod3 = prod1 / prod2 rayPoint - rayVector * prod3 } case class Vector3D(x: Double, y: Double, z: Double) { def +(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z) def -(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z) def *(s: Double) = Vector3D(s * x, s * y, s * z) def dot(v: Vector3D): Double = x * v.x + y * v.y + z * v.z override def toString = s"($x, $y, $z)" } println(s"The ray intersects the plane at $ip") }
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 => Green.bold().paint("T"), Burning => Red.bold().paint("B"), Heating => Yellow.bold().paint("T"), }; write!(f, "{}", output) } }
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) ? [] \ : missingPerms(elts - e, ePerms).collect { [e] + it } }.sum() }
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, month, lastDay[month]); date.setDate(date.getDate() - date.getDay()); sundays.push(date.toISOString().substring(0, 10)); } return sundays; } console.log(lastSundayOfEachMonths(2013).join('\n'));
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" , "BCAD" , "CADB" , "CDBA" , "CBAD" , "ABDC" , "ADBC" , "BDCA" , "DCBA" , "BACD" , "BADC" , "BDAC" , "CBDA" , "DBCA" , "DCAB" ] main :: IO () main = print $ missingPerm deficientPermsList
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,y) end def to_s end end l1 = Line.new(Point.new(4, 0), Point.new(6, 10)) l2 = Line.new(Point.new(0, 3), Point.new(10, 7)) puts
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==4 then list[#list+1]=months[i] end if i==1 and year%4==0 and year%100~=0 or year%400==0 then startday=startday+1 end startday=(startday+v)%7 end return list end local cnt_months=0 local cnt_no5we=0 for y=1900,2100 do local list=find5weMonths(y) cnt_months=cnt_months+#list if #list==0 then cnt_no5we=cnt_no5we+1 end print(y.." "..#list..": "..table.concat(list,", ")) end print("Months with 5 weekends: ",cnt_months) print("Years without 5 weekends in the same month:",cnt_no5we)
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 (Object item: fromTreeList) { if (item instanceof List<?>) { flatten((List<?>) item, toFlatList); } else { toFlatList.add(item); } } } }
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.0.y; let b1 = self.0.x - self.1.x; let c1 = a1 * self.0.x + b1 * self.0.y; let a2 = other.1.y - other.0.y; let b2 = other.0.x - other.1.x; let c2 = a2 * other.0.x + b2 * other.0.y; let delta = a1 * b2 - a2 * b1; if delta == 0.0 { return None; } Some(Point { x: (b2 * c1 - b1 * c2) / delta, y: (a1 * c2 - a2 * c1) / delta, }) } } fn main() { let l1 = Line(Point::new(4.0, 0.0), Point::new(6.0, 10.0)); let l2 = Line(Point::new(0.0, 3.0), Point::new(10.0, 7.0)); println!("{:?}", l1.intersect(l2)); let l1 = Line(Point::new(0.0, 0.0), Point::new(1.0, 1.0)); let l2 = Line(Point::new(1.0, 2.0), Point::new(4.0, 5.0)); println!("{:?}", l1.intersect(l2)); }
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 = l2.s.x - l2.e.x val c2 = a2 * l2.s.x + b2 * l2.s.y val delta = a1 * b2 - a2 * b1
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)) for n in rows[-1]] for row in rows: print( ' '.join('%*i'% space_n for space_n in zip(colspace, row))) >>> pfloyd() 1 2 3 4 5 6 7 8 9 10 >>> pfloyd(floyd(5)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 >>> pfloyd(floyd(14)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 >>>
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.of("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"); for (ArrayList<Character> cs : Utils.Permutations(Lists.newArrayList( 'A', 'B', 'C', 'D'))) if (!s.contains(joiner.join(cs))) System.out.println(joiner.join(cs)); } }
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 isLeapYear(year) then monthLength[2] = 29 end for month = 1, 12 do day = monthLength[month] while dayOfWeek(year, month, day) ~= wday do day = day - 1 end print(year .. "-" .. month .. "-" .. day) end end lastWeekdays("Sunday", tonumber(arg[1]))
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 guard ourSlope!= theirSlope else { return nil } if ourSlope.isNaN &&!theirSlope.isNaN { return Point(x: p1.x, y: (p1.x - other.p1.x) * theirSlope + other.p1.y) } else if theirSlope.isNaN &&!ourSlope.isNaN { return Point(x: other.p1.x, y: (other.p1.x - p1.x) * ourSlope + p1.y) } else { let x = (ourSlope*p1.x - theirSlope*other.p1.x + other.p1.y - p1.y) / (ourSlope - theirSlope) return Point(x: x, y: theirSlope*(x - other.p1.x) + other.p1.y) } } } let l1 = Line(p1: Point(x: 4.0, y: 0.0), p2: Point(x: 6.0, y: 10.0)) let l2 = Line(p1: Point(x: 0.0, y: 3.0), p2: Point(x: 10.0, y: 7.0)) print("Intersection at: \(l1.intersection(of: l2)!)")
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 ); print join "\n", map { compose($flist1[$_], $flist2[$_]) -> (0.5) } 0..2;
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]); echo $f(0.5), PHP_EOL; }
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","B","C","D"}) do pStr = table.concat(perm) if not tablex.find(permList, pStr) then print(pStr) end end
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); } let row = v.iter().map(|x| x.to_string()).collect::<Vec<_>>(); triangle.push(row); } for row in &triangle { let arranged_row: Vec<_> = row .iter() .enumerate() .map(|(i, number)| { let space_len = triangle.last().unwrap()[i].len() - number.len() + 1; let spaces = " ".repeat(space_len); let mut padded_number = spaces; padded_number.push_str(&number); padded_number }) .collect(); println!("{}", arranged_row.join("")) } }
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 . ' ' . $year)) . ; } } printLastSundayOfAllMonth($argv[1]);
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 , day => 1 ) ; if ( $dt->day_of_week == 5 ) { $countmonths++ ; my $yearfound = $dt->year ; my $monthfound = $dt->month_name ; push ( @happymonths , "$yearfound $monthfound" ) ; } } if ( $countmonths == 0 ) { push ( @workhardyears, $year ) ; } } print "There are " . @happymonths . " months with 5 full weekends!\n" ; print "The first 5 and the last 5 of them are:\n" ; foreach my $i ( 0..4 ) { print "$happymonths[ $i ]\n" ; } foreach my $i ( -5..-1 ) { print "$happymonths[ $i ]\n" ; } print "No long weekends in the following " . @workhardyears . " years:\n" ; map { print "$_\n" } @workhardyears ;
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, funclisti)] [0.5, 0.4999999999999999, 0.5] >>>
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_sunday))
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.iter() .zip(&invlist) .map(|(f,i)| compose(f,i)(0.5)) .collect::<Vec<_>>(); println!("{:?}", result); } fn compose<'a, F, G, T, U, V>(f: F, g: G) -> impl 'a + Fn(T) -> V where F: 'a + Fn(T) -> U, G: 'a + Fn(U) -> V, { move |x| g(f(x)) }
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.concat(flatten(test_list), ","))
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_perm(@perms), "\n";
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 fiveweekends = [] while when < stop: year, mon, _mday, _h, _m, _s, wday, _yday, _isdst = when.timetuple() if mon != lastmonth: if weekenddays >= 15: fiveweekends.append(when - DAY) weekenddays = 0 lastmonth = mon if wday in WEEKEND: weekenddays += 1 when += DAY return fiveweekends dates = fiveweekendspermonth() indent = ' ' print('There are%s months of which the first and last five are:'% len(dates)) print(indent +('\n'+indent).join(d.strftime(FMT) for d in dates[:5])) print(indent +'...') print(indent +('\n'+indent).join(d.strftime(FMT) for d in dates[-5:])) print('\nThere are%i years in the range that do not have months with five weekends' % len(set(range(START.year, STOP.year)) - {d.year for d in dates}))
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 = Duration::days(((date.weekday().number_from_sunday() as i64 + 5)% 7) + 1); println!("{}", date - 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(tail(ms, 5), collapse = ", "))
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 = Array(,,,,,,,,,,,,,,,,,,,,,,); $given = Array(,,,); permut($given); print_r(array_diff($finalres,$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(funclist, funclisti)) { f, inversef in compose(f, inversef)(0.5) })
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, day: 0, hour: 12) let date = calendar.date(from: dateComponents)! let weekday = calendar.component(.weekday, from: date) if weekday!= 1 { dateComponents.day! -= weekday - 1 } dates.append(calendar.date(from: dateComponents)!) } return dates } var dateFormatter = DateFormatter() dateFormatter.dateStyle = .short print(lastSundays(of: 2013).map(dateFormatter.string).joined(separator: "\n"))
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.join()
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", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB") setdiff(perms3, incomplete)
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 YearMonth(year=s1,month=s2) def -(other: Seq[T]): Seq[T] = seq diff other } def has5weekends(ym: { val year: Int; val month: Int}) = { val date = new GregorianCalendar(ym.year, ym.month-1, 1) date.get(DAY_OF_WEEK) == FRIDAY && date.getActualMaximum(DAY_OF_MONTH) == 31 } val expectedFirstFive = Seq( YearMonth(1901,3), YearMonth(1902,8), YearMonth(1903,5), YearMonth(1904,1), YearMonth(1904,7)) val expectedFinalFive = Seq( YearMonth(2097,3), YearMonth(2098,8), YearMonth(2099,5), YearMonth(2100,1), YearMonth(2100,10)) val expectedNon5erYears = Seq(1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951, 1956, 1962, 1973, 1979, 1984, 1990, 2001, 2007, 2012, 2018, 2029, 2035, 2040, 2046, 2057, 2063, 2068, 2074, 2085, 2091, 2096) "Five Weekend Algorithm" should "match specification" in { val months = (1900 to 2100) x (1 to 12) filter has5weekends months.size shouldBe 201 months.take(5) shouldBe expectedFirstFive months.takeRight(5) shouldBe expectedFinalFive (1900 to 2100) - months.map(_.year) shouldBe expectedNon5erYears } }
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" ]; fn main() { const PERMUTATION_LEN: usize = GIVEN_PERMUTATIONS[0].len(); let mut bytes_result: [u8; PERMUTATION_LEN] = [0; PERMUTATION_LEN]; for permutation in &GIVEN_PERMUTATIONS { for (i, val) in permutation.bytes().enumerate() { bytes_result[i] ^= val; } } println!("{}", std::str::from_utf8(&bytes_result).unwrap()); }
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: String, perms: Array[String]): String = { for { i <- 0 until fat(start.size) p = perm(i, start).mkString } if (!perms.contains(p)) return p "" } val perms = """ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB""".stripMargin.split("\n") println(findMissingPerm(perms(0), perms))
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 string) hash { bytes, err := ioutil.ReadFile(filePath) check(err) return hash(md5.Sum(bytes)) } func findDuplicates(dirPath string, minSize int64) [][2]fileData { var dups [][2]fileData m := make(map[hash]fileData) werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && info.Size() >= minSize { h := checksum(path) fd, ok := m[h] fd2 := fileData{path, info} if !ok { m[h] = fd2 } else { dups = append(dups, [2]fileData{fd, fd2}) } } return nil }) check(werr) return dups } func main() { dups := findDuplicates(".", 1) fmt.Println("The following pairs of files have the same size and the same hash:\n") fmt.Println("File name Size Date last modified") fmt.Println("==========================================================") sort.Slice(dups, func(i, j int) bool { return dups[i][0].info.Size() > dups[j][0].info.Size()
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 required."); System.exit(1); } try { findDuplicateFiles(args[0], Long.parseLong(args[1])); } catch (Exception e) { e.printStackTrace(); } } private static void findDuplicateFiles(String directory, long minimumSize) throws IOException, NoSuchAlgorithmException { System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes."); Path path = FileSystems.getDefault().getPath(directory); FileVisitor visitor = new FileVisitor(path, minimumSize); Files.walkFileTree(path, visitor); System.out.println("The following sets of files have the same size and checksum:"); for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) { Map<Object, List<String>> map = e.getValue(); if (!containsDuplicates(map)) continue; List<List<String>> fileSets = new ArrayList<>(map.values()); for (List<String> files : fileSets) Collections.sort(files); Collections.sort(fileSets, new StringListComparator()); FileKey key = e.getKey(); System.out.println(); System.out.println("Size: " + key.size_ + " bytes"); for (List<String> files : fileSets) { for (int i = 0, n = files.size(); i < n; ++i) { if (i > 0) System.out.print(" = "); System.out.print(files.get(i)); } System.out.println(); } } } private static class StringListComparator implements Comparator<List<String>> { public int compare(List<String> a, List<String> b) { int len1 = a.size(), len2 = b.size(); for (int i = 0; i < len1 && i < len2; ++i) { int c = a.get(i).compareTo(b.get(i)); if (c != 0) return c; } return Integer.compare(len1, len2); } } private static boolean containsDuplicates(Map<Object, List<String>> map) { if (map.size() > 1) return true; for (List<String> files : map.values()) { if (files.size() > 1) return true; } return false; } private static class FileVisitor extends SimpleFileVisitor<Path> { private MessageDigest digest_; private Path directory_; private long minimumSize_; private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>(); private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException { directory_ = directory; minimumSize_ = minimumSize; digest_ = MessageDigest.getInstance("MD5"); } public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.size() >= minimumSize_) { FileKey key = new FileKey(file, attrs, getMD5Sum(file)); Map<Object, List<String>> map = fileMap_.get(key); if (map == null) fileMap_.put(key, map = new HashMap<>()); List<String> files = map.get(attrs.fileKey()); if (files == null) map.put(attrs.fileKey(), files = new ArrayList<>()); Path relative = directory_.relativize(file); files.add(relative.toString()); } return FileVisitResult.CONTINUE; } private byte[] getMD5Sum(Path file) throws IOException { digest_.reset(); try (InputStream in = new FileInputStream(file.toString())) { byte[] buffer = new byte[8192]; int bytes; while ((bytes = in.read(buffer)) != -1) { digest_.update(buffer, 0, bytes); } } return digest_.digest(); } } private static class FileKey implements Comparable<FileKey> { private byte[] hash_; private long size_; private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException { size_ = attrs.size(); hash_ = hash; } public int compareTo(FileKey other) { int c = Long.compare(other.size_, size_); if (c == 0) c = hashCompare(hash_, other.hash_); return c; } } private static int hashCompare(byte[] a, byte[] b) { int len1 = a.length, len2 = b.length; for (int i = 0; i < len1 && i < len2; ++i) { int c = Byte.compare(a[i], b[i]); if (c != 0) return c; } return Integer.compare(len1, len2); } }
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 ntable = map[string]int{"01": 0, "02": 1, "03": 2, "04": 3, "12": 4, "13": 5, "14": 6, "23": 7, "24": 8, "34": 9} func g2l(pieces string) string { lets := "" for _, p := range pieces { lets += g2lMap[p] } return lets } func spid(pieces string) int { pieces = g2l(pieces)
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 exactly one $_" for <K Q>; 2 == @{[ $setup =~ /$_/g ]} or die "Illegal position: should have exactly two $_\'s" for <B N R>; $setup =~ m/R .* K .* R/x or die 'Illegal position: King not between rooks.'; index($setup,'B')%2 != rindex($setup,'B')%2 or die 'Illegal position: Bishops not on opposite colors.'; my @knights = indexes { 'N' eq $_ } split '', $setup =~ s/[QB]//gr; my $knight = indexes { join('', @knights) eq $_ } <01 02 03 04 12 13 14 23 24 34>; my @bishops = indexes { 'B' eq $_ } split '', $setup; my $dark = int ((grep { $_ % 2 == 0 } @bishops)[0]) / 2; my $light = int ((grep { $_ % 2 == 1 } @bishops)[0]) / 2; my $queen = index(($setup =~ s/B//gr), 'Q'); int 4*(4*(6*$knight + $queen)+$dark)+$light; } say "$_ " . sp_id($_) for <QNRBBNKR RNBQKBNR>;
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_ui(value[i], tens[i], d); if (!mpz_probab_prime_p(value[i], 1)) continue; if (i > seen_depth || (i == seen_depth && mpz_cmp(value[i], answer) == 1)) { if (!mpz_probab_prime_p(value[i], 50)) continue; mpz_set(answer, value[i]); seen_depth = i; gmp_fprintf(stderr, , base, i, answer); } add_digit(i+1); } } void do_base() { ulong i; mpz_set_ui(answer, 0); mpz_set_ui(tens[0], 1); for (i = 1; i < MAX_STACK; i++) mpz_mul_ui(tens[i], tens[i-1], base); for (seen_depth = i = 0; small_primes[i] < base; i++) { fprintf(stderr, , base, small_primes[i]); mpz_set_ui(value[0], small_primes[i]); add_digit(1); } gmp_printf(, base, answer); } int main(void) { ulong i; for (i = 0; i < MAX_STACK; i++) { mpz_init_set_ui(tens[i], 0); mpz_init_set_ui(value[i], 0); } mpz_init_set_ui(answer, 0); for (base = 22; base < 30; base++) do_base(); return 0; }
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 @{$files{-s _}}, $_ } } => $dir; foreach my $files (values %files) { next unless @$files; my %dups; foreach my $a (0 .. @$files - 1) { for (my $b = $a + 1 ; $b < @$files ; $b++) { next if compare(@$files[$a], @$files[$b]); push @{$dups{ @$files[$a] }}, splice @$files, $b--, 1; } } while (my ($original, $clones) = each %dups) { push @results, sprintf "%8d%s\n", (stat($original))[7], join ', ', sort $original, @$clones; } } reverse nsort @results; } print for find_dups(@ARGV);
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) == valid_pieces[piece_type] ), f bishops_pos = [index for index, value in enumerate(candidate) if value == ] assert ( bishops_pos[0]% 2 != bishops_pos[1]% 2 ), f assert [piece for piece in candidate if piece in ] == [ , , , ], def calc_position(start_pos: str): try: validate_position(start_pos) except AssertionError: raise AssertionError subset_step1 = [piece for piece in start_pos if piece not in ] nights_positions = [ index for index, value in enumerate(subset_step1) if value == ] nights_table = { (0, 1): 0, (0, 2): 1, (0, 3): 2, (0, 4): 3, (1, 2): 4, (1, 3): 5, (1, 4): 6, (2, 3): 7, (2, 4): 8, (3, 4): 9, } N = nights_table.get(tuple(nights_positions)) subset_step2 = [piece for piece in start_pos if piece != ] Q = subset_step2.index() dark_squares = [ piece for index, piece in enumerate(start_pos) if index in range(0, 9, 2) ] light_squares = [ piece for index, piece in enumerate(start_pos) if index in range(1, 9, 2) ] D = dark_squares.index() L = light_squares.index() return 4 * (4 * (6*N + Q) + D) + L
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(fullFina) if isSymLink: continue si = os.path.getsize(fullFina) if si < minSize: continue if si not in knownFiles: knownFiles[si] = {} h = hashlib.new(hashName) h.update(open(fullFina, ).read()) hashed = h.digest() if hashed in knownFiles[si]: fileRec = knownFiles[si][hashed] fileRec.append(fullFina) else: knownFiles[si][hashed] = [fullFina] sizeList = list(knownFiles.keys()) sizeList.sort(reverse=True) for si in sizeList: filesAtThisSize = knownFiles[si] for hashVal in filesAtThisSize: if len(filesAtThisSize[hashVal]) < 2: continue fullFinaLi = filesAtThisSize[hashVal] print () for fullFina in fullFinaLi: st = os.stat(fullFina) isHardLink = st.st_nlink > 1 infoStr = [] if isHardLink: infoStr.append() fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ') print (fmtModTime, si, os.path.relpath(fullFina, pth), .join(infoStr)) if __name__==: FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
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 + l end positions = [, ] positions.each{|pos| puts }
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.size==1 puts fs.each{|file| puts } end end end end find_duplicate_files()
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++ { values[i].Set(&values[i-1]) bigTemp.SetUint64(uint64(d)) bigTemp.Mul(bigTemp, &tens[i]) values[i].Add(&values[i], bigTemp) if !values[i].ProbablyPrime(0) { continue } if i > seenDepth || (i == seenDepth && values[i].Cmp(answer) == 1) { if !values[i].ProbablyPrime(0) { continue } answer.Set(&values[i]) seenDepth = i } addDigit(i + 1) } } func doBase() { answer.SetUint64(0) tens[0].SetUint64(1) bigTemp.SetUint64(uint64(base)) seenDepth = 0 for i := 1; i < maxStack; i++ { tens[i].Mul(&tens[i-1], bigTemp) } for i := 0; smallPrimes[i] < base; i++ { values[0].SetUint64(uint64(smallPrimes[i])) addDigit(1) } fmt.Printf("%2d:%s\n", base, answer.String()) } func main() { for base = 3; base <= 17; base++ { doBase() } }
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_size: u64) -> std::io::Result<Duplicates> { let mut result = Self { found: BTreeMap::new(), min_size, }; result.walk(path)?; Ok(result.found) } fn walk(&mut self, path: impl AsRef<Path>) -> std::io::Result<()> { let listing = read_dir(path.as_ref())?; for entry in listing { let entry = entry?; let path = entry.path(); if path.is_dir() { self.walk(path)?; } else { self.compute_digest(&path)?; } } Ok(()) } fn compute_digest(&mut self, file: &Path) -> std::io::Result<()> { let size = file.metadata()?.len(); if size < self.min_size { return Ok(()); }
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 millerRabinPrimality n a | a >= n_ = True | b0 == 1 || b0 == n_ = True | otherwise = iter (tail b) where n_ = n-1 (k,m) = find2km n_ b0 = powMod n a m b = take k $ iterate (squareMod n) b0 iter [] = False iter (x:xs) | x == 1 = False | x == n_ = True | otherwise = iter xs pow_ :: (Num a, Integral b) => (a->a->a) -> (a->a) -> a -> b -> a pow_ _ _ _ 0 = 1 pow_ mul sq x_ n_ = f x_ n_ 1 where f x n y | n == 1 = x `mul` y | r == 0 = f x2 q y | otherwise = f x2 q (x `mul` y) where (q,r) = quotRem n 2 x2 = sq x mulMod :: Integral a => a -> a -> a -> a mulMod a b c = (b * c) `mod` a squareMod :: Integral a => a -> a -> a squareMod a b = (b * b) `rem` a powMod :: Integral a => a -> a -> a -> a powMod m = pow_ (mulMod m) (squareMod m) is_prime w n | n < 100 = n `elem` primesTo100 | any ((==0).(n`mod`)) primesTo100 = False | otherwise = all (millerRabinPrimality n) w left_trunc base = head $ filter (is_prime primesTo100) (reverse hopeful) where hopeful = extend base $ takeWhile (<base) primesTo100 where extend b x = if null d then x else extend (b*base) d where d = concatMap addDigit [1..base-1] addDigit a = filter (is_prime [3]) $ map (a*b+) x main = mapM_ print $ map (\x->(x, left_trunc x)) [3..21]
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()), leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), } } } enum ListIter<T> { NodeIter(vec::IntoIter<List<T>>), LeafIter(iter::Once<List<T>>), } impl<T> ListIter<T> { fn flatten(self) -> Flatten<T> { Flatten { stack: Vec::new(), curr: self, } } } impl<T> Iterator for ListIter<T> { type Item = List<T>; fn next(&mut self) -> Option<Self::Item> { match *self { ListIter::NodeIter(ref mut v_iter) => v_iter.next(), ListIter::LeafIter(ref mut o_iter) => o_iter.next(), } } } struct Flatten<T> { stack: Vec<ListIter<T>>, curr: ListIter<T>, }
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) ? "" : n.toString(radix); for (int i = 1; i < radix; i++) { BigInteger p = new BigInteger(Integer.toString(i, radix) + baseString, radix); if (p.isProbablePrime(millerRabinCertainty)) probablePrimes.add(p); } return probablePrimes; } public static BigInteger getLargestLeftTruncatablePrime(int radix, int millerRabinCertainty) { List<BigInteger> lastList = null; List<BigInteger> list = getNextLeftTruncatablePrimes(BigInteger.ZERO, radix, millerRabinCertainty); while (!list.isEmpty()) { lastList = list; list = new ArrayList<BigInteger>(); for (BigInteger n : lastList) list.addAll(getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty)); } if (lastList == null) return null; Collections.sort(lastList); return lastList.get(lastList.size() - 1); } public static void main(String[] args) { if (args.length != 2) { System.err.println("There must be exactly two command line arguments."); return; } int maxRadix; try { maxRadix = Integer.parseInt(args[0]); if (maxRadix < 3) throw new NumberFormatException(); } catch (NumberFormatException e) { System.err.println("Radix must be an integer greater than 2."); return; } int millerRabinCertainty; try { millerRabinCertainty = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println("Miiller-Rabin Certainty must be an integer."); return; } for (int radix = 3; radix <= maxRadix; radix++) { BigInteger largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty); System.out.print("n=" + radix + ": "); if (largest == null) System.out.println("No left-truncatable prime"); else System.out.println(largest + " (in base " + radix + "): " + largest.toString(radix)); } } }
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) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = min(x1, min(x2, x3)) - EPS; double xMax = max(x1, max(x2, x3)) + EPS; double yMin = min(y1, min(y2, y3)) - EPS; double yMax = max(y1, max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { printf(, x, y); } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { printf(); printPoint(x1, y1); printf(); printPoint(x2, y2); printf(); printPoint(x3, y3); printf(); } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); printf(); printPoint(x, y); printf(); if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { printf(); } else { printf(); } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); printf(); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); printf(); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); printf(); return 0; }
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('0' + (n%base)), n /= base; } while(n); printf(, base); } void show(xint n) { printf(, n); print(n, 2); print(n, 3); putchar('\n'); } xint min(xint a, xint b) { return a < b ? a : b; } xint max(xint a, xint b) { return a > b ? a : b; } int main(void) { xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n; int cnt; show(0); cnt = 1; lo = 0; hi = pow2 = pow3 = 1; while (1) { for (i = lo; i < hi; i++) { n = (i * 3 + 1) * pow3 + reverse3(i); if (!is_palin2(n)) continue; show(n); if (++cnt >= 7) return 0; } if (i == pow3) pow3 *= 3; else pow2 *= 4; while (1) { while (pow2 <= pow3) pow2 *= 4; lo2 = (pow2 / pow3 - 1) / 3; hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1; lo3 = pow3 / 3; hi3 = pow3; if (lo2 >= hi3) pow3 *= 3; else if (lo3 >= hi2) pow2 *= 4; else { lo = max(lo2, lo3); hi = min(hi2, hi3); break; } } } return 0; }
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; } @v = @u; } die unless is_provable_prime($best); $best; } printf "%2d%s\n", $_, lltp($_) for 3 .. 17;
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 = quotient def try_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True for i in range(k): a = random.randrange(2, n) if try_composite(a): return False return True def largest_left_truncatable_prime(base): radix = 0 candidates = [0] while True: new_candidates=[] multiplier = base**radix for i in range(1,base): new_candidates += [x+i*multiplier for x in candidates if is_probable_prime(x+i*multiplier,30)] if len(new_candidates)==0: return max(candidates) candidates = new_candidates radix += 1 for b in range(3,24): print(% (b,largest_left_truncatable_prime(b)))
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 checkSide2 := side(x2, y2, x3, y3, x, y) >= 0 checkSide3 := side(x3, y3, x1, y1, x, y) >= 0 return checkSide1 && checkSide2 && checkSide3 } func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool { xMin := math.Min(x1, math.Min(x2, x3)) - EPS xMax := math.Max(x1, math.Max(x2, x3)) + EPS yMin := math.Min(y1, math.Min(y2, y3)) - EPS yMax := math.Max(y1, math.Max(y2, y3)) + EPS return !(x < xMin || xMax < x || y < yMin || yMax < y) } func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 { p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength if dotProduct < 0 { return (x-x1)*(x-x1) + (y-y1)*(y-y1) } else if dotProduct <= 1 { p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y) return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength } else { return (x-x2)*(x-x2) + (y-y2)*(y-y2) } } func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool { if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) { return false } if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) { return true } if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE { return true } if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE { return true } if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE { return true } return false } func main() { pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}} tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}} fmt.Println("Triangle is", tri) x1, y1 := tri[0][0], tri[0][1] x2, y2 := tri[1][0], tri[1][1] x3, y3 := tri[2][0], tri[2][1] for _, pt := range pts { x, y := pt[0], pt[1] within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) fmt.Println("Point", pt, "is within triangle?", within) } fmt.Println() tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}} fmt.Println("Triangle is", tri) x1, y1 = tri[0][0], tri[0][1] x2, y2 = tri[1][0], tri[1][1] x3, y3 = tri[2][0], tri[2][1] x := x1 + (3.0/7)*(x2-x1) y := y1 + (3.0/7)*(y2-y1) pt := [2]float64{x, y} within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) fmt.Println("Point", pt, "is within triangle?", within) fmt.Println() tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}} fmt.Println("Triangle is", tri) x3 = tri[2][0] y3 = tri[2][1] within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) fmt.Println("Point", pt, "is within triangle?", within) }
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: Int, millerRabinCertainty: Int) = { def baseString = if (n == 0) "" else n.toString(radix) for {i <- (1 until radix).par p = BigInt(Integer.toString(i, radix) + baseString, radix) if p.isProbablePrime(millerRabinCertainty) } yield p } def iter(list: ParSeq[BigInt], lastList: ParSeq[BigInt]): ParSeq[BigInt] = { if (list.isEmpty) lastList else iter((for (n <- list.par) yield getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty)).flatten, list) } iter(getNextLeftTruncatablePrimes(0, radix, millerRabinCertainty), ParSeq.empty).max } for (radix <- (3 to maxRadix).par) { val largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty) println(f"n=$radix%3d: " + (if (largest == null) "No left-truncatable prime" else f"$largest%35d (in base $radix%3d) ${largest.toString(radix)}")) } } val argu: Array[String] = if (args.length >=2 ) args.slice(0, 2) else Array("17", "100") val maxRadix = argu(0).toInt.ensuring(_ > 2, "Radix must be an integer greater than 2.") try { val millerRabinCertainty = argu(1).toInt println(s"Run with maxRadix = $maxRadix and millerRabinCertainty = $millerRabinCertainty") leftTruncatablePrime(maxRadix, millerRabinCertainty) println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]") } catch { case _: NumberFormatException => Console.err.println("Miller-Rabin Certainty must be an integer.") } }
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*)malloc((len+2)*sizeof(char)); startPath[0] = '\'; strncpy(startPath+1,argV[1],len); startPath[len+2] = argV[1][len]; sprintf(commandString,cmd /c echo @fsize\,startPath); } else if(strlen(argV[1])==1 && argV[1][0]=='.') strcpy(commandString,cmd /c echo @fsize\); else sprintf(commandString,cmd /c echo @fsize\,argV[1]); fp = popen(commandString,); while(fgets(str,100,fp)!=NULL){ if(str[0]=='0') fileSizeLog[0]++; else fileSizeLog[strlen(str)]++; } if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){ for(i=0;i<MAXORDER;i++){ printf(,i,fileSizeLog[i]); } } else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){ CONSOLE_SCREEN_BUFFER_INFO csbi; int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi); if(val) { max = fileSizeLog[0]; for(i=1;i<MAXORDER;i++) (fileSizeLog[i]>max)?max=fileSizeLog[i]:max; (max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max); for(i=0;i<MAXORDER;i++){ printf(,i); for(j=0;j<(int)(scale*fileSizeLog[i]);j++) printf(,219); printf(,fileSizeLog[i]); } } } return 0; } }
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(0) for n != 0 { x = x*3 + (n % 3) n /= 3 } return x } func show(n uint64) { fmt.Println("Decimal:", n) fmt.Println("Binary :", strconv.FormatUint(n, 2)) fmt.Println("Ternary:", strconv.FormatUint(n, 3)) fmt.Println("Time :", time.Since(start)) fmt.Println() } func min(a, b uint64) uint64 { if a < b { return a } return b } func max(a, b uint64) uint64 { if a > b { return a } return b } var start time.Time func main() { start = time.Now() fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are:\n") show(0) cnt := 1 var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1 for { i := lo for ; i < hi; i++ { n := (i*3+1)*pow3 + reverse3(i) if !isPalindrome2(n) { continue } show(n) cnt++ if cnt >= 7 { return } } if i == pow3 { pow3 *= 3 } else { pow2 *= 4 } for { for pow2 <= pow3 { pow2 *= 4 } lo2 := (pow2/pow3 - 1) / 3 hi2 := (pow2*2/pow3-1)/3 + 1 lo3 := pow3 / 3 hi3 := pow3 if lo2 >= hi3 { pow3 *= 3 } else if lo3 >= hi2 { pow2 *= 4 } else { lo = max(lo2, lo3) hi = min(hi2, hi3) break } } } }
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*multiplier).isPrime(rounds: 30)) }) .filter({ $0.1 }) .map({ $0.0 }) } if newCandidates.count == 0 { return candidates.max()! } candidates = newCandidates radix += 1 } } for i in 3..<18 { print("\(i): \(largestLeftTruncatablePrime(i))") }
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 s = x2*(y0-y1)+x0*(y1-y2)+x1*(-y0+y2) in ( abs s , ( signum s * (x2*(-y+y0)+x0*(y-y2)+x*(-y0+y2)) , signum s * (x1*(y-y0)+x*(y0-y1)+x0*(-y+y1)))) overlapping :: (Eq a, Ord a, Num a) => Triangle a -> Pt a -> Overlapping overlapping t p = case toTriangle t p of (s, (x, y)) | s == 0 && (x == 0 || y == 0) -> Boundary | s == 0 -> Outside | x > 0 && y > 0 && y < s - x -> Inside | (x <= s && x >= 0) && (y <= s && y >= 0) && (x == 0 || y == 0 || y == s - x) -> Boundary | otherwise -> Outside
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, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list() ) println(s) let result: [Int] = flatten(s) println(result)
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 -> String base3Palindrome = ((<>) <*> (('1':) . reverse)) . showBase 3 isBinPal :: Integer -> Bool isBinPal n = ( \s -> ( \(q, r) -> (1 == r) && drop (succ q) s == reverse (take q s) ) $ quotRem (length s) 2 ) $ showBase 2 n main :: IO () main = mapM_ putStrLn ( unwords <$> transpose ( ( fmap =<< flip justifyLeft ' ' . succ . maximum . fmap length ) <$> transpose ( ["Decimal", "Ternary", "Binary"]: fmap ( (<*>) [show, showBase 3, showBase 2] . return ) dualPalindromics ) ) ) where justifyLeft n c s = take n (s <> replicate n c) readBase3 :: String -> Integer readBase3 = fst . head . readInt 3 isDigit digitToInt showBase :: Integer -> Integer -> String showBase base n = showIntAtBase base intToDigit n []
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; } public double getX() { return x; } public double getY() { return y; } @Override public String toString() { return String.format("(%f,%f)", x, y); } } public static class Triangle { private final Point p1, p2, p3; public Triangle(Point p1, Point p2, Point p3) { this.p1 = Objects.requireNonNull(p1); this.p2 = Objects.requireNonNull(p2); this.p3 = Objects.requireNonNull(p3); } public Point getP1() { return p1; } public Point getP2() { return p2; } public Point getP3() { return p3; } private boolean pointInTriangleBoundingBox(Point p) { var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS; var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS; var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS; var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS; return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY()); } private static double side(Point p1, Point p2, Point p) { return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY()); } private boolean nativePointInTriangle(Point p) { boolean checkSide1 = side(p1, p2, p) >= 0; boolean checkSide2 = side(p2, p3, p) >= 0; boolean checkSide3 = side(p3, p1, p) >= 0; return checkSide1 && checkSide2 && checkSide3; } private double distanceSquarePointToSegment(Point p1, Point p2, Point p) { double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY()); double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength; if (dotProduct < 0) { return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY()); } if (dotProduct <= 1) { double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY()); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY()); } private boolean accuratePointInTriangle(Point p) { if (!pointInTriangleBoundingBox(p)) { return false; } if (nativePointInTriangle(p)) { return true; } if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) { return true; } return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE; } public boolean within(Point p) { Objects.requireNonNull(p); return accuratePointInTriangle(p); } @Override public String toString() { return String.format("Triangle[%s,%s,%s]", p1, p2, p3); } } private static void test(Triangle t, Point p) { System.out.println(t); System.out.printf("Point%s is within triangle?%s\n", p, t.within(p)); } public static void main(String[] args) { var p1 = new Point(1.5, 2.4); var p2 = new Point(5.1, -3.1); var p3 = new Point(-3.8, 1.2); var tri = new Triangle(p1, p2, p3); test(tri, new Point(0, 0)); test(tri, new Point(0, 1)); test(tri, new Point(3, 1)); System.out.println(); p1 = new Point(1.0 / 10, 1.0 / 9); p2 = new Point(100.0 / 8, 100.0 / 3); p3 = new Point(100.0 / 4, 100.0 / 9); tri = new Triangle(p1, p2, p3); var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY())); test(tri, pt); System.out.println(); p3 = new Point(-100.0 / 8, 100.0 / 6); tri = new Triangle(p1, p2, p3); test(tri, pt); } }
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