code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): n = len(a) r = range(n) s = spermutations(n) return fsum(sign * prod(a[i][sigma[i]] for i in r) for sigma, sign in s) if __name__ == '__main__': from pprint import pprint as pp for a in ( [ [1, 2], [3, 4]], [ [1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]], [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], ): print('') pp(a) print('Perm:%s Det:%s'% (perm(a), det(a)))
947Determinant and permanent
3python
0tesq
use strict; use warnings; use feature 'say'; use utf8; binmode(STDOUT, ':utf8'); use List::AllUtils qw(uniq); use Unicode::UCD 'charinfo'; for my $str ( '', '.', 'abcABC', 'XYZ ZYX', '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ', '01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X', '', '', ) { my @S; push @S, $1 while $str =~ /(\X)/g; printf qq{\n"$str" (length: %d) has }, scalar @S; if (@S != uniq @S ) { say "duplicated characters:"; my %P; push @{ $P{$S[$_]} }, 1+$_ for 0..$ for my $k (sort keys %P) { next unless @{$P{$k}} > 1; printf "'%s'%s (0x%x) in positions:%s\n", $k, charinfo(ord $k)->{'name'}, ord($k), join ', ', @{$P{$k}}; } } else { say "no duplicated characters." } }
952Determine if a string has all unique characters
2perl
hwljl
let strings = [ "", #""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "" ] let collapsedStrings = strings.map { $0.replacingOccurrences( of: #"(.)\1*"#, with: "$1", options: .regularExpression)} for (original, collapsed) in zip(strings, collapsedStrings) { print (String(format: "%03d %@\n%03d %@\n", original.count, original, collapsed.count, collapsed)) }
948Determine if a string is collapsible
17swift
i6xo0
require 'mutex_m' class Philosopher def initialize(name, left_fork, right_fork) @name = name @left_fork = left_fork @right_fork = right_fork @meals = 0 end def go while @meals < 5 think dine end puts end def think puts sleep(rand()) puts end def dine fork1, fork2 = @left_fork, @right_fork while true pickup(fork1, :wait => true) puts if pickup(fork2, :wait => false) break end puts release(fork1) fork1, fork2 = fork2, fork1 end puts puts sleep(rand()) puts @meals += 1 release(@left_fork) release(@right_fork) end def pickup(fork, opt) puts opt[:wait]? fork.mutex.mu_lock: fork.mutex.mu_try_lock end def release(fork) puts fork.mutex.unlock end end n = 5 Fork = Struct.new(:fork_id, :mutex) forks = Array.new(n) {|i| Fork.new(i, Object.new.extend(Mutex_m))} philosophers = Array.new(n) do |i| Thread.new(i, forks[i], forks[(i+1)%n]) do |id, f1, f2| ph = Philosopher.new(id, f1, f2).go end end philosophers.each {|thread| thread.join}
941Dining philosophers
14ruby
vh52n
use std::cmp::Ordering; use std::collections::BinaryHeap; use std::usize; struct Grid<T> { nodes: Vec<Node<T>>, } struct Node<T> { data: T, edges: Vec<(usize,usize)>, } #[derive(Copy, Clone, Eq, PartialEq)] struct State { node: usize, cost: usize, }
942Dijkstra's algorithm
15rust
7ejrc
use strict; package Delegator; sub new { bless {} } sub operation { my ($self) = @_; if (defined $self->{delegate} && $self->{delegate}->can('thing')) { $self->{delegate}->thing; } else { 'default implementation'; } } 1; package Delegate; sub new { bless {}; } sub thing { 'delegate implementation' } 1; package main; my $a = Delegator->new; $a->operation eq 'default implementation' or die; $a->{delegate} = 'A delegate may be any object'; $a->operation eq 'default implementation' or die; $a->{delegate} = Delegate->new; $a->operation eq 'delegate implementation' or die;
955Delegates
2perl
pslb0
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError() return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__==: t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
950Determine if two triangles overlap
3python
r1cgq
library(combinat) perm <- function(A) { stopifnot(is.matrix(A)) n <- nrow(A) if(n != ncol(A)) stop("Matrix is not square.") if(n < 1) stop("Matrix has a dimension of size 0.") sum(sapply(combinat::permn(n), function(sigma) prod(sapply(1:n, function(i) A[i, sigma[i]])))) } testData <- list("Test 1" = rbind(c(1, 2), c(3, 4)), "Test 2" = rbind(c(1, 2, 3, 4), c(4, 5, 6, 7), c(7, 8, 9, 10), c(10, 11, 12, 13)), "Test 3" = rbind(c(0, 1, 2, 3, 4), c(5, 6, 7, 8, 9), c(10, 11, 12, 13, 14), c(15, 16, 17, 18, 19), c(20, 21, 22, 23, 24))) print(sapply(testData, function(x) list(Determinant = det(x), Permanent = perm(x))))
947Determinant and permanent
13r
wibe5
null
953Detect division by zero
11kotlin
8zk0q
package main import ( "fmt" "strconv" ) func isNumeric(s string) bool { _, err := strconv.ParseFloat(s, 64) return err == nil } func main() { fmt.Println("Are these strings numeric?") strings := []string{"1", "3.14", "-100", "1e2", "NaN", "rose"} for _, s := range strings { fmt.Printf(" %4s ->%t\n", s, isNumeric(s)) } }
956Determine if a string is numeric
0go
m5qyi
'''Determine if a string has all the same characters''' from itertools import groupby def firstDifferingCharLR(s): '''Either a message reporting that no character changes were seen, or a dictionary with details of the first character (if any) that differs from that at the head of the string. ''' def details(xs): c = xs[1][0] return { 'char': repr(c), 'hex': hex(ord(c)), 'index': s.index(c), 'total': len(s) } xs = list(groupby(s)) return Right(details(xs)) if 1 < len(xs) else ( Left('Total length ' + str(len(s)) + ' - No character changes.') ) def main(): '''Test of 7 strings''' print(fTable('First, if any, points of difference:\n')(repr)( either(identity)( lambda dct: dct['char'] + ' (' + dct['hex'] + ') at character ' + str(1 + dct['index']) + ' of ' + str(dct['total']) + '.' ) )(firstDifferingCharLR)([ '', ' ', '2', '333', '.55', 'tttTTT', '4444 444' ])) def either(fl): '''The application of fl to e if e is a Left value, or the application of fr to e if e is a Right value. ''' return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right']) def identity(x): '''The identity function.''' return x def fTable(s): '''Heading -> x display function -> fx display function -> f -> xs -> tabular string. ''' def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def Left(x): '''Constructor for an empty Either (option type) value with an associated string. ''' return {'type': 'Either', 'Right': None, 'Left': x} def Right(x): '''Constructor for a populated Either (option type) value''' return {'type': 'Either', 'Left': None, 'Right': x} if __name__ == '__main__': main()
949Determine if a string has all the same characters
3python
273lz
use std::thread; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, } } fn eat(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); let _right = table.forks[self.right].lock().unwrap(); println!("{} is eating.", self.name); thread::sleep_ms(1000); println!("{} is done eating.", self.name); } } struct Table { forks: Vec<Mutex<()>>, } fn main() { let table = Arc::new(Table { forks: vec![ Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), ]}); let philosophers = vec![ Philosopher::new("Baruch Spinoza", 0, 1), Philosopher::new("Gilles Deleuze", 1, 2), Philosopher::new("Karl Marx", 2, 3), Philosopher::new("Friedrich Nietzsche", 3, 4), Philosopher::new("Michel Foucault", 0, 4), ]; let handles: Vec<_> = philosophers.into_iter().map(|p| { let table = table.clone(); thread::spawn(move || { p.eat(&table); }) }).collect(); for h in handles { h.join().unwrap(); } }
941Dining philosophers
15rust
uk4vj
class Delegator { function __construct() { $this->delegate = NULL ; } function operation() { if(method_exists($this->delegate, )) return $this->delegate->thing() ; return 'default implementation' ; } } class Delegate { function thing() { return 'Delegate Implementation' ; } } $a = new Delegator() ; print ; $a->delegate = 'A delegate may be any object' ; print ; $a->delegate = new Delegate() ; print ;
955Delegates
12php
yuq61
import java.io.File; public class FileDeleteTest { public static boolean deleteFile(String filename) { boolean exists = new File(filename).delete(); return exists; } public static void test(String type, String filename) { System.out.println("The following " + type + " called " + filename + (deleteFile(filename) ? " was deleted." : " could not be deleted.") ); } public static void main(String args[]) { test("file", "input.txt"); test("file", File.seperator + "input.txt"); test("directory", "docs"); test("directory", File.seperator + "docs" + File.seperator); } }
957Delete a file
9java
10cp2
def isNumeric = { def formatter = java.text.NumberFormat.instance def pos = [0] as java.text.ParsePosition formatter.parse(it, pos)
956Determine if a string is numeric
7groovy
tc1fh
isInteger s = case reads s :: [(Integer, String)] of [(_, "")] -> True _ -> False isDouble s = case reads s :: [(Double, String)] of [(_, "")] -> True _ -> False isNumeric :: String -> Bool isNumeric s = isInteger s || isDouble s
956Determine if a string is numeric
8haskell
kxmh0
isAllSame <- function(string) { strLength <- nchar(string) if(length(strLength) > 1) { stop("This task is intended for character vectors with lengths of at most 1.") } else if(length(strLength) == 0) { cat("Examining a character vector of length 0.\n") TRUE } else if(strLength == 0) { cat("Examining a character vector of length 1, containing an empty string.\n") TRUE } else { cat("Examining the string", paste0(sQuote(string), ","), "which is of length", paste0(strLength, ":"), "\n") characters <- strsplit(string, "")[[1]] differentElementIndex <- match(FALSE, characters[1] == characters, nomatch = 0) if(differentElementIndex == 0) { cat("It has no duplicates.\n") TRUE } else { cat("It has duplicates. ") firstDifferentCharacter <- characters[differentElementIndex] cat(sQuote(firstDifferentCharacter), "is the first different character. It has hex value", sprintf("0x%X", as.integer(charToRaw(firstDifferentCharacter))), "and is at index", paste0(differentElementIndex, "."), "\n") FALSE } } } cat("Test: A string of length 0 (an empty string):\n") cat("Test 1 of 2: An empty character vector:\n") print(isAllSame(character(0))) cat("Test 2 of 2: A character vector containing the empty string:\n") print(isAllSame("")) cat("Test: A string of length 3 which contains three blanks:\n") print(isAllSame(" ")) cat("Test: A string of length 1 which contains 2:\n") print(isAllSame("2")) cat("Test: A string of length 3 which contains 333:\n") print(isAllSame("333")) cat("Test: A string of length 3 which contains .55:\n") print(isAllSame(".55")) cat("Test: A string of length 6 which contains tttTTT:\n") print(isAllSame("tttTTT")) cat("Test: A string of length 9 which contains 4444 444k:\n") print(isAllSame("4444 444k"))
949Determine if a string has all the same characters
13r
m5dy4
require 'date' class DiscordianDate SEASON_NAMES = [,,,,] DAY_NAMES = [,,,,] YEAR_OFFSET = 1166 DAYS_PER_SEASON = 73 DAYS_PER_WEEK = 5 ST_TIBS_DAY_OF_YEAR = 60 def initialize(year, month, day) gregorian_date = Date.new(year, month, day) @day_of_year = gregorian_date.yday @st_tibs = false if gregorian_date.leap? if @day_of_year == ST_TIBS_DAY_OF_YEAR @st_tibs = true elsif @day_of_year > ST_TIBS_DAY_OF_YEAR @day_of_year -= 1 end end @season, @day = (@day_of_year-1).divmod(DAYS_PER_SEASON) @day += 1 @year = gregorian_date.year + YEAR_OFFSET end attr_reader :year, :day def season SEASON_NAMES[@season] end def weekday if @st_tibs else DAY_NAMES[(@day_of_year - 1) % DAYS_PER_WEEK] end end def to_s %Q{ end end
944Discordian date
14ruby
94ymz
object Dijkstra { type Path[Key] = (Double, List[Key]) def Dijkstra[Key](lookup: Map[Key, List[(Double, Key)]], fringe: List[Path[Key]], dest: Key, visited: Set[Key]): Path[Key] = fringe match { case (dist, path) :: fringe_rest => path match {case key :: path_rest => if (key == dest) (dist, path.reverse) else { val paths = lookup(key).flatMap {case (d, key) => if (!visited.contains(key)) List((dist + d, key :: path)) else Nil} val sorted_fringe = (paths ++ fringe_rest).sortWith {case ((d1, _), (d2, _)) => d1 < d2} Dijkstra(lookup, sorted_fringe, dest, visited + key) } } case Nil => (0, List()) } def main(x: Array[String]): Unit = { val lookup = Map( "a" -> List((7.0, "b"), (9.0, "c"), (14.0, "f")), "b" -> List((10.0, "c"), (15.0, "d")), "c" -> List((11.0, "d"), (2.0, "f")), "d" -> List((6.0, "e")), "e" -> List((9.0, "f")), "f" -> Nil ) val res = Dijkstra[String](lookup, List((0, List("a"))), "e", Set()) println(res) } }
942Dijkstra's algorithm
16scala
kqbhk
class Delegator: def __init__(self): self.delegate = None def operation(self): if hasattr(self.delegate, 'thing') and callable(self.delegate.thing): return self.delegate.thing() return 'default implementation' class Delegate: def thing(self): return 'delegate implementation' if __name__ == '__main__': a = Delegator() assert a.operation() == 'default implementation' a.delegate = 'A delegate may be any object' assert a.operation() == 'default implementation' a.delegate = Delegate() assert a.operation() == 'delegate implementation'
955Delegates
3python
102pc
var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.DeleteFile('input.txt'); fso.DeleteFile('c:/input.txt'); fso.DeleteFolder('docs'); fso.DeleteFolder('c:/docs');
957Delete a file
10javascript
qd5x8
require 'matrix' class Matrix def permanent r = (0...row_count).to_a r.permutation.inject(0) do |sum, sigma| sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] } end end end m1 = Matrix[[1,2],[3,4]] m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]] m3 = Matrix[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]] [m1, m2, m3].each do |m| puts , puts end
947Determinant and permanent
14ruby
o3x8v
local function div(a,b) if b == 0 then error() end return a/b end
953Detect division by zero
1lua
o3b8h
'''Determine if a string has all unique characters''' from itertools import groupby def duplicatedCharIndices(s): '''Just the first duplicated character, and the indices of its occurrence, or Nothing if there are no duplications. ''' def go(xs): if 1 < len(xs): duplicates = list(filter(lambda kv: 1 < len(kv[1]), [ (k, list(v)) for k, v in groupby( sorted(xs, key=swap), key=snd ) ])) return Just(second(fmap(fst))( sorted( duplicates, key=lambda kv: kv[1][0] )[0] )) if duplicates else Nothing() else: return Nothing() return go(list(enumerate(s))) def main(): '''Test over various strings.''' def showSample(s): return repr(s) + ' (' + str(len(s)) + ')' def showDuplicate(cix): c, ix = cix return repr(c) + ( ' (' + hex(ord(c)) + ') at ' + repr(ix) ) print( fTable('First duplicated character, if any:')( showSample )(maybe('None')(showDuplicate))(duplicatedCharIndices)([ '', '.', 'abcABC', 'XYZ ZYX', '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ' ]) ) def fTable(s): '''Heading -> x display function -> fx display function -> f -> xs -> tabular string. ''' def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def Just(x): '''Constructor for an inhabited Maybe (option type) value. Wrapper containing the result of a computation. ''' return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): '''Constructor for an empty Maybe (option type) value. Empty wrapper returned where a computation is not possible. ''' return {'type': 'Maybe', 'Nothing': True} def fmap(f): '''fmap over a list. f lifted to a function over a list. ''' return lambda xs: [f(x) for x in xs] def fst(tpl): '''First member of a pair.''' return tpl[0] def head(xs): '''The first element of a non-empty list.''' return xs[0] if isinstance(xs, list) else next(xs) def maybe(v): '''Either the default value v, if m is Nothing, or the application of f to x, where m is Just(x). ''' return lambda f: lambda m: v if ( None is m or m.get('Nothing') ) else f(m.get('Just')) def second(f): '''A simple function lifted to a function over a tuple, with f applied only to the second of two values. ''' return lambda xy: (xy[0], f(xy[1])) def snd(tpl): '''Second member of a pair.''' return tpl[1] def swap(tpl): '''The swapped components of a pair.''' return (tpl[1], tpl[0]) if __name__ == '__main__': main()
952Determine if a string has all unique characters
3python
kx2hf
extern crate chrono; use chrono::NaiveDate; use std::str::FromStr; fn main() { let date = std::env::args().nth(1).expect("Please provide a YYYY-MM-DD date."); println!("{} is {}", date, NaiveDate::from_str(&date).unwrap().to_poee()); }
944Discordian date
15rust
cgm9z
class Delegator attr_accessor :delegate def operation if @delegate.respond_to?(:thing) @delegate.thing else 'default implementation' end end end class Delegate def thing 'delegate implementation' end end if __FILE__ == $PROGRAM_NAME a = Delegator.new puts a.operation a.delegate = 'A delegate may be any object' puts a.operation a.delegate = Delegate.new puts a.operation end
955Delegates
14ruby
eouax
null
957Delete a file
11kotlin
je37r
fn main() { let mut m1: Vec<Vec<f64>> = vec![vec![1.0,2.0],vec![3.0,4.0]]; let mut r_m1 = &mut m1; let rr_m1 = &mut r_m1; let mut m2: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0, 4.0], vec![4.0, 5.0, 6.0, 7.0], vec![7.0, 8.0, 9.0, 10.0], vec![10.0, 11.0, 12.0, 13.0]]; let mut r_m2 = &mut m2; let rr_m2 = &mut r_m2; let mut m3: Vec<Vec<f64>> = vec![vec![0.0, 1.0, 2.0, 3.0, 4.0], vec![5.0, 6.0, 7.0, 8.0, 9.0], vec![10.0, 11.0, 12.0, 13.0, 14.0], vec![15.0, 16.0, 17.0, 18.0, 19.0], vec![20.0, 21.0, 22.0, 23.0, 24.0]]; let mut r_m3 = &mut m3; let rr_m3 = &mut r_m3; println!("Determinant of m1: {}", determinant(rr_m1)); println!("Permanent of m1: {}", permanent(rr_m1)); println!("Determinant of m2: {}", determinant(rr_m2)); println!("Permanent of m2: {}", permanent(rr_m2)); println!("Determinant of m3: {}", determinant(rr_m3)); println!("Permanent of m3: {}", permanent(rr_m3)); } fn minor( a: &mut Vec<Vec<f64>>, x: usize, y: usize) -> Vec<Vec<f64>> { let mut out_vec: Vec<Vec<f64>> = vec![vec![0.0; a.len() - 1]; a.len() -1]; for i in 0..a.len()-1 { for j in 0..a.len()-1 { match () { _ if (i < x && j < y) => { out_vec[i][j] = a[i][j]; }, _ if (i >= x && j < y) => { out_vec[i][j] = a[i + 1][j]; }, _ if (i < x && j >= y) => { out_vec[i][j] = a[i][j + 1]; }, _ => {
947Determinant and permanent
15rust
i6qod
def permutationsSgn[T]: List[T] => List[(Int,List[T])] = { case Nil => List((1,Nil)) case xs => { for { (x, i) <- xs.zipWithIndex (sgn,ys) <- permutationsSgn(xs.take(i) ++ xs.drop(1 + i)) } yield { val sgni = sgn * (2 * (i%2) - 1) (sgni, (x :: ys)) } } } def det(m:List[List[Int]]) = { val summands = for { (sgn,sigma) <- permutationsSgn((0 to m.length - 1).toList).toList } yield { val factors = for (i <- 0 to (m.length - 1)) yield m(i)(sigma(i)) factors.toList.foldLeft(sgn)({case (x,y) => x * y}) } summands.toList.foldLeft(0)({case (x,y) => x + y})
947Determinant and permanent
16scala
f98d4
isAllUnique <- function(string) { strLength <- nchar(string) if(length(strLength) > 1) { stop("This task is intended for character vectors with lengths of at most 1.") } else if(length(strLength) == 0) { cat("Examining a character vector of length 0.", "It is therefore made entirely of unique characters.\n") TRUE } else if(strLength == 0) { cat("Examining a character vector of length 1, containing an empty string.", "It is therefore made entirely of unique characters.\n") TRUE } else if(strLength == 1) { cat("Examining the string", paste0(sQuote(string), ","), "which is of length", paste0(strLength, "."), "It is therefore made entirely of unique characters.\n") TRUE } else { cat("Examining the string", paste0(sQuote(string), ","), "which is of length", paste0(strLength, ":"), "\n") characters <- strsplit(string, "")[[1]] indexesOfDuplicates <- sapply(seq_len(strLength), function(i) match(TRUE, characters[i] == characters[-i], nomatch = -1)) + 1 firstDuplicateElementIndex <- indexesOfDuplicates[indexesOfDuplicates != 0][1] if(is.na(firstDuplicateElementIndex)) { cat("It has no duplicates. It is therefore made entirely of unique characters.\n") TRUE } else { cat("It has duplicates. ") firstDuplicatedCharacter <- characters[firstDuplicateElementIndex] cat(sQuote(firstDuplicatedCharacter), "is the first duplicated character. It has hex value", sprintf("0x%X", as.integer(charToRaw(firstDuplicatedCharacter))), "and is at index", paste0(firstDuplicateElementIndex, "."), "\nThis is a duplicate of the character at index", paste0(match(firstDuplicateElementIndex, indexesOfDuplicates), "."), "\n") FALSE } } } cat("Test: A string of length 0 (an empty string):\n") cat("Test 1 of 2: An empty character vector:\n") print(isAllUnique(character(0))) cat("Test 2 of 2: A character vector containing the empty string:\n") print(isAllUnique("")) cat("Test: A string of length 1 which contains .:\n") print(isAllUnique(".")) cat("Test: A string of length 6 which contains abcABC:\n") print(isAllUnique("abcABC")) cat("Test: A string of length 7 which contains XYZ ZYX:\n") print(isAllUnique("XYZ ZYX")) cat("Test: A string of length 36 doesn't contain the letter 'oh':\n") print(isAllUnique("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"))
952Determine if a string has all unique characters
13r
r1mgj
package rosetta import java.util.GregorianCalendar import java.util.Calendar object DDate extends App { private val DISCORDIAN_SEASONS = Array("Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath")
944Discordian date
16scala
vjl2s
typealias WeightedEdge = (Int, Int, Int) struct Grid<T> { var nodes: [Node<T>] mutating func addNode(data: T) -> Int { nodes.append(Node(data: data, edges: [])) return nodes.count - 1 } mutating func createEdges(weights: [WeightedEdge]) { for (start, end, weight) in weights { nodes[start].edges.append((end, weight)) nodes[end].edges.append((start, weight)) } } func findPath(start: Int, end: Int) -> ([Int], Int)? { var dist = Array(repeating: (Int.max, nil as Int?), count: nodes.count) var heap = Heap<State>(sort: { $0.cost < $1.cost }) dist[start] = (0, nil) heap.insert(State(node: start, cost: 0)) while let state = heap.remove(at: 0) { if state.node == end { var path = [end] var currentDist = dist[end] while let prev = currentDist.1 { path.append(prev) currentDist = dist[prev] } return (path.reversed(), state.cost) } guard state.cost <= dist[state.node].0 else { continue } for edge in nodes[state.node].edges { let next = State(node: edge.0, cost: state.cost + edge.1) if next.cost < dist[next.node].0 { dist[next.node] = (next.cost, state.node) heap.insert(next) } } } return nil } } struct Node<T> { var data: T var edges: [(Int, Int)] } struct State { var node: Int var cost: Int } var grid = Grid<String>(nodes: []) let (a, b, c, d, e, f) = ( grid.addNode(data: "a"), grid.addNode(data: "b"), grid.addNode(data: "c"), grid.addNode(data: "d"), grid.addNode(data: "e"), grid.addNode(data: "f") ) grid.createEdges(weights: [ (a, b, 7), (a, c, 9), (a, f, 14), (b, c, 10), (b, d, 15), (c, d, 11), (c, f, 2), (d, e, 6), (e, f, 9) ]) guard let (path, cost) = grid.findPath(start: a, end: e) else { fatalError("Could not find path") } print("Cost: \(cost)") print(path.map({ grid.nodes[$0].data }).joined(separator: " -> "))
942Dijkstra's algorithm
17swift
g1r49
trait Thingable { fn thing(&self) -> &str; } struct Delegator<T>(Option<T>); struct Delegate {} impl Thingable for Delegate { fn thing(&self) -> &'static str { "Delegate implementation" } } impl<T: Thingable> Thingable for Delegator<T> { fn thing(&self) -> &str { self.0.as_ref().map(|d| d.thing()).unwrap_or("Default implmementation") } } fn main() { let d: Delegator<Delegate> = Delegator(None); println!("{}", d.thing()); let d: Delegator<Delegate> = Delegator(Some(Delegate {})); println!("{}", d.thing()); }
955Delegates
15rust
wi5e4
trait Thingable { def thing: String } class Delegator { var delegate: Thingable = _ def operation: String = if (delegate == null) "default implementation" else delegate.thing } class Delegate extends Thingable { override def thing = "delegate implementation" }
955Delegates
16scala
sfrqo
strings = [, , , , , , , , , ] strings.each do |str| pos = str.empty?? nil: str =~ /[^ print puts pos? : end
949Determine if a string has all the same characters
14ruby
uhyvz
import Foundation protocol Thingable {
955Delegates
17swift
a8v1i
require def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print , t1, print , t2, print % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print , t1, print , t2, print % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print , t1, print , t2, print % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print , t1, print , t2, print % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print , t1, print , t2, print % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print , t1, print , t2, print % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print , t1, print , t2, print % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print , t1, print , t2, print % [triTri2D(t1, t2, 0.0, false, false)] end main()
950Determine if two triangles overlap
14ruby
je27x
public boolean isNumeric(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) {
956Determine if a string is numeric
9java
4bf58
function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } var value = "123.45e7";
956Determine if a string is numeric
10javascript
hwyjh
fn test_string(input: &str) { println!("Checking string {:?} of length {}:", input, input.chars().count()); let mut chars = input.chars(); match chars.next() { Some(first) => { if let Some((character, pos)) = chars.zip(2..).filter(|(c, _)| *c!= first).next() { println!("\tNot all characters are the same."); println!("\t{:?} (0x{:X}) at position {} differs.", character, character as u32, pos); return; } }, None => {} } println!("\tAll characters in the string are the same"); } fn main() { let tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pp", "", ""]; for string in &tests { test_string(string); } }
949Determine if a string has all the same characters
15rust
5kmuq
import scala.collection.immutable.ListMap object StringAllSameCharacters { def countChar( s : String) : Map[Char, Int] = { val mapChar = s.toSeq.groupBy(identity).map{ case (a,b) => a->s.indexOf(a) } val orderedMapChar = ListMap(mapChar.toSeq.sortWith(_._2 < _._2):_*) orderedMapChar } def areAllCharEquals ( mapChar : Map[Char, Int] ) : Boolean = { return mapChar.size <= 1 } def findFirstDifferentChar ( mapChar : Map[Char, Int] ) : Char = { if(areAllCharEquals(mapChar) == false) mapChar.keys.toList(1) else 0.toChar } def charToHexString ( c : Char) : String = "0x" + c.toHexString def reportResults( s : String) : String = { val mapChar = countChar(s) if (areAllCharEquals(mapChar)) s + " -- length " + s.size + " -- contains all the same character." else { val diffChar = findFirstDifferentChar(mapChar) s + " -- length " + s.size + " -- contains a different character at index " + (s.indexOf(diffChar).toInt+1).toString + ": " + charToHexString(diffChar) } } def main(args: Array[String]): Unit = { println(reportResults("")) println(reportResults(" ")) println(reportResults("2")) println(reportResults("333")) println(reportResults(".55")) println(reportResults("tttTTT")) println(reportResults("4444 444k")) } }
949Determine if a string has all the same characters
16scala
r1lgn
def digital_root (n): ap = 0 n = abs(int(n)) while n >= 10: n = sum(int(digit) for digit in str(n)) ap += 1 return ap, n if __name__ == '__main__': for n in [627615, 39390, 588225, 393900588225, 55]: persistance, root = digital_root(n) print( % (n, persistance, root))
945Digital root
3python
dmon1
object Overlap { type Point = (Double, Double) class Triangle(var p1: Point, var p2: Point, var p3: Point) { override def toString: String = s"Triangle: $p1, $p2, $p3" } def det2D(t: Triangle): Double = { val (p1, p2, p3) = (t.p1, t.p2, t.p3) p1._1 * (p2._2 - p3._2) + p2._1 * (p3._2 - p1._2) + p3._1 * (p1._2 - p2._2) } def checkTriWinding(t: Triangle, allowReversed: Boolean): Unit = { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw new RuntimeException("Triangle has wrong winding direction") } } def boundaryCollideChk(t: Triangle, eps: Double): Boolean = det2D(t) < eps def boundaryDoesntCollideChk(t: Triangle, eps: Double): Boolean = det2D(t) <= eps def triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean = {
950Determine if two triangles overlap
16scala
ps4bj
os.remove("input.txt") os.remove("/input.txt") os.remove("docs") os.remove("/docs")
957Delete a file
1lua
hw6j8
strings = [, , , , , , , , , ,] strings.each do |str| seen = {} print res = str.chars.each_with_index do |c,i| if seen[c].nil? seen[c] = i else res = break end end puts res end
952Determine if a string has all unique characters
14ruby
psubh
WITH FUNCTION same_characters_in_string(p_in_str IN varchar2) RETURN varchar2 IS v_que varchar2(32767):= p_in_str; v_res varchar2(32767); v_first varchar2(1); v_next varchar2(1); BEGIN v_first:= substr(v_que,1,1); IF v_first IS NULL THEN v_res:= ' length:0 all characters are the same'; ELSE FOR i IN 2..LENGTH(v_que) loop v_next:= substr(v_que,i,1); IF v_first!= v_next THEN v_res:= ' length:'||LENGTH(v_que)||', first different character (0x'||rawtohex(utl_raw.cast_to_raw(v_next))||') at position:'|| i; exit; END IF; END loop; v_res:= nvl(v_res,' length:'||LENGTH(v_que)||' all characters are the same'); END IF; RETURN v_res; END; --Test SELECT same_characters_in_string('') AS res FROM dual UNION ALL SELECT same_characters_in_string(' ') AS res FROM dual UNION ALL SELECT same_characters_in_string('2') AS res FROM dual UNION ALL SELECT same_characters_in_string('333') AS res FROM dual UNION ALL SELECT same_characters_in_string('.55') AS res FROM dual UNION ALL SELECT same_characters_in_string('tttTTT') AS res FROM dual UNION ALL SELECT same_characters_in_string('4444 444k') AS res FROM dual ;
949Determine if a string has all the same characters
19sql
hwujn
import Foundation let monthDays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] let seasons = ["Chaos", "Discord", "Confusion", "Bureacracy", "The Aftermath"] let dayNames = ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"] let holyDays1 = ["Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"] let holyDays2 = ["Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"] func discordianDate(date: Date) -> String { let calendar = Calendar.current let year = calendar.component(.year, from: date) let month = calendar.component(.month, from: date) let day = calendar.component(.day, from: date) let discYear = year + 1166 if month == 2 && day == 29 { return "St. Tib's Day in the YOLD \(discYear)" } let dayOfYear = monthDays[month - 1] + day - 1 let season = dayOfYear/73 let weekDay = dayOfYear% 5 let dayOfSeason = 1 + dayOfYear% 73 let ddate = "\(dayNames[weekDay]), day \(dayOfSeason) of \(seasons[season]) in the YOLD \(discYear)" switch (dayOfSeason) { case 5: return ddate + ". Celebrate \(holyDays1[season])!" case 50: return ddate + ". Celebrate \(holyDays2[season])!" default: return ddate } } func showDiscordianDate(year: Int, month: Int, day: Int) { let calendar = Calendar.current let date = calendar.date(from: DateComponents(year: year, month: month, day: day))! let ddate = discordianDate(date: date) let format = DateFormatter() format.dateFormat = "yyyy-MM-dd" print("\(format.string(from: date)): \(ddate)") } showDiscordianDate(year: 2022, month: 1, day: 20) showDiscordianDate(year: 2020, month: 9, day: 21) showDiscordianDate(year: 2020, month: 2, day: 29) showDiscordianDate(year: 2019, month: 7, day: 15) showDiscordianDate(year: 2025, month: 3, day: 19) showDiscordianDate(year: 2017, month: 12, day: 8)
944Discordian date
17swift
m56yk
y=1 digital_root=function(n){ x=sum(as.numeric(unlist(strsplit(as.character(n),"")))) if(x<10){ k=x }else{ y=y+1 assign("y",y,envir = globalenv()) k=digital_root(x) } return(k) } print("Given number has additive persistence",y)
945Digital root
13r
8zq0x
package main import "fmt" func main() { fmt.Println("Police Sanitation Fire") fmt.Println("------ ---------- ----") count := 0 for i := 2; i < 7; i += 2 { for j := 1; j < 8; j++ { if j == i { continue } for k := 1; k < 8; k++ { if k == i || k == j { continue } if i + j + k != 12 { continue } fmt.Printf(" %d %d %d\n", i, j, k) count++ } } } fmt.Printf("\n%d valid combinations\n", count) }
958Department numbers
0go
sf5qa
null
956Determine if a string is numeric
11kotlin
lr8cp
fn unique(s: &str) -> Option<(usize, usize, char)> { s.chars().enumerate().find_map(|(i, c)| { s.chars() .enumerate() .skip(i + 1) .find(|(_, other)| c == *other) .map(|(j, _)| (i, j, c)) }) } fn main() { let strings = [ "", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X", "htrognit", "", "", "", ]; for string in &strings { print!("\"{}\" (length {})", string, string.chars().count()); match unique(string) { None => println!(" is unique"), Some((i, j, c)) => println!( " is not unique\n\tfirst duplicate: \"{}\" (U+{:0>4X}) at indices {} and {}", c, c as usize, i, j ), } } }
952Determine if a string has all unique characters
15rust
105pu
class DepartmentNumbers { static void main(String[] args) { println("Police Sanitation Fire") println("------ ---------- ----") int count = 0 for (int i = 2; i <= 6; i += 2) { for (int j = 1; j <= 7; ++j) { if (j == i) continue for (int k = 1; k <= 7; ++k) { if (k == i || k == j) continue if (i + j + k != 12) continue println(" $i $j $k") count++ } } } println() println("$count valid combinations") } }
958Department numbers
7groovy
a8c1p
class String def digroot_persistence(base=10) num = self.to_i(base) persistence = 0 until num < base do num = num.digits(base).sum persistence += 1 end [num.to_s(base), persistence] end end puts %w(627615 39390 588225 393900588225).each do |str| puts % [str, *str.digroot_persistence] end puts format = [[, 2], [ , 16], [, 8], [, 36]].each do |(str, base)| puts format % [str, base, *str.digroot_persistence(base)] end
945Digital root
14ruby
tcnf2
main :: IO () main = mapM_ print $ [2, 4, 6] >>= \x -> [1 .. 7] >>= \y -> [12 - (x + y)] >>= \z -> case y /= z && 1 <= z && z <= 7 of True -> [(x, y, z)] _ -> []
958Department numbers
8haskell
94xmo
fn sum_digits(mut n: u64, base: u64) -> u64 { let mut sum = 0u64; while n > 0 { sum = sum + (n% base); n = n / base; } sum }
945Digital root
15rust
zldto
if tonumber(a) ~= nil then
956Determine if a string is numeric
1lua
27ol3
def digitalRoot(x:BigInt, base:Int=10):(Int,Int) = { def sumDigits(x:BigInt):Int=x.toString(base) map (_.asDigit) sum def loop(s:Int, c:Int):(Int,Int)=if (s < 10) (s, c) else loop(sumDigits(s), c+1) loop(sumDigits(x), 1) } Seq[BigInt](627615, 39390, 588225, BigInt("393900588225")) foreach {x => var (s, c)=digitalRoot(x) println("%d has additive persistance%d and digital root of%d".format(x,c,s)) } var (s, c)=digitalRoot(0x7e0, 16) println("%x has additive persistance%d and digital root of%d".format(0x7e0,c,s))
945Digital root
16scala
yuz63
public class DepartmentNumbers { public static void main(String[] args) { System.out.println("Police Sanitation Fire"); System.out.println("------ ---------- ----"); int count = 0; for (int i = 2; i <= 6; i += 2) { for (int j = 1; j <= 7; ++j) { if (j == i) continue; for (int k = 1; k <= 7; ++k) { if (k == i || k == j) continue; if (i + j + k != 12) continue; System.out.printf(" %d %d %d\n", i, j, k); count++; } } } System.out.printf("\n%d valid combinations", count); } }
958Department numbers
9java
tcbf9
sub div_check {local $@; eval {$_[0] / $_[1]}; $@ and $@ =~ /division by zero/;}
953Detect division by zero
2perl
4b35d
(function () { 'use strict';
958Department numbers
10javascript
m5wyv
function div_check($x, $y) { @trigger_error(''); @($x / $y); $e = error_get_last(); return $e['message'] != ''; }
953Detect division by zero
12php
i6pov
sub dotprod { my($vec_a, $vec_b) = @_; die "they must have the same size\n" unless @$vec_a == @$vec_b; my $sum = 0; $sum += $vec_a->[$_] * $vec_b->[$_] for 0..$ return $sum; } my @vec_a = (1,3,-5); my @vec_b = (4,-2,-1); print dotprod(\@vec_a,\@vec_b), "\n";
938Dot product
2perl
uk7vr
null
958Department numbers
11kotlin
o3r8z
use File::Spec::Functions qw(catfile rootdir); unlink 'input.txt'; rmdir 'docs'; unlink catfile rootdir, 'input.txt'; rmdir catfile rootdir, 'docs';
957Delete a file
2perl
tcpfg
print( "Fire", "Police", "Sanitation" ) sol = 0 for f = 1, 7 do for p = 1, 7 do for s = 1, 7 do if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then print( f, p, s ); sol = sol + 1 end end end end print( string.format( "\n%d solutions found", sol ) )
958Department numbers
1lua
i67ot
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
957Delete a file
12php
kxyhv
def div_check(x, y): try: x / y except ZeroDivisionError: return True else: return False
953Detect division by zero
3python
gp64h
d <- 5/0 if ( !is.finite(d) ) { }
953Detect division by zero
13r
vjf27
null
945Digital root
20typescript
4bv53
<?php function dot_product($v1, $v2) { if (count($v1) != count($v2)) throw new Exception('Arrays have different lengths'); return array_sum(array_map('bcmul', $v1, $v2)); } echo dot_product(array(1, 3, -5), array(4, -2, -1)), ; ?>
938Dot product
12php
83f0m
import os os.remove() os.rmdir() os.remove() os.rmdir()
957Delete a file
3python
zl1tt
def div_check(x, y) begin x / y rescue ZeroDivisionError true else false end end
953Detect division by zero
14ruby
7amri
fn test_division(numerator: u32, denominator: u32) { match numerator.checked_div(denominator) { Some(result) => println!("{} / {} = {}", numerator, denominator, result), None => println!("{} / {} results in a division by zero", numerator, denominator) } } fn main() { test_division(5, 4); test_division(4, 0); }
953Detect division by zero
15rust
je972
file.remove("input.txt") file.remove("/input.txt") file.remove("input.txt", "/input.txt") unlink("input.txt"); unlink("/input.txt") unlink("docs", recursive = TRUE) unlink("/docs", recursive = TRUE)
957Delete a file
13r
nyhi2
object DivideByZero extends Application { def check(x: Int, y: Int): Boolean = { try { val result = x / y println(result) return false } catch { case x: ArithmeticException => { return true } } } println("divided by zero = " + check(1, 0)) def check1(x: Int, y: Int): Boolean = { import scala.util.Try Try(y/x).isFailure } println("divided by zero = " + check1(1, 0)) }
953Detect division by zero
16scala
bq2k6
def dotp(a,b): assert len(a) == len(b), 'Vector sizes must match' return sum(aterm * bterm for aterm,bterm in zip(a, b)) if __name__ == '__main__': a, b = [1, 3, -5], [4, -2, -1] assert dotp(a,b) == 3
938Dot product
3python
5bjux
my @even_numbers; for (1..7) { if ( $_ % 2 == 0) { push @even_numbers, $_; } } print "Police\tFire\tSanitation\n"; foreach my $police_number (@even_numbers) { for my $fire_number (1..7) { for my $sanitation_number (1..7) { if ( $police_number + $fire_number + $sanitation_number == 12 && $police_number != $fire_number && $fire_number != $sanitation_number && $sanitation_number != $police_number) { print "$police_number\t$fire_number\t$sanitation_number\n"; } } } }
958Department numbers
2perl
gpd4e
File.delete(, ) Dir.delete() Dir.delete()
957Delete a file
14ruby
6ve3t
x <- c(1, 3, -5) y <- c(4, -2, -1) sum(x*y) x%*% y dotp <- function(x, y) { n <- length(x) if(length(y)!= n) stop("invalid argument") s <- 0 for(i in 1:n) s <- s + x[i]*y[i] s } dotp(x, y)
938Dot product
13r
l74ce
use std::io::{self, Write}; use std::fs::{remove_file,remove_dir}; use std::path::Path; use std::{process,display}; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME: &'static str = "docs"; fn main() { delete(".").and(delete("/")) .unwrap_or_else(|e| error_handler(e,1)); } fn delete<P>(root: P) -> io::Result<()> where P: AsRef<Path> { remove_file(root.as_ref().join(FILE_NAME)) .and(remove_dir(root.as_ref().join(DIR_NAME))) } fn error_handler<E: fmt::Display>(error: E, code: i32) ->! { let _ = writeln!(&mut io::stderr(), "{:?}", error); process::exit(code) }
957Delete a file
15rust
yuw68
use Scalar::Util qw(looks_like_number); print looks_like_number($str) ? "numeric" : "not numeric\n";
956Determine if a string is numeric
2perl
qd4x6
<?php $valid = 0; for ($police = 2 ; $police <= 6 ; $police += 2) { for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) { $fire = 12 - $police - $sanitation; if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) { echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL; $valid++; } } } echo $valid, ' valid combinations found.', PHP_EOL;
958Department numbers
12php
nyjig
import java.util._ import java.io.File object FileDeleteTest extends App { def deleteFile(filename: String) = { new File(filename).delete() } def test(typ: String, filename: String) = { System.out.println("The following " + typ + " called " + filename + (if (deleteFile(filename)) " was deleted." else " could not be deleted.")) } test("file", "input.txt") test("file", File.separatorChar + "input.txt") test("directory", "docs") test("directory", File.separatorChar + "docs" + File.separatorChar) }
957Delete a file
16scala
cgs93
<?php $string = '123'; if(is_numeric(trim($string))) { } ?>
956Determine if a string is numeric
12php
vji2v
from itertools import permutations def solve(): c, p, f, s = .split(',') print(f) c = 1 for p, f, s in permutations(range(1, 8), r=3): if p + s + f == 12 and p% 2 == 0: print(f) c += 1 if __name__ == '__main__': solve()
958Department numbers
3python
r1fgq
irb(main):001:0> require 'matrix' => true irb(main):002:0> Vector[1, 3, -5].inner_product Vector[4, -2, -1] => 3
938Dot product
14ruby
g1k4q
allPermutations <- setNames(expand.grid(seq(2, 7, by = 2), 1:7, 1:7), c("Police", "Sanitation", "Fire")) solution <- allPermutations[which(rowSums(allPermutations)==12 & apply(allPermutations, 1, function(x) !any(duplicated(x)))),] solution <- solution[order(solution$Police, solution$Sanitation),] row.names(solution) <- paste0("Solution print(solution)
958Department numbers
13r
uhovx
null
938Dot product
15rust
rabg5
def is_numeric(s): try: float(s) return True except (ValueError, TypeError): return False is_numeric('123.0')
956Determine if a string is numeric
3python
sfgq9
class Dot[T](v1: Seq[T])(implicit n: Numeric[T]) { import n._
938Dot product
16scala
hxaja
(1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }
958Department numbers
14ruby
jez7x
> strings <- c("152", "-3.1415926", "Foo123") > suppressWarnings(!is.na(as.numeric(strings))) [1] TRUE TRUE FALSE
956Determine if a string is numeric
13r
eovad
extern crate num_iter; fn main() { println!("Police Sanitation Fire"); println!("----------------------"); for police in num_iter::range_step(2, 7, 2) { for sanitation in 1..8 { for fire in 1..8 { if police!= sanitation && sanitation!= fire && fire!= police && police + fire + sanitation == 12 { println!("{:6}{:11}{:4}", police, sanitation, fire); } } } } }
958Department numbers
15rust
hw3j2
val depts = { (1 to 7).permutations.map{ n => (n(0),n(1),n(2)) }.toList.distinct
958Department numbers
16scala
psmbj
let res = [2, 4, 6].map({x in return (1...7) .filter({ $0!= x }) .map({y -> (Int, Int, Int)? in let z = 12 - (x + y) guard y!= z && 1 <= z && z <= 7 else { return nil } return (x, y, z) }).compactMap({ $0 }) }).flatMap({ $0 }) for result in res { print(result) }
958Department numbers
17swift
7atrq
def is_numeric?(s) begin Float(s) rescue false else true end end
956Determine if a string is numeric
14ruby
8z701
SELECT i, k, SUM(A.N*B.N) AS N FROM A INNER JOIN B ON A.j=B.j GROUP BY i, k
938Dot product
19sql
p0xb1
null
956Determine if a string is numeric
15rust
o3j83
null
958Department numbers
20typescript
8zg0i
import scala.util.control.Exception.allCatch def isNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined
956Determine if a string is numeric
16scala
dmbng