code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import qualified Data.Set as S semordnilaps :: (Ord a, Foldable t) => t [a] -> [[a]] semordnilaps = let f x (s, w) | S.member (reverse x) s = (s, x: w) | otherwise = (S.insert x s, w) in snd . foldr f (S.empty, []) main :: IO () main = do s <- readFile "unixdict.txt" let l = semordnilaps (lines s) print $ length l mapM_ (print . ((,) <*> reverse)) $ take 5 (filter ((4 <) . length) l)
305Semordnilap
8haskell
mo4yf
function semiprime (n) local divisor, count = 2, 0 while count < 3 and n ~= 1 do if n % divisor == 0 then n = n / divisor count = count + 1 else divisor = divisor + 1 end end return count == 2 end for n = 1675, 1680 do print(n, semiprime(n)) end
304Semiprime
1lua
tx2fn
package main import ( "fmt" "math" ) func remarkable(n int) int { return n + int(.5+math.Sqrt(float64(n))) } func main() {
306Sequence of non-squares
0go
rm1gm
function Is_self_describing( n ) local s = tostring( n ) local t = {} for i = 0, 9 do t[i] = 0 end for i = 1, s:len() do local idx = tonumber( s:sub(i,i) ) t[idx] = t[idx] + 1 end for i = 1, s:len() do if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end end return true end for i = 1, 999999999 do print( Is_self_describing( i ) ) end
308Self-describing numbers
1lua
2fgl3
def nonSquare = { long n -> n + ((1/2 + n**0.5) as long) }
306Sequence of non-squares
7groovy
vtj28
char* eratosthenes(int n, int *c) { char* sieve; int i, j, m; if(n < 2) return NULL; *c = n-1; m = (int) sqrt((double) n); sieve = calloc(n+1,sizeof(char)); sieve[0] = 1; sieve[1] = 1; for(i = 2; i <= m; i++) if(!sieve[i]) for (j = i*i; j <= n; j += i) if(!sieve[j]){ sieve[j] = 1; --(*c); } return sieve; }
309Sieve of Eratosthenes
5c
i1to2
import java.nio.file.*; import java.util.*; public class Semordnilap { public static void main(String[] args) throws Exception { List<String> lst = Files.readAllLines(Paths.get("unixdict.txt")); Set<String> seen = new HashSet<>(); int count = 0; for (String w: lst) { w = w.toLowerCase(); String r = new StringBuilder(w).reverse().toString(); if (seen.contains(r)) { if (count++ < 5) System.out.printf("%-10s%-10s\n", w, r); } else seen.add(w); } System.out.println("\nSemordnilap pairs found: " + count); } }
305Semordnilap
9java
fwcdv
nonsqr :: Integral a => a -> a nonsqr n = n + round (sqrt (fromIntegral n))
306Sequence of non-squares
8haskell
0kts7
chars = (32..127).map do |ord| k = case ord when 32 then when 127 then else ord.chr end end chars.each_slice(chars.size/6).to_a.transpose.each{|s| puts s.join()}
288Show ASCII table
14ruby
shjqw
#!/usr/bin/env node var fs = require('fs'); var sys = require('sys'); var dictFile = process.argv[2] || "unixdict.txt"; var dict = {}; fs.readFileSync(dictFile) .toString() .split('\n') .forEach(function(word) { dict[word] = word.split("").reverse().join(""); }); function isSemordnilap(word) { return dict[dict[word]]; }; var semordnilaps = [] for (var key in dict) { if (isSemordnilap(key)) { var rev = dict[key]; if (key < rev) { semordnilaps.push([key,rev]) ; } } } var count = semordnilaps.length; sys.puts("There are " + count + " semordnilaps in " + dictFile + ". Here are 5:" ); var indices=[] for (var i=0; i<count; ++i) { if (Math.random() < 1/Math.ceil(i/5.0)) { indices[i%5] = i } } indices.sort() for (var i=0; i<5; ++i) { sys.puts(semordnilaps[indices[i]]); }
305Semordnilap
10javascript
y856r
sub isprime { my $n = shift; return ($n >= 2) if $n < 4; return unless $n % 2 && $n % 3; my $sqrtn = int(sqrt($n)); for (my $i = 5; $i <= $sqrtn; $i += 6) { return unless $n % $i && $n % ($i+2); } 1; } print join(" ", grep { isprime($_) } 0 .. 100 ), "\n"; print join(" ", grep { isprime($_) } 12345678 .. 12345678+100 ), "\n";
303Sequence of primes by trial division
2perl
rmwgd
fn main() { for i in 0u8..16 { for j in ((32+i)..128).step_by(16) { let k = (j as char).to_string(); print!("{:3}: {:<3} ", j, match j { 32 => "Spc", 127 => "Del", _ => &k, }); } println!(); } }
288Show ASCII table
15rust
0khsl
object AsciiTable extends App { val (strtCharVal, lastCharVal, nColumns) = (' '.toByte, '\u007F'.toByte, 6) require(nColumns % 2 == 0, "Number of columns must be even.") val nChars = lastCharVal - strtCharVal + 1 val step = nChars / nColumns val threshold = strtCharVal + (nColumns - 1) * step def indexGen(start: Byte): LazyList[Byte] = start #:: indexGen( (if (start >= threshold) strtCharVal + start % threshold + 1 else start + step).toByte ) def k(j: Byte): Char = j match { case `strtCharVal` => '\u2420' case 0x7F => '\u2421' case _ => j.toChar } indexGen(strtCharVal) .take(nChars) .sliding(nColumns, nColumns) .map(_.map(byte => f"$byte%3d: ${k(byte)}")) .foreach(line => println(line.mkString(" "))) }
288Show ASCII table
16scala
i1pox
def sierpinski_carpet(n) carpet = [] n.times do carpet = carpet.collect {|x| x + x + x} + carpet.collect {|x| x + x.tr(,) + x} + carpet.collect {|x| x + x + x} end carpet end 4.times{|i| puts , sierpinski_carpet(i)}
283Sierpinski carpet
14ruby
fw0dr
null
305Semordnilap
11kotlin
8b30q
public class SeqNonSquares { public static int nonsqr(int n) { return n + (int)Math.round(Math.sqrt(n)); } public static void main(String[] args) {
306Sequence of non-squares
9java
a481y
package main import "fmt"
307Set
0go
fwmd0
(defn primes< [n] (remove (set (mapcat #(range (* % %) n %) (range 2 (Math/sqrt n)))) (range 2 n)))
309Sieve of Eratosthenes
6clojure
zqmtj
fn main() { for i in 0..4 { println!("\nN={}", i); println!("{}", sierpinski_carpet(i)); } } fn sierpinski_carpet(n: u32) -> String { let mut carpet = vec!["#".to_string()]; for _ in 0..n { let mut top: Vec<_> = carpet.iter().map(|x| x.repeat(3)).collect(); let middle: Vec<_> = carpet .iter() .map(|x| x.to_string() + &x.replace("#", " ") + x) .collect(); let bottom = top.clone(); top.extend(middle); top.extend(bottom); carpet = top; } carpet.join("\n") }
283Sierpinski carpet
15rust
tx8fd
use ntheory "is_semiprime"; for ([1..100], [1675..1681], [2,4,99,100,1679,5030,32768,1234567,9876543,900660121]) { print join(" ",grep { is_semiprime($_) } @$_),"\n"; }
304Semiprime
2perl
hlqjl
sub is_selfdesc { local $_ = shift; my @b = (0) x length; $b[$_]++ for my @a = split //; return "@a" eq "@b"; } for (0 .. 100000, 3211000, 42101000) { print "$_\n" if is_selfdesc($_); }
308Self-describing numbers
2perl
qjix6
var a = []; for (var i = 1; i < 23; i++) a[i] = i + Math.floor(1/2 + Math.sqrt(i)); console.log(a); for (i = 1; i < 1000000; i++) if (Number.isInteger(i + Math.floor(1/2 + Math.sqrt(i))) === false) { console.log("The ",i,"th element of the sequence is a square"); }
306Sequence of non-squares
10javascript
shfqz
def s1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set def m1 = 6 def m2 = 7 def s2 = [0, 2, 4, 6, 8] as Set assert m1 in s1 : 'member' assert ! (m2 in s2) : 'not a member' def su = s1 + s2 assert su == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set: 'union' def si = s1.intersect(s2) assert si == [8, 6, 4, 2] as Set : 'intersection' def sd = s1 - s2 assert sd == [1, 3, 5, 7, 9, 10] as Set : 'difference' assert s1.containsAll(si) : 'subset' assert ! s1.containsAll(s2) : 'not a subset' assert (si + sd) == s1 : 'equality' assert (s2 + sd) != s1 : 'inequality' assert s1 != su && su.containsAll(s1) : 'proper subset' s1 << 0 assert s1 == su : 'added element 0 to s1'
307Set
7groovy
8bt0b
def nextCarpet(carpet: List[String]): List[String] = ( carpet.map(x => x + x + x) ::: carpet.map(x => x + x.replace('#', ' ') + x) ::: carpet.map(x => x + x + x)) def sierpinskiCarpets(n: Int) = (Iterator.iterate(List("#"))(nextCarpet) drop n next) foreach println
283Sierpinski carpet
16scala
60n31
<?php function is_describing($number) { foreach (str_split((int) $number) as $place => $value) { if (substr_count($number, $place) != $value) { return false; } } return true; } for ($i = 0; $i <= 50000000; $i += 10) { if (is_describing($i)) { echo $i . PHP_EOL; } } ?>
308Self-describing numbers
12php
vtr2v
Prelude> import Data.Set Prelude Data.Set> empty :: Set Integer fromList [] Prelude Data.Set> let s1 = fromList [1,2,3,4,3] Prelude Data.Set> s1 fromList [1,2,3,4] Prelude Data.Set> let s2 = fromList [3,4,5,6] Prelude Data.Set> union s1 s2 fromList [1,2,3,4,5,6] Prelude Data.Set> intersection s1 s2 fromList [3,4] Prelude Data.Set> s1 \\ s2 fromList [1,2] Prelude Data.Set> s1 `isSubsetOf` s1 True Prelude Data.Set> fromList [3,1] `isSubsetOf` s1 True Prelude Data.Set> s1 `isProperSubsetOf` s1 False Prelude Data.Set> fromList [3,1] `isProperSubsetOf` s1 True Prelude Data.Set> fromList [3,2,4,1] == s1 True Prelude Data.Set> s1 == s2 False Prelude Data.Set> 2 `member` s1 True Prelude Data.Set> 10 `notMember` s1 True Prelude Data.Set> size s1 4 Prelude Data.Set> insert 99 s1 fromList [1,2,3,4,99] Prelude Data.Set> delete 3 s1 fromList [1,2,4]
307Set
8haskell
46k5s
#!/usr/bin/env lua
305Semordnilap
1lua
op68h
def prime(a): return not (a < 2 or any(a% x == 0 for x in xrange(2, int(a**0.5) + 1))) def primes_below(n): return [i for i in range(n) if prime(i)]
303Sequence of primes by trial division
3python
79xrm
null
306Sequence of non-squares
11kotlin
hlwj3
from prime_decomposition import decompose def semiprime(n): d = decompose(n) try: return next(d) * next(d) == n except StopIteration: return False
304Semiprime
3python
k2shf
import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.TreeSet; public class Sets { public static void main(String[] args){ Set<Integer> a = new TreeSet<>();
307Set
9java
cn49h
package main import ( "fmt" "strings" "strconv" ) const input = `710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 B B0003 B000300 A00030 E00030 I00030 O00030 U00030 00030 0003` var weight = [...]int{1,3,1,7,3,9} func csd(code string) string { switch len(code) { case 6: case 0: return "No data" default: return "Invalid length" } sum := 0 for i, c := range code { n, err := strconv.ParseInt(string(c), 36, 0) if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' { return "Invalid character" } sum += int(n)*weight[i] } return strconv.Itoa(9-(sum-1)%10) } func main() { for _, s := range strings.Split(input, "\n") { d := csd(s) if len(d) > 1 { fmt.Printf(":%s:%s\n", s, d) } else { fmt.Println(s + d) } } }
310SEDOLs
0go
shoqa
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
308Self-describing numbers
3python
shnq9
require pg = Prime::TrialDivisionGenerator.new p pg.take(10) p pg.next
303Sequence of primes by trial division
14ruby
hlsjx
fn is_prime(number: u32) -> bool { #[allow(clippy::cast_precision_loss)] let limit = (number as f32).sqrt() as u32 + 1;
303Sequence of primes by trial division
15rust
k20h5
function nonSquare (n) return n + math.floor(1/2 + math.sqrt(n)) end for n = 1, 22 do io.write(nonSquare(n) .. " ") end print() local sr for n = 1, 10^6 do sr = math.sqrt(nonSquare(n)) if sr == math.floor(sr) then print("Result for n = " .. n .. " is square!") os.exit() end end print("No squares found")
306Sequence of non-squares
1lua
k2xh2
var set = new Set(); set.add(0); set.add(1); set.add('two'); set.add('three'); set.has(0);
307Set
10javascript
53hur
import Foundation func sierpinski_carpet(n:Int) -> String { func middle(str:String) -> String { let spacer = str.stringByReplacingOccurrencesOfString("#", withString:" ", options:nil, range:nil) return str + spacer + str } var carpet = ["#"] for i in 1...n { let a = carpet.map{$0 + $0 + $0} let b = carpet.map(middle) carpet = a + b + a } return "\n".join(carpet) } println(sierpinski_carpet(3))
283Sierpinski carpet
17swift
desnh
require 'prime' class Integer def semi_prime? prime_division.sum(&:last) == 2 end end p 1679.semi_prime? p ( 1..100 ).select( &:semi_prime? )
304Semiprime
14ruby
pu8bh
def checksum(text) { assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/): "Invalid SEDOL text: $text" def sum = 0 (0..5).each { index -> sum += Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index] } text + (10 - (sum % 10)) % 10 } String.metaClass.sedol = { this.&checksum(delegate) }
310SEDOLs
7groovy
a4x1p
def sieve(nums: Stream[Int]): Stream[Int] = Stream.cons(nums.head, sieve((nums.tail).filter(_ % nums.head != 0))) val primes = 2 #:: sieve(Stream.from(3, 2)) println(primes take 10 toList)
303Sequence of primes by trial division
16scala
15ipf
extern crate primal; fn isqrt(n: usize) -> usize { (n as f64).sqrt() as usize } fn is_semiprime(mut n: usize) -> bool { let root = isqrt(n) + 1; let primes1 = primal::Sieve::new(root); let mut count = 0; for i in primes1.primes_from(2).take_while(|&x| x < root) { while n% i == 0 { n /= i; count += 1; } if n == 1 { break; } } if n!= 1 { count += 1; } count == 2 } #[test] fn test1() { assert_eq!((2..10).filter(|&n| is_semiprime(n)).count(), 3); } #[test] fn test2() { assert_eq!((2..100).filter(|&n| is_semiprime(n)).count(), 34); } #[test] fn test3() { assert_eq!((2..1_000).filter(|&n| is_semiprime(n)).count(), 299); } #[test] fn test4() { assert_eq!((2..10_000).filter(|&n| is_semiprime(n)).count(), 2_625); } #[test] fn test5() { assert_eq!((2..100_000).filter(|&n| is_semiprime(n)).count(), 23_378); } #[test] fn test6() { assert_eq!((2..1_000_000).filter(|&n| is_semiprime(n)).count(), 210_035); }
304Semiprime
15rust
15opu
object Semiprime extends App { def isSP(n: Int): Boolean = { var nf: Int = 0 var l = n for (i <- 2 to l/2) { while (l % i == 0) { if (nf == 2) return false nf +=1 l /= i } } nf == 2 } (2 to 100) filter {isSP(_) == true} foreach {i => print("%d ".format(i))} println 1675 to 1681 foreach {i => println(i+" -> "+isSP(i))} }
304Semiprime
16scala
wrdes
import Data.Char (isAsciiUpper, isDigit, ord) checkSum :: String -> String checkSum x = case traverse sedolValue x of Right xs -> (show . checkSumFromSedolValues) xs Left annotated -> annotated checkSumFromSedolValues :: [Int] -> Int checkSumFromSedolValues xs = rem ( 10 - rem ( sum $ zipWith (*) [1, 3, 1, 7, 3, 9] xs ) 10 ) 10 sedolValue :: Char -> Either String Int sedolValue c | c `elem` "AEIOU" = Left " Unexpected vowel." | isDigit c = Right (ord c - ord '0') | isAsciiUpper c = Right (ord c - ord 'A' + 10) main :: IO () main = mapM_ (putStrLn . ((<>) <*> checkSum)) [ "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "BOYBKT", "B00030" ]
310SEDOLs
8haskell
9i2mo
import Foundation extension SequenceType { func takeWhile(include: Generator.Element -> Bool) -> AnyGenerator<Generator.Element> { var g = self.generate() return anyGenerator { g.next().flatMap{include($0)? $0: nil }} } } var pastPrimes = [2] var primes = anyGenerator { _ -> Int? in defer { pastPrimes.append(pastPrimes.last!) let c = pastPrimes.count - 1 for p in anyGenerator({++pastPrimes[c]}) { let lim = Int(sqrt(Double(p))) if (!pastPrimes.takeWhile{$0 <= lim}.contains{p% $0 == 0}) { break } } } return pastPrimes.last }
303Sequence of primes by trial division
17swift
jcq74
while (<>) { chomp; my $r = reverse; $seen{$r}++ and $c++ < 5 and print "$_ $r\n" or $seen{$_}++; } print "$c\n"
305Semordnilap
2perl
46p5d
null
307Set
11kotlin
3slz5
null
309Sieve of Eratosthenes
18dart
x78wh
import Foundation func primes(n: Int) -> AnyGenerator<Int> { var (seive, i) = ([Int](0..<n), 1) let lim = Int(sqrt(Double(n))) return anyGenerator { while ++i < n { if seive[i]!= 0 { if i <= lim { for notPrime in stride(from: i*i, to: n, by: i) { seive[notPrime] = 0 } } return i } } return nil } } func isSemiPrime(n: Int) -> Bool { let g = primes(n) while let first = g.next() { if n% first == 0 { if first * first == n { return true } else { while let second = g.next() { if first * second == n { return true } } } } } return false }
304Semiprime
17swift
bv0kd
def self_describing?(n) digits = n.digits.reverse digits.each_with_index.all?{|digit, idx| digits.count(idx) == digit} end 3_300_000.times {|n| puts n if self_describing?(n)}
308Self-describing numbers
14ruby
8bf01
<?php $dictionary = array_fill_keys(file( 'http: FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ), true); foreach (array_keys($dictionary) as $word) { $reversed_word = strrev($word); if (isset($dictionary[$reversed_word]) && $word > $reversed_word) $words[$word] = $reversed_word; } echo count($words), ; foreach (array_rand($words, 5) as $word) echo ;
305Semordnilap
12php
i1yov
null
304Semiprime
20typescript
decn0
import java.util.Scanner; public class SEDOL{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String sedol = sc.next(); System.out.println(sedol + getSedolCheckDigit(sedol)); } } private static final int[] mult = {1, 3, 1, 7, 3, 9}; public static int getSedolCheckDigit(String str){ if(!validateSedol(str)){ System.err.println("SEDOL strings must contain six characters with no vowels."); return -1; } str = str.toUpperCase(); int total = 0; for(int i = 0;i < 6; i++){ char s = str.charAt(i); total += Character.digit(s, 36) * mult[i]; } return (10 - (total % 10)) % 10; } public static boolean validateSedol(String str){ return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?"); } }
310SEDOLs
9java
tx6f9
fn is_self_desc(xx: u64) -> bool { let s: String = xx.to_string(); let mut count_vec = vec![0; 10]; for c in s.chars() { count_vec[c.to_digit(10).unwrap() as usize] += 1; } for (i, c) in s.chars().enumerate() { if count_vec[i]!= c.to_digit(10).unwrap() as usize { return false; } } return true; } fn main() { for i in 1..100000000 { if is_self_desc(i) { println!("{}", i) } } }
308Self-describing numbers
15rust
opt83
function sedol(input) { return input + sedol_check_digit(input); } var weight = [1, 3, 1, 7, 3, 9, 1]; function sedol_check_digit(char6) { if (char6.search(/^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}$/) == -1) throw "Invalid SEDOL number '" + char6 + "'"; var sum = 0; for (var i = 0; i < char6.length; i++) sum += weight[i] * parseInt(char6.charAt(i), 36); var check = (10 - sum%10) % 10; return check.toString(); } var input = [ '710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT', "BOATER" , "12345", "123456", "1234567" ]; var expected = [ '7108899', 'B0YBKJ7', '4065663', 'B0YBLH2', '2282765', 'B0YBKL9', '5579107', 'B0YBKR5', '5852842', 'B0YBKT7', null, null, '1234563', null ]; for (var i in input) { try { var sedolized = sedol(input[i]); if (sedolized == expected[i]) print(sedolized); else print("error: calculated sedol for input " + input[i] + " is " + sedolized + ", but it should be " + expected[i] ); } catch (e) { print("error: " + e); } }
310SEDOLs
10javascript
molyv
object SelfDescribingNumbers extends App { def isSelfDescribing(a: Int): Boolean = { val s = Integer.toString(a) (0 until s.length).forall(i => s.count(_.toString.toInt == i) == s(i).toString.toInt) } println("Curious numbers n = x0 x1 x2...x9 such that xi is the number of digits equal to i in n.") for (i <- 0 to 42101000 by 10 if isSelfDescribing(i)) println(i) println("Successfully completed without errors.") }
308Self-describing numbers
16scala
de6ng
import Foundation extension BinaryInteger { @inlinable public var isSelfDescribing: Bool { let stringChars = String(self).map({ String($0) }) let counts = stringChars.reduce(into: [Int: Int](), {res, char in res[Int(char), default: 0] += 1}) for (i, n) in stringChars.enumerated() where counts[i, default: 0]!= Int(n) { return false } return true } } print("Self-describing numbers less than 100,000,000:") DispatchQueue.concurrentPerform(iterations: 100_000_000) {i in defer { if i == 100_000_000 - 1 { exit(0) } } guard i.isSelfDescribing else { return } print(i) } dispatchMain()
308Self-describing numbers
17swift
0kds6
function emptySet() return { } end function insert(set, item) set[item] = true end function remove(set, item) set[item] = nil end function member(set, item) return set[item] end function size(set) local result = 0 for _ in pairs(set) do result = result + 1 end return result end function fromTable(tbl)
307Set
1lua
60239
null
310SEDOLs
11kotlin
opd8z
>>> with open('unixdict.txt') as f: wordset = set(f.read().strip().split()) >>> revlist = (''.join(word[::-1]) for word in wordset) >>> pairs = set((word, rev) for word, rev in zip(wordset, revlist) if word < rev and rev in wordset) >>> len(pairs) 158 >>> sorted(pairs, key=lambda p: (len(p[0]), p))[-5:] [('damon', 'nomad'), ('lager', 'regal'), ('leper', 'repel'), ('lever', 'revel'), ('kramer', 'remark')] >>>
305Semordnilap
3python
gy14h
sub nonsqr { my $n = shift; $n + int(0.5 + sqrt $n) } print join(' ', map nonsqr($_), 1..22), "\n"; foreach my $i (1..1_000_000) { my $root = sqrt nonsqr($i); die "Oops, nonsqr($i) is a square!" if $root == int $root; }
306Sequence of non-squares
2perl
zqltb
<?php for($i=1;$i<=22;$i++){ echo($i + floor(1/2 + sqrt($i)) . ); } $found_square=False; for($i=1;$i<=1000000;$i++){ $non_square=$i + floor(1/2 + sqrt($i)); if(sqrt($non_square)==intval(sqrt($non_square))){ $found_square=True; } } echo(); if($found_square){ echo(); } else { echo(); } ?>
306Sequence of non-squares
12php
bvqk9
dict = File.readlines().collect(&:strip) i = 0 res = dict.collect(&:reverse).sort.select do |z| i += 1 while z > dict[i] and i < dict.length-1 z == dict[i] and z < z.reverse end puts res.take(5).each {|z| puts }
305Semordnilap
14ruby
79eri
use std::collections::HashSet; use std::fs::File; use std::io::{self, BufRead}; use std::iter::FromIterator; fn semordnilap(filename: &str) -> std::io::Result<()> { let file = File::open(filename)?; let mut seen = HashSet::new(); let mut count = 0; for line in io::BufReader::new(file).lines() { let mut word = line?; word.make_ascii_lowercase(); let rev = String::from_iter(word.chars().rev()); if seen.contains(&rev) { if count < 5 { println!("{}\t{}", word, rev); } count += 1; } else { seen.insert(word); } } println!("\nSemordnilap pairs found: {}", count); Ok(()) } fn main() { match semordnilap("unixdict.txt") { Ok(()) => {} Err(error) => eprintln!("{}", error), } }
305Semordnilap
15rust
jcw72
val wordsAll = scala.io.Source. fromURL("http:
305Semordnilap
16scala
bvsk6
use List::Util qw(sum); use POSIX qw(strtol); sub zip(&\@\@) { my $f = shift; my @a = @{shift()}; my @b = @{shift()}; my @result; push(@result, $f->(shift @a, shift @b)) while @a && @b; return @result; } my @weights = (1, 3, 1, 7, 3, 9); sub sedol($) { my $s = shift; $s =~ /[AEIOU]/ and die "No vowels"; my @vs = map {(strtol $_, 36)[0]} split //, $s; my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights); my $check_digit = (10 - $checksum % 10) % 10; return $s . $check_digit; } while (<>) { chomp; print sedol($_), "\n"; }
310SEDOLs
2perl
gyj4e
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
306Sequence of non-squares
3python
3s2zc
nonsqr <- function(n) n + floor(1/2 + sqrt(n)) nonsqr(1:22)
306Sequence of non-squares
13r
demnt
guard let data = try? String(contentsOfFile: "unixdict.txt") else { fatalError() } let words = Set(data.components(separatedBy: "\n")) let pairs = words .map({ ($0, String($0.reversed())) }) .filter({ $0.0 < $0.1 && words.contains($0.1) }) print("Found \(pairs.count) pairs") print("Five examples: \(pairs.prefix(5))")
305Semordnilap
17swift
rmagg
function char2value($c) { assert(stripos('AEIOU', $c) === FALSE); return intval($c, 36); } $sedolweight = array(1,3,1,7,3,9); function checksum($sedol) { global $sedolweight; $tmp = array_sum(array_map(create_function('$ch, $weight', 'return char2value($ch) * $weight;'), str_split($sedol), $sedolweight) ); return strval((10 - ($tmp % 10)) % 10); } foreach (array('710889', 'B0YBKJ', '406566', 'B0YBLH', '228276', 'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT') as $sedol) echo $sedol, checksum($sedol), ;
310SEDOLs
12php
natig
def f(n) n + (0.5 + Math.sqrt(n)).floor end (1..22).each { |n| puts } non_squares = (1..1_000_000).map { |n| f(n) } squares = (1..1001).map { |n| n**2 } (squares & non_squares).each do |n| puts end
306Sequence of non-squares
14ruby
y8u6n
fn f(n: i64) -> i64 { n + (0.5 + (n as f64).sqrt()) as i64 } fn is_sqr(n: i64) -> bool { let a = (n as f64).sqrt() as i64; n == a * a || n == (a+1) * (a+1) || n == (a-1) * (a-1) } fn main() { println!( "{:?}", (1..23).map(|n| f(n)).collect::<Vec<i64>>() ); let count = (1..1_000_000).map(|n| f(n)).filter(|&n| is_sqr(n)).count(); println!("{} unexpected squares found", count); }
306Sequence of non-squares
15rust
mo5ya
def nonsqr(n:Int)=n+math.round(math.sqrt(n)).toInt for(n<-1 to 22) println(n + " "+ nonsqr(n)) val test=(1 to 1000000).exists{n => val j=math.sqrt(nonsqr(n)) j==math.floor(j) } println("squares up to one million="+test)
306Sequence of non-squares
16scala
ldrcq
def char2value(c): assert c not in 'AEIOU', return int(c, 36) sedolweight = [1,3,1,7,3,9] def checksum(sedol): tmp = sum(map(lambda ch, weight: char2value(ch) * weight, sedol, sedolweight) ) return str((10 - (tmp% 10))% 10) for sedol in ''' 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT '''.split(): print sedol + checksum(sedol)
310SEDOLs
3python
rmhgq
use strict; package Set; use overload '""' => \&str, 'bool' => \&count, '+=' => \&add, '-=' => \&del, '-' => \&diff, '==' => \&eq, '&' => \&intersection, '|' => \&union, '^' => \&xdiff; sub str { my $set = shift; "Set{ ". join(", " => sort map("$_", values %$set)) . " }" } sub new { my $pkg = shift; my $h = bless {}; $h->add($_) for @_; $h } sub add { my ($set, $elem) = @_; $set->{$elem} = $elem; $set } sub del { my ($set, $elem) = @_; delete $set->{$elem}; $set } sub has { my ($set, $elem) = @_; exists $set->{$elem} } sub union { my ($this, $that) = @_; bless { %$this, %$that } } sub intersection { my ($this, $that) = @_; my $s = new Set; for (keys %$this) { $s->{$_} = $this->{$_} if exists $that->{$_} } $s } sub diff { my ($this, $that) = @_; my $s = Set->new; for (keys %$this) { $s += $this->{$_} unless exists $that->{$_} } $s } sub xdiff { my ($this, $that) = @_; my $s = new Set; bless { %{ ($this - $that) | ($that - $this) } } } sub count { scalar(keys %{+shift}) } sub eq { my ($this, $that) = @_; !($this - $that) && !($that - $this); } sub contains { my ($this, $that) = @_; for (keys %$that) { return 0 unless $this->has($_) } return 1 } package main; my ($x, $y, $z, $w); $x = Set->new(1, 2, 3); $x += $_ for (5 .. 7); $y = Set->new(1, 2, 4, $x); print "set x is: $x\nset y is: $y\n"; for (1 .. 4, $x) { print "$_ is", $y->has($_) ? "" : " not", " in y\n"; } print "union: ", $x | $y, "\n"; print "intersect: ", $x & $y, "\n"; print "z = x - y = ", $z = $x - $y, "\n"; print "y is ", $x->contains($y) ? "" : "not ", "a subset of x\n"; print "z is ", $x->contains($z) ? "" : "not ", "a subset of x\n"; print "z = (x | y) - (x & y) = ", $z = ($x | $y) - ($x & $y), "\n"; print "w = x ^ y = ", $w = ($x ^ $y), "\n"; print "w is ", ($w == $z) ? "" : "not ", "equal to z\n"; print "w is ", ($w == $x) ? "" : "not ", "equal to x\n";
307Set
2perl
puqb0
datalines <- readLines(tc <- textConnection("710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT")); close(tc) checkSedol <- function(datalines) { ok <- grep("^[[:digit:][:upper:]]{6}$", datalines) if(length(ok) < length(datalines)) { stop("there are invalid lines") } } checkSedol(datalines) appendCheckDigit <- function(x) { if(length(x) > 1) return(sapply(x, appendCheckDigit)) ascii <- as.integer(charToRaw(x)) scores <- ifelse(ascii < 65, ascii - 48, ascii - 55) weights <- c(1, 3, 1, 7, 3, 9) chkdig <- (10 - sum(scores * weights) %% 10) %% 10 paste(x, as.character(chkdig), sep="") } withchkdig <- appendCheckDigit(datalines) writeLines(withchkdig)
310SEDOLs
13r
uzgvx
Sedol_char = Sedolweight = [1,3,1,7,3,9] def char2value(c) raise ArgumentError, unless Sedol_char.include?(c) c.to_i(36) end def checksum(sedol) raise ArgumentError, unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight } ((10 - (sum % 10)) % 10).to_s end data = %w(710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 C0000 1234567 00000A) data.each do |sedol| print % sedol begin puts sedol + checksum(sedol) rescue => e p e end end
310SEDOLs
14ruby
jcb7x
fn sedol(input: &str) -> Option<String> { let weights = vec![1, 3, 1, 7, 3, 9, 1]; let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ"; if input.len()!= 6 { return None; }
310SEDOLs
15rust
hlpj2
class SEDOL(s: String) { require(s.size == 6 || s.size == 7, "SEDOL length must be 6 or 7 characters") require(s.size == 6 || s(6).asDigit == chksum, "Incorrect SEDOL checksum") require(s forall (c => !("aeiou" contains c.toLower)), "Vowels not allowed in SEDOL") def chksum = 10 - ((s zip List(1, 3, 1, 7, 3, 9) map { case (c, w) => c.asDigit * w } sum) % 10) override def toString = s.take(6) + chksum }
310SEDOLs
16scala
puebj
>>> s1, s2 = {1, 2, 3, 4}, {3, 4, 5, 6} >>> s1 | s2 {1, 2, 3, 4, 5, 6} >>> s1 & s2 {3, 4} >>> s1 - s2 {1, 2} >>> s1 < s1 False >>> {3, 1} < s1 True >>> s1 <= s1 True >>> {3, 1} <= s1 True >>> {3, 2, 4, 1} == s1 True >>> s1 == s2 False >>> 2 in s1 True >>> 10 not in s1 True >>> {1, 2, 3, 4, 5} > s1 True >>> {1, 2, 3, 4} > s1 False >>> {1, 2, 3, 4} >= s1 True >>> s1 ^ s2 {1, 2, 5, 6} >>> len(s1) 4 >>> s1.add(99) >>> s1 {99, 1, 2, 3, 4} >>> s1.discard(99) >>> s1 {1, 2, 3, 4} >>> s1 |= s2 >>> s1 {1, 2, 3, 4, 5, 6} >>> s1 -= s2 >>> s1 {1, 2} >>> s1 ^= s2 >>> s1 {1, 2, 3, 4, 5, 6} >>>
307Set
3python
15spc
package main import "fmt" func main() { const limit = 201
309Sieve of Eratosthenes
0go
gyh4n
>> require 'set' => true >> s1, s2 = Set[1, 2, 3, 4], [3, 4, 5, 6].to_set => [ >> s1 | s2 => >> s1 & s2 => >> s1 - s2 => >> s1.proper_subset?(s1) => false >> Set[3, 1].proper_subset?(s1) => true >> s1.subset?(s1) => true >> Set[3, 1].subset?(s1) => true >> Set[3, 2, 4, 1] == s1 => true >> s1 == s2 => false >> s1.include?(2) => true >> Set[1, 2, 3, 4, 5].proper_superset?(s1) => true >> Set[1, 2, 3, 4].proper_superset?(s1) => false >> Set[1, 2, 3, 4].superset?(s1) => true >> s1 ^ s2 => >> s1.size => 4 >> s1 << 99 => >> s1.delete(99) => >> s1.merge(s2) => >> s1.subtract(s2) => >>
307Set
14ruby
eg8ax
def sievePrimes = { bound -> def isPrime = new BitSet(bound) isPrime[0..1] = false isPrime[2..bound] = true (2..(Math.sqrt(bound))).each { pc -> if (isPrime[pc]) { ((pc**2)..bound).step(pc) { isPrime[it] = false } } } (0..bound).findAll { isPrime[it] } }
309Sieve of Eratosthenes
7groovy
2f4lv
use std::collections::HashSet; fn main() { let a = vec![1, 3, 4].into_iter().collect::<HashSet<i32>>(); let b = vec![3, 5, 6].into_iter().collect::<HashSet<i32>>(); println!("Set A: {:?}", a.iter().collect::<Vec<_>>()); println!("Set B: {:?}", b.iter().collect::<Vec<_>>()); println!("Does A contain 4? {}", a.contains(&4)); println!("Union: {:?}", a.union(&b).collect::<Vec<_>>()); println!("Intersection: {:?}", a.intersection(&b).collect::<Vec<_>>()); println!("Difference: {:?}", a.difference(&b).collect::<Vec<_>>()); println!("Is A a subset of B? {}", a.is_subset(&b)); println!("Is A equal to B? {}", a == b); }
307Set
15rust
wroe4
import Control.Monad.ST ( runST, ST ) import Data.Array.Base ( MArray(newArray, unsafeRead, unsafeWrite), IArray(unsafeAt), STUArray, unsafeFreezeSTUArray, assocs ) import Data.Time.Clock.POSIX ( getPOSIXTime ) primesTo :: Int -> [Int] primesTo limit = runST $ do let lmt = limit - 2 cmpsts <- newArray (2, limit) False cmpstsf <- unsafeFreezeSTUArray cmpsts let getbpndx bp = (bp, bp * bp - 2) cullcmpst i = unsafeWrite cmpsts i True cull4bpndx (bp, si0) = mapM_ cullcmpst [ si0, si0 + bp .. lmt ] mapM_ cull4bpndx $ takeWhile ((>=) lmt . snd) [ getbpndx bp | (bp, False) <- assocs cmpstsf ] return [ p | (p, False) <- assocs cmpstsf ] main :: IO () main = do putStrLn $ "The primes up to 100 are " ++ show (primesTo 100) putStrLn $ "The number of primes up to a million is " ++ show (length $ primesTo 1000000) let top = 1000000000 start <- getPOSIXTime let answr = length $ primesTo top stop <- answr `seq` getPOSIXTime let elpsd = round $ 1e3 * (stop - start) :: Int putStrLn $ "Found " ++ show answr ++ " to " ++ show top ++ " in " ++ show elpsd ++ " milliseconds."
309Sieve of Eratosthenes
8haskell
shiqk
object sets { val set1 = Set(1,2,3,4,5) val set2 = Set(3,5,7,9) println(set1 contains 3) println(set1 | set2) println(set1 & set2) println(set1 diff set2) println(set1 subsetOf set2) println(set1 == set2) }
307Set
16scala
shdqo
with open('Traceback.txt', 'r' ) as f: rawText = f.read() paragraphs = rawText.split( ) for p in paragraphs: if in p: index = p.find( ) if -1 != index: print( p[index:] ) print( )
311Search in paragraph's text
3python
uz4vd
import java.util.LinkedList; public class Sieve{ public static LinkedList<Integer> sieve(int n){ if(n < 2) return new LinkedList<Integer>(); LinkedList<Integer> primes = new LinkedList<Integer>(); LinkedList<Integer> nums = new LinkedList<Integer>(); for(int i = 2;i <= n;i++){
309Sieve of Eratosthenes
9java
15xp2
function eratosthenes(limit) { var primes = []; if (limit >= 2) { var sqrtlmt = Math.sqrt(limit) - 2; var nums = new Array();
309Sieve of Eratosthenes
10javascript
qjox8
-- set of numbers is a table -- create one set with 3 elements CREATE TABLE myset1 (element NUMBER); INSERT INTO myset1 VALUES (1); INSERT INTO myset1 VALUES (2); INSERT INTO myset1 VALUES (3); commit; -- check if 1 is an element SELECT 'TRUE' BOOL FROM dual WHERE 1 IN (SELECT element FROM myset1); -- create second set with 3 elements CREATE TABLE myset2 (element NUMBER); INSERT INTO myset2 VALUES (1); INSERT INTO myset2 VALUES (5); INSERT INTO myset2 VALUES (6); commit; -- union sets SELECT element FROM myset1 UNION SELECT element FROM myset2; -- intersection SELECT element FROM myset1 INTERSECT SELECT element FROM myset2; -- difference SELECT element FROM myset1 minus SELECT element FROM myset2; -- subset -- change myset2 to only have 1 as element DELETE FROM myset2 WHERE NOT element = 1; commit; -- check if myset2 subset of myset1 SELECT 'TRUE' BOOL FROM dual WHERE 0 = (SELECT COUNT(*) FROM (SELECT element FROM myset2 minus SELECT element FROM myset1)); -- equality -- change myset1 to only have 1 as element DELETE FROM myset1 WHERE NOT element = 1; commit; -- check if myset2 subset of myset1 and -- check if myset1 subset of myset2 and SELECT 'TRUE' BOOL FROM dual WHERE 0 = (SELECT COUNT(*) FROM (SELECT element FROM myset2 minus SELECT element FROM myset1)) AND 0 = (SELECT COUNT(*) FROM (SELECT element FROM myset1 minus SELECT element FROM myset2));
307Set
19sql
opz8e
var s1: Set<Int> = [1, 2, 3, 4] let s2: Set<Int> = [3, 4, 5, 6] println(s1.union(s2))
307Set
17swift
a401i
int main(void) { FILE *fh = tmpfile(); fclose(fh); return 0; }
312Secure temporary file
5c
mo9ys
(let [temp-file (java.io.File/createTempFile "pre" ".suff")] (.delete temp-file))
312Secure temporary file
6clojure
vtu2f
import kotlin.math.sqrt fun sieve(max: Int): List<Int> { val xs = (2..max).toMutableList() val limit = sqrt(max.toDouble()).toInt() for (x in 2..limit) xs -= x * x..max step x return xs } fun main(args: Array<String>) { println(sieve(100)) }
309Sieve of Eratosthenes
11kotlin
jcp7r
package main import ( "fmt" "io/ioutil" "log" "os" ) func main() { f, err := ioutil.TempFile("", "foo") if err != nil { log.Fatal(err) } defer f.Close()
312Secure temporary file
0go
a4e1f
int a; static int p; extern float v; int code(int arg) { int myp; static int myc; } static void code2(void) { v = v * 1.02; }
313Scope modifiers
5c
4645t
def file = File.createTempFile( "xxx", ".txt" )
312Secure temporary file
7groovy
hlkj9
import System.IO main = do (pathOfTempFile, h) <- openTempFile "." "prefix.suffix" return ()
312Secure temporary file
8haskell
zq3t0
import java.io.File; import java.io.IOException; public class CreateTempFile { public static void main(String[] args) { try {
312Secure temporary file
9java
opi8d
null
312Secure temporary file
11kotlin
x7qws