code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
Node = Struct.new(:val, :back)
def lis(n)
pileTops = []
for x in n
low, high = 0, pileTops.size-1
while low <= high
mid = low + (high - low) / 2
if pileTops[mid].val >= x
high = mid - 1
else
low = mid + 1
end
end
i = low
node = Node.new(x)
node.back = pileTops[i-1] if i > 0
pileTops[i] = node
end
result = []
node = pileTops.last
while node
result.unshift(node.val)
node = node.back
end
result
end
p lis([3, 2, 6, 4, 5, 1])
p lis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]) | 631Longest increasing subsequence
| 14ruby
| eybax |
def luhn_valid?(str)
str.scan(/\d/).reverse
.each_slice(2)
.sum { |i, k = 0| i.to_i + ((k.to_i)*2).digits.sum }
.modulo(10).zero?
end
[, , , ].map{ |i| luhn_valid?(i) } | 621Luhn test of credit card numbers
| 14ruby
| tjcf2 |
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
System.out.println();
} | 630Loops/For
| 9java
| a6b1y |
package main
import "fmt"
func main() {
fmt.Println(727 == 0x2d7) | 645Literals/Integer
| 0go
| yb164 |
let double = 1.0 as Double | 639Literals/Floating point
| 17swift
| n4pil |
import Control.Monad
import System.Random
loopBreak n k = do
r <- randomRIO (0,n)
print r
unless (r==k) $ do
print =<< randomRIO (0,n)
loopBreak n k | 640Loops/Break
| 8haskell
| dgpn4 |
fn lis(x: &[i32])-> Vec<i32> {
let n = x.len();
let mut m = vec![0; n];
let mut p = vec![0; n];
let mut l = 0;
for i in 0..n {
let mut lo = 1;
let mut hi = l;
while lo <= hi {
let mid = (lo + hi) / 2;
if x[m[mid]] <= x[i] {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
let new_l = lo;
p[i] = m[new_l - 1];
m[new_l] = i;
if new_l > l {
l = new_l;
}
}
let mut o = vec![0; l];
let mut k = m[l];
for i in (0..l).rev() {
o[i] = x[k];
k = p[k];
}
o
}
fn main() {
let list = vec![3, 2, 6, 4, 5, 1];
println!("{:?}", lis(&list));
let list = vec![0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15];
println!("{:?}", lis(&list));
} | 631Longest increasing subsequence
| 15rust
| wmpe4 |
i <- 0
repeat
{
i <- i + 1
print(i)
if(i%% 6 == 0) break
} | 629Loops/Do-while
| 13r
| vxl27 |
var i, j;
for (i = 1; i <= 5; i += 1) {
s = '';
for (j = 0; j < i; j += 1)
s += '*';
document.write(s + '<br>');
} | 630Loops/For
| 10javascript
| slwqz |
println 025 | 645Literals/Integer
| 7groovy
| frjdn |
public struct Eratosthenes: Sequence, IteratorProtocol {
private let n: Int
private let limit: Int
private var i = 2
private var sieve: [Int]
public init(upTo: Int) {
if upTo <= 1 {
self.n = 0
self.limit = -1
self.sieve = []
} else {
self.n = upTo
self.limit = Int(Double(n).squareRoot())
self.sieve = Array(0...n)
}
}
public mutating func next() -> Int? {
while i < n {
defer { i += 1 }
if sieve[i]!= 0 {
if i <= limit {
for notPrime in stride(from: i * i, through: n, by: i) {
sieve[notPrime] = 0
}
}
return i
}
}
return nil
}
}
func findPeriod(n: Int) -> Int {
let r = (1...n+1).reduce(1, {res, _ in (10 * res)% n })
var rr = r
var period = 0
repeat {
rr = (10 * rr)% n
period += 1
} while r!= rr
return period
}
let longPrimes = Eratosthenes(upTo: 64000).dropFirst().lazy.filter({ findPeriod(n: $0) == $0 - 1 })
print("Long primes less than 500: \(Array(longPrimes.prefix(while: { $0 <= 500 })))")
let counts =
longPrimes.reduce(into: [500: 0, 1000: 0, 2000: 0, 4000: 0, 8000: 0, 16000: 0, 32000: 0, 64000: 0], {counts, n in
for key in counts.keys where n < key {
counts[key]! += 1
}
})
for key in counts.keys.sorted() {
print("There are \(counts[key]!) long primes less than \(key)")
} | 635Long primes
| 17swift
| 5syu8 |
object LongestIncreasingSubsequence extends App {
val tests = Map(
"3,2,6,4,5,1" -> Seq("2,4,5", "3,4,5"),
"0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15" -> Seq("0,2,6,9,11,15", "0,2,6,9,13,15", "0,4,6,9,13,15", "0,4,6,9,11,15")
)
def lis(l: Array[Int]): Seq[Array[Int]] =
if (l.length < 2) Seq(l)
else {
def increasing(done: Array[Int], remaining: Array[Int]): Seq[Array[Int]] =
if (remaining.isEmpty) Seq(done)
else
(if (remaining.head > done.last)
increasing(done :+ remaining.head, remaining.tail)
else Nil) ++ increasing(done, remaining.tail) | 631Longest increasing subsequence
| 16scala
| sleqo |
extern crate luhn_test_of_credit_card_numbers;
use luhn_test_of_credit_card_numbers::luhn_test;
fn validate_isin(isin: &str) -> bool {
if!isin.chars().all(|x| x.is_alphanumeric()) || isin.len()!= 12 {
return false;
}
if!isin[..2].chars().all(|x| x.is_alphabetic())
||!isin[2..12].chars().all(|x| x.is_alphanumeric())
||!isin.chars().last().unwrap().is_numeric()
{
return false;
}
let bytes = isin.as_bytes();
let s2 = bytes
.iter()
.flat_map(|&c| {
if c.is_ascii_digit() {
vec![c]
} else {
(c + 10 - ('A' as u8)).to_string().into_bytes()
}
})
.collect::<Vec<u8>>();
let string = std::str::from_utf8(&s2).unwrap();
let number = string.parse::<u64>().unwrap();
return luhn_test(number as u64);
}
#[cfg(test)]
mod tests {
use super::validate_isin;
#[test]
fn test_validate_isin() {
assert_eq!(validate_isin("US0378331005"), true);
assert_eq!(validate_isin("US0373831005"), false);
assert_eq!(validate_isin("U50378331005"), false);
assert_eq!(validate_isin("US03378331005"), false);
assert_eq!(validate_isin("AU0000XVGZA3"), true);
assert_eq!(validate_isin("AU0000VXGZA3"), true);
assert_eq!(validate_isin("FR0000988040"), true);
}
} | 621Luhn test of credit card numbers
| 15rust
| zhlto |
for($i=2; $i <= 8; $i += 2) {
print "$i, ";
}
print "who do we appreciate?\n"; | 628Loops/For with a specified step
| 2perl
| hfhjl |
char a = 'a'; | 643Literals/String
| 9java
| hd3jm |
Prelude> 727 == 0o1327
True
Prelude> 727 == 0x2d7
True | 645Literals/Integer
| 8haskell
| hdtju |
function LCS( a, b )
if #a == 0 or #b == 0 then
return ""
elseif string.sub( a, -1, -1 ) == string.sub( b, -1, -1 ) then
return LCS( string.sub( a, 1, -2 ), string.sub( b, 1, -2 ) ) .. string.sub( a, -1, -1 )
else
local a_sub = LCS( a, string.sub( b, 1, -2 ) )
local b_sub = LCS( string.sub( a, 1, -2 ), b )
if #a_sub > #b_sub then
return a_sub
else
return b_sub
end
end
end
print( LCS( "thisisatest", "testing123testing" ) ) | 637Longest common subsequence
| 1lua
| frwdp |
object Luhn {
private def parse(s: String): Seq[Int] = s.map{c =>
assert(c.isDigit)
c.asDigit
}
def checksum(digits: Seq[Int]): Int = {
digits.reverse.zipWithIndex.foldLeft(0){case (sum,(digit,i))=>
if (i%2 == 0) sum + digit
else sum + (digit*2)/10 + (digit*2)%10
} % 10
}
def validate(digits: Seq[Int]): Boolean = checksum(digits) == 0
def checksum(number: String): Int = checksum(parse(number))
def validate(number: String): Boolean = validate(parse(number))
}
object LuhnTest extends App {
Seq(("49927398716", true),
("49927398717", false),
("1234567812345678", false),
("1234567812345670", true)
).foreach { case (n, expected) =>
println(s"$n ${Luhn.validate(n)}")
assert(Luhn.validate(n) == expected)
}
} | 621Luhn test of credit card numbers
| 16scala
| ypu63 |
(function () {
return " "
})();
(function() {
return "\u03b1\u03b2\u03b3\u03b4 \u4e2d\u95f4\u6765\u70b9\u4e2d\u6587 \ud83d\udc2b \u05d0\u05d1\u05d2\u05d3";
})(); | 643Literals/String
| 10javascript
| a6c10 |
var i = 1024
while i > 0 {
println(i)
i /= 2
} | 625Loops/While
| 17swift
| vq42r |
<?php
foreach (range(2, 8, 2) as $i)
echo ;
echo ;
?> | 628Loops/For with a specified step
| 12php
| zhzt1 |
null | 646Long multiplication
| 0go
| hdfjq |
import java.util.Random;
Random rand = new Random();
while(true){
int a = rand.nextInt(20);
System.out.println(a);
if(a == 10) break;
int b = rand.nextInt(20);
System.out.println(b);
} | 640Loops/Break
| 9java
| slrq0 |
let mut x = 0;
loop {
x += 1;
println!(, x);
if x% 6 == 0 { break; }
} | 629Loops/Do-while
| 14ruby
| 7igri |
let mut x = 0;
loop {
x += 1;
println!("{}", x);
if x% 6 == 0 { break; }
} | 629Loops/Do-while
| 15rust
| jnr72 |
import Data.List (transpose, inits)
import Data.Char (digitToInt)
longmult :: Integer -> Integer -> Integer
longmult x y = foldl1 ((+) . (10 *)) (polymul (digits x) (digits y))
polymul :: [Integer] -> [Integer] -> [Integer]
polymul xs ys =
sum <$>
transpose
(zipWith
(<>)
(inits $ repeat 0)
((\f x -> fmap ((<$> x) . f)) (*) xs ys))
digits :: Integer -> [Integer]
digits = fmap (fromIntegral . digitToInt) . show
main :: IO ()
main = print $ (2 ^ 64) `longmult` (2 ^ 64) | 646Long multiplication
| 8haskell
| i54or |
null | 643Literals/String
| 11kotlin
| 40n57 |
public class IntegerLiterals {
public static void main(String[] args) {
System.out.println( 727 == 0x2d7 &&
727 == 01327 );
}
} | 645Literals/Integer
| 9java
| 5s8uf |
if ( 727 == 0x2d7 &&
727 == 01327 )
window.alert("true"); | 645Literals/Integer
| 10javascript
| jnf7n |
for (;;) {
var a = Math.floor(Math.random() * 20);
print(a);
if (a == 10)
break;
a = Math.floor(Math.random() * 20);
print(a);
} | 640Loops/Break
| 10javascript
| n4biy |
import Foundation
extension Array where Element: Comparable {
@inlinable
public func longestIncreasingSubsequence() -> [Element] {
var startI = [Int](repeating: 0, count: count)
var endI = [Int](repeating: 0, count: count + 1)
var len = 0
for i in 0..<count {
var lo = 1
var hi = len
while lo <= hi {
let mid = Int(ceil((Double(lo + hi)) / 2))
if self[endI[mid]] <= self[i] {
lo = mid + 1
} else {
hi = mid - 1
}
}
startI[i] = endI[lo-1]
endI[lo] = i
if lo > len {
len = lo
}
}
var s = [Element]()
var k = endI[len]
for _ in 0..<len {
s.append(self[k])
k = startI[k]
}
return s.reversed()
}
}
let l1 = [3, 2, 6, 4, 5, 1]
let l2 = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
print("\(l1) = \(l1.longestIncreasingSubsequence())")
print("\(l2) = \(l2.longestIncreasingSubsequence())") | 631Longest increasing subsequence
| 17swift
| a6k1i |
{
var (x, l) = (0, List[Int]())
do {
x += 1
l :+= x | 629Loops/Do-while
| 16scala
| bthk6 |
fun main(args: Array<String>) {
(1..5).forEach {
(1..it).forEach { print('*') }
println()
}
} | 630Loops/For
| 11kotlin
| hdrj3 |
null | 645Literals/Integer
| 11kotlin
| caw98 |
import java.util.Random
fun main(args: Array<String>) {
val rand = Random()
while (true) {
val a = rand.nextInt(20)
println(a)
if (a == 10) break
println(rand.nextInt(20))
}
} | 640Loops/Break
| 11kotlin
| a6v13 |
public class LongMult {
private static byte[] stringToDigits(String num) {
byte[] result = new byte[num.length()];
for (int i = 0; i < num.length(); i++) {
char c = num.charAt(i);
if (c < '0' || c > '9') {
throw new IllegalArgumentException("Invalid digit " + c
+ " found at position " + i);
}
result[num.length() - 1 - i] = (byte) (c - '0');
}
return result;
}
public static String longMult(String num1, String num2) {
byte[] left = stringToDigits(num1);
byte[] right = stringToDigits(num2);
byte[] result = new byte[left.length + right.length];
for (int rightPos = 0; rightPos < right.length; rightPos++) {
byte rightDigit = right[rightPos];
byte temp = 0;
for (int leftPos = 0; leftPos < left.length; leftPos++) {
temp += result[leftPos + rightPos];
temp += rightDigit * left[leftPos];
result[leftPos + rightPos] = (byte) (temp % 10);
temp /= 10;
}
int destPos = rightPos + left.length;
while (temp != 0) {
temp += result[destPos] & 0xFFFFFFFFL;
result[destPos] = (byte) (temp % 10);
temp /= 10;
destPos++;
}
}
StringBuilder stringResultBuilder = new StringBuilder(result.length);
for (int i = result.length - 1; i >= 0; i--) {
byte digit = result[i];
if (digit != 0 || stringResultBuilder.length() > 0) {
stringResultBuilder.append((char) (digit + '0'));
}
}
return stringResultBuilder.toString();
}
public static void main(String[] args) {
System.out.println(longMult("18446744073709551616",
"18446744073709551616"));
}
} | 646Long multiplication
| 9java
| x9cwy |
function mult(strNum1,strNum2){
var a1 = strNum1.split("").reverse();
var a2 = strNum2.toString().split("").reverse();
var aResult = new Array;
for ( var iterNum1 = 0; iterNum1 < a1.length; iterNum1++ ) {
for ( var iterNum2 = 0; iterNum2 < a2.length; iterNum2++ ) {
var idxIter = iterNum1 + iterNum2; | 646Long multiplication
| 10javascript
| ou586 |
singlequotestring = 'can contain "double quotes"'
doublequotestring = "can contain 'single quotes'"
longstring = [[can contain
newlines]]
longstring2 = [==[ can contain [[ other ]=] longstring " and ' string [===[ qualifiers]==] | 643Literals/String
| 1lua
| g8d4j |
for i in xrange(2, 9, 2):
print % i,
print | 628Loops/For with a specified step
| 3python
| ktkhf |
45, 0x45 | 645Literals/Integer
| 1lua
| lexck |
func printLogic(a, b bool) {
fmt.Println("a and b is", a && b)
fmt.Println("a or b is", a || b)
fmt.Println("not a is", !a)
} | 647Logical operations
| 0go
| qccxz |
sub lcs {
my ($a, $b) = @_;
if (!length($a) || !length($b)) {
return "";
}
if (substr($a, 0, 1) eq substr($b, 0, 1)) {
return substr($a, 0, 1) . lcs(substr($a, 1), substr($b, 1));
}
my $c = lcs(substr($a, 1), $b) || "";
my $d = lcs($a, substr($b, 1)) || "";
return length($c) > length($d) ? $c : $d;
}
print lcs("thisisatest", "testing123testing") . "\n"; | 637Longest common subsequence
| 2perl
| jnc7f |
package main
import (
"fmt"
"strconv"
)
func lss(s string) (r string) {
c := s[0]
nc := 1
for i := 1; i < len(s); i++ {
d := s[i]
if d == c {
nc++
continue
}
r += strconv.Itoa(nc) + string(c)
c = d
nc = 1
}
return r + strconv.Itoa(nc) + string(c)
}
func main() {
s := "1"
fmt.Println(s)
for i := 0; i < 8; i++ {
s = lss(s)
fmt.Println(s)
}
} | 642Look-and-say sequence
| 0go
| 5snul |
foreach (1..10) {
print $_;
if ($_ % 5 == 0) {
print "\n";
next;
}
print ', ';
} | 634Loops/Continue
| 2perl
| g8c4e |
for(a in seq(2,8,2)) {
cat(a, ", ")
}
cat("who do we appreciate?\n") | 628Loops/For with a specified step
| 13r
| rirgj |
def logical = { a, b ->
println """
a AND b = ${a} && ${b} = ${a & b}
a OR b = ${a} || ${b} = ${a | b}
NOT a =! ${a} = ${! a}
a XOR b = ${a}!= ${b} = ${a!= b}
a EQV b = ${a} == ${b} = ${a == b}
"""
} | 647Logical operations
| 7groovy
| 133p6 |
def lookAndSay(sequence) {
def encoded = new StringBuilder()
(sequence.toString() =~ /(([0-9])\2*)/).each { matcher ->
encoded.append(matcher[1].size()).append(matcher[2])
}
encoded.toString()
} | 642Look-and-say sequence
| 7groovy
| cas9i |
fun String.toDigits() = mapIndexed { i, c ->
if (!c.isDigit())
throw IllegalArgumentException("Invalid digit $c found at position $i")
c - '0'
}.reversed()
operator fun String.times(n: String): String {
val left = toDigits()
val right = n.toDigits()
val result = IntArray(left.size + right.size)
right.mapIndexed { rightPos, rightDigit ->
var tmp = 0
left.indices.forEach { leftPos ->
tmp += result[leftPos + rightPos] + rightDigit * left[leftPos]
result[leftPos + rightPos] = tmp % 10
tmp /= 10
}
var destPos = rightPos + left.size
while (tmp != 0) {
tmp += (result[destPos].toLong() and 0xFFFFFFFFL).toInt()
result[destPos] = tmp % 10
tmp /= 10
destPos++
}
}
return result.foldRight(StringBuilder(result.size), { digit, sb ->
if (digit != 0 || sb.length > 0) sb.append('0' + digit)
sb
}).toString()
}
fun main(args: Array<out String>) {
println("18446744073709551616" * "18446744073709551616")
} | 646Long multiplication
| 11kotlin
| pz3b6 |
a = False
b = True
a_and_b = a && b
a_or_b = a || b
not_a = not a
a_xor_b = a /= b
a_nxor_b = a == b
a_implies_b = a <= b | 647Logical operations
| 8haskell
| mppyf |
repeat
k = math.random(19)
print(k)
if k == 10 then break end
print(math.random(19)
until false | 640Loops/Break
| 1lua
| eyuac |
import Control.Monad (liftM2)
import Data.List (group)
lookAndSay :: Integer -> Integer
lookAndSay = read
. concatMap
(liftM2 (++) (show . length)
(take 1))
. group
. show
lookAndSay2 :: Integer -> Integer
lookAndSay2 = read . concatMap (liftM2 (++) (show . length)
(take 1))
. group . show
lookAndSay3 :: Integer -> Integer
lookAndSay3 n = read (concatMap describe (group (show n)))
where describe run = show (length run) ++ take 1 run
main = mapM_ print (iterate lookAndSay 1) | 642Look-and-say sequence
| 8haskell
| x9uw4 |
for ($i = 1; $i <= 10; $i++) {
echo $i;
if ($i % 5 == 0) {
echo ;
continue;
}
echo ', ';
} | 634Loops/Continue
| 12php
| n4xig |
var val = 0
repeat {
val += 1
print(val)
} while val% 6!= 0 | 629Loops/Do-while
| 17swift
| ro4gg |
func luhn(_ number: String) -> Bool {
return number.reversed().enumerated().map({
let digit = Int(String($0.element))!
let even = $0.offset% 2 == 0
return even? digit: digit == 9? 9: digit * 2% 9
}).reduce(0, +)% 10 == 0
}
luhn("49927398716") | 621Luhn test of credit card numbers
| 17swift
| f79dk |
2.step(8,2) {|n| print }
puts | 628Loops/For with a specified step
| 14ruby
| p3pbh |
fn main() {
for i in (2..=8).step_by(2) {
print!("{}", i);
}
println!("who do we appreciate?!");
} | 628Loops/For with a specified step
| 15rust
| 161pu |
package main
import "fmt"
var a1 = []string{"a", "b", "c"}
var a2 = []byte{'A', 'B', 'C'}
var a3 = []int{1, 2, 3}
func main() {
for i := range a1 {
fmt.Printf("%v%c%v\n", a1[i], a2[i], a3[i])
}
} | 644Loop over multiple arrays simultaneously
| 0go
| 40i52 |
public static void logic(boolean a, boolean b){
System.out.println("a AND b: " + (a && b));
System.out.println("a OR b: " + (a || b));
System.out.println("NOT a: " + (!a));
} | 647Logical operations
| 9java
| frrdv |
public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
char repeat= number.charAt(0);
number= number.substring(1) + " ";
int times= 1;
for(char actual: number.toCharArray()){
if(actual != repeat){
result.append(times + "" + repeat);
times= 1;
repeat= actual;
}else{
times+= 1;
}
}
return result.toString();
} | 642Look-and-say sequence
| 9java
| btmk3 |
for i in xrange(1,11):
if i% 5 == 0:
print i
continue
print i, , | 634Loops/Continue
| 3python
| rolgq |
function logic(a,b) {
print("a AND b: " + (a && b));
print("a OR b: " + (a || b));
print("NOT a: " + (!a));
} | 647Logical operations
| 10javascript
| ybb6r |
def synchedConcat = { a1, a2, a3 ->
assert a1 && a2 && a3
assert a1.size() == a2.size()
assert a2.size() == a3.size()
[a1, a2, a3].transpose().collect { "${it[0]}${it[1]}${it[2]}" }
} | 644Loop over multiple arrays simultaneously
| 7groovy
| leqc1 |
def lcs(xstr, ystr):
if not xstr or not ystr:
return
x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]
if x == y:
return str(lcs(xs, ys)) + x
else:
return max(lcs(xstr, ys), lcs(xs, ystr), key=len) | 637Longest common subsequence
| 3python
| hdljw |
function lookandsay(str) {
return str.replace(/(.)\1*/g, function(seq, p1){return seq.length.toString() + p1})
}
var num = "1";
for (var i = 10; i > 0; i--) {
alert(num);
num = lookandsay(num);
} | 642Look-and-say sequence
| 10javascript
| wmve2 |
for(i in 1:10)
{
cat(i)
if(i%% 5 == 0)
{
cat("\n")
next
}
cat(", ")
} | 634Loops/Continue
| 13r
| uqyvx |
for (i <- 2 to 8 by 2) println(i) | 628Loops/For with a specified step
| 16scala
| w9wes |
for i=1,5 do
for j=1,i do
io.write("*")
end
io.write("\n")
end | 630Loops/For
| 1lua
| kf7h2 |
'c';
'hello';
"hello";
'Hi $name. How are you?';
"Hi $name. How are you?";
'\n';
"\n";
`ls`;
q/hello/;
qq/hello/;
qw/one two three/;
qx/ls/;
qr/regex/;
<<END;
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END
<<'END';
Same as above, but no interpolation of $variables.
END | 643Literals/String
| 2perl
| i57o3 |
print "true\n" if ( 727 == 0x2d7 &&
727 == 01327 &&
727 == 0b1011010111 &&
12345 == 12_345
); | 645Literals/Integer
| 2perl
| x9lw8 |
null | 647Logical operations
| 11kotlin
| 8vv0q |
main = sequence [ putStrLn [x, y, z] | x <- "abd" | y <- "ABC" | z <- "123"] | 644Loop over multiple arrays simultaneously
| 8haskell
| qcvx9 |
'c';
'hello';
;
'Hi $name. How are you?';
;
'\n';
;
`ls`;
<<END
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END;
<<'END'
Same as above, but no interpolation of $variables.
END; | 643Literals/String
| 12php
| rofge |
<?php
if (727 == 0x2d7 &&
727 == 01327) {
echo ;
}
$a = 1234;
$a = 0123;
$a = 0x1A;
$a = 0b11111111;
$a = 1_234_567; | 645Literals/Integer
| 12php
| 2wql4 |
null | 642Look-and-say sequence
| 11kotlin
| rotgo |
for i in 1..10 do
print i
if i % 5 == 0 then
puts
next
end
print ', '
end | 634Loops/Continue
| 14ruby
| jnv7x |
fn main() {
for i in 1..=10 {
print!("{}", i);
if i% 5 == 0 {
println!();
continue;
}
print!(", ");
}
} | 634Loops/Continue
| 15rust
| hduj2 |
=begin
irb(main):001:0> lcs('thisisatest', 'testing123testing')
=>
=end
def lcs(xstr, ystr)
return if xstr.empty? || ystr.empty?
x, xs, y, ys = xstr[0..0], xstr[1..-1], ystr[0..0], ystr[1..-1]
if x == y
x + lcs(xs, ys)
else
[lcs(xstr, ys), lcs(xs, ystr)].max_by {|x| x.size}
end
end | 637Longest common subsequence
| 14ruby
| btvkq |
null | 642Look-and-say sequence
| 1lua
| 7izru |
for (i <- 1 to 10) {
print(i)
if (i % 5 == 0) println() else print(", ")
} | 634Loops/Continue
| 16scala
| pzgbj |
for i in stride(from: 1, to: 10, by: 2) {
print(i)
} | 628Loops/For with a specified step
| 17swift
| bzbkd |
use strict;
sub add_with_carry
{
my $resultref = shift;
my $addend = shift;
my $addendpos = shift;
push @$resultref, (0) while (scalar @$resultref < $addendpos + 1);
my $addend_result = $addend + $resultref->[$addendpos];
my @addend_digits = reverse split //, $addend_result;
$resultref->[$addendpos] = shift @addend_digits;
my $carry_digit = shift @addend_digits;
&add_with_carry($resultref, $carry_digit, $addendpos + 1)
if( defined $carry_digit )
}
sub longhand_multiplication
{
my @multiplicand = reverse split //, shift;
my @multiplier = reverse split //, shift;
my @result = ();
my $multiplicand_offset = 0;
foreach my $multiplicand_digit (@multiplicand)
{
my $multiplier_offset = $multiplicand_offset;
foreach my $multiplier_digit (@multiplier)
{
my $multiplication_result = $multiplicand_digit * $multiplier_digit;
my @result_digit_addend_list = reverse split //, $multiplication_result;
my $addend_offset = $multiplier_offset;
foreach my $result_digit_addend (@result_digit_addend_list)
{
&add_with_carry(\@result, $result_digit_addend, $addend_offset++)
}
++$multiplier_offset;
}
++$multiplicand_offset;
}
@result = reverse @result;
return join '', @result;
}
my $sixtyfour = "18446744073709551616";
my $onetwentyeight = &longhand_multiplication($sixtyfour, $sixtyfour);
print "$onetwentyeight\n"; | 646Long multiplication
| 2perl
| ybp6u |
>>>
>>> 0b1011010111 == 0o1327 == 727 == 0x2d7
True
>>> | 645Literals/Integer
| 3python
| qc2xi |
function logic(a,b)
return a and b, a or b, not a
end | 647Logical operations
| 1lua
| ouu8h |
String[][] list1 = {{"a","b","c"}, {"A", "B", "C"}, {"1", "2", "3"}};
for (int i = 0; i < list1.length; i++) {
for (String[] lista : list1) {
System.out.print(lista[i]);
}
System.out.println();
} | 644Loop over multiple arrays simultaneously
| 9java
| pzyb3 |
'c' ==
'text' ==
' ' "
'\x20' == ' '
u'unicode string'
u'\u05d0' | 643Literals/String
| 3python
| n4jiz |
0x2d7==727
identical(0x2d7, 727)
is.numeric(727)
is.integer(727)
is.integer(727L)
is.numeric(0x2d7)
is.integer(0x2d7)
is.integer(0x2d7L) | 645Literals/Integer
| 13r
| a6m1z |
var a = ["a","b","c"],
b = ["A","B","C"],
c = [1,2,3],
output = "",
i;
for (i = 0; i < a.length; i += 1) {
output += a[i] + b[i] + c[i] + "\n";
} | 644Loop over multiple arrays simultaneously
| 10javascript
| x92w9 |
use std::cmp;
fn lcs(string1: String, string2: String) -> (usize, String){
let total_rows = string1.len() + 1;
let total_columns = string2.len() + 1; | 637Longest common subsequence
| 15rust
| pzubu |
<?php
function longMult($a, $b)
{
$as = (string) $a;
$bs = (string) $b;
for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)
{
for($p = 0; $p < $pi; $p++)
{
$regi[$ai][] = 0;
}
for($bi = strlen($bs) - 1; $bi >= 0; $bi--)
{
$regi[$ai][] = $as[$ai] * $bs[$bi];
}
}
return $regi;
}
function longAdd($arr)
{
$outer = count($arr);
$inner = count($arr[$outer-1]) + $outer;
for($i = 0; $i <= $inner; $i++)
{
for($o = 0; $o < $outer; $o++)
{
$val = isset($arr[$o][$i])? $arr[$o][$i] : 0;
@$sum[$i] += $val;
}
}
return $sum;
}
function carry($arr)
{
for($i = 0; $i < count($arr); $i++)
{
$s = (string) $arr[$i];
switch(strlen($s))
{
case 2:
$arr[$i] = $s{1};
@$arr[$i+1] += $s{0};
break;
case 3:
$arr[$i] = $s{2};
@$arr[$i+1] += $s{0}.$s{1};
break;
}
}
return ltrim(implode('',array_reverse($arr)),'0');
}
function lm($a,$b)
{
return carry(longAdd(longMult($a,$b)));
}
if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')
{
echo 'pass!';
}; | 646Long multiplication
| 12php
| a6y12 |
str1 <- "the quick brown fox, etc."
str2 <- 'the quick brown fox, etc.'
identical(str1, str2) | 643Literals/String
| 13r
| 024sg |
def lcsLazy[T](u: IndexedSeq[T], v: IndexedSeq[T]): IndexedSeq[T] = {
def su = subsets(u).to(LazyList)
def sv = subsets(v).to(LazyList)
su.intersect(sv).headOption match{
case Some(sub) => sub
case None => IndexedSeq[T]()
}
}
def subsets[T](u: IndexedSeq[T]): Iterator[IndexedSeq[T]] = {
u.indices.reverseIterator.flatMap{n => u.indices.combinations(n + 1).map(_.map(u))}
} | 637Longest common subsequence
| 16scala
| eygab |
'single quotes with \'embedded quote\' and \\backslash'
%q(not interpolating with (nested) parentheses
and newline) | 643Literals/String
| 14ruby
| frkdr |
727 == 0b1011010111
727 == 0x2d7
727 == 0o1327
727 == 01327
12345 == 12_345 | 645Literals/Integer
| 14ruby
| 02usu |
val c = 'c' | 643Literals/String
| 16scala
| 6ka31 |
10 | 645Literals/Integer
| 15rust
| 8v507 |
scala> 16
res10: Int = 16
scala> 020L
res11: Long = 16
scala> 0x10: Byte
res12: Byte = 16
scala> 16: Short
res13: Short = 16
scala> 020: Int
res14: Int = 16
scala> 0x10: Long
res15: Long = 16 | 645Literals/Integer
| 16scala
| n4ric |
while (1) {
my $a = int(rand(20));
print "$a\n";
if ($a == 10) {
last;
}
my $b = int(rand(20));
print "$b\n";
} | 640Loops/Break
| 2perl
| 910mn |
for i in 1...10 {
print(i, terminator: "")
if i% 5 == 0 {
print()
continue
}
print(", ", terminator: "")
} | 634Loops/Continue
| 17swift
| 7i2rq |
SELECT 'The boy said ''hello''.'; | 643Literals/String
| 19sql
| 91xm6 |
null | 644Loop over multiple arrays simultaneously
| 11kotlin
| 7ifr4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.