code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
function addsub( a, b )
return a+b, a-b
end
s, d = addsub( 7, 5 )
print( s, d ) | 348Return multiple values
| 1lua
| q7qx0 |
user=> (distinct [1 3 2 9 1 2 3 8 8 1 0 2])
(1 3 2 9 8 0)
user=> | 362Remove duplicate elements
| 6clojure
| 5tnuz |
recaman :: Int -> [Int]
recaman n = fst <$> reverse (go n)
where
go 0 = []
go 1 = [(0, 1)]
go x =
let xs@((r, i):_) = go (pred x)
back = r - i
in ( if 0 < back && not (any ((back ==) . fst) xs)
then back
else r + i
, succ i):
xs
main :: IO ()
main = print $ recaman 15 | 361Recaman's sequence
| 8haskell
| p2cbt |
M_E;
M_PI;
sqrt(x);
log(x);
exp(x);
abs(x);
fabs(x);
floor(x);
ceil(x);
pow(x,y); | 365Real constants and functions
| 5c
| 6qp32 |
(() => {
'use strict';
const main = () => { | 358Rep-string
| 10javascript
| okb86 |
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are:%s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] =%d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
} | 361Recaman's sequence
| 9java
| r6zg0 |
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than%d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than%d lines after line%d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
} | 360Remove lines from a file
| 0go
| 6qx3p |
null | 356Regular expressions
| 11kotlin
| 7ycr4 |
def repeat(f,n):
for i in range(n):
f();
def procedure():
print();
repeat(procedure,3); | 352Repeat
| 3python
| co39q |
local lines = {}
for line in (s .. "\n"):gmatch("(.-)\n") do
local this = {}
for word in line:gmatch("%S+") do
table.insert(this, 1, word)
end
lines[#lines + 1] = table.concat(this, " ")
end
print(table.concat(lines, "\n")) | 349Reverse words in a string
| 1lua
| fandp |
fn rot13(string: &str) -> String {
string.chars().map(|c| {
match c {
'a'..='m' | 'A'..='M' => ((c as u8) + 13) as char,
'n'..='z' | 'N'..='Z' => ((c as u8) - 13) as char,
_ => c
}
}).collect()
}
fn main () {
assert_eq!(rot13("abc"), "nop");
} | 338Rot-13
| 15rust
| hcsj2 |
(() => {
const main = () => {
console.log(
'First 15 Recaman:\n' +
recamanUpto(i => 15 === i)
);
console.log(
'\n\nFirst duplicated Recaman:\n' +
last(recamanUpto(
(_, set, rs) => set.size !== rs.length
))
);
const setK = new Set(enumFromTo(0, 1000));
console.log(
'\n\nNumber of Recaman terms needed to generate' +
'\nall integers from [0..1000]:\n' +
(recamanUpto(
(_, setR) => isSubSetOf(setK, setR)
).length - 1)
);
}; | 361Recaman's sequence
| 10javascript
| bl9ki |
static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer) | 360Remove lines from a file
| 7groovy
| d1pn3 |
null | 358Rep-string
| 11kotlin
| p2vb6 |
(Math/E)
(Math/PI)
(Math/sqrt x)
(Math/log x)
(Math/exp x)
(Math/abs x)
(Math/floor x)
(Math/ceil x)
(Math/pow x y) | 365Real constants and functions
| 6clojure
| lixcb |
import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
) | 360Remove lines from a file
| 8haskell
| jmy7g |
test = "My name is Lua."
pattern = ".*name is (%a*).*"
if test:match(pattern) then
print("Name found.")
end
sub, num_matches = test:gsub(pattern, "Hello,%1!")
print(sub) | 356Regular expressions
| 1lua
| jml71 |
const char *sa = ;
const char *su = ;
int is_comb(wchar_t c)
{
if (c >= 0x300 && c <= 0x36f) return 1;
if (c >= 0x1dc0 && c <= 0x1dff) return 1;
if (c >= 0x20d0 && c <= 0x20ff) return 1;
if (c >= 0xfe20 && c <= 0xfe2f) return 1;
return 0;
}
wchar_t* mb_to_wchar(const char *s)
{
wchar_t *u;
size_t len = mbstowcs(0, s, 0) + 1;
if (!len) return 0;
u = malloc(sizeof(wchar_t) * len);
mbstowcs(u, s, len);
return u;
}
wchar_t* ws_reverse(const wchar_t* u)
{
size_t len, i, j;
wchar_t *out;
for (len = 0; u[len]; len++);
out = malloc(sizeof(wchar_t) * (len + 1));
out[len] = 0;
j = 0;
while (len) {
for (i = len - 1; i && is_comb(u[i]); i--);
wcsncpy(out + j, u + i, len - i);
j += len - i;
len = i;
}
return out;
}
char *mb_reverse(const char *in)
{
size_t len;
char *out;
wchar_t *u = mb_to_wchar(in);
wchar_t *r = ws_reverse(u);
len = wcstombs(0, r, 0) + 1;
out = malloc(len);
wcstombs(out, r, len);
free(u);
free(r);
return out;
}
int main(void)
{
setlocale(LC_CTYPE, );
printf(, sa, mb_reverse(sa));
printf(, su, mb_reverse(su));
return 0;
} | 366Reverse a string
| 5c
| liwcy |
f1 <- function(...){print("coucou")}
f2 <-function(f,n){
lapply(seq_len(n),eval(f))
}
f2(f1,4) | 352Repeat
| 13r
| 6qd3e |
Symbols = { 1=>'I', 5=>'V', 10=>'X', 50=>'L', 100=>'C', 500=>'D', 1000=>'M' }
Subtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]
def roman(num)
return Symbols[num] if Symbols.has_key?(num)
Subtractors.each do |cutPoint, subtractor|
return roman(cutPoint) + roman(num - cutPoint) if num > cutPoint
return roman(subtractor) + roman(num + subtractor) if num >= cutPoint - subtractor and num < cutPoint
end
end
[1990, 2008, 1666].each do |i|
puts % [i, roman(i)]
end | 341Roman numerals/Encode
| 14ruby
| 7mari |
null | 361Recaman's sequence
| 11kotlin
| vdi21 |
scala> def rot13(s: String) = s map {
| case c if 'a' <= c.toLower && c.toLower <= 'm' => c + 13 toChar
| case c if 'n' <= c.toLower && c.toLower <= 'z' => c - 13 toChar
| case c => c
| }
rot13: (s: String)String
scala> rot13("7 Cities of Gold.")
res61: String = 7 Pvgvrf bs Tbyq.
scala> rot13(res61)
res62: String = 7 Cities of Gold. | 338Rot-13
| 16scala
| pvobj |
local a = {[0]=0}
local used = {[0]=true}
local used1000 = {[0]=true}
local foundDup = false
local n = 1
while n<=15 or not foundDup or #used1000<1001 do
local nxt = a[n - 1] - n
if nxt<1 or used[nxt] ~= nil then
nxt = nxt + 2 * n
end
local alreadyUsed = used[nxt] ~= nil
table.insert(a, nxt)
if not alreadyUsed then
used[nxt] = true
if 0<=nxt and nxt<=1000 then
used1000[nxt] = true
end
end
if n==14 then
io.write("The first 15 terms of the Recaman sequence are:")
for k=0,#a do
io.write(" "..a[k])
end
print()
end
if not foundDup and alreadyUsed then
print("The first duplicated term is a["..n.."] = "..nxt)
foundDup = true
end
if #used1000 == 1001 then
print("Terms up to a["..n.."] are needed to generate 0 to 1000")
end
n = n + 1
end | 361Recaman's sequence
| 1lua
| ufnvl |
struct RomanNumeral {
symbol: &'static str,
value: u32
}
const NUMERALS: [RomanNumeral; 13] = [
RomanNumeral {symbol: "M", value: 1000},
RomanNumeral {symbol: "CM", value: 900},
RomanNumeral {symbol: "D", value: 500},
RomanNumeral {symbol: "CD", value: 400},
RomanNumeral {symbol: "C", value: 100},
RomanNumeral {symbol: "XC", value: 90},
RomanNumeral {symbol: "L", value: 50},
RomanNumeral {symbol: "XL", value: 40},
RomanNumeral {symbol: "X", value: 10},
RomanNumeral {symbol: "IX", value: 9},
RomanNumeral {symbol: "V", value: 5},
RomanNumeral {symbol: "IV", value: 4},
RomanNumeral {symbol: "I", value: 1}
];
fn to_roman(mut number: u32) -> String {
let mut min_numeral = String::new();
for numeral in NUMERALS.iter() {
while numeral.value <= number {
min_numeral = min_numeral + numeral.symbol;
number -= numeral.value;
}
}
min_numeral
}
fn main() {
let nums = [2014, 1999, 25, 1666, 3888];
for &n in nums.iter() { | 341Roman numerals/Encode
| 15rust
| j9e72 |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{ | 360Remove lines from a file
| 9java
| ufdvv |
4.times{ puts }
def repeat(proc,num)
num.times{ proc.call }
end
repeat(->{ puts }, 4) | 352Repeat
| 14ruby
| 2nylw |
val romanDigits = Map(
1 -> "I", 5 -> "V",
10 -> "X", 50 -> "L",
100 -> "C", 500 -> "D",
1000 -> "M",
4 -> "IV", 9 -> "IX",
40 -> "XL", 90 -> "XC",
400 -> "CD", 900 -> "CM")
val romanDigitsKeys = romanDigits.keysIterator.toList sortBy (x => -x)
def toRoman(n: Int): String = romanDigitsKeys find (_ >= n) match {
case Some(key) => romanDigits(key) + toRoman(n - key)
case None => ""
} | 341Roman numerals/Encode
| 16scala
| b2qk6 |
fn repeat(f: impl FnMut(usize), n: usize) {
(0..n).for_each(f);
} | 352Repeat
| 15rust
| vdm2t |
def repeat[A](n:Int)(f: => A)= ( 0 until n).foreach(_ => f)
repeat(3) { println("Example") } | 352Repeat
| 16scala
| 4zl50 |
package main
import "fmt"
type matrix [][]float64
func (m matrix) print() {
for _, r := range m {
fmt.Println(r)
}
fmt.Println("")
}
func main() {
m := matrix{
{ 1, 2, -1, -4},
{ 2, 3, -1, -11},
{-2, 0, -3, 22},
}
m.print()
rref(m)
m.print()
}
func rref(m matrix) {
lead := 0
rowCount := len(m)
columnCount := len(m[0])
for r := 0; r < rowCount; r++ {
if lead >= columnCount {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if columnCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
f := 1 / m[r][lead]
for j, _ := range m[r] {
m[r][j] *= f
}
for i = 0; i < rowCount; i++ {
if i != r {
f = m[i][lead]
for j, e := range m[r] {
m[i][j] -= e * f
}
}
}
lead++
}
} | 364Reduced row echelon form
| 0go
| kc3hz |
null | 360Remove lines from a file
| 11kotlin
| 980mh |
use File::Copy qw(move);
use File::Spec::Functions qw(catfile rootdir);
move 'input.txt', 'output.txt';
move 'docs', 'mydocs';
move (catfile rootdir, 'input.txt'), (catfile rootdir, 'output.txt');
move (catfile rootdir, 'docs'), (catfile rootdir, 'mydocs'); | 353Rename a file
| 2perl
| kc4hc |
sub foo {
my ($a, $b) = @_;
return $a + $b, $a * $b;
} | 348Return multiple values
| 2perl
| 2d2lf |
use bignum;
$max = 1000;
$remaining += $_ for 1..$max;
my @recamans = 0;
my $previous = 0;
while ($remaining > 0) {
$term++;
my $this = $previous - $term;
$this = $previous + $term unless $this > 0 and !$seen{$this};
push @recamans, $this;
$dup = $term if !$dup and defined $seen{$this};
$remaining -= $this if $this <= $max and ! defined $seen{$this};
$seen{$this}++;
$previous = $this;
}
print "First fifteen terms of Recaman's sequence: " . join(' ', @recamans[0..14]) . "\n";
print "First duplicate at term: a[$dup]\n";
print "Range 0..1000 covered by terms up to a[$term]\n"; | 361Recaman's sequence
| 2perl
| 0jrs4 |
enum Pivoting {
NONE({ i, it -> 1 }),
PARTIAL({ i, it -> - (it[i].abs()) }),
SCALED({ i, it -> - it[i].abs()/(it.inject(0) { sum, elt -> sum + elt.abs() } ) });
public final Closure comparer
private Pivoting(Closure c) {
comparer = c
}
}
def isReducibleMatrix = { matrix ->
def m = matrix.size()
m > 1 && matrix[0].size() > m && matrix[1..<m].every { row -> row.size() == matrix[0].size() }
}
def reducedRowEchelonForm = { matrix, Pivoting pivoting = Pivoting.NONE ->
assert isReducibleMatrix(matrix)
def m = matrix.size()
def n = matrix[0].size()
(0..<m).each { i ->
matrix[i..<m].sort(pivoting.comparer.curry(i))
matrix[i][i..<n] = matrix[i][i..<n].collect { it/matrix[i][i] }
((0..<i) + ((i+1)..<m)).each { k ->
(i..<n).reverse().each { j ->
matrix[k][j] -= matrix[i][j]*matrix[k][i]
}
}
}
matrix
} | 364Reduced row echelon form
| 7groovy
| g3n46 |
(defn reverse-string [s]
"Returns a string with all characters in reverse"
(apply str (reduce conj '() s))) | 366Reverse a string
| 6clojure
| 4z85o |
function addsub($x, $y) {
return array($x + $y, $x - $y);
} | 348Return multiple values
| 12php
| sjsqs |
import Data.List (find)
rref :: Fractional a => [[a]] -> [[a]]
rref m = f m 0 [0 .. rows - 1]
where rows = length m
cols = length $ head m
f m _ [] = m
f m lead (r: rs)
| indices == Nothing = m
| otherwise = f m' (lead' + 1) rs
where indices = find p l
p (col, row) = m !! row !! col /= 0
l = [(col, row) |
col <- [lead .. cols - 1],
row <- [r .. rows - 1]]
Just (lead', i) = indices
newRow = map (/ m!! i!! lead') $ m !! i
m' = zipWith g [0..] $
replace r newRow $
replace i (m!! r) m
g n row
| n == r = row
| otherwise = zipWith h newRow row
where h = subtract . (* row!! lead')
replace :: Int -> a -> [a] -> [a]
replace n e l = a ++ e: b
where (a, _: b) = splitAt n l | 364Reduced row echelon form
| 8haskell
| np7ie |
function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end | 360Remove lines from a file
| 1lua
| co892 |
foreach (qw(1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1)) {
print "$_\n";
if (/^(.+)\1+(.*$)(?(?{ substr($1, 0, length $2) eq $2 })|(?!))/) {
print ' ' x length $1, "$1\n\n";
} else {
print " (no repeat)\n\n";
}
} | 358Rep-string
| 2perl
| ys06u |
func repeat(n: Int, f: () -> ()) {
for _ in 0..<n {
f()
}
}
repeat(4) { println("Example") } | 352Repeat
| 17swift
| li6c2 |
<?php
rename('input.txt', 'output.txt');
rename('docs', 'mydocs');
rename('/input.txt', '/output.txt');
rename('/docs', '/mydocs');
?> | 353Rename a file
| 12php
| 3xizq |
<?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo ;
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo ;
else
echo ;
}
echo ;
}
if (!$foundDup && $alreadyUsed) {
printf(, $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf(, $n);
}
$n++;
} | 361Recaman's sequence
| 12php
| 5tdus |
import "io/ioutil"
data, err := ioutil.ReadFile(filename)
sv := string(data) | 363Read entire file
| 0go
| xgvwf |
def fileContent = new File("c:\\file.txt").text | 363Read entire file
| 7groovy
| p2mbo |
print join(" ", reverse split), "\n" for <DATA>;
__DATA__
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- | 349Reverse words in a string
| 2perl
| jmr7f |
import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;
class Matrix {
LinkedList<LinkedList<Fraction>> matrix;
int numRows;
int numCols;
static class Coordinate {
int row;
int col;
Coordinate(int r, int c) {
row = r;
col = c;
}
public String toString() {
return "(" + row + ", " + col + ")";
}
}
Matrix(double [][] m) {
numRows = m.length;
numCols = m[0].length;
matrix = new LinkedList<LinkedList<Fraction>>();
for (int i = 0; i < numRows; i++) {
matrix.add(new LinkedList<Fraction>());
for (int j = 0; j < numCols; j++) {
try {
matrix.get(i).add(new Fraction(m[i][j]));
} catch (FractionConversionException e) {
System.err.println("Fraction could not be converted from double by apache commons . . .");
}
}
}
}
public void Interchange(Coordinate a, Coordinate b) {
LinkedList<Fraction> temp = matrix.get(a.row);
matrix.set(a.row, matrix.get(b.row));
matrix.set(b.row, temp);
int t = a.row;
a.row = b.row;
b.row = t;
}
public void Scale(Coordinate x, Fraction d) {
LinkedList<Fraction> row = matrix.get(x.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).multiply(d));
}
}
public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
LinkedList<Fraction> row = matrix.get(to.row);
LinkedList<Fraction> rowMultiplied = matrix.get(from.row);
for (int i = 0; i < numCols; i++) {
row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
}
}
public void RREF() {
Coordinate pivot = new Coordinate(0,0);
int submatrix = 0;
for (int x = 0; x < numCols; x++) {
pivot = new Coordinate(pivot.row, x); | 364Reduced row echelon form
| 9java
| qrvxa |
do text <- readFile filepath | 363Read entire file
| 8haskell
| yse66 |
import os
os.rename(, )
os.rename(, )
os.rename(os.sep + , os.sep + )
os.rename(os.sep + , os.sep + ) | 353Rename a file
| 3python
| blgkr |
<?php
function strInv ($string) {
$str_inv = '' ;
for ($i=0,$s=count($string);$i<$s;$i++){
$str_inv .= implode(' ',array_reverse(explode(' ',$string[$i])));
$str_inv .= '<br>';
}
return $str_inv;
}
$string[] = ;
$string[] = ;
$string[] = ;
$string[] = ;
$string[] = ;
$string[] = ;
$string[] = ;
$string[] = ;
$string[] = ;
$string[] = ;
echo strInv($string); | 349Reverse words in a string
| 12php
| tedf1 |
SELECT translate(
'The quick brown fox jumps over the lazy dog.',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
)
FROM dual; | 338Rot-13
| 19sql
| e4dau |
fmt.Println(strings.Repeat("ha", 5)) | 359Repeat a string
| 0go
| qrrxz |
def addsub(x, y):
return x + y, x - y | 348Return multiple values
| 3python
| vfv29 |
null | 364Reduced row echelon form
| 10javascript
| ibrol |
print unless $. >= $from && $. <= $to; | 360Remove lines from a file
| 2perl
| w45e6 |
$string = "I am a string";
if ($string =~ /string$/) {
print "Ends with 'string'\n";
}
if ($string !~ /^You/) {
print "Does not start with 'You'\n";
} | 356Regular expressions
| 2perl
| faxd7 |
println 'ha' * 5 | 359Repeat a string
| 7groovy
| 1vvp6 |
addsub <- function(x, y) list(add=(x + y), sub=(x - y)) | 348Return multiple values
| 13r
| 9o9mg |
from itertools import islice
class Recamans():
def __init__(self):
self.a = None
self.n = None
def __call__(self):
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print(,
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f)
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f)
break | 361Recaman's sequence
| 3python
| 8h70o |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws IOException{
String fileContents = readEntireFile("./foo.txt");
}
private static String readEntireFile(String filename) throws IOException {
FileReader in = new FileReader(filename);
StringBuilder contents = new StringBuilder();
char[] buffer = new char[4096];
int read = 0;
do {
contents.append(buffer, 0, read);
read = in.read(buffer);
} while (read >= 0);
in.close();
return contents.toString();
}
} | 363Read entire file
| 9java
| d1hn9 |
def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)
if text.startswith(text[x:]): return x
return 0
matchstr =
for line in matchstr.split():
ln = is_repeated(line)
print('%r has a repetition length of%i i.e.%s'
% (line, ln, repr(line[:ln]) if ln else '*not* a rep-string')) | 358Rep-string
| 3python
| m08yh |
func rot13char(c: UnicodeScalar) -> UnicodeScalar {
switch c {
case "A"..."M", "a"..."m":
return UnicodeScalar(UInt32(c) + 13)
case "N"..."Z", "n"..."z":
return UnicodeScalar(UInt32(c) - 13)
default:
return c
}
}
func rot13(str: String) -> String {
return String(map(str.unicodeScalars){ c in Character(rot13char(c)) })
}
println(rot13("The quick brown fox jumps over the lazy dog")) | 338Rot-13
| 17swift
| 7mxrq |
visited <- vector('logical', 1e8)
terms <- vector('numeric')
in_a_interval <- function(v) {
visited[[v+1]]
}
add_value <- function(v) {
visited[[v+1]] <<- TRUE
terms <<- append(terms, v)
}
add_value(0)
step <- 1
value <- 0
founddup <- FALSE
repeat {
if ((value-step>0) && (!in_a_interval(value-step))) {
value <- value - step
} else {
value <- value + step
}
if (in_a_interval(value) && !founddup) {
cat("The first duplicated term is a[",step,"] = ",value,"\n", sep = "")
founddup <- TRUE
}
add_value(value)
if (all(visited[1:1000])) {
cat("Terms up to a[",step,"] are needed to generate 0 to 1000\n",sep = "")
break
}
step <- step + 1
if (step == 15) {
cat("The first 15 terms are:")
for (aterm in terms) { cat(aterm," ", sep = "") }
cat("\n")
}
} | 361Recaman's sequence
| 13r
| xg5w2 |
null | 364Reduced row echelon form
| 11kotlin
| 1vmpd |
package main
import (
"fmt"
"math"
"math/big"
)
func main() { | 365Real constants and functions
| 0go
| p26bg |
var fso=new ActiveXObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile("c:\\myfile.txt",1);
var s=f.ReadAll();
f.Close();
try{alert(s)}catch(e){WScript.Echo(s)} | 363Read entire file
| 10javascript
| 6qa38 |
$string = 'I am a string';
if (preg_match('/string$/', $string))
{
echo ;
}
$string = preg_replace('/\ba\b/', 'another', $string);
echo ; | 356Regular expressions
| 12php
| h92jf |
concat $ replicate 5 "ha" | 359Repeat a string
| 8haskell
| m00yf |
function ToReducedRowEchelonForm ( M )
local lead = 1
local n_rows, n_cols = #M, #M[1]
for r = 1, n_rows do
if n_cols <= lead then break end
local i = r
while M[i][lead] == 0 do
i = i + 1
if n_rows == i then
i = r
lead = lead + 1
if n_cols == lead then break end
end
end
M[i], M[r] = M[r], M[i]
local m = M[r][lead]
for k = 1, n_cols do
M[r][k] = M[r][k] / m
end
for i = 1, n_rows do
if i ~= r then
local m = M[i][lead]
for k = 1, n_cols do
M[i][k] = M[i][k] - m * M[r][k]
end
end
end
lead = lead + 1
end
end
M = { { 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 } }
res = ToReducedRowEchelonForm( M )
for i = 1, #M do
for j = 1, #M[1] do
io.write( M[i][j], " " )
end
io.write( "\n" )
end | 364Reduced row echelon form
| 1lua
| au91v |
println ((-22).abs()) | 365Real constants and functions
| 7groovy
| 7ydrz |
exp 1
pi
sqrt x
log x
exp x
abs x
floor x
ceiling x
x ** y
x ^ y
x ^^ y | 365Real constants and functions
| 8haskell
| fajd1 |
text = '''\
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------'''
for line in text.split('\n'): print(' '.join(line.split()[::-1])) | 349Reverse words in a string
| 3python
| h97jw |
--
-- This only works under Oracle and has the limitation of 1 to 3999
SQL> SELECT to_char(1666, 'RN') urcoman, to_char(1666, 'rn') lcroman FROM dual;
URCOMAN LCROMAN
--------------- ---------------
MDCLXVI mdclxvi | 341Roman numerals/Encode
| 19sql
| a581t |
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip()
fileinput.close() | 360Remove lines from a file
| 3python
| xg4wr |
import java.io.File
fun main(args: Array<String>) {
println(File("unixdict.txt").readText(charset = Charsets.UTF_8))
} | 363Read entire file
| 11kotlin
| 0j4sf |
import re
string =
if re.search('string$', string):
print()
string = re.sub(, , string)
print(string) | 356Regular expressions
| 3python
| teqfw |
File.rename('input.txt', 'output.txt')
File.rename('/input.txt', '/output.txt')
File.rename('docs', 'mydocs')
File.rename('/docs', '/mydocs') | 353Rename a file
| 14ruby
| 1v7pw |
whack <- function(s) {
paste( rev( unlist(strsplit(s, " "))), collapse=' ' ) }
poem <- unlist( strsplit(
'------------ Eldorado ----------
... here omitted lines ...
Mountains the "Over
Moon, the Of
Shadow, the of Valley the Down
ride," boldly Ride,
replied,--- shade The
Eldorado!" for seek you "If
Poe Edgar -----------------------', "\n"))
for (line in poem) cat( whack(line), "\n" ) | 349Reverse words in a string
| 13r
| g3547 |
func ator(var n: Int) -> String {
var result = ""
for (value, letter) in
[( 1000, "M"),
( 900, "CM"),
( 500, "D"),
( 400, "CD"),
( 100, "C"),
( 90, "XC"),
( 50, "L"),
( 40, "XL"),
( 10, "X"),
( 9, "IX"),
( 5, "V"),
( 4, "IV"),
( 1, "I")]
{
while n >= value {
result += letter
n -= value
}
}
return result
} | 341Roman numerals/Encode
| 17swift
| ry1gg |
require 'set'
a = [0]
used = Set[0]
used1000 = Set[0]
foundDup = false
n = 1
while n <= 15 or not foundDup or used1000.size < 1001
nxt = a[n - 1] - n
if nxt < 1 or used === nxt then
nxt = nxt + 2 * n
end
alreadyUsed = used === nxt
a << nxt
if not alreadyUsed then
used << nxt
if nxt >= 0 and nxt <= 1000 then
used1000 << nxt
end
end
if n == 14 then
print , a,
end
if not foundDup and alreadyUsed then
print , n, , nxt,
foundDup = true
end
if used1000.size == 1001 then
print , n,
end
n = n + 1
end | 361Recaman's sequence
| 14ruby
| ibhoh |
ar = %w(1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1)
ar.each do |str|
rep_pos = (str.size/2).downto(1).find{|pos| str.start_with? str[pos..-1]}
puts str, rep_pos? *rep_pos + str[0, rep_pos]: ,
end | 358Rep-string
| 14ruby
| coi9k |
pattern <- "string"
text1 <- "this is a matching string"
text2 <- "this does not match" | 356Regular expressions
| 13r
| ibao5 |
String reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed); | 366Reverse a string
| 18dart
| 3xkzz |
use std::fs;
fn main() {
let err = "File move error";
fs::rename("input.txt", "output.txt").ok().expect(err);
fs::rename("docs", "mydocs").ok().expect(err);
fs::rename("/input.txt", "/output.txt").ok().expect(err);
fs::rename("/docs", "/mydocs").ok().expect(err);
} | 353Rename a file
| 15rust
| auj14 |
import scala.language.implicitConversions
import java.io.File
object Rename0 {
def main(args: Array[String]) { | 353Rename a file
| 16scala
| xgbwg |
def addsub(x, y)
[x + y, x - y]
end | 348Return multiple values
| 14ruby
| 5z5uj |
import scala.collection.mutable
object RecamansSequence extends App {
val (a, used) = (mutable.ArrayBuffer[Int](0), mutable.BitSet())
var (foundDup, hop, nUsed1000) = (false, 1, 0)
while (nUsed1000 < 1000) {
val _next = a(hop - 1) - hop
val next = if (_next < 1 || used.contains(_next)) _next + 2 * hop else _next
val alreadyUsed = used.contains(next)
a += next
if (!alreadyUsed) {
used.add(next)
if (next <= 1000) nUsed1000 += 1
}
if (!foundDup && alreadyUsed) {
println(s"The first duplicate term is a($hop) = $next")
foundDup = true
}
if (nUsed1000 == 1000)
println(s"Terms up to $hop are needed to generate 0 to 1000")
hop += 1
}
println(s"The first 15 terms of the Recaman sequence are: ${a.take(15)}")
} | 361Recaman's sequence
| 16scala
| te1fb |
Math.E; | 365Real constants and functions
| 9java
| 0juse |
fn main() {
let strings = vec![
String::from("1001110011"),
String::from("1110111011"),
String::from("0010010010"),
String::from("1010101010"),
String::from("1111111111"),
String::from("0100101101"),
String::from("0100100"),
String::from("101"),
String::from("11"),
String::from("00"),
String::from("1"),
];
for string in strings {
match rep_string(&string) {
Some(rep_string) => println!(
"Longuest rep-string for '{}' is '{}' ({} chars)",
string,
rep_string,
rep_string.len(),
),
None => println!("No rep-string found for '{}'", string),
};
}
}
fn rep_string(string: &str) -> Option<&str> {
let index = string.len() / 2;
for split_index in (1..=index).rev() {
let mut is_rep_string = true;
let (first, last) = string.split_at(split_index);
let inter = last.chars().collect::<Vec<char>>();
let mut iter = inter.chunks_exact(split_index);
for chunk in iter.by_ref() {
if first!= chunk.iter().collect::<String>() {
is_rep_string = false;
break;
}
}
let rmnd = iter.remainder().iter().collect::<String>(); | 358Rep-string
| 15rust
| lincc |
object RepString extends App {
def repsOf(s: String) = s.trim match {
case s if s.length < 2 => Nil
case s => (1 to (s.length/2)).map(s take _)
.filter(_ * s.length take s.length equals s)
}
val tests = Array(
"1001110011",
"1110111011",
"0010010010",
"1010101010",
"1111111111",
"0100101101",
"0100100",
"101",
"11",
"00",
"1"
)
def printReps(s: String) = repsOf(s) match {
case Nil => s+": NO"
case r => s+": YES ("+r.mkString(", ")+")"
}
val todo = if (args.length > 0) args else tests
todo.map(printReps).foreach(println)
} | 358Rep-string
| 16scala
| uftv8 |
public static String repeat(String str, int times) {
StringBuilder sb = new StringBuilder(str.length() * times);
for (int i = 0; i < times; i++)
sb.append(str);
return sb.toString();
}
public static void main(String[] args) {
System.out.println(repeat("ha", 5));
} | 359Repeat a string
| 9java
| faadv |
fn multi_hello() -> (&'static str, i32) {
("Hello",42)
}
fn main() {
let (str,num)=multi_hello();
println!("{},{}",str,num);
} | 348Return multiple values
| 15rust
| 4345u |
package main
import "fmt"
func uniq(list []int) []int {
unique_set := make(map[int]bool, len(list))
for _, x := range list {
unique_set[x] = true
}
result := make([]int, 0, len(unique_set))
for x := range unique_set {
result = append(result, x)
}
return result
}
func main() {
fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) | 362Remove duplicate elements
| 0go
| w4veg |
Math.E
Math.PI
Math.sqrt(x)
Math.log(x)
Math.exp(x)
Math.abs(x)
Math.floor(x)
Math.ceil(x)
Math.pow(x,y) | 365Real constants and functions
| 10javascript
| d17nu |
require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts
File.open(filename, ) {|fh| (1..5).each {|i| fh.puts *i + i.to_s}}
puts , File.read(filename)
end
def teardown(filename)
puts , File.read(filename)
puts
File.unlink(filename)
end
filename =
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
end | 360Remove lines from a file
| 14ruby
| s7rqw |
String.prototype.repeat = function(n) {
return new Array(1 + (n || 0)).join(this);
}
console.log("ha".repeat(5)); | 359Repeat a string
| 10javascript
| yss6r |
def addSubMult(x: Int, y: Int) = (x + y, x - y, x * y) | 348Return multiple values
| 16scala
| 7m7r9 |
def list = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
assert list.size() == 12
println " Original List: ${list}" | 362Remove duplicate elements
| 7groovy
| blmky |
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use std::io::{BufReader,BufRead};
use std::fs::File;
const USAGE: &'static str = "
Usage: rosetta <start> <count> <file>
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_start: usize,
arg_count: usize,
arg_file: String,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
let file = BufReader::new(File::open(args.arg_file).unwrap());
for (i, line) in file.lines().enumerate() {
let cur = i + 1;
if cur < args.arg_start || cur >= (args.arg_start + args.arg_count) {
println!("{}", line.unwrap());
}
}
} | 360Remove lines from a file
| 15rust
| 0j7sl |
null | 363Read entire file
| 1lua
| 8hg0e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.