code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
void putm(char* string, size_t m) { while(*string && m--) putchar(*string++); } int main(void) { char string[] = int n = 3; int m = 4; char knownCharacter = '('; char knownSubstring[] = ; putm(string+n-1, m ); putchar('\n'); puts(string+n+1); putchar('\n'); putm(string, strlen(string)-1); putchar('\n'); putm(strchr(string, knownCharacter), m ); putchar('\n'); putm(strstr(string, knownSubstring), m ); putchar('\n'); return EXIT_SUCCESS; }
183Substring
5c
lzncy
private fun sieve(limit: Int): Array<Int> { val primes = mutableListOf<Int>() primes.add(2) val c = BooleanArray(limit + 1)
173Successive prime differences
11kotlin
t8tf0
> (apply str (take-while #(not (#{\# \ "apples "
182Strip comments from a string
6clojure
5m3uz
(def range-of-chars (apply str (map char (range 256)))) (apply str (filter #(not (Character/isISOControl %)) range-of-chars)) (apply str (filter #(<= 32 (int %) 126) range-of-chars))
180Strip control codes and extended characters from a string
6clojure
xkhwk
def sumMul = { n, f -> BigInteger n1 = (n - 1) / f; f * n1 * (n1 + 1) / 2 } def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) }
167Sum multiples of 3 and 5
7groovy
k4wh7
def digitsum = { number, radix = 10 -> Integer.toString(number, radix).collect { Integer.parseInt(it, radix) }.sum() }
169Sum digits of an integer
7groovy
xb8wl
function sumsq(array) { var sum = 0; var i, iLen; for (i = 0, iLen = array.length; i < iLen; i++) { sum += array[i] * array[i]; } return sum; } alert(sumsq([1,2,3,4,5]));
166Sum of squares
10javascript
mf5yv
use ntheory qw(primes vecfirst); sub comma { (my $s = reverse shift) =~ s/(.{3})/$1,/g; $s =~ s/,(-?)$/$1/; $s = reverse $s; } sub below { my ($m, @a) = @_; vecfirst { $a[$_] > $m } 0..$ my (@strong, @weak, @balanced); my @primes = @{ primes(10_000_019) }; for my $k (1 .. $ my $x = ($primes[$k - 1] + $primes[$k + 1]) / 2; if ($x > $primes[$k]) { push @weak, $primes[$k] } elsif ($x < $primes[$k]) { push @strong, $primes[$k] } else { push @balanced, $primes[$k] } } for ([\@strong, 'strong', 36, 1e6, 1e7], [\@weak, 'weak', 37, 1e6, 1e7], [\@balanced, 'balanced', 28, 1e6, 1e7]) { my($pr, $type, $d, $c1, $c2) = @$_; print "\nFirst $d $type primes:\n", join ' ', map { comma $_ } @$pr[0..$d-1], "\n"; print "Count of $type primes <= @{[comma $c1]}: " . comma below($c1,@$pr) . "\n"; print "Count of $type primes <= @{[comma $c2]}: " . comma scalar @$pr . "\n"; }
174Strong and weak primes
2perl
dqinw
from itertools import product, islice def expr(p): return .format(*p) def gen_expr(): op = ['+', '-', ''] return [expr(p) for p in product(op, repeat=9) if p[0] != '+'] def all_exprs(): values = {} for expr in gen_expr(): val = eval(expr) if val not in values: values[val] = 1 else: values[val] += 1 return values def sum_to(val): for s in filter(lambda x: x[0] == val, map(lambda x: (eval(x), x), gen_expr())): print(s) def max_solve(): print(. format(*max(all_exprs().items(), key=lambda x: x[1]))) def min_solve(): values = all_exprs() for i in range(123456789): if i not in values: print(.format(i)) return def highest_sums(n=10): sums = map(lambda x: x[0], islice(sorted(all_exprs().items(), key=lambda x: x[0], reverse=True), n)) print(.format(list(sums))) sum_to(100) max_solve() min_solve() highest_sums()
165Sum to 100
3python
zo2tt
import Data.List (nub) sum35 :: Integer -> Integer sum35 n = f 3 + f 5 - f 15 where f = sumMul n sumMul :: Integer -> Integer -> Integer sumMul n f = f * n1 * (n1 + 1) `div` 2 where n1 = (n - 1) `div` f main :: IO () main = mapM_ print [ sum35 1000, sum35 100000000000000000000000000000000, sumMulS 1000 [3, 5], sumMulS 10000000 [2, 3, 5, 7, 11, 13] ] pairLCM :: [Integer] -> [Integer] pairLCM [] = [] pairLCM (x: xs) = (lcm x <$> xs) <> pairLCM xs sumMulS :: Integer -> [Integer] -> Integer sumMulS _ [] = 0 sumMulS n s = ( ((-) . sum . fmap f) <*> (g . pairLCM) ) (nub s) where f = sumMul n g = sumMulS n
167Sum multiples of 3 and 5
8haskell
3ilzj
digsum :: Integral a => a -> a -> a digsum base = f 0 where f a 0 = a f a n = f (a + r) q where (q, r) = n `quotRem` base main :: IO () main = print $ digsum 16 255
169Sum digits of an integer
8haskell
264ll
use strict; use warnings; use List::EachCons; use Array::Compare; use ntheory 'primes'; my $limit = 1E6; my @primes = (2, @{ primes($limit) }); my @intervals = map { $primes[$_] - $primes[$_-1] } 1..$ print "Groups of successive primes <= $limit\n"; my $c = Array::Compare->new; for my $diffs ([2], [1], [2,2], [2,4], [4,2], [6,4,2]) { my $n = -1; my @offsets = grep {$_} each_cons @$diffs, @intervals, sub { $n++; $n if $c->compare(\@_, \@$diffs) }; printf "%10s has%5d sets:%15s %s\n", '(' . join(' ',@$diffs) . ')', scalar @offsets, join(' ', @primes[$offsets[ 0]..($offsets[ 0]+@$diffs)]), join(' ', @primes[$offsets[-1]..($offsets[-1]+@$diffs)]); }
173Successive prime differences
2perl
k4khc
package main import ( "fmt" "strings" )
177Strip block comments
0go
ynf64
import kotlin.random.Random import kotlin.system.measureTimeMillis import kotlin.time.milliseconds enum class Summer { MAPPING { override fun sum(values: DoubleArray) = values.map {it * it}.sum() }, SEQUENCING { override fun sum(values: DoubleArray) = values.asSequence().map {it * it}.sum() }, FOLDING { override fun sum(values: DoubleArray) = values.fold(0.0) {acc, it -> acc + it * it} }, FOR_LOOP { override fun sum(values: DoubleArray): Double { var sum = 0.0 values.forEach { sum += it * it } return sum } }, ; abstract fun sum(values: DoubleArray): Double } fun main() { run { val testArrays = listOf( doubleArrayOf(), doubleArrayOf(Random.nextInt(100) / 10.0), DoubleArray(6) { Random.nextInt(100) / 10.0 }, ) for (impl in Summer.values()) { println("Test with ${impl.name}:") for (v in testArrays) println(" ${v.contentToString()} -> ${impl.sum(v)}") } } run { val elements = 100_000 val longArray = DoubleArray(elements) { Random.nextDouble(10.0) } for (impl in Summer.values()) { val time = measureTimeMillis { impl.sum(longArray) }.milliseconds println("Summing $elements with ${impl.name} takes: $time") } var acc = 0.0 for (v in longArray) acc += v } }
166Sum of squares
11kotlin
ow38z
(def string "alphabet") (def n 2) (def m 4) (def len (count string)) (println (subs string n (+ n m))) (println (subs string n)) (println (subs string 0 (dec len))) (let [pos (.indexOf string (int \l))] (println (subs string pos (+ pos m)))) (let [pos (.indexOf string "ph")] (println (subs string pos (+ pos m))))
183Substring
6clojure
4935o
use 5.10.0; use strict; { my @state; my $mod = 1_000_000_000; sub bentley_clever { my @s = ( shift() % $mod, 1); push @s, ($s[-2] - $s[-1]) % $mod while @s < 55; @state = map($s[(34 + 34 * $_) % 55], 0 .. 54); subrand() for (55 .. 219); } sub subrand() { bentley_clever(0) unless @state; my $x = (shift(@state) - $state[-24]) % $mod; push @state, $x; $x; } } bentley_clever(292929); say subrand() for (1 .. 10);
172Subtractive generator
2perl
9tcmn
def code = """ function subroutine() { a = b + c; } function something() { } """ println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
177Strip block comments
7groovy
fs8dn
test = "This
177Strip block comments
8haskell
hu4ju
import numpy as np def primesfrom2to(n): sieve = np.ones(n sieve[0] = False for i in range(int(n**0.5) if sieve[i]: k=3*i+1|1 sieve[ ((k*k) sieve[(k*k+4*k-2*k*(i&1)) return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)] p = primes10m = primesfrom2to(10_000_000) s = strong10m = [t for s, t, u in zip(p, p[1:], p[2:]) if t > (s + u) / 2] w = weak10m = [t for s, t, u in zip(p, p[1:], p[2:]) if t < (s + u) / 2] b = balanced10m = [t for s, t, u in zip(p, p[1:], p[2:]) if t == (s + u) / 2] print('The first 36 strong primes:', s[:36]) print('The count of the strong primes below 1,000,000:', sum(1 for p in s if p < 1_000_000)) print('The count of the strong primes below 10,000,000:', len(s)) print('\nThe first 37 weak primes:', w[:37]) print('The count of the weak primes below 1,000,000:', sum(1 for p in w if p < 1_000_000)) print('The count of the weak primes below 10,000,000:', len(w)) print('\n\nThe first 10 balanced primes:', b[:10]) print('The count of balanced primes below 1,000,000:', sum(1 for p in b if p < 1_000_000)) print('The count of balanced primes below 10,000,000:', len(b)) print('\nTOTAL primes below 1,000,000:', sum(1 for pr in p if pr < 1_000_000)) print('TOTAL primes below 10,000,000:', len(p))
174Strong and weak primes
3python
fsnde
package main import "fmt" func main() { sum, prod := 0, 1 for _, x := range []int{1,2,5} { sum += x prod *= x } fmt.Println(sum, prod) }
170Sum and product of an array
0go
8en0g
[1,2,3,4,5].sum()
170Sum and product of an array
7groovy
wksel
class SumMultiples { public static long getSum(long n) { long sum = 0; for (int i = 3; i < n; i++) { if (i % 3 == 0 || i % 5 == 0) sum += i; } return sum; } public static void main(String[] args) { System.out.println(getSum(1000)); } }
167Sum multiples of 3 and 5
9java
ix3os
import java.math.BigInteger; public class SumDigits { public static int sumDigits(long num) { return sumDigits(num, 10); } public static int sumDigits(long num, int base) { String s = Long.toString(num, base); int result = 0; for (int i = 0; i < s.length(); i++) result += Character.digit(s.charAt(i), base); return result; } public static int sumDigits(BigInteger num) { return sumDigits(num, 10); } public static int sumDigits(BigInteger num, int base) { String s = num.toString(base); int result = 0; for (int i = 0; i < s.length(); i++) result += Character.digit(s.charAt(i), base); return result; } public static void main(String[] args) { System.out.println(sumDigits(1)); System.out.println(sumDigits(12345)); System.out.println(sumDigits(123045)); System.out.println(sumDigits(0xfe, 16)); System.out.println(sumDigits(0xf0e, 16)); System.out.println(sumDigits(new BigInteger("12345678901234567890"))); } }
169Sum digits of an integer
9java
6nc3z
package main import ( "io" "log" "os" ) func main() { var mem = []int{ 15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1,
178Subleq
0go
hu5jq
import java.io.*; public class StripBlockComments{ public static String readFile(String filename) { BufferedReader reader = new BufferedReader(new FileReader(filename)); try { StringBuilder fileContents = new StringBuilder(); char[] buffer = new char[4096]; while (reader.read(buffer, 0, 4096) > 0) { fileContents.append(buffer); } return fileContents.toString(); } finally { reader.close(); } } public static String stripComments(String beginToken, String endToken, String input) { StringBuilder output = new StringBuilder(); while (true) { int begin = input.indexOf(beginToken); int end = input.indexOf(endToken, begin+beginToken.length()); if (begin == -1 || end == -1) { output.append(input); return output.toString(); } output.append(input.substring(0, begin)); input = input.substring(end + endToken.length()); } } public static void main(String[] args) { if (args.length < 3) { System.out.println("Usage: BeginToken EndToken FileToProcess"); System.exit(1); } String begin = args[0]; String end = args[1]; String input = args[2]; try { System.out.println(stripComments(begin, end, readFile(input))); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
177Strip block comments
9java
5mcuf
digits = (..).to_a ar = [, , ].repeated_permutation(digits.size).filter_map do |op_perm| str = op_perm.zip(digits).join str unless str.start_with?() end res = ar.group_by{|str| eval(str)} puts res[100] , sum, solutions = res.max_by{|k,v| v.size} puts , no_solution = (1..).find{|n| res[n] == nil} puts , puts res.max(10).map{|pair| pair.join()}
165Sum to 100
14ruby
6nu3t
char *strip_chars(const char *string, const char *chars) { char * newstr = malloc(strlen(string) + 1); int counter = 0; for ( ; *string; string++) { if (!strchr(chars, *string)) { newstr[ counter ] = *string; ++ counter; } } newstr[counter] = 0; return newstr; } int main(void) { char *new = strip_chars(, ); printf(, new); free(new); return 0; }
184Strip a set of characters from a string
5c
z8wtx
Number.MAX_SAFE_INTEGER
167Sum multiples of 3 and 5
10javascript
zoct2
function sumDigits(n) { n += '' for (var s=0, i=0, e=n.length; i<e; i+=1) s+=parseInt(n.charAt(i),36) return s } for (var n of [1, 12345, 0xfe, 'fe', 'f0e', '999ABCXYZ']) document.write(n, ' sum to ', sumDigits(n), '<br>')
169Sum digits of an integer
10javascript
l35cf
import Control.Monad.State import Data.Char (chr, ord) import Data.IntMap subleq = loop 0 where loop ip = when (ip >= 0) $ do m0 <- gets (! ip) m1 <- gets (! (ip + 1)) if m0 < 0 then do modify . insert m1 ch . ord =<< liftIO getChar loop (ip + 3) else if m1 < 0 then do liftIO . putChar . chr =<< gets (! m0) loop (ip + 3) else do v <- (-) <$> gets (! m1) <*> gets (! m0) modify $ insert m1 v if v <= 0 then loop =<< gets (! (ip + 2)) else loop (ip + 3) main = evalStateT subleq helloWorld where helloWorld = fromList $ zip [0..] [15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33, 10, 0]
178Subleq
8haskell
iwxor
from sympy import Sieve def nsuccprimes(count, mx): sieve = Sieve() sieve.extend(mx) primes = sieve._list return zip(*(primes[n:] for n in range(count))) def check_value_diffs(diffs, values): return all(v[1] - v[0] == d for d, v in zip(diffs, zip(values, values[1:]))) def successive_primes(offsets=(2, ), primes_max=1_000_000): return (sp for sp in nsuccprimes(len(offsets) + 1, primes_max) if check_value_diffs(offsets, sp)) if __name__ == '__main__': for offsets, mx in [((2,), 1_000_000), ((1,), 1_000_000), ((2, 2), 1_000_000), ((2, 4), 1_000_000), ((4, 2), 1_000_000), ((6, 4, 2), 1_000_000), ]: print(f f) for count, last in enumerate(successive_primes(offsets, mx), 1): if count == 1: first = last print(, str(first)[1:-1]) print(, str(last)[1:-1]) print(, count)
173Successive prime differences
3python
bgbkr
values = [1..10] s = sum values p = product values s1 = foldl (+) 0 values p1 = foldl (*) 1 values
170Sum and product of an array
8haskell
l3uch
package main import ( "fmt" "strings" "unicode" ) const commentChars = "#;" func stripComment(source string) string { if cut := strings.IndexAny(source, commentChars); cut >= 0 { return strings.TrimRightFunc(source[:cut], unicode.IsSpace) } return source } func main() { for _, s := range []string{ "apples, pears # and bananas", "apples, pears; and bananas", "no bananas", } { fmt.Printf("source: %q\n", s) fmt.Printf("stripped:%q\n", stripComment(s)) } }
182Strip comments from a string
0go
whreg
null
177Strip block comments
11kotlin
ct398
object SumTo100 { def main(args: Array[String]): Unit = { val exps = expressions(9).map(str => (str, eval(str))) val sums = exps.map(_._2).sortWith(_>_) val s1 = exps.filter(_._2 == 100) val s2 = sums.distinct.map(s => (s, sums.count(_ == s))).maxBy(_._2) val s3 = sums.distinct.reverse.filter(_>0).zipWithIndex.dropWhile{case (n, i) => n == i + 1}.head._2 + 1 val s4 = sums.distinct.take(10) println(s"""All ${s1.size} solutions that sum to 100: |${s1.sortBy(_._1.length).map(p => s"${p._2} = ${p._1.tail}").mkString("\n")} | |Most common sum: ${s2._1} (${s2._2}) |Lowest unreachable sum: $s3 |Highest 10 sums: ${s4.mkString(", ")}""".stripMargin) } def expressions(l: Int): LazyList[String] = configurations(l).map(p => p.zipWithIndex.map{case (op, n) => s"${opChar(op)}${n + 1}"}.mkString) def configurations(l: Int): LazyList[Vector[Int]] = LazyList.range(0, math.pow(3, l).toInt).map(config(l)).filter(_.head != 0) def config(l: Int)(num: Int): Vector[Int] = Iterator.iterate((num%3, num/3)){case (_, n) => (n%3, n/3)}.map(_._1 - 1).take(l).toVector def eval(exp: String): Int = (exp.headOption, exp.tail.takeWhile(_.isDigit), exp.tail.dropWhile(_.isDigit)) match{ case (Some(op), n, str) => doOp(op, n.toInt) + eval(str) case _ => 0 } def doOp(sel: Char, n: Int): Int = if(sel == '-') -n else n def opChar(sel: Int): String = sel match{ case -1 => "-" case 1 => "+" case _ => "" } }
165Sum to 100
16scala
czr93
(defn strip [coll chars] (apply str (remove #((set chars) %) coll))) (strip "She was a soul stripper. She took my heart!" "aei")
184Strip a set of characters from a string
6clojure
9f8ma
package main import ( "golang.org/x/text/transform" "golang.org/x/text/unicode/norm" "fmt" "strings" )
180Strip control codes and extended characters from a string
0go
6io3p
char *sconcat(const char *s1, const char *s2) { char *s0 = malloc(strlen(s1)+strlen(s2)+1); strcpy(s0, s1); strcat(s0, s2); return s0; } int main() { const char *s = ; char *s2; printf(, s); printf(, s, ); s2 = sconcat(s, ); puts(s2); free(s2); }
185String concatenation
5c
6ix32
require 'prime' strong_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b<b} } weak_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b>b} } puts puts strong_gen.take(36).join(), puts puts weak_gen.take(37).join(), [1_000_000, 10_000_000].each do |limit| strongs, weaks = 0, 0 Prime.each_cons(3) do |a,b,c| strongs += 1 if b > a+c-b weaks += 1 if b < a+c-b break if c > limit end puts end
174Strong and weak primes
14ruby
z8ftw
import collections s= collections.deque(maxlen=55) seed = 292929 s.append(seed) s.append(1) for n in xrange(2, 55): s.append((s[n-2] - s[n-1])% 10**9) r = collections.deque(maxlen=55) for n in xrange(55): i = (34 * (n+1))% 55 r.append(s[i]) def getnextr(): r.append((r[0]-r[31])%10**9) return r[54] for n in xrange(219 - 54): getnextr() for i in xrange(5): print , getnextr()
172Subtractive generator
3python
czl9q
def stripComments = { it.replaceAll(/\s*[#;].*$/, '') }
182Strip comments from a string
7groovy
b4vky
ms = ";#" main = getContents >>= mapM_ (putStrLn . takeWhile (`notElem` ms)) . lines
182Strip comments from a string
8haskell
6i03k
int main() { const char *extra = ; printf(, extra); return 0; }
186String interpolation (included)
5c
lz8cy
s := "world!" s = "Hello, " + s
179String prepend
0go
qbbxz
Prelude> let f = (++" World!") Prelude> f "Hello"
179String prepend
8haskell
mddyf
def stripControl = { it.replaceAll(/\p{Cntrl}/, '') } def stripControlAndExtended = { it.replaceAll(/[^\p{Print}]/, '') }
180Strip control codes and extended characters from a string
7groovy
dqxn3
import Control.Applicative (liftA2) strip, strip2 :: String -> String strip = filter (liftA2 (&&) (> 31) (< 126) . fromEnum) strip2 = filter (((&&) <$> (> 31) <*> (< 126)) . fromEnum) main :: IO () main = (putStrLn . unlines) $ [strip, strip2] <*> ["alphabetic with some less parochial parts"]
180Strip control codes and extended characters from a string
8haskell
jv27g
null
169Sum digits of an integer
11kotlin
ds3nz
function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end function squaresumt(t) return squaresum(unpack(t)) end print(squaresumt{3, 5, 4, 1, 7})
166Sum of squares
1lua
ix6ot
fn is_prime(n: i32) -> bool { for i in 2..n { if i * i > n { return true; } if n% i == 0 { return false; } } n > 1 } fn next_prime(n: i32) -> i32 { for i in (n+1).. { if is_prime(i) { return i; } } 0 } fn main() { let mut n = 0; let mut prime_q = 5; let mut prime_p = 3; let mut prime_o = 2; print!("First 36 strong primes: "); while n < 36 { if prime_p > (prime_o + prime_q) / 2 { print!("{} ",prime_p); n += 1; } prime_o = prime_p; prime_p = prime_q; prime_q = next_prime(prime_q); } println!(""); while prime_p < 1000000 { if prime_p > (prime_o + prime_q) / 2 { n += 1; } prime_o = prime_p; prime_p = prime_q; prime_q = next_prime(prime_q); } println!("strong primes below 1,000,000: {}", n); while prime_p < 10000000 { if prime_p > (prime_o + prime_q) / 2 { n += 1; } prime_o = prime_p; prime_p = prime_q; prime_q = next_prime(prime_q); } println!("strong primes below 10,000,000: {}", n); n = 0; prime_q = 5; prime_p = 3; prime_o = 2; print!("First 36 weak primes: "); while n < 36 { if prime_p < (prime_o + prime_q) / 2 { print!("{} ",prime_p); n += 1; } prime_o = prime_p; prime_p = prime_q; prime_q = next_prime(prime_q); } println!(""); while prime_p < 1000000 { if prime_p < (prime_o + prime_q) / 2 { n += 1; } prime_o = prime_p; prime_p = prime_q; prime_q = next_prime(prime_q); } println!("weak primes below 1,000,000: {}", n); while prime_p < 10000000 { if prime_p < (prime_o + prime_q) / 2 { n += 1; } prime_o = prime_p; prime_p = prime_q; prime_q = next_prime(prime_q); } println!("weak primes below 10,000,000: {}", n); }
174Strong and weak primes
15rust
3otz8
import java.util.Scanner; public class Subleq { public static void main(String[] args) { int[] mem = {15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10, 0}; Scanner input = new Scanner(System.in); int instructionPointer = 0; do { int a = mem[instructionPointer]; int b = mem[instructionPointer + 1]; if (a == -1) { mem[b] = input.nextInt(); } else if (b == -1) { System.out.printf("%c", (char) mem[a]); } else { mem[b] -= mem[a]; if (mem[b] < 1) { instructionPointer = mem[instructionPointer + 2]; continue; } } instructionPointer += 3; } while (instructionPointer >= 0); } }
178Subleq
9java
xkbwy
package main import ( "fmt" "unicode/utf8" ) func main() {
175Substring/Top and tail
0go
v6c2m
filename = "Text1.txt" fp = io.open( filename, "r" ) str = fp:read( "*all" ) fp:close() stripped = string.gsub( str, "/%*.-%*/", "" ) print( stripped )
177Strip block comments
1lua
lz6ck
(let [little "little"] (println (format "Mary had a%s lamb." little)))
186String interpolation (included)
6clojure
49f5o
(def a-str "abcd") (println (str a-str "efgh")) (def a-new-str (str a-str "efgh")) (println a-new-str)
185String concatenation
6clojure
lzocb
null
167Sum multiples of 3 and 5
11kotlin
qpnx1
object StrongWeakPrimes { def main(args: Array[String]): Unit = { val bnd = 1000000 println( f"""|First 36 Strong Primes: ${strongPrimes.take(36).map(n => f"$n%,d").mkString(", ")} |Strong Primes < 1,000,000: ${strongPrimes.takeWhile(_ < bnd).size}%,d |Strong Primes < 10,000,000: ${strongPrimes.takeWhile(_ < 10*bnd).size}%,d | |First 37 Weak Primes: ${weakPrimes.take(37).map(n => f"$n%,d").mkString(", ")} |Weak Primes < 1,000,000: ${weakPrimes.takeWhile(_ < bnd).size}%,d |Weak Primes < 10,000,000: ${weakPrimes.takeWhile(_ < 10*bnd).size}%,d""".stripMargin) } def weakPrimes: LazyList[Int] = primeTrips.filter{case a +: b +: c +: _ => b < (a + c)/2.0}.map(_(1)).to(LazyList) def strongPrimes: LazyList[Int] = primeTrips.filter{case a +: b +: c +: _ => b > (a + c)/2}.map(_(1)).to(LazyList) def primeTrips: Iterator[LazyList[Int]] = primes.sliding(3) def primes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(n => !Iterator.range(3, math.sqrt(n).toInt + 1, 2).exists(n%_ == 0)) }
174Strong and weak primes
16scala
md6yc
def top = { it.size() > 1 ? it[0..-2]: '' } def tail = { it.size() > 1 ? it[1..-1]: '' }
175Substring/Top and tail
7groovy
md3y5
import java.io.*; public class StripLineComments{ public static void main( String[] args ){ if( args.length < 1 ){ System.out.println("Usage: java StripLineComments StringToProcess"); } else{ String inputFile = args[0]; String input = ""; try{ BufferedReader reader = new BufferedReader( new FileReader( inputFile ) ); String line = ""; while((line = reader.readLine()) != null){ System.out.println( line.split("[#;]")[0] ); } } catch( Exception e ){ e.printStackTrace(); } } } }
182Strip comments from a string
9java
nxaih
function stripComments(s) { var re1 = /^\s+|\s+$/g;
182Strip comments from a string
10javascript
3osz0
null
179String prepend
9java
fssdv
null
179String prepend
10javascript
ynn6r
null
178Subleq
11kotlin
pgrb6
require 'prime' PRIMES = Prime.each(1_000_000).to_a difs = [[2], [1], [2,2], [2,4], [4,2], [6,4,2]] difs.each do |ar| res = PRIMES.each_cons(ar.size+1).select do |slice| slice.each_cons(2).zip(ar).all? {|(a,b), c| a+c == b} end puts end
173Successive prime differences
14ruby
171pw
public class SumProd { public static void main(final String[] args) { int sum = 0; int prod = 1; int[] arg = {1,2,3,4,5}; for (int i: arg) { sum += i; prod *= i; } } }
170Sum and product of an array
9java
3imzg
null
182Strip comments from a string
11kotlin
sphq7
use strict ; use warnings ; open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ; my $code = "" ; { local $/ ; $code = <FH> ; } close FH ; $code =~ s,/\*.*?\*/,,sg ; print $code . "\n" ;
177Strip block comments
2perl
xkpw8
null
179String prepend
11kotlin
8aa0q
if (strcmp(a,b)) action_on_equality();
187String comparison
5c
72zrg
int startsWith(const char* container, const char* target) { size_t clen = strlen(container), tlen = strlen(target); if (clen < tlen) return 0; return strncmp(container, target, tlen) == 0; } int endsWith(const char* container, const char* target) { size_t clen = strlen(container), tlen = strlen(target); if (clen < tlen) return 0; return strncmp(container + clen - tlen, target, tlen) == 0; } int doesContain(const char* container, const char* target) { return strstr(container, target) != 0; } int main(void) { printf(, startsWith(,)); printf(, endsWith(,)); printf(, doesContain(,)); return 0; }
188String matching
5c
fskd3
import java.util.function.IntPredicate; public class StripControlCodes { public static void main(String[] args) { String s = "\u0000\n abc\u00E9def\u007F"; System.out.println(stripChars(s, c -> c > '\u001F' && c != '\u007F')); System.out.println(stripChars(s, c -> c > '\u001F' && c < '\u007F')); } static String stripChars(String s, IntPredicate include) { return s.codePoints().filter(include::test).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); } }
180Strip control codes and extended characters from a string
9java
uy6vv
(function (strTest) {
180Strip control codes and extended characters from a string
10javascript
72lrd
package main import ( "fmt" "strings" "unicode" ) var simple = ` simple ` func main() { show("original", simple) show("leading ws removed", strings.TrimLeftFunc(simple, unicode.IsSpace)) show("trailing ws removed", strings.TrimRightFunc(simple, unicode.IsSpace))
181Strip whitespace from a string/Top and tail
0go
ctd9g
import Foundation class PrimeSieve { var composite: [Bool] init(size: Int) { composite = Array(repeating: false, count: size/2) var p = 3 while p * p <= size { if!composite[p/2 - 1] { let inc = p * 2 var q = p * p while q <= size { composite[q/2 - 1] = true q += inc } } p += 2 } } func isPrime(number: Int) -> Bool { if number < 2 { return false } if (number & 1) == 0 { return number == 2 } return!composite[number/2 - 1] } } func commatize(_ number: Int) -> String { let n = NSNumber(value: number) return NumberFormatter.localizedString(from: n, number: .decimal) } let limit1 = 1000000 let limit2 = 10000000 class PrimeInfo { let maxPrint: Int var count1: Int var count2: Int var primes: [Int] init(maxPrint: Int) { self.maxPrint = maxPrint count1 = 0 count2 = 0 primes = [] } func addPrime(prime: Int) { count2 += 1 if prime < limit1 { count1 += 1 } if count2 <= maxPrint { primes.append(prime) } } func printInfo(name: String) { print("First \(maxPrint) \(name) primes: \(primes)") print("Number of \(name) primes below \(commatize(limit1)): \(commatize(count1))") print("Number of \(name) primes below \(commatize(limit2)): \(commatize(count2))") } } var strongPrimes = PrimeInfo(maxPrint: 36) var weakPrimes = PrimeInfo(maxPrint: 37) let sieve = PrimeSieve(size: limit2 + 100) var p1 = 2, p2 = 3, p3 = 5 while p2 < limit2 { if sieve.isPrime(number: p3) { let diff = p1 + p3 - 2 * p2 if diff < 0 { strongPrimes.addPrime(prime: p2) } else if diff > 0 { weakPrimes.addPrime(prime: p2) } p1 = p2 p2 = p3 } p3 += 2 } strongPrimes.printInfo(name: "strong") weakPrimes.printInfo(name: "weak")
174Strong and weak primes
17swift
t0dfl
function subleq (prog) local mem, p, A, B, C = {}, 0 for word in prog:gmatch("%S+") do mem[p] = tonumber(word) p = p + 1 end p = 0 repeat A, B, C = mem[p], mem[p + 1], mem[p + 2] if A == -1 then mem[B] = io.read() elseif B == -1 then io.write(string.char(mem[A])) else mem[B] = mem[B] - mem[A] if mem[B] <= 0 then p = C end end p = p + 3 until not mem[mem[p]] end subleq("15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0")
178Subleq
1lua
1r7po
fn is_prime(num: u32) -> bool { match num { x if x < 4 => x > 1, x if x% 2 == 0 => false, x => { let limit = (x as f32).sqrt().ceil() as u32; (3..=limit).step_by(2).all(|a| x% a!= 0) } } } fn primes_by_diffs(primes: &[u32], diffs: &[u32]) -> Vec<Vec<u32>> { fn select(diffs: &[u32], prime_win: &[u32], acc: bool) -> bool { if diffs.is_empty() ||!acc { acc } else { let acc1 = prime_win[0] + diffs[0] == prime_win[1]; select(&diffs[1..], &prime_win[1..], acc1) } } primes.windows(diffs.len() + 1) .filter(|&win| select(diffs, win, true)) .map(|win| win.to_vec()) .collect() } fn main() { let limit = 1_000_000u32; let start = std::time::Instant::now(); let primes = (2..).filter(|&i| is_prime(i)); let prime_list: Vec<u32> = primes.take_while(|&p| p <= limit).collect(); let duration = start.elapsed(); println!("primes time: {:?}", duration); for diffs in vec!(vec!(1), vec!(2), vec!(2,2), vec!(2,4), vec!(4,2), vec!(6,4,2), vec!(2,4,6)) { let result_list = primes_by_diffs(&prime_list, &diffs); let len = result_list.len(); println!("{:?} number: {}\n\tfirst: {:?}", diffs, len, result_list[0]); if len == 1 { println!() } if len > 1 { println!("\tlast: {:?}\n", result_list.last().unwrap()) } } }
173Successive prime differences
15rust
aja14
remFirst, remLast, remBoth :: String -> String remFirst "" = "" remFirst cs = tail cs remLast "" = "" remLast cs = init cs remBoth (c:cs) = remLast cs remBoth _ = "" main :: IO () main = do let s = "Some string." mapM_ (\f -> putStrLn . f $ s) [remFirst, remLast, remBoth]
175Substring/Top and tail
8haskell
ejpai
class SubRandom attr_reader :seed def initialize(seed = Kernel.rand(1_000_000_000)) (0..999_999_999).include? seed or raise ArgumentError, ary = [seed, 1] 53.times { ary << ary[-2] - ary[-1] } @state = [] 34.step(1870, 34) {|i| @state << ary[i % 55] } 220.times { rand } @seed = seed end def initialize_copy(orig) @state = @state.dup end def rand @state << (@state[-55] - @state[-24]) % 1_000_000_000 @state.shift end end rng = SubRandom.new(292929) p (1..3).map { rng.rand }
172Subtractive generator
14ruby
26vlw
var array = [1, 2, 3, 4, 5], sum = 0, prod = 1, i; for (i = 0; i < array.length; i += 1) { sum += array[i]; prod *= array[i]; } alert(sum + ' ' + prod);
170Sum and product of an array
10javascript
czv9j
function sum_digits(n, base) sum = 0 while n > 0.5 do m = math.floor(n / base) digit = n - m * base sum = sum + digit n = m end return sum end print(sum_digits(1, 10)) print(sum_digits(1234, 10)) print(sum_digits(0xfe, 16)) print(sum_digits(0xf0e, 16))
169Sum digits of an integer
1lua
f06dp
null
181Strip whitespace from a string/Top and tail
7groovy
3o0zd
package main import "fmt"
176Sudoku
0go
49252
object SuccessivePrimeDiffs { def main(args: Array[String]): Unit = { val d2 = primesByDiffs(2)(1000000) val d1 = primesByDiffs(1)(1000000) val d22 = primesByDiffs(2, 2)(1000000) val d24 = primesByDiffs(2, 4)(1000000) val d42 = primesByDiffs(4, 2)(1000000) val d642 = primesByDiffs(6, 4, 2)(1000000) if(true) println( s"""|Diffs: (First), (Last), Count |2: (${d2.head.mkString(", ")}), (${d2.last.mkString(", ")}), ${d2.size} |1: (${d1.head.mkString(", ")}), (${d1.last.mkString(", ")}), ${d1.size} |2-2: (${d22.head.mkString(", ")}), (${d22.last.mkString(", ")}), ${d22.size} |2-4: (${d24.head.mkString(", ")}), (${d24.last.mkString(", ")}), ${d24.size} |4-2: (${d42.head.mkString(", ")}), (${d42.last.mkString(", ")}), ${d42.size} |6-4-2: (${d642.head.mkString(", ")}), (${d642.last.mkString(", ")}), ${d642.size} |""".stripMargin) } def primesByDiffs(diffs: Int*)(max: Int): LazyList[Vector[Int]] = { primesSliding(diffs.size + 1) .takeWhile(_.last <= max) .filter{vec => diffs.zip(vec.init).map{case (a, b) => a + b} == vec.tail} .to(LazyList) } def primesSliding(len: Int): Iterator[Vector[Int]] = primes.sliding(len).map(_.toVector) def primes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(n => !Iterator.range(3, math.sqrt(n).toInt + 1, 2).exists(n%_ == 0)) }
173Successive prime differences
16scala
xbxwg
struct SubtractiveGenerator {
172Subtractive generator
15rust
vyu2t
comment_symbols = ";#" s1 = "apples, pears # and bananas" s2 = "apples, pears; and bananas" print ( string.match( s1, "[^"..comment_symbols.."]+" ) ) print ( string.match( s2, "[^"..comment_symbols.."]+" ) )
182Strip comments from a string
1lua
01ksd
function strip_block_comments( $test_string ) { $pattern = ; return preg_replace( $pattern, '', $test_string ); } echo . strip_block_comments( ) . ;
177Strip block comments
12php
23yl4
s = "12345678" s = "0" .. s print(s)
179String prepend
1lua
oee8h
(= "abc" "def") (= "abc" "abc") (not= "abc" "def") (not= "abc" "abc")
187String comparison
6clojure
pg9bd
null
180Strip control codes and extended characters from a string
11kotlin
9fdmh
import Data.Char (isSpace) import Data.List (dropWhileEnd) trimLeft :: String -> String trimLeft = dropWhile isSpace trimRight :: String -> String trimRight = dropWhileEnd isSpace trim :: String -> String trim = trimLeft . trimRight
181Strip whitespace from a string/Top and tail
8haskell
pg5bt
public class RM_chars { public static void main( String[] args ){ System.out.println( "knight".substring( 1 ) ); System.out.println( "socks".substring( 0, 4 ) ); System.out.println( "brooms".substring( 1, 5 ) );
175Substring/Top and tail
9java
hurjm
void str_toupper(char *s) { while(*s) { *s=toupper(*s); s++; } } void str_tolower(char *s) { while(*s) { *s=tolower(*s); s++; } } int main(int argc, char *argv[]) { char t[255]=; str_toupper(t); printf(, t); str_tolower(t); printf(, t); return 0; }
189String case
5c
015st
(def evals '((. "abcd" startsWith "ab") (. "abcd" endsWith "zn") (. "abab" contains "bb") (. "abab" contains "ab") (. "abab" indexOf "bb") (let [loc (. "abab" indexOf "ab")] (. "abab" indexOf "ab" (dec loc))))) user> (for [i evals] [i (eval i)]) ([(. "abcd" startsWith "ab") true] [(. "abcd" endsWith "zn") false] [(. "abab" contains "bb") false] [(. "abab" contains "ab") true] [(. "abab" indexOf "bb") -1] [(let [loc (. "abab" indexOf "ab")] (. "abab" indexOf "ab" (dec loc))) 0])
188String matching
6clojure
yne6b
function tri (n) return n * (n + 1) / 2 end function sum35 (n) n = n - 1 return ( 3 * tri(math.floor(n / 3)) + 5 * tri(math.floor(n / 5)) - 15 * tri(math.floor(n / 15)) ) end print(sum35(1000)) print(sum35(1e+20))
167Sum multiples of 3 and 5
1lua
s1dq8
final CELL_VALUES = ('1'..'9') class GridException extends Exception { GridException(String message) { super(message) } } def string2grid = { string -> assert string.size() == 81 (0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } } } def gridRow = { grid, slot -> grid[slot.i] as Set } def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set } def gridBox = { grid, slot -> def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3] (0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set } def slotList = { grid -> def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \ .collect {j -> [i: i, j: j] } }.flatten() } def assignCandidates = { grid, slots = slotList(grid) -> slots.each { slot -> def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set slot.candidates = CELL_VALUES - unavailable } slots.sort { - it.candidates.size() } if (slots && ! slots[-1].candidates) { throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1]) } slots } def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) } def solve solve = { grid -> def slots = assignCandidates(grid) if (! slots) { return grid } while (slots[-1].candidates.size() == 1) { def slot = slots.pop() grid[slot.i][slot.j] = slot.candidates[0] if (! slots) { return grid } slots = assignCandidates(grid, slots) } if (! slots) { return grid } def slot = slots.pop() slot.candidates.each { if (! isSolved(grid)) { try { def sGrid = grid.collect { row -> row.collect { cell -> cell } } sGrid[slot.i][slot.j] = it grid = solve(sGrid) } catch (GridException ge) { grid[slot.i][slot.j] = '.' } } } if (!isSolved(grid)) { slots = assignCandidates(grid) throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots) } grid }
176Sudoku
7groovy
lzyc1
alert("knight".slice(1));
175Substring/Top and tail
10javascript
a7b10
null
170Sum and product of an array
11kotlin
nqtij
function Strip_Control_Codes( str ) local s = "" for i in str:gmatch( "%C+" ) do s = s .. i end return s end function Strip_Control_and_Extended_Codes( str ) local s = "" for i = 1, str:len() do if str:byte(i) >= 32 and str:byte(i) <= 126 then s = s .. str:sub(i,i) end end return s end q = "" for i = 0, 255 do q = q .. string.char(i) end print( Strip_Control_Codes(q) ) print( Strip_Control_and_Extended_Codes(q) )
180Strip control codes and extended characters from a string
1lua
ctf92
public class Trims{ public static String ltrim(String s) { int i = 0; while (i < s.length() && Character.isWhitespace(s.charAt(i))) { i++; } return s.substring(i); } public static String rtrim(String s) { int i = s.length() - 1; while (i > 0 && Character.isWhitespace(s.charAt(i))) { i--; } return s.substring(0, i + 1); } public static String trim(String s) { return rtrim(ltrim(s)); } public static void main(String[] args) { String s = " \t \r \n String with spaces \u2009 \t \r \n "; System.out.printf("[%s]\n", ltrim(s)); System.out.printf("[%s]\n", rtrim(s)); System.out.printf("[%s]\n", trim(s)); } }
181Strip whitespace from a string/Top and tail
9java
rl9g0
public class Sudoku { private int mBoard[][]; private int mBoardSize; private int mBoxSize; private boolean mRowSubset[][]; private boolean mColSubset[][]; private boolean mBoxSubset[][]; public Sudoku(int board[][]) { mBoard = board; mBoardSize = mBoard.length; mBoxSize = (int)Math.sqrt(mBoardSize); initSubsets(); } public void initSubsets() { mRowSubset = new boolean[mBoardSize][mBoardSize]; mColSubset = new boolean[mBoardSize][mBoardSize]; mBoxSubset = new boolean[mBoardSize][mBoardSize]; for(int i = 0; i < mBoard.length; i++) { for(int j = 0; j < mBoard.length; j++) { int value = mBoard[i][j]; if(value != 0) { setSubsetValue(i, j, value, true); } } } } private void setSubsetValue(int i, int j, int value, boolean present) { mRowSubset[i][value - 1] = present; mColSubset[j][value - 1] = present; mBoxSubset[computeBoxNo(i, j)][value - 1] = present; } public boolean solve() { return solve(0, 0); } public boolean solve(int i, int j) { if(i == mBoardSize) { i = 0; if(++j == mBoardSize) { return true; } } if(mBoard[i][j] != 0) { return solve(i + 1, j); } for(int value = 1; value <= mBoardSize; value++) { if(isValid(i, j, value)) { mBoard[i][j] = value; setSubsetValue(i, j, value, true); if(solve(i + 1, j)) { return true; } setSubsetValue(i, j, value, false); } } mBoard[i][j] = 0; return false; } private boolean isValid(int i, int j, int val) { val boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val]; return !isPresent; } private int computeBoxNo(int i, int j) { int boxRow = i / mBoxSize; int boxCol = j / mBoxSize; return boxRow * mBoxSize + boxCol; } public void print() { for(int i = 0; i < mBoardSize; i++) { if(i % mBoxSize == 0) { System.out.println(" } for(int j = 0; j < mBoardSize; j++) { if(j % mBoxSize == 0) { System.out.print("| "); } System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-"); System.out.print(' '); } System.out.println("|"); } System.out.println(" } public static void main(String[] args) { int[][] board = { {8, 5, 0, 0, 0, 2, 4, 0, 0}, {7, 2, 0, 0, 0, 0, 0, 0, 9}, {0, 0, 4, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 7, 0, 0, 2}, {3, 0, 5, 0, 0, 0, 9, 0, 0}, {0, 4, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 8, 0, 0, 7, 0}, {0, 1, 7, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 3, 6, 0, 4, 0} }; Sudoku s = new Sudoku(board); System.out.print("Starting grid:\n"); s.print(); if (s.solve()) { System.out.print("\nSolution:\n"); s.print(); } else { System.out.println("\nUnsolvable!"); } } }
176Sudoku
8haskell
qbax9