code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
def _commentstripper(txt, delim): 'Strips first nest of block comments' deliml, delimr = delim out = '' if deliml in txt: indx = txt.index(deliml) out += txt[:indx] txt = txt[indx+len(deliml):] txt = _commentstripper(txt, delim) assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt indx = txt.index(delimr) out += txt[(indx+len(delimr)):] else: out = txt return out def commentstripper(txt, delim=('')): 'Strips nests of block comments' deliml, delimr = delim while deliml in txt: txt = _commentstripper(txt, delim) return txt
177Strip block comments
3python
qb1xi
int main(void) { const char *string = ; size_t length = strlen(string); return 0; }
190String length
5c
dq7nv
{ let s = " \t String with spaces \t ";
181Strip whitespace from a string/Top and tail
10javascript
b4uki
null
175Substring/Top and tail
11kotlin
49v57
package main import ("fmt"; "math") func main() { fmt.Println("known: ", math.Pi*math.Pi/6) sum := 0. for i := 1e3; i > 0; i-- { sum += 1 / (i * i) } fmt.Println("computed:", sum) }
171Sum of a series
0go
26ul7
while (<>) { s/[ s/^\s+//; s/\s+$//; print }
182Strip comments from a string
2perl
uyzvr
(def string "alphaBETA") (println (.toUpperCase string)) (println (.toLowerCase string))
189String case
6clojure
dqjnb
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
9java
pgjb3
println ((1000..1).collect { x -> 1/(x*x) }.sum())
171Sum of a series
7groovy
yd96o
def remove_comments!(str, comment_start='') while start_idx = str.index(comment_start) end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1 str[start_idx .. end_idx] = end str end def remove_comments(str, comment_start='') remove_comments!(str.dup, comment_start, comment_end) end example = <<END_OF_STRING function subroutine() { a = b + c; } function something() { } END_OF_STRING puts remove_comments example
177Strip block comments
14ruby
01esu
use strict; use warnings; use feature ':all'; $_ = 'bar'; $_ = 'Foo' . $_; say; $_ = 'bar'; substr $_, 0, 0, 'Foo'; say; $_ = 'bar'; $_ = "Foo$_"; say;
179String prepend
2perl
4995d
fun main(args: Array<String>) { val s = " \tRosetta Code \r \u2009 \n" println("Untrimmed => [$s]") println("Left Trimmed => [${s.trimStart()}]") println("Right Trimmed => [${s.trimEnd()}]") println("Fully Trimmed => [${s.trim()}]") }
181Strip whitespace from a string/Top and tail
11kotlin
v6z21
null
176Sudoku
10javascript
xk1w9
use strict; use warnings; my $file = shift; my @memory = (); open (my $fh, $file); while (<$fh>) { chomp; push @memory, split; } close($fh); my $ip = 0; while ($ip >= 0 && $ip < @memory) { my ($a, $b, $c) = @memory[$ip,$ip+1,$ip+2]; $ip += 3; if ($a < 0) { $memory[$b] = ord(getc); } elsif ($b < 0) { print chr($memory[$a]); } else { if (($memory[$b] -= $memory[$a]) <= 0) { $ip = $c; } } }
178Subleq
2perl
ynd6u
sum [1 / x ^ 2 | x <- [1..1000]]
171Sum of a series
8haskell
ajw1g
import java.util.regex.Pattern.quote def strip1(x: String, s: String = "") = x.replaceAll("(?s)"+quote(s)+".*?"+quote(e), "")
177Strip block comments
16scala
nxsic
(def utf-8-octet-length #(-> % (.getBytes "UTF-8") count)) (map utf-8-octet-length ["mse" "" "J\u0332o\u0332s\u0332e\u0301\u0332"]) (def utf-16-octet-length (comp (partial * 2) count)) (map utf-16-octet-length ["mse" "" "J\u0332o\u0332s\u0332e\u0301\u0332"]) (def code-unit-length count) (map code-unit-length ["mse" "" "J\u0332o\u0332s\u0332e\u0301\u0332"])
190String length
6clojure
6ip3q
use strict ; my @letters ; my @nocontrols ; my @noextended ; for ( 1..40 ) { push @letters , int( rand( 256 ) ) ; } print "before sanitation: " ; print join( '' , map { chr( $_ ) } @letters ) ; print "\n" ; @nocontrols = grep { $_ > 32 && $_ != 127 } @letters ; print "Without controls: " ; print join( '' , map { chr( $_ ) } @nocontrols ) ; @noextended = grep { $_ < 127 } @nocontrols ; print "\nWithout extended: " ; print join( '' , map { chr( $_ ) } @noextended ) ; print "\n" ;
180Strip control codes and extended characters from a string
2perl
whje6
function sumf(a, ...) return a and a + sumf(...) or 0 end function sumt(t) return sumf(unpack(t)) end function prodf(a, ...) return a and a * prodf(...) or 1 end function prodt(t) return prodf(unpack(t)) end print(sumt{1, 2, 3, 4, 5}) print(prodt{1, 2, 3, 4, 5})
170Sum and product of an array
1lua
dsznq
def remove_comments(line, sep): for s in sep: i = line.find(s) if i >= 0: line = line[:i] return line.strip() print remove_comments('apples; pears print remove_comments('apples; pears
182Strip comments from a string
3python
5m3ux
import Foundation func stripBlocks(from str: String, open: String = "") -> String { guard!open.isEmpty &&!close.isEmpty else { return str } var ret = str while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) { ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "") } return ret } let test = """ function subroutine() { a = b + c; } function something() { } """ print(stripBlocks(from: test))
177Strip block comments
17swift
spaqt
package main import ( "fmt" "strings" ) func stripchars(str, chr string) string { return strings.Map(func(r rune) rune { if strings.IndexRune(chr, r) < 0 { return r } return -1 }, str) } func main() { fmt.Println(stripchars("She was a soul stripper. She took my heart!", "aei")) }
184Strip a set of characters from a string
0go
k5chz
null
176Sudoku
11kotlin
725r4
strip_comments <- function(str) { if(!require(stringr)) stop("you need to install the stringr package") str_trim(str_split_fixed(str, " }
182Strip comments from a string
13r
lzdce
def stripChars = { string, stripChars -> def list = string as List list.removeAll(stripChars as List) list.join() }
184Strip a set of characters from a string
7groovy
gc346
stripChars :: String -> String -> String stripChars = filter . flip notElem
184Strip a set of characters from a string
8haskell
nxpie
s = s = + s print(s)
179String prepend
3python
gcc4h
str = " \t \r \n String with spaces \t \r \n " print( string.format( "Leading whitespace removed:%s", str:match( "^%s*(.+)" ) ) ) print( string.format( "Trailing whitespace removed:%s", str:match( "(.-)%s*$" ) ) ) print( string.format( "Leading and trailing whitespace removed:%s", str:match( "^%s*(.-)%s*$" ) ) )
181Strip whitespace from a string/Top and tail
1lua
uy3vl
null
176Sudoku
1lua
jv471
print (string.sub("knights",2))
175Substring/Top and tail
1lua
gcu4j
package main import ( "fmt" ) func main() { str := "Mary had a%s lamb" txt := "little" out := fmt.Sprintf(str, txt) fmt.Println(out) }
186String interpolation (included)
0go
xk5wf
def adj = 'little' assert 'Mary had a little lamb.' == "Mary had a ${adj} lamb."
186String interpolation (included)
7groovy
pgcbo
import Text.Printf main = printf "Mary had a%s lamb\n" "little"
186String interpolation (included)
8haskell
ynx66
import sys def subleq(a): i = 0 try: while i >= 0: if a[i] == -1: a[a[i + 1]] = ord(sys.stdin.read(1)) elif a[i + 1] == -1: print(chr(a[a[i]]), end=) else: a[a[i + 1]] -= a[a[i]] if a[a[i + 1]] <= 0: i = a[i + 2] continue i += 3 except (ValueError, IndexError, KeyboardInterrupt): print() print(a) 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
3python
mdfyh
class String def strip_comment( markers = [' re = Regexp.union( markers ) if index = (self =~ re) self[0, index].rstrip else rstrip end end end p 'apples, pears str = 'apples, pears; and bananas' p str.strip_comment str = 'apples, pears and bananas ' p str.strip_comment p str.strip_comment('and') p .strip_comment p .strip_comment
182Strip comments from a string
14ruby
gcy4q
fn strip_comment<'a>(input: &'a str, markers: &[char]) -> &'a str { input .find(markers) .map(|idx| &input[..idx]) .unwrap_or(input) .trim() } fn main() { println!("{:?}", strip_comment("apples, pears # and bananas", &['#', ';'])); println!("{:?}", strip_comment("apples, pears; and bananas", &['#', ';'])); println!("{:?}", strip_comment("apples, pears and bananas ", &['#', ';'])); }
182Strip comments from a string
15rust
rlmg5
class StripChars { public static String stripChars(String inString, String toStrip) { return inString.replaceAll("[" + toStrip + "]", ""); } public static void main(String[] args) { String sentence = "She was a soul stripper. She took my heart!"; String chars = "aei"; System.out.println("sentence: " + sentence); System.out.println("to strip: " + chars); System.out.println("stripped: " + stripChars(sentence, chars)); } }
184Strip a set of characters from a string
9java
qbrxa
function stripchars(string, chars) { return string.replace(RegExp('['+chars+']','g'), ''); }
184Strip a set of characters from a string
10javascript
iwbol
str = str.prepend() p str
179String prepend
14ruby
722ri
let mut s = "World".to_string(); s.insert_str(0, "Hello "); println!("{}", s);
179String prepend
15rust
jvv72
val s = "World"
179String prepend
16scala
b44k6
mem <- c(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) getFromMemory <- function(addr) { mem[[addr + 1]] } setMemory <- function(addr, value) { mem[[addr + 1]] <<- value } subMemory <- function(x, y) { setMemory(x, getFromMemory(x) - getFromMemory(y)) } instructionPointer <- 0 while (instructionPointer >= 0) { a <- getFromMemory(instructionPointer) b <- getFromMemory(instructionPointer + 1) c <- getFromMemory(instructionPointer + 2) if (b == -1) { cat(rawToChar(as.raw(getFromMemory(a)))) } else { subMemory(b, a) if (getFromMemory(b) < 1) { instructionPointer <- getFromMemory(instructionPointer + 2) next } } instructionPointer <- instructionPointer + 3 }
178Subleq
13r
z8oth
public class Sum{ public static double f(double x){ return 1/(x*x); } public static void main(String[] args){ double start = 1; double end = 1000; double sum = 0; for(double x = start;x <= end;x++) sum += f(x); System.out.println("Sum of f(x) from " + start + " to " + end +" is " + sum); } }
171Sum of a series
9java
juk7c
object StripComments { def stripComments1(s:String, markers:String =";#")=s takeWhile (!markers.contains(_)) trim
182Strip comments from a string
16scala
hulja
String original = "Mary had a X lamb"; String little = "little"; String replaced = original.replace("X", little);
186String interpolation (included)
9java
dqbn9
package main import ( "fmt" "strings" ) func main() {
187String comparison
0go
dqkne
stripped = lambda s: .join(i for i in s if 31 < ord(i) < 127) print(stripped())
180Strip control codes and extended characters from a string
3python
xkhwr
package main import ( "fmt" "strings" ) func main() { s := "ABCDEFGH" n, m := 2, 3
183Substring
0go
xkrwf
function sum(a,b,fn) { var s = 0; for ( ; a <= b; a++) s += fn(a); return s; } sum(1,1000, function(x) { return 1/(x*x) } )
171Sum of a series
10javascript
17ep7
var original = "Mary had a X lamb"; var little = "little"; var replaced = original.replace("X", little);
186String interpolation (included)
10javascript
6iw38
null
184Strip a set of characters from a string
11kotlin
1rvpd
var str = ", World" str = "Hello \(str)" println(str)
179String prepend
17swift
rllgg
> "abc" == "abc" True > "abc" /= "abc" False > "abc" <= "abcd" True > "abc" <= "abC" False > "HELLOWORLD" == "HelloWorld" False >:m +Data.Char > map toLower "ABC" "abc" > map toLower "HELLOWORLD" == map toLower "HelloWorld" True
187String comparison
8haskell
5mnug
package main import "fmt" func main() {
185String concatenation
0go
pglbg
sub sum_of_squares { my $sum = 0; $sum += $_**2 foreach @_; return $sum; } print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";
166Sum of squares
2perl
glp4e
def str = 'abcdefgh' def n = 2 def m = 3
183Substring
7groovy
pgvbo
null
186String interpolation (included)
11kotlin
01rsf
class String def strip_control_characters() chars.each_with_object() do |char, str| str << char unless char.ascii_only? and (char.ord < 32 or char.ord == 127) end end def strip_control_and_extended_characters() chars.each_with_object() do |char, str| str << char if char.ascii_only? and char.ord.between?(32,126) end end end p s = p s.strip_control_characters p s.strip_control_and_extended_characters
180Strip control codes and extended characters from a string
14ruby
spbqw
def s = "Greetings " println s + "Earthlings" def s1 = s + "Earthlings" println s1
185String concatenation
7groovy
726rz
import System.IO s = "hello" s1 = s ++ " literal" main = do putStrLn (s ++ " literal") putStrLn s1
185String concatenation
8haskell
fs1d1
use strict; use warnings; my %letval = map { $_ => $_ } 0 .. 9; $letval{$_} = ord($_) - ord('a') + 10 for 'a' .. 'z'; $letval{$_} = ord($_) - ord('A') + 10 for 'A' .. 'Z'; sub sumdigits { my $number = shift; my $sum = 0; $sum += $letval{$_} for (split //, $number); $sum; } print "$_ sums to " . sumdigits($_) . "\n" for (qw/1 1234 1020304 fe f0e DEADBEEF/);
169Sum digits of an integer
2perl
jup7f
*Main> take 3 $ drop 2 "1234567890" "345" *Main> drop 2 "1234567890" "34567890" *Main> init "1234567890" "123456789"
183Substring
8haskell
yn066
class Computer def initialize program @memory = program.map &:to_i @instruction_pointer = 0 end def step return nil if @instruction_pointer < 0 a, b, c = @memory[@instruction_pointer .. @instruction_pointer + 2] @instruction_pointer += 3 if a == -1 b = readchar elsif b == -1 writechar @memory[a] else difference = @memory[b] -= @memory[a] @instruction_pointer = c if difference <= 0 end @instruction_pointer end def run current_pointer = @instruction_pointer current_pointer = step while current_pointer >= 0 end private def readchar gets[0].ord end def writechar code_point print code_point.chr end end subleq = Computer.new ARGV subleq.run
178Subleq
14ruby
ctz9k
import java.util.Scanner object Subleq extends App { val mem = Array(15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', 10, 0) val input = new Scanner(System.in) var instructionPointer = 0 do { val (a, b) = (mem(instructionPointer), mem(instructionPointer + 1)) if (a == -1) mem(b) = input.nextInt else if (b == -1) print(f"${mem(a)}%c") else { mem(b) -= mem(a) if (mem(b) < 1) instructionPointer = mem(instructionPointer + 2) - 3 } instructionPointer += 3 } while (instructionPointer >= 0) }
178Subleq
16scala
uymv8
public class Compare { public static void main (String[] args) { compare("Hello", "Hello"); compare("5", "5.0"); compare("java", "Java"); compare("V", "V"); compare("V", "v"); } public static void compare (String A, String B) { if (A.equals(B)) System.out.printf("'%s' and '%s' are lexically equal.", A, B); else System.out.printf("'%s' and '%s' are not lexically equal.", A, B); System.out.println(); if (A.equalsIgnoreCase(B)) System.out.printf("'%s' and '%s' are case-insensitive lexically equal.", A, B); else System.out.printf("'%s' and '%s' are not case-insensitive lexically equal.", A, B); System.out.println(); if (A.compareTo(B) < 0) System.out.printf("'%s' is lexically before '%s'.\n", A, B); else if (A.compareTo(B) > 0) System.out.printf("'%s' is lexically after '%s'.\n", A, B); if (A.compareTo(B) >= 0) System.out.printf("'%s' is not lexically before '%s'.\n", A, B); if (A.compareTo(B) <= 0) System.out.printf("'%s' is not lexically after '%s'.\n", A, B); System.out.printf("The lexical relationship is:%d\n", A.compareTo(B)); System.out.printf("The case-insensitive lexical relationship is:%d\n\n", A.compareToIgnoreCase(B)); } }
187String comparison
9java
9fqmu
val controlCode : (Char) => Boolean = (c:Char) => (c <= 32 || c == 127) val extendedCode : (Char) => Boolean = (c:Char) => (c <= 32 || c > 127)
180Strip control codes and extended characters from a string
16scala
iweox
function sum_squares(array $args) { return array_reduce( $args, create_function('$x, $y', 'return $x+$y*$y;'), 0 ); }
166Sum of squares
12php
nqyig
str = string.gsub( "Mary had a X lamb.", "X", "little" ) print( str )
186String interpolation (included)
1lua
8a70e
function stripchars(str, chrs) local s = str:gsub("["..chrs:gsub("%W","%%%1").."]", '') return s end print( stripchars( "She was a soul stripper. She took my heart!", "aei" ) )
184Strip a set of characters from a string
1lua
a7u1v
console.log( "abcd" == "abcd",
187String comparison
10javascript
uyivb
public class Str{ public static void main(String[] args){ String s = "hello"; System.out.println(s + " literal"); String s2 = s + " literal"; System.out.println(s2); } }
185String concatenation
9java
017se
<?php function sumDigits($num, $base = 10) { $s = base_convert($num, 10, $base); foreach (str_split($s) as $c) $result += intval($c, $base); return $result; } echo sumDigits(1), ; echo sumDigits(12345), ; echo sumDigits(123045), ; echo sumDigits(0xfe, 16), ; echo sumDigits(0xf0e, 16), ; ?>
169Sum digits of an integer
12php
t8yf1
func subleq(_ inst: inout [Int]) { var i = 0 while i >= 0 { if inst[i] == -1 { inst[inst[i + 1]] = Int(readLine(strippingNewline: true)!.unicodeScalars.first!.value) } else if inst[i + 1] == -1 { print(String(UnicodeScalar(inst[inst[i]])!), terminator: "") } else { inst[inst[i + 1]] -= inst[inst[i]] if inst[inst[i + 1]] <= 0 { i = inst[i + 2] continue } } i += 3 } } var prog = [ 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 ] subleq(&prog)
178Subleq
17swift
9ftmj
null
171Sum of a series
11kotlin
59gua
null
187String comparison
11kotlin
z81ts
var s = "hello" print(s + " there!")
185String concatenation
10javascript
dqpnu
sub ltrim { shift =~ s/^\s+//r } sub rtrim { shift =~ s/\s+$//r } sub trim { ltrim rtrim shift } my $p = " this is a string "; print "'", $p, "'\n"; print "'", trim($p), "'\n"; print "'", ltrim($p), "'\n"; print "'", rtrim($p), "'\n";
181Strip whitespace from a string/Top and tail
2perl
01bs4
public static String Substring(String str, int n, int m){ return str.substring(n, n+m); } public static String Substring(String str, int n){ return str.substring(n); } public static String Substring(String str){ return str.substring(0, str.length()-1); } public static String Substring(String str, char c, int m){ return str.substring(str.indexOf(c), str.indexOf(c)+m+1); } public static String Substring(String str, String sub, int m){ return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1); }
183Substring
9java
dqan9
use integer; use strict; my @A = qw( 5 3 0 0 2 4 7 0 0 0 0 2 0 0 0 8 0 0 1 0 0 7 0 3 9 0 2 0 0 8 0 7 2 0 4 9 0 2 0 9 8 0 0 7 0 7 9 0 0 0 0 0 8 0 0 0 0 0 3 0 5 0 6 9 6 0 0 1 0 3 0 0 0 5 0 6 9 0 0 1 0 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i% 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
176Sudoku
2perl
fsod7
fun main(args: Array<String>) { val s1 = "James" val s2 = "Bond" println(s1) println(s2) val s3 = s1 + " " + s2 println(s3) }
185String concatenation
11kotlin
ejua4
use v5.20; use experimental qw(signatures); use List::Util qw( sum ) ; sub sum_3_5($limit) { return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ; } say "The sum is ${\(sum_3_5 1000)}!\n" ;
167Sum multiples of 3 and 5
2perl
vy720
<?php $string = ' this is a string '; echo '^'.trim($string) .'$'.PHP_EOL; echo '^'.ltrim($string).'$'.PHP_EOL; echo '^'.rtrim($string).'$'.PHP_EOL;
181Strip whitespace from a string/Top and tail
12php
5m6us
var str = "abcdefgh"; var n = 2; var m = 3;
183Substring
10javascript
6is38
function compare(a, b) print(("%s is of type%s and%s is of type%s"):format( a, type(a), b, type(b) )) if a < b then print(('%s is strictly less than%s'):format(a, b)) end if a <= b then print(('%s is less than or equal to%s'):format(a, b)) end if a > b then print(('%s is strictly greater than%s'):format(a, b)) end if a >= b then print(('%s is greater than or equal to%s'):format(a, b)) end if a == b then print(('%s is equal to%s'):format(a, b)) end if a ~= b then print(('%s is not equal to%s'):format(a, b)) end print "" end compare('YUP', 'YUP') compare('BALL', 'BELL') compare('24', '123') compare(24, 123) compare(5.0, 5)
187String comparison
1lua
3oazo
class SudokuSolver { protected $grid = []; protected $emptySymbol; public static function parseString($str, $emptySymbol = '0') { $grid = str_split($str); foreach($grid as &$v) { if($v == $emptySymbol) { $v = 0; } else { $v = (int)$v; } } return $grid; } public function __construct($str, $emptySymbol = '0') { if(strlen($str) !== 81) { throw new \Exception('Error sudoku'); } $this->grid = static::parseString($str, $emptySymbol); $this->emptySymbol = $emptySymbol; } public function solve() { try { $this->placeNumber(0); return false; } catch(\Exception $e) { return true; } } protected function placeNumber($pos) { if($pos == 81) { throw new \Exception('Finish'); } if($this->grid[$pos] > 0) { $this->placeNumber($pos+1); return; } for($n = 1; $n <= 9; $n++) { if($this->checkValidity($n, $pos%9, floor($pos/9))) { $this->grid[$pos] = $n; $this->placeNumber($pos+1); $this->grid[$pos] = 0; } } } protected function checkValidity($val, $x, $y) { for($i = 0; $i < 9; $i++) { if(($this->grid[$y*9+$i] == $val) || ($this->grid[$i*9+$x] == $val)) { return false; } } $startX = (int) ((int)($x/3)*3); $startY = (int) ((int)($y/3)*3); for($i = $startY; $i<$startY+3;$i++) { for($j = $startX; $j<$startX+3;$j++) { if($this->grid[$i*9+$j] == $val) { return false; } } } return true; } public function display() { $str = ''; for($i = 0; $i<9; $i++) { for($j = 0; $j<9;$j++) { $str .= $this->grid[$i*9+$j]; $str .= ; if($j == 2 || $j == 5) { $str .= ; } } $str .= PHP_EOL; if($i == 2 || $i == 5) { $str .= .PHP_EOL; } } echo $str; } public function __toString() { foreach ($this->grid as &$item) { if($item == 0) { $item = $this->emptySymbol; } } return implode('', $this->grid); } } $solver = new SudokuSolver('009170000020600001800200000200006053000051009005040080040000700006000320700003900'); $solver->solve(); $solver->display();
176Sudoku
12php
hugjf
print substr("knight",1), "\n"; print substr("socks", 0, -1), "\n"; print substr("brooms", 1, -1), "\n";
175Substring/Top and tail
2perl
iw0o3
$extra = "little"; print "Mary had a $extra lamb.\n"; printf "Mary had a%s lamb.\n", $extra;
186String interpolation (included)
2perl
5mdu2
$max = 1000; $sum = 0; for ($i = 1 ; $i < $max ; $i++) { if (($i % 3 == 0) or ($i % 5 == 0)) { $sum += $i; } } echo $sum, PHP_EOL;
167Sum multiples of 3 and 5
12php
0afsp
sum(x * x for x in [1, 2, 3, 4, 5]) sum(x ** 2 for x in [1, 2, 3, 4, 5]) sum(pow(x, 2) for x in [1, 2, 3, 4, 5])
166Sum of squares
3python
r21gq
<?php $extra = 'little'; echo ; printf(, $extra); ?>
186String interpolation (included)
12php
oej85
a = "hello " print(a .. "world") c = a .. "world" print(c)
185String concatenation
1lua
wh5ea
arr <- c(1,2,3,4,5) result <- sum(arr^2)
166Sum of squares
13r
umhvx
null
183Substring
11kotlin
01hsf
<?php echo substr(, 1), ; echo substr(, 0, -1), ; echo substr(, 1, -1), ; ?>
175Substring/Top and tail
12php
rl5ge
package main import ( "fmt" "strings" "unicode" "unicode/utf8" ) func main() { show("alphaBETA") show("alpha BETA")
189String case
0go
uy8vt
package main import ( "fmt" "strings" ) func match(first, second string) { fmt.Printf("1.%s starts with%s:%t\n", first, second, strings.HasPrefix(first, second)) i := strings.Index(first, second) fmt.Printf("2.%s contains%s:%t,\n", first, second, i >= 0) if i >= 0 { fmt.Printf("2.1. at location%d,\n", i) for start := i+1;; { if i = strings.Index(first[start:], second); i < 0 { break } fmt.Printf("2.2. at location%d,\n", start+i) start += i+1 } fmt.Println("2.2. and that's all") } fmt.Printf("3.%s ends with%s:%t\n", first, second, strings.HasSuffix(first, second)) } func main() { match("abracadabra", "abr") }
188String matching
0go
jvz7d
from numpy import base_repr def sumDigits(num, base=10): return sum(int(x, base) for x in list(base_repr(num, base)))
169Sum digits of an integer
3python
h51jw
sub stripchars { my ($s, $chars) = @_; $s =~ s/[$chars]//g; return $s; } print stripchars("She was a soul stripper. She took my heart!", "aei"), "\n";
184Strip a set of characters from a string
2perl
md0yz
def str = 'alphaBETA' println str.toUpperCase() println str.toLowerCase()
189String case
7groovy
9fwm4
import Data.Char s = "alphaBETA" lower = map toLower s upper = map toUpper s
189String case
8haskell
whled