code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
assert "abcd".startsWith("ab") assert ! "abcd".startsWith("zn") assert "abcd".endsWith("cd") assert ! "abcd".endsWith("zn") assert "abab".contains("ba") assert ! "abab".contains("bb") assert "abab".indexOf("bb") == -1
188String matching
7groovy
5miuv
>>> s = ' \t \r \n String with spaces \t \r \n ' >>> s ' \t \r \n String with spaces \t \r \n ' >>> s.lstrip() 'String with spaces \t \r \n ' >>> s.rstrip() ' \t \r \n String with spaces' >>> s.strip() 'String with spaces' >>>
181Strip whitespace from a string/Top and tail
3python
8ap0o
<?php function stripchars($s, $chars) { return str_replace(str_split($chars), , $s); } echo stripchars(, ), ; ?>
184Strip a set of characters from a string
12php
ej5a9
> import Data.List > "abc" `isPrefixOf` "abcdefg" True > "efg" `isSuffixOf` "abcdefg" True > "bcd" `isInfixOf` "abcdefg" True > "abc" `isInfixOf` "abcdefg" True > let infixes a b = findIndices (isPrefixOf a) $ tails b > infixes "ab" "abcdefabqqab" [0,6,10]
188String matching
8haskell
oer8p
change.base <- function(n, base) { ret <- integer(as.integer(logb(x=n, base=base))+1L) for (i in 1:length(ret)) { ret[i] <- n %% base n <- n %/% base } return(ret) } sum.digits <- function(n, base=10) { if (base < 2) stop("base must be at least 2") return(sum(change.base(n=n, base=base))) } sum.digits(1) sum.digits(12345) sum.digits(123045) sum.digits(0xfe, 16) sum.digits(0xf0e, 16)
169Sum digits of an integer
13r
glh47
s <- " Ars Longa " trimws(s) [1] "Ars Longa" trimws(s, "left") [1] "Ars Longa " trimws(s, "right") [1] " Ars Longa"
181Strip whitespace from a string/Top and tail
13r
xkjw2
my @list = ( 1, 2, 3 ); my ( $sum, $prod ) = ( 0, 1 ); $sum += $_ foreach @list; $prod *= $_ foreach @list;
170Sum and product of an array
2perl
7vkrh
sum = 0 for i = 1, 1000 do sum = sum + 1/i^2 end print(sum)
171Sum of a series
1lua
4cr5c
>>> original = 'Mary had a%s lamb.' >>> extra = 'little' >>> original% extra 'Mary had a little lamb.'
186String interpolation (included)
3python
49f5k
use v5.16; sub compare { my ($a, $b) = @_; my $A = "'$a'"; my $B = "'$b'"; print "$A and $B are lexically equal.\n" if $a eq $b; print "$A and $B are not lexically equal.\n" if $a ne $b; print "$A is lexically before $B.\n" if $a lt $b; print "$A is lexically after $B.\n" if $a gt $b; print "$A is not lexically before $B.\n" if $a ge $b; print "$A is not lexically after $B.\n" if $a le $b; print "The lexical relationship is: ", $a cmp $b, "\n"; print "The case-insensitive lexical relationship is: ", fc($a) cmp fc($b), "\n"; print "\n"; } compare('Hello', 'Hello'); compare('5', '5.0'); compare('perl', 'Perl');
187String comparison
2perl
b4mk4
package main import "fmt" func main() { m := "mse" u := "" j := "Jos" fmt.Printf("%d%s% x\n", len(m), m, m) fmt.Printf("%d%s%x\n", len(u), u, u) fmt.Printf("%d%s% x\n", len(j), j, j) }
190String length
0go
72dr2
def initiate(): box.append([0, 1, 2, 9, 10, 11, 18, 19, 20]) box.append([3, 4, 5, 12, 13, 14, 21, 22, 23]) box.append([6, 7, 8, 15, 16, 17, 24, 25, 26]) box.append([27, 28, 29, 36, 37, 38, 45, 46, 47]) box.append([30, 31, 32, 39, 40, 41, 48, 49, 50]) box.append([33, 34, 35, 42, 43, 44, 51, 52, 53]) box.append([54, 55, 56, 63, 64, 65, 72, 73, 74]) box.append([57, 58, 59, 66, 67, 68, 75, 76, 77]) box.append([60, 61, 62, 69, 70, 71, 78, 79, 80]) for i in range(0, 81, 9): row.append(range(i, i+9)) for i in range(9): column.append(range(i, 80+i, 9)) def valid(n, pos): current_row = pos/9 current_col = pos%9 current_box = (current_row/3)*3 + (current_col/3) for i in row[current_row]: if (grid[i] == n): return False for i in column[current_col]: if (grid[i] == n): return False for i in box[current_box]: if (grid[i] == n): return False return True def solve(): i = 0 proceed = 1 while(i < 81): if given[i]: if proceed: i += 1 else: i -= 1 else: n = grid[i] prev = grid[i] while(n < 9): if (n < 9): n += 1 if valid(n, i): grid[i] = n proceed = 1 break if (grid[i] == prev): grid[i] = 0 proceed = 0 if proceed: i += 1 else: i -=1 def inputs(): nextt = 'T' number = 0 pos = 0 while(not(nextt == 'N' or nextt == 'n')): print , pos = int(raw_input()) given[pos - 1] = True print , number = int(raw_input()) grid[pos - 1] = number print nextt = raw_input() grid = [0]*81 given = [False]*81 box = [] row = [] column = [] initiate() inputs() solve() for i in range(9): print grid[i*9:i*9+9] raw_input()
176Sudoku
3python
t0ifw
$array = array(1,2,3,4,5,6,7,8,9); echo array_sum($array); echo array_product($array);
170Sum and product of an array
12php
f03dh
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase());
189String case
9java
k53hm
alert( "alphaBETA".toUpperCase() ); alert( "alphaBETA".toLowerCase() );
189String case
10javascript
ejcao
"abcd".startsWith("ab")
188String matching
9java
wh2ej
println "Hello World!".size()
190String length
7groovy
uy0v9
[3,1,4,1,5,9].reduce(0){|sum,x| sum + x*x}
166Sum of squares
14ruby
jue7x
var stringA = "tacoloco" , stringB = "co" , q1, q2, q2multi, m , q2matches = []
188String matching
10javascript
8ag0l
import Data.Encoding import Data.ByteString as B strUTF8 :: ByteString strUTF8 = encode UTF8 "Hello World!" strUTF32 :: ByteString strUTF32 = encode UTF32 "Hello World!" strlenUTF8 = B.length strUTF8 strlenUTF32 = B.length strUTF32
190String length
8haskell
8a50z
def sum35a(n): 'Direct count' return sum(x for x in range(n) if x%3==0 or x%5==0) def sum35b(n): return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15)) def sum35c(n): 'Sum the arithmetic progressions: sum3 + sum5 - sum15' consts = (3, 5, 15) divs = [(n-1) sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)] return sums[0] + sums[1] - sums[2] for n in range(1001): sa, sb, sc = sum35a(n), sum35b(n), sum35c(n) assert sa == sb == sc print('For n =%7i ->%i\n'% (n, sc)) for p in range(7): print('For n =%7i ->%i'% (10**p, sum35c(10**p))) p = 20 print('\nFor n =%20i ->%i'% (10**p, sum35c(10**p)))
167Sum multiples of 3 and 5
3python
umjvd
fn sq_sum(v: &[f64]) -> f64 { v.iter().fold(0., |sum, &num| sum + num*num) } fn main() { let v = vec![3.0, 1.0, 4.0, 1.0, 5.5, 9.7]; println!("{}", sq_sum(&v)); let u: Vec<f64> = vec![]; println!("{}", sq_sum(&u)); }
166Sum of squares
15rust
h5wj2
s = p s p s.lstrip p s.rstrip p s.strip
181Strip whitespace from a string/Top and tail
14ruby
iwaoh
print [1:] print [:-1] print [1:-1]
175Substring/Top and tail
3python
nx8iz
irb(main):001:0> extra = 'little' => irb(main):002:0> => irb(main):003:0> % extra =>
186String interpolation (included)
14ruby
rlzgs
def sum_of_squares(xs: Seq[Double]) = xs.foldLeft(0) {(a,x) => a + x*x}
166Sum of squares
16scala
prsbj
fn main() { let spaces = " \t\n\x0B\x0C\r \u{A0} \u{2000}\u{3000}"; let string_with_spaces = spaces.to_owned() + "String without spaces" + spaces; assert_eq!(string_with_spaces.trim(), "String without spaces"); assert_eq!(string_with_spaces.trim_left(), "String without spaces".to_owned() + spaces); assert_eq!(string_with_spaces.trim_right(), spaces.to_owned() + "String without spaces"); }
181Strip whitespace from a string/Top and tail
15rust
nxei4
fn main() { println!("Mary had a {} lamb", "little");
186String interpolation (included)
15rust
723rc
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars(, ) 'Sh ws soul strppr. Sh took my hrt!'
184Strip a set of characters from a string
3python
9f8mf
def compare(a, b): print( % (a, type(a), b, type(b))) if a < b: print('%r is strictly less than %r'% (a, b)) if a <= b: print('%r is less than or equal to%r'% (a, b)) if a > b: print('%r is strictly greater than %r'% (a, b)) if a >= b: print('%r is greater than or equal to%r'% (a, b)) if a == b: print('%r is equal to%r'% (a, b)) if a != b: print('%r is not equal to%r'% (a, b)) if a is b: print('%r has object identity with%r'% (a, b)) if a is not b: print('%r has negated object identity with%r'% (a, b)) compare('YUP', 'YUP') compare('BALL', 'BELL') compare('24', '123') compare(24, 123) compare(5.0, 5)
187String comparison
3python
pg9bm
null
189String case
11kotlin
gcn4d
def sum_digits(num, base = 10) = num.digits(base).sum
169Sum digits of an integer
14ruby
bgekq
def trimLeft(str: String) = str dropWhile(_.isWhitespace) def trimRight(str: String) = str take (str.lastIndexWhere(!_.isWhitespace) + 1) def trimRight2(str: String) = trimLeft(str reverse) reverse def trim(str: String) = str trim def testTrim() = { val str = " \u001F String with spaces \t \n \r " println("original : |" + str + "|") println("trimLeft : |" + trimLeft(str) + "|") println("trimRight: |" + trimRight(str) + "|") println("trimRight2: |" + trimRight2(str) + "|") println("trim : |" + trim(str) + "|") }
181Strip whitespace from a string/Top and tail
16scala
t0qfb
object StringInterpolation extends App { import util.matching.Regex._ val size = "little" {
186String interpolation (included)
16scala
k5mhk
m35 = function(n) sum(unique(c( seq(3, n-1, by = 3), seq(5, n-1, by = 5)))) m35(1000)
167Sum multiples of 3 and 5
13r
cz495
struct DigitIter(usize, usize); impl Iterator for DigitIter { type Item = usize; fn next(&mut self) -> Option<Self::Item> { if self.0 == 0 { None } else { let ret = self.0% self.1; self.0 /= self.1; Some(ret) } } } fn main() { println!("{}", DigitIter(1234,10).sum::<usize>()); }
169Sum digits of an integer
15rust
prwbu
compare <- function(a, b) { cat(paste(a, "is of type", class(a), "and", b, "is of type", class(b), "\n")) if (a < b) cat(paste(a, "is strictly less than", b, "\n")) if (a <= b) cat(paste(a, "is less than or equal to", b, "\n")) if (a > b) cat(paste(a, "is strictly greater than", b, "\n")) if (a >= b) cat(paste(a, "is greater than or equal to", b, "\n")) if (a == b) cat(paste(a, "is equal to", b, "\n")) if (a != b) cat(paste(a, "is not equal to", b, "\n")) invisible() } compare('YUP', 'YUP') compare('BALL', 'BELL') compare('24', '123') compare(24, 123) compare(5.0, 5)
187String comparison
13r
jv378
null
188String matching
11kotlin
b4ykb
def sumDigits(x:BigInt, base:Int=10):BigInt=sumDigits(x.toString(base), base) def sumDigits(x:String, base:Int):BigInt = x map(_.asDigit) sum
169Sum digits of an integer
16scala
ehsab
def read_matrix(data) lines = data.lines 9.times.collect { |i| 9.times.collect { |j| lines[i][j].to_i } } end def permissible(matrix, i, j) ok = [nil, *1..9] check = ->(x,y) { ok[matrix[x][y]] = nil if matrix[x][y].nonzero? } 9.times { |x| check[x, j] } 9.times { |y| check[i, y] } xary = [ *(x = (i / 3) * 3) .. x + 2 ] yary = [ *(y = (j / 3) * 3) .. y + 2 ] xary.product(yary).each { |x, y| check[x, y] } ok.compact end def deep_copy_sudoku(matrix) matrix.collect { |row| row.dup } end def solve_sudoku(matrix) loop do options = [] 9.times do |i| 9.times do |j| next if matrix[i][j].nonzero? p = permissible(matrix, i, j) return if p.empty? options << [i, j, p] end end return matrix if options.empty? i, j, permissible = options.min_by { |x| x.last.length } if permissible.length == 1 matrix[i][j] = permissible[0] next end permissible.each do |v| mtmp = deep_copy_sudoku(matrix) mtmp[i][j] = v ret = solve_sudoku(mtmp) return ret if ret end return end end def print_matrix(matrix) puts or return unless matrix border = 9.times do |i| puts border if i%3 == 0 9.times do |j| print j%3 == 0? : print matrix[i][j] == 0? : matrix[i][j] end puts end puts border end data = <<EOS 394__267_ ___3__4__ 5__69__2_ _45___9__ 6_______7 __7___58_ _1__67__8 __9__8___ _264__735 EOS matrix = read_matrix(data) print_matrix(matrix) puts print_matrix(solve_sudoku(matrix))
176Sudoku
14ruby
3odz7
str = "alphaBETA" print( string.upper(str) ) print( string.lower(str) )
189String case
1lua
rldga
SELECT SUM(x*x) FROM vector
166Sum of squares
19sql
ehoau
str = "abcdefghijklmnopqrstuvwxyz" n, m = 5, 15 print( string.sub( str, n, m ) )
183Substring
1lua
8ak0e
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i]!= val && sudoku_ar[i * 9 + x]!= val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j]!= val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos% 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1)% 3 == 0 && (i + 1)% 9!= 0 { print!("| "); } if (i + 1)% 9 == 0 { println!(" "); } if (i + 1)% 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
176Sudoku
15rust
6if3l
puts [1..-1] puts [0..-2] puts .chop puts [1..-2] puts [1..-2]
175Substring/Top and tail
14ruby
fsidr
numbers = [1, 2, 3] total = sum(numbers) product = 1 for i in numbers: product *= i
170Sum and product of an array
3python
jub7p
let extra = "little" println("Mary had a \(extra) lamb.")
186String interpolation (included)
17swift
gct49
.delete()
184Strip a set of characters from a string
14ruby
lzicl
String s = "Hello, world!"; int byteCountUTF16 = s.getBytes("UTF-16").length;
190String length
9java
ej9a5
fn main() { let s = String::from("luouk k"); let mut modified = s.clone(); modified.remove(0); println!("{}", modified); let mut modified = s.clone(); modified.pop(); println!("{}", modified); let mut modified = s; modified.remove(0); modified.pop(); println!("{}", modified); }
175Substring/Top and tail
15rust
t0nfd
println("knight".tail)
175Substring/Top and tail
16scala
6it31
fn strip_characters(original: &str, to_strip: &str) -> String { let mut result = String::new(); for c in original.chars() { if!to_strip.contains(c) { result.push(c); } } result }
184Strip a set of characters from a string
15rust
23nlt
var s = "Hello, world!"; var byteCount = s.length * 2;
190String length
10javascript
01usz
func sumSq(s: [Int]) -> Int { return s.map{$0 * $0}.reduce(0, +) }
166Sum of squares
17swift
7varq
object SudokuSolver extends App { class Solver { var solution = new Array[Int](81)
176Sudoku
16scala
9f3m5
total <- sum(1:5) product <- prod(1:5)
170Sum and product of an array
13r
4c75y
def stripChars(s:String, ch:String)= s filterNot (ch contains _) stripChars("She was a soul stripper. She took my heart!", "aei")
184Strip a set of characters from a string
16scala
5mtut
def sum35(n) (1...n).select{|i|i%3==0 or i%5==0}.sum end puts sum35(1000)
167Sum multiples of 3 and 5
14ruby
4ck5p
WITH FUNCTION sum_digits(p_in_str IN varchar2) RETURN varchar2 IS v_in_str VARCHAR(32767):= translate(p_in_str,'*-+','*'); v_sum INTEGER; BEGIN -- IF regexp_count(v_in_str,'[0-9A-F]',1,'i')=LENGTH(v_in_str) THEN -- base 16 EXECUTE immediate 'select sum('||regexp_replace(v_in_str,'(\w)','to_number(''\1'',''X'')+')||'0) from dual' INTO v_sum; -- elsif regexp_count(v_in_str,'[0-9]',1,'i')=LENGTH(v_in_str) THEN -- base 10 EXECUTE immediate 'select sum('||regexp_replace(v_in_str,'(\d)','\1+')||'0) from dual' INTO v_sum; -- ELSE RETURN 'Sum of digits for integer not defined'; -- END IF; -- RETURN 'Sum of digits for integer = '||v_sum; END; --Test SELECT sum_digits('') AS res FROM dual UNION ALL SELECT sum_digits('000') AS res FROM dual UNION ALL SELECT sum_digits('-010') AS res FROM dual UNION ALL SELECT sum_digits('+010') AS res FROM dual UNION ALL SELECT sum_digits('120034') AS res FROM dual UNION ALL SELECT sum_digits('FE') AS res FROM dual UNION ALL SELECT sum_digits('f0e') AS res FROM dual UNION ALL SELECT sum_digits('st12') AS res FROM dual;
169Sum digits of an integer
19sql
qpoxb
method_names = [:==,:!=,:>,:>=,:<,:<=,:<=>, :casecmp] [[, ], [, ], [,], [, ]].each do |str1, str2| method_names.each{|m| puts % [str1, m, str2, str1.send(m, str2)]} puts end
187String comparison
14ruby
a7l1s
my $s = 'hello'; print $s . ' literal', "\n"; my $s1 = $s . ' literal'; print $s1, "\n";
185String concatenation
2perl
ct89a
use std::ascii::AsciiExt;
187String comparison
15rust
ej2aj
object Compare extends App { def compare(a: String, b: String) { if (a == b) println(s"'$a' and '$b' are lexically equal.") else println(s"'$a' and '$b' are not lexically equal.") if (a.equalsIgnoreCase(b)) println(s"'$a' and '$b' are case-insensitive lexically equal.") else println(s"'$a' and '$b' are not case-insensitive lexically equal.") if (a.compareTo(b) < 0) println(s"'$a' is lexically before '$b'.") else if (a.compareTo(b) > 0) println(s"'$a' is lexically after '$b'.") if (a.compareTo(b) >= 0) println(s"'$a' is not lexically before '$b'.") if (a.compareTo(b) <= 0) println(s"'$a' is not lexically after '$b'.") println(s"The lexical relationship is: ${a.compareTo(b)}") println(s"The case-insensitive lexical relationship is: ${a.compareToIgnoreCase(b)}\n") } compare("Hello", "Hello") compare("5", "5.0") compare("java", "Java") compare("V", "V") compare("V", "v") }
187String comparison
16scala
qb5xw
null
190String length
11kotlin
k5zh3
<?php $s = ; echo $s . . ; $s1 = $s . ; echo $s1 . ; ?>
185String concatenation
12php
xk4w5
extern crate rug; use rug::Integer; use rug::ops::Pow; fn main() { for i in [3, 20, 100, 1_000].iter() { let ten = Integer::from(10); let mut limit = Integer::from(Integer::from(&ten.pow(*i as u32)) - 1); let mut aux_3_1 = &limit.mod_u(3u32); let mut aux_3_2 = Integer::from(&limit - aux_3_1); let mut aux_3_3 = Integer::from(&aux_3_2/3); let mut aux_3_4 = Integer::from(3 + aux_3_2); let mut aux_3_5 = Integer::from(&aux_3_3*&aux_3_4); let mut aux_3_6 = Integer::from(&aux_3_5/2); let mut aux_5_1 = &limit.mod_u(5u32); let mut aux_5_2 = Integer::from(&limit - aux_5_1); let mut aux_5_3 = Integer::from(&aux_5_2/5); let mut aux_5_4 = Integer::from(5 + aux_5_2); let mut aux_5_5 = Integer::from(&aux_5_3*&aux_5_4); let mut aux_5_6 = Integer::from(&aux_5_5/2); let mut aux_15_1 = &limit.mod_u(15u32); let mut aux_15_2 = Integer::from(&limit - aux_15_1); let mut aux_15_3 = Integer::from(&aux_15_2/15); let mut aux_15_4 = Integer::from(15 + aux_15_2); let mut aux_15_5 = Integer::from(&aux_15_3*&aux_15_4); let mut aux_15_6 = Integer::from(&aux_15_5/2); let mut result_aux_1 = Integer::from(&aux_3_6 + &aux_5_6); let mut result = Integer::from(&result_aux_1 - &aux_15_6); println!("Sum for 10^{}: {}",i,result); } }
167Sum multiples of 3 and 5
15rust
glb4o
s1 = "string" s2 = "str" s3 = "ing" s4 = "xyz" print( "s1 starts with s2: ", string.find( s1, s2 ) == 1 ) print( "s1 starts with s3: ", string.find( s1, s3 ) == 1, "\n" ) print( "s1 contains s3: ", string.find( s1, s3 ) ~= nil ) print( "s1 contains s3: ", string.find( s1, s4 ) ~= nil, "\n" ) print( "s1 ends with s2: ", select( 2, string.find( s1, s2 ) ) == string.len( s1 ) ) print( "s1 ends with s3: ", select( 2, string.find( s1, s3 ) ) == string.len( s1 ) )
188String matching
1lua
pgmbw
def sum35( max:BigInt ) : BigInt = max match {
167Sum multiples of 3 and 5
16scala
jua7i
extension String: Error { func sumDigits(withBase base: Int) throws -> Int { func characterToInt(_ base: Int) -> (Character) -> Int? { return { char in return Int(String(char), radix: base) } } return try self.map(characterToInt(base)) .flatMap { guard $0!= nil else { throw "Invalid input" } return $0 } .reduce(0, +) } } print(try! "1".sumDigits(withBase: 10)) print(try! "1234".sumDigits(withBase: 10)) print(try! "fe".sumDigits(withBase: 16)) print(try! "f0e".sumDigits(withBase: 16))
169Sum digits of an integer
17swift
k4ahx
WITH symbols (d) AS (SELECT to_char(level) FROM dual CONNECT BY level <= 9) , board (i) AS (SELECT level FROM dual CONNECT BY level <= 81) , neighbors (i, j) AS ( SELECT b1.i, b2.i FROM board b1 INNER JOIN board b2 ON b1.i!= b2.i AND ( MOD(b1.i - b2.i, 9) = 0 OR CEIL(b1.i / 9) = CEIL(b2.i / 9) OR CEIL(b1.i / 27) = CEIL(b2.i / 27) AND trunc(MOD(b1.i - 1, 9) / 3) = trunc(MOD(b2.i - 1, 9) / 3) ) ) , r (str, pos) AS ( SELECT :game, instr(:game, ' ') FROM dual UNION ALL SELECT substr(r.str, 1, r.pos - 1) || s.d || substr(r.str, r.pos + 1), instr(r.str, ' ', r.pos + 1) FROM r INNER JOIN symbols s ON r.pos > 0 AND NOT EXISTS ( SELECT * FROM neighbors n WHERE r.pos = n.i AND s.d = substr(r.str, n.j, 1) ) ) SELECT str FROM r WHERE pos = 0 ;
176Sudoku
19sql
23mlc
let txt = "0123456789" println(dropFirst(txt)) println(dropLast(txt)) println(dropFirst(dropLast(txt)))
175Substring/Top and tail
17swift
dqonh
extension String { func stripCharactersInSet(chars: [Character]) -> String { return String(seq: filter(self) {find(chars, $0) == nil}) } } let aString = "She was a soul stripper. She took my heart!" let chars: [Character] = ["a", "e", "i"] println(aString.stripCharactersInSet(chars))
184Strip a set of characters from a string
17swift
cto9t
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value!= 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return!isPresent } func printBoard() { for i in 0..<mBoardSize { if i% mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j% mBoxSize == 0 { print("| ") } print(mBoard[i][j]!= 0? String(mBoard[i][j]): " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j]!= 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
176Sudoku
17swift
z8ntu
arr = [1,2,3,4,5] p sum = arr.inject(0) { |sum, item| sum + item } p product = arr.inject(1) { |prod, element| prod * element }
170Sum and product of an array
14ruby
k41hg
s1 = print s1 + s2 = s1 + print s2
185String concatenation
3python
lzocv
fn main() { let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
170Sum and product of an array
15rust
bgakx
func compare (a: String, b: String) { if a == b { println("'\(a)' and '\(b)' are lexically equal.") } if a!= b { println("'\(a)' and '\(b)' are not lexically equal.") } if a < b { println("'\(a)' is lexically before '\(b)'.") } if a > b { println("'\(a)' is lexically after '\(b)'.") } if a >= b { println("'\(a)' is not lexically before '\(b)'.") } if a <= b { println("'\(a)' is not lexically after '\(b)'.") } } compare("cat", "dog")
187String comparison
17swift
1rcpt
hello <- "hello" paste(hello, "literal") hl <- paste(hello, "literal") paste("no", "spaces", "between", "words", sep="")
185String concatenation
13r
ynq6h
var n:Int=1000 func sum(x:Int)->Int{ var s:Int=0 for i in 0...x{ if i%3==0 || i%5==0 { s=s+i } } return s } var sumofmult:Int=sum(x:n) print(sumofmult)
167Sum multiples of 3 and 5
17swift
59hu8
null
169Sum digits of an integer
20typescript
nqzi5
str = "Hello world" length = #str
190String length
1lua
b43ka
val seq = Seq(1, 2, 3, 4, 5) val sum = seq.foldLeft(0)(_ + _) val product = seq.foldLeft(1)(_ * _)
170Sum and product of an array
16scala
ajx1n
my $sum = 0; $sum += 1 / $_ ** 2 foreach 1..1000; print "$sum\n";
171Sum of a series
2perl
own8x
s = puts puts s puts s + puts s s += puts s s << puts s s = puts s.concat() puts s puts s.prepend() puts s
185String concatenation
14ruby
v6n2n
<?php function sum_of_a_series($n,$k) { $sum_of_a_series = 0; for($i=$k;$i<=$n;$i++) { $sum_of_a_series += (1/($i*$i)); } return $sum_of_a_series; } echo sum_of_a_series(1000,1);
171Sum of a series
12php
gl742
my $string = "alphaBETA"; print uc($string), "\n"; print lc($string), "\n"; $string =~ tr/[a-z][A-Z]/[A-Z][a-z]/; print "$string\n"; print ucfirst($string), "\n"; print lcfirst("FOObar"), "\n";
189String case
2perl
nx7iw
fn main() { let s = "hello".to_owned(); println!("{}", s); let s1 = s + " world"; println!("{}", s1); }
185String concatenation
15rust
uydvj
$str = ; echo strtoupper($str), ; echo strtolower($str), ; echo ucfirst($str), ; echo lcfirst(), ; echo ucwords(), ; echo lcwords(), ;
189String case
12php
72frp
val s = "hello"
185String concatenation
16scala
gcz4i
my $str = 'abcdefgh'; print substr($str, 2, 3), "\n"; print substr($str, 2), "\n"; print substr($str, 0, -1), "\n"; print substr($str, index($str, 'd'), 3), "\n"; print substr($str, index($str, 'de'), 3), "\n";
183Substring
2perl
5mzu2
let a = [1, 2, 3, 4, 5] println(a.reduce(0, +))
170Sum and product of an array
17swift
h5pj0
<?php $str = 'abcdefgh'; $n = 2; $m = 3; echo substr($str, $n, $m), ; echo substr($str, $n), ; echo substr($str, 0, -1), ; echo substr($str, strpos($str, 'd'), $m), ; echo substr($str, strpos($str, 'de'), $m), ; ?>
183Substring
12php
oeb85
$str1 =~ /^\Q$str2\E/ $str1 =~ /\Q$str2\E/ $str1 =~ /\Q$str2\E$/
188String matching
2perl
6ia36
<?php $haystack = $_POST['haystack']; if ($haystack=='') {$haystack='no haystack given';} $needle = $_POST['needle']; if ($needle=='') {$needle='no needle given';} function rexxpos($h,$n) { $pos = strpos($h,$n); if ($pos === false) { $pos=-1; } else { $pos=$pos+1; } return ($pos); } $pos=rexxpos($haystack,$needle); $tx1 = ; if ($pos==-1){ $n=0; } else { $n=1; } if ($pos==1){ $tx1=; } if ($pos==strlen($haystack)-strlen($needle)+1) { $tx1=; } if ($n>0) { $pl=$pos; $p=$pos; $x=; $h=$haystack; while ($p>0) { $h=substr($x,0,$p).substr($h,$p); $p=rexxpos($h,$needle); if ( $p>0 ) { $n=$n+1; $pl=$pl..$p; } } if ($n==1) { $txt=; } else if ($n==2) { $txt=; } else { $txt=; } } else { $txt=; } ?> <html> <head> <title>Character Matching</title> <meta name= content=> <meta name= content=> <style> p { font: 120% courier; } </style> </head> <body> <p><strong>Haystack:&nbsp;'<?php echo ?>'</strong></p> <p><strong>Needle:&nbsp;&nbsp;&nbsp;'<?php echo ?>'</strong></p> <p><strong><?php echo ?></strong></p> <!-- special message: --> <p style=;><strong><?php echo ?></strong></p> </body> </html>
188String matching
12php
1r9pq
let s = "hello" println(s + " literal") let s1 = s + " literal" println(s1)
185String concatenation
17swift
23ilj
print ( sum(1.0 / (x * x) for x in range(1, 1001)) )
171Sum of a series
3python
ixdof
s = print s.upper() print s.lower() print s.swapcase() print .capitalize() print .title() import string print string.capwords()
189String case
3python
dqjn1
str <- "alphaBETA" toupper(str) tolower(str)
189String case
13r
8a40x
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
183Substring
3python
4935k
print( sum( 1/seq(1000)^2 ) )
171Sum of a series
13r
s18qy