code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import Foundation
func repString(_ input: String) -> [String] {
return (1..<(1 + input.count / 2)).compactMap({x -> String? in
let i = input.index(input.startIndex, offsetBy: x)
return input.hasPrefix(input[i...])? String(input.prefix(x)): nil
})
}
let testCases = """
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
""".components(separatedBy: "\n")
for testCase in testCases {
print("\(testCase) has reps: \(repString(testCase))")
} | 358Rep-string
| 17swift
| 98omj |
puts <<EOS
---------- 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 -----------------------
EOS
.each_line.map {|line| line.split.reverse.join(' ')} | 349Reverse words in a string
| 14ruby
| blhkq |
null | 365Real constants and functions
| 11kotlin
| e59a4 |
object RemoveLinesFromAFile extends App {
args match {
case Array(filename, start, num) =>
import java.nio.file.{Files,Paths}
val lines = scala.io.Source.fromFile(filename).getLines
val keep = start.toInt - 1
val top = lines.take(keep).toList
val drop = lines.take(num.toInt).toList
Files.write(Paths.get(filename), scala.collection.JavaConversions.asJavaIterable(top ++ lines))
if (top.size < keep || drop.size < num.toInt)
println(s"Too few lines: removed only ${drop.size} of $num lines starting at $start")
case _ =>
println("Usage: RemoveLinesFromAFile <filename> <startLine> <numLines>")
}
} | 360Remove lines from a file
| 16scala
| ibkox |
const TEXT: &'static str =
"---------- 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 -----------------------";
fn main() {
println!("{}",
TEXT.lines() | 349Reverse words in a string
| 15rust
| p2kbu |
fun main(args: Array<String>) {
println("ha".repeat(5))
} | 359Repeat a string
| 11kotlin
| 8hh0q |
print $ unique [4, 5, 4, 2, 3, 3, 4]
[4,5,2,3] | 362Remove duplicate elements
| 8haskell
| 6qe3k |
str =
p if str =~ /string$/
p unless str =~ /^You/ | 356Regular expressions
| 14ruby
| 3x0z7 |
null | 341Roman numerals/Encode
| 20typescript
| 0hts3 |
use regex::Regex;
fn main() {
let s = "I am a string";
if Regex::new("string$").unwrap().is_match(s) {
println!("Ends with string.");
}
println!("{}", Regex::new(" a ").unwrap().replace(s, " another "));
} | 356Regular expressions
| 15rust
| 6q83l |
object ReverseWords extends App {
"""| ---------- 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 ----------------------- """
.stripMargin.lines.toList.map{_.split(" ")}.map{_.reverse}
.map(_.mkString(" "))
.foreach{println}
} | 349Reverse words in a string
| 16scala
| e51ab |
func addsub(x: Int, y: Int) -> (Int, Int) {
return (x + y, x - y)
} | 348Return multiple values
| 17swift
| utuvg |
val Bottles1 = "(\\d+) bottles of beer".r | 356Regular expressions
| 16scala
| 98nm5 |
sub rref
{our @m; local *m = shift;
@m or return;
my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));
foreach my $r (0 .. $rows - 1)
{$lead < $cols or return;
my $i = $r;
until ($m[$i][$lead])
{++$i == $rows or next;
$i = $r;
++$lead == $cols and return;}
@m[$i, $r] = @m[$r, $i];
my $lv = $m[$r][$lead];
$_ /= $lv foreach @{ $m[$r] };
my @mr = @{ $m[$r] };
foreach my $i (0 .. $rows - 1)
{$i == $r and next;
($lv, my $n) = ($m[$i][$lead], -1);
$_ -= $lv * $mr[++$n] foreach @{ $m[$i] };}
++$lead;}}
sub display { join("\n" => map join(" " => map(sprintf("%4d", $_), @$_)), @{+shift})."\n" }
@m =
(
[ 1, 2, -1, -4 ],
[ 2, 3, -1, -11 ],
[ -2, 0, -3, 22 ]
);
rref(\@m);
print display(\@m); | 364Reduced row echelon form
| 2perl
| m0eyz |
math.exp(1)
math.pi
math.sqrt(x)
math.log(x)
math.log10(x)
math.exp(x)
math.abs(x)
math.floor(x)
math.ceil(x)
x^y | 365Real constants and functions
| 1lua
| w4cea |
<?php
function rref($matrix)
{
$lead = 0;
$rowCount = count($matrix);
if ($rowCount == 0)
return $matrix;
$columnCount = 0;
if (isset($matrix[0])) {
$columnCount = count($matrix[0]);
}
for ($r = 0; $r < $rowCount; $r++) {
if ($lead >= $columnCount)
break; {
$i = $r;
while ($matrix[$i][$lead] == 0) {
$i++;
if ($i == $rowCount) {
$i = $r;
$lead++;
if ($lead == $columnCount)
return $matrix;
}
}
$temp = $matrix[$r];
$matrix[$r] = $matrix[$i];
$matrix[$i] = $temp;
} {
$lv = $matrix[$r][$lead];
for ($j = 0; $j < $columnCount; $j++) {
$matrix[$r][$j] = $matrix[$r][$j] / $lv;
}
}
for ($i = 0; $i < $rowCount; $i++) {
if ($i != $r) {
$lv = $matrix[$i][$lead];
for ($j = 0; $j < $columnCount; $j++) {
$matrix[$i][$j] -= $lv * $matrix[$r][$j];
}
}
}
$lead++;
}
return $matrix;
}
?> | 364Reduced row echelon form
| 12php
| e5ca9 |
function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end | 359Repeat a string
| 1lua
| okk8h |
import java.util.*;
class Test {
public static void main(String[] args) {
Object[] data = {1, 1, 2, 2, 3, 3, 3, "a", "a", "b", "b", "c", "d"};
Set<Object> uniqueSet = new HashSet<Object>(Arrays.asList(data));
for (Object o: uniqueSet)
System.out.printf("%s ", o);
}
} | 362Remove duplicate elements
| 9java
| nphih |
import Foundation
let str = "I am a string"
if let range = str.rangeOfString("string$", options: .RegularExpressionSearch) {
println("Ends with 'string'")
} | 356Regular expressions
| 17swift
| zwstu |
import Foundation | 349Reverse words in a string
| 17swift
| kcjhx |
function unique(ary) { | 362Remove duplicate elements
| 10javascript
| 3xaz0 |
def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / float(lv) for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[-2, 0, -3, 22],]
ToReducedRowEchelonForm( mtx )
for rw in mtx:
print ', '.join( (str(rv) for rv in rw) ) | 364Reduced row echelon form
| 3python
| 98wmf |
rref <- function(m) {
pivot <- 1
norow <- nrow(m)
nocolumn <- ncol(m)
for(r in 1:norow) {
if ( nocolumn <= pivot ) break;
i <- r
while( m[i,pivot] == 0 ) {
i <- i + 1
if ( norow == i ) {
i <- r
pivot <- pivot + 1
if ( nocolumn == pivot ) return(m)
}
}
trow <- m[i, ]
m[i, ] <- m[r, ]
m[r, ] <- trow
m[r, ] <- m[r, ] / m[r, pivot]
for(i in 1:norow) {
if ( i != r )
m[i, ] <- m[i, ] - m[r, ] * m[i, pivot]
}
pivot <- pivot + 1
}
return(m)
}
m <- matrix(c(1, 2, -1, -4,
2, 3, -1, -11,
-2, 0, -3, 22), 3, 4, byrow=TRUE)
print(m)
print(rref(m)) | 364Reduced row echelon form
| 13r
| 3xpzt |
perl -n -0777 -e 'print "file len: ".length' stuff.txt | 363Read entire file
| 2perl
| 5tiu2 |
fun main(args: Array<String>) {
val data = listOf(1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d")
val set = data.distinct()
println(data)
println(set)
} | 362Remove duplicate elements
| 11kotlin
| s74q7 |
file_get_contents($filename) | 363Read entire file
| 12php
| okr85 |
def reduced_row_echelon_form(ary)
lead = 0
rows = ary.size
cols = ary[0].size
rary = convert_to(ary, :to_r)
catch :done do
rows.times do |r|
throw :done if cols <= lead
i = r
while rary[i][lead] == 0
i += 1
if rows == i
i = r
lead += 1
throw :done if cols == lead
end
end
rary[i], rary[r] = rary[r], rary[i]
v = rary[r][lead]
rary[r].collect! {|x| x / v}
rows.times do |i|
next if i == r
v = rary[i][lead]
rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]}
end
lead += 1
end
end
rary
end
def convert_to(ary, type)
ary.each_with_object([]) do |row, new|
new << row.collect {|elem| elem.send(type)}
end
end
class Rational
alias _to_s to_s
def to_s
denominator==1? numerator.to_s: _to_s
end
end
def print_matrix(m)
max = m[0].collect {-1}
m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}}
m.each {|row| row.each_index {|i| print % row[i]}; puts}
end
mtx = [
[ 1, 2, -1, -4],
[ 2, 3, -1,-11],
[-2, 0, -3, 22]
]
print_matrix reduced_row_echelon_form(mtx)
puts
mtx = [
[ 1, 2, 3, 7],
[-4, 7,-2, 7],
[ 3, 3, 0, 7]
]
reduced = reduced_row_echelon_form(mtx)
print_matrix reduced
print_matrix convert_to(reduced, :to_f) | 364Reduced row echelon form
| 14ruby
| liqcl |
fn main() {
let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0],
vec![2.0, 3.0, -1.0, -11.0],
vec![-2.0, 0.0, -3.0, 22.0]];
let mut r_mat_to_red = &mut matrix_to_reduce;
let rr_mat_to_red = &mut r_mat_to_red;
println!("Matrix to reduce:\n{:?}", rr_mat_to_red);
let reduced_matrix = reduced_row_echelon_form(rr_mat_to_red);
println!("Reduced matrix:\n{:?}", reduced_matrix);
}
fn reduced_row_echelon_form(matrix: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>> {
let mut matrix_out: Vec<Vec<f64>> = matrix.to_vec();
let mut pivot = 0;
let row_count = matrix_out.len();
let column_count = matrix_out[0].len();
'outer: for r in 0..row_count {
if column_count <= pivot {
break;
}
let mut i = r;
while matrix_out[i][pivot] == 0.0 {
i = i+1;
if i == row_count {
i = r;
pivot = pivot + 1;
if column_count == pivot {
pivot = pivot - 1;
break 'outer;
}
}
}
for j in 0..row_count {
let temp = matrix_out[r][j];
matrix_out[r][j] = matrix_out[i][j];
matrix_out[i][j] = temp;
}
let divisor = matrix_out[r][pivot];
if divisor!= 0.0 {
for j in 0..column_count {
matrix_out[r][j] = matrix_out[r][j] / divisor;
}
}
for j in 0..row_count {
if j!= r {
let hold = matrix_out[j][pivot];
for k in 0..column_count {
matrix_out[j][k] = matrix_out[j][k] - ( hold * matrix_out[r][k]);
}
}
}
pivot = pivot + 1;
}
matrix_out
} | 364Reduced row echelon form
| 15rust
| 2nslt |
open(filename).read() | 363Read entire file
| 3python
| 4zn5k |
items = {1,2,3,4,1,2,3,4,"bird","cat","dog","dog","bird"}
flags = {}
io.write('Unique items are:')
for i=1,#items do
if not flags[items[i]] then
io.write(' ' .. items[i])
flags[items[i]] = true
end
end
io.write('\n') | 362Remove duplicate elements
| 1lua
| 0jgsd |
use POSIX;
exp(1);
4 * atan2(1, 1);
sqrt($x);
log($x);
exp($x);
abs($x);
floor($x);
ceil($x);
$x ** $y;
use Math::Trig;
pi;
use Math::Complex;
pi; | 365Real constants and functions
| 2perl
| cow9a |
fname <- "notes.txt"
contents <- readChar(fname, file.info(fname)$size) | 363Read entire file
| 13r
| 2n0lg |
M_E;
M_PI;
sqrt(x);
log(x);
exp(x);
abs(x);
floor(x);
ceil(x);
pow(x,y); | 365Real constants and functions
| 12php
| xglw5 |
var lead = 0
for r in 0..<rows {
if (cols <= lead) { break }
var i = r
while (m[i][lead] == 0) {
i += 1
if (i == rows) {
i = r
lead += 1
if (cols == lead) {
lead -= 1
break
}
}
}
for j in 0..<cols {
let temp = m[r][j]
m[r][j] = m[i][j]
m[i][j] = temp
}
let div = m[r][lead]
if (div!= 0) {
for j in 0..<cols {
m[r][j] /= div
}
}
for j in 0..<rows {
if (j!= r) {
let sub = m[j][lead]
for k in 0..<cols {
m[j][k] -= (sub * m[r][k])
}
}
}
lead += 1
} | 364Reduced row echelon form
| 17swift
| cox9t |
str = IO.read
str = IO.read | 363Read entire file
| 14ruby
| r6fgs |
use std::fs::File;
use std::io::Read;
fn main() {
let mut file = File::open("somefile.txt").unwrap();
let mut contents: Vec<u8> = Vec::new(); | 363Read entire file
| 15rust
| 7ytrc |
object TextFileSlurper extends App {
val fileLines =
try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch {
case e: java.io.FileNotFoundException => e.getLocalizedMessage()
}
} | 363Read entire file
| 16scala
| kc6hk |
"ha" x 5 | 359Repeat a string
| 2perl
| 4zz5d |
import math
math.e
math.pi
math.sqrt(x)
math.log(x)
math.log10(x)
math.exp(x)
abs(x)
math.floor(x)
math.ceil(x)
x ** y
pow(x, y[, n]) | 365Real constants and functions
| 3python
| lixcv |
exp(1)
pi
sqrt(x)
log(x)
log10(x)
log(x, y)
exp(x)
abs(x)
floor(x)
ceiling(x)
x^y | 365Real constants and functions
| 13r
| ys16h |
str_repeat(, 5) | 359Repeat a string
| 12php
| ibbov |
import Foundation
let path = "~/input.txt".stringByExpandingTildeInPath
if let string = String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
println(string) | 363Read entire file
| 17swift
| g3d49 |
x.abs
x.magnitude
x.floor
x.ceil
x ** y
include Math
E
PI
sqrt(x)
log(x)
log(x, y)
log10(x)
exp(x) | 365Real constants and functions
| 14ruby
| vds2n |
use std::f64::consts::*;
fn main() { | 365Real constants and functions
| 15rust
| uf0vj |
object RealConstantsFunctions extends App{
println(math.E) | 365Real constants and functions
| 16scala
| g3i4i |
package main
import (
"fmt"
"unicode"
"unicode/utf8"
) | 366Reverse a string
| 0go
| xgcwf |
* 5 | 359Repeat a string
| 3python
| g334h |
import Darwin
M_E | 365Real constants and functions
| 17swift
| 2nqlj |
println "Able was I, 'ere I saw Elba.".reverse() | 366Reverse a string
| 7groovy
| p23bo |
strrep("ha", 5) | 359Repeat a string
| 13r
| vdd27 |
reverse = foldl (flip (:)) [] | 366Reverse a string
| 8haskell
| ysp66 |
* 5 | 359Repeat a string
| 14ruby
| 7yyri |
std::iter::repeat("ha").take(5).collect::<String>(); | 359Repeat a string
| 15rust
| jmm72 |
use List::MoreUtils qw(uniq);
my @uniq = uniq qw(1 2 3 a b c 2 3 4 b c d); | 362Remove duplicate elements
| 2perl
| ufivr |
public static String reverseString(String s) {
return new StringBuffer(s).reverse().toString();
} | 366Reverse a string
| 9java
| d1rn9 |
"ha" * 5 | 359Repeat a string
| 16scala
| bllk6 |
int main(void)
{
char *locale = setlocale(LC_ALL, );
FILE *in = fopen(, );
wint_t c;
while ((c = fgetwc(in)) != WEOF)
putwchar(c);
fclose(in);
return EXIT_SUCCESS;
} | 367Read a file character by character/UTF8
| 5c
| 7yirg |
null | 366Reverse a string
| 10javascript
| 6qb38 |
struct rate_state_s
{
time_t lastFlush;
time_t period;
size_t tickCount;
};
void tic_rate(struct rate_state_s* pRate)
{
pRate->tickCount += 1;
time_t now = time(NULL);
if((now - pRate->lastFlush) >= pRate->period)
{
size_t tps = 0.0;
if(pRate->tickCount > 0)
tps = pRate->tickCount / (now - pRate->lastFlush);
printf(, tps);
pRate->tickCount = 0;
pRate->lastFlush = now;
}
}
void something_we_do()
{
volatile size_t anchor = 0;
size_t x = 0;
for(x = 0; x < 0xffff; ++x)
{
anchor = x;
}
}
int main()
{
time_t start = time(NULL);
struct rate_state_s rateWatch;
rateWatch.lastFlush = start;
rateWatch.tickCount = 0;
rateWatch.period = 5;
time_t latest = start;
for(latest = start; (latest - start) < 20; latest = time(NULL))
{
something_we_do();
tic_rate(&rateWatch);
}
return 0;
} | 368Rate counter
| 5c
| fagd3 |
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list); | 362Remove duplicate elements
| 12php
| 8hr0m |
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func Runer(r io.RuneReader) func() (rune, error) {
return func() (r rune, err error) {
r, _, err = r.ReadRune()
return
}
}
func main() {
runes := Runer(bufio.NewReader(os.Stdin))
for r, err := runes(); err != nil; r,err = runes() {
fmt.Printf("%c", r)
}
} | 367Read a file character by character/UTF8
| 0go
| d1gne |
SELECT rpad('', 10, 'ha') | 359Repeat a string
| 19sql
| auu1t |
#!/usr/bin/env runhaskell
import System.Environment (getArgs)
import System.IO (
Handle, IOMode (..),
hGetChar, hIsEOF, hSetEncoding, stdin, utf8, withFile
)
import Control.Monad (forM_, unless)
import Text.Printf (printf)
import Data.Char (ord)
processCharacters :: Handle -> IO ()
processCharacters h = do
done <- hIsEOF h
unless done $ do
c <- hGetChar h
putStrLn $ printf "U+%04X" (ord c)
processCharacters h
processOneFile :: Handle -> IO ()
processOneFile h = do
hSetEncoding h utf8
processCharacters h
main :: IO ()
main = do
args <- getArgs
case args of
[] -> processOneFile stdin
xs -> forM_ xs $ \name -> do
putStrLn name
withFile name ReadMode processOneFile | 367Read a file character by character/UTF8
| 8haskell
| 5tsug |
fun main(args: Array<String>) {
println("asdf".reversed())
} | 366Reverse a string
| 11kotlin
| 0jvsf |
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws IOException {
var reader = new FileReader("input.txt", StandardCharsets.UTF_8);
while (true) {
int c = reader.read();
if (c == -1) break;
System.out.print(Character.toChars(c));
}
}
} | 367Read a file character by character/UTF8
| 9java
| 981mu |
print(String(repeating:"*", count: 5)) | 359Repeat a string
| 17swift
| r66gg |
items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items)) | 362Remove duplicate elements
| 3python
| 5tnux |
null | 367Read a file character by character/UTF8
| 11kotlin
| zwjts |
null | 367Read a file character by character/UTF8
| 1lua
| 3xhzo |
package main
import (
"fmt"
"math/rand"
"time"
) | 368Rate counter
| 0go
| jmi7d |
items <- c(1,2,3,2,4,3,2)
unique (items) | 362Remove duplicate elements
| 13r
| li0ce |
import Control.Monad
import Control.Concurrent
import Data.Time
getTime :: IO DiffTime
getTime = fmap utctDayTime getCurrentTime
addSample :: MVar [a] -> a -> IO ()
addSample q v = modifyMVar_ q (return . (v:))
timeit :: Int -> IO a -> IO [DiffTime]
timeit n task = do
samples <- newMVar []
forM_ [0..n] $ \n -> do
t1 <- getTime
task
t2 <- getTime
addSample samples (t2 - t1)
readMVar samples
main = timeit 10 (threadDelay 1000000) | 368Rate counter
| 8haskell
| okv8p |
binmode STDOUT, ':utf8';
open my $fh, "<:encoding(UTF-8)", "input.txt" or die "$!\n";
while (read $fh, my $char, 1) {
printf "got character $char [U+%04x]\n", ord $char;
}
close $fh; | 367Read a file character by character/UTF8
| 2perl
| bltk4 |
def get_next_character(f):
c = f.read(1)
while c:
while True:
try:
yield c.decode('utf-8')
except UnicodeDecodeError:
c += f.read(1)
else:
c = f.read(1)
break
with open(,) as f:
for c in get_next_character(f):
print(c) | 367Read a file character by character/UTF8
| 3python
| p2zbm |
import java.util.function.Consumer;
public class RateCounter {
public static void main(String[] args) {
for (double d : benchmark(10, x -> System.out.print(""), 10))
System.out.println(d);
}
static double[] benchmark(int n, Consumer<Integer> f, int arg) {
double[] timings = new double[n];
for (int i = 0; i < n; i++) {
long time = System.nanoTime();
f.accept(arg);
timings[i] = System.nanoTime() - time;
}
return timings;
}
} | 368Rate counter
| 9java
| w4yej |
function millis() { | 368Rate counter
| 10javascript
| 8h20l |
int read_file_line(const char *path, int line_no)
{
struct stat s;
char *buf;
off_t start = -1, end = -1;
size_t i;
int ln, fd, ret = 1;
if (line_no == 1) start = 0;
else if (line_no < 1){
warn();
return 0;
}
line_no--;
fd = open(path, O_RDONLY);
fstat(fd, &s);
buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
madvise(buf, s.st_size, MADV_SEQUENTIAL);
for (i = ln = 0; i < s.st_size && ln <= line_no; i++) {
if (buf[i] != '\n') continue;
if (++ln == line_no) start = i + 1;
else if (ln == line_no + 1) end = i + 1;
}
if (start >= s.st_size || start < 0) {
warn(, line_no + 1);
ret = 0;
} else {
}
munmap(buf, s.st_size);
close(fd);
return ret;
} | 369Read a specific line from a file
| 5c
| 0jcst |
ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant']
p ary.uniq | 362Remove duplicate elements
| 14ruby
| g3f4q |
File.open('input.txt', 'r:utf-8') do |f|
f.each_char{|c| p c}
end | 367Read a file character by character/UTF8
| 14ruby
| au61s |
null | 368Rate counter
| 11kotlin
| blfkb |
use std::collections::HashSet;
use std::hash::Hash;
fn remove_duplicate_elements_hashing<T: Hash + Eq>(elements: &mut Vec<T>) {
let set: HashSet<_> = elements.drain(..).collect();
elements.extend(set.into_iter());
}
fn remove_duplicate_elements_sorting<T: Ord>(elements: &mut Vec<T>) {
elements.sort_unstable(); | 362Remove duplicate elements
| 15rust
| r6tg5 |
use std::{
convert::TryFrom,
fmt::{Debug, Display, Formatter},
io::Read,
};
pub struct ReadUtf8<I: Iterator> {
source: std::iter::Peekable<I>,
}
impl<R: Read> From<R> for ReadUtf8<std::io::Bytes<R>> {
fn from(source: R) -> Self {
ReadUtf8 {
source: source.bytes().peekable(),
}
}
}
impl<I, E> Iterator for ReadUtf8<I>
where
I: Iterator<Item = Result<u8, E>>,
{
type Item = Result<char, Error<E>>;
fn next(&mut self) -> Option<Self::Item> {
self.source.next().map(|next| match next {
Ok(lead) => self.complete_char(lead),
Err(e) => Err(Error::SourceError(e)),
})
}
}
impl<I, E> ReadUtf8<I>
where
I: Iterator<Item = Result<u8, E>>,
{
fn continuation(&mut self) -> Result<u32, Error<E>> {
if let Some(Ok(byte)) = self.source.peek() {
let byte = *byte;
return if byte & 0b1100_0000 == 0b1000_0000 {
self.source.next();
Ok((byte & 0b0011_1111) as u32)
} else {
Err(Error::InvalidByte(byte))
};
}
match self.source.next() {
None => Err(Error::InputTruncated),
Some(Err(e)) => Err(Error::SourceError(e)),
Some(Ok(_)) => unreachable!(),
}
}
fn complete_char(&mut self, lead: u8) -> Result<char, Error<E>> {
let a = lead as u32; | 367Read a file character by character/UTF8
| 15rust
| e5yaj |
(defn read-nth-line
"Read line-number from the given text file. The first line has the number 1."
[file line-number]
(with-open [rdr (clojure.java.io/reader file)]
(nth (line-seq rdr) (dec line-number)))) | 369Read a specific line from a file
| 6clojure
| d15nb |
val list = List(1,2,3,4,2,3,4,99)
val l2 = list.distinct | 362Remove duplicate elements
| 16scala
| h96ja |
theString = theString:reverse() | 366Reverse a string
| 1lua
| 8hu0e |
use Benchmark;
timethese COUNT,{ 'Job1' => &job1, 'Job2' => &job2 };
sub job1
{
...job1 code...
}
sub job2
{
...job2 code...
} | 368Rate counter
| 2perl
| 6qh36 |
WITH
FUNCTION remove_duplicate_elements(p_in_str IN varchar2, p_delimiter IN varchar2 DEFAULT ',') RETURN varchar2 IS
v_in_str varchar2(32767):= REPLACE(p_in_str,p_delimiter,',');
v_res varchar2(32767);
BEGIN
--
EXECUTE immediate 'select listagg(distinct cv,:p_delimiter) from (select (column_value).getstringval() cv from xmltable(:v_in_str))'
INTO v_res USING p_delimiter, v_in_str;
--
RETURN v_res;
--
END;
--Test
SELECT remove_duplicate_elements('1, 2, 3, , , , 2, 3, 4, , , ') AS res FROM dual
UNION ALL
SELECT remove_duplicate_elements('3 9 1 10 3 7 6 5 2 7 4 7 4 2 2 2 2 8 2 10 4 9 2 4 9 3 4 3 4 7',' ') AS res FROM dual
; | 362Remove duplicate elements
| 19sql
| p29b1 |
println(Array(Set([3,2,1,2,3,4]))) | 362Remove duplicate elements
| 17swift
| 4zd5g |
import subprocess
import time
class Tlogger(object):
def __init__(self):
self.counts = 0
self.tottime = 0.0
self.laststart = 0.0
self.lastreport = time.time()
def logstart(self):
self.laststart = time.time()
def logend(self):
self.counts +=1
self.tottime += (time.time()-self.laststart)
if (time.time()-self.lastreport)>5.0:
self.report()
def report(self):
if ( self.counts > 4*self.tottime):
print % (self.counts/self.tottime);
else:
print %(self.tottime/self.counts);
self.lastreport = time.time()
def taskTimer( n, subproc_args ):
logger = Tlogger()
for x in range(n):
logger.logstart()
p = subprocess.Popen(subproc_args)
p.wait()
logger.logend()
logger.report()
import timeit
import sys
def main( ):
s =
timer = timeit.Timer(s)
rzlts = timer.repeat(5, 5000)
for t in rzlts:
print ,t
print ,sys.argv[1]
print ,sys.argv[2:]
print
for k in range(3):
taskTimer( int(sys.argv[1]), sys.argv[2:])
main() | 368Rate counter
| 3python
| ysk6q |
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: line%d", n)
}
f, err := os.Open(fn)
if err != nil {
return "", err
}
defer f.Close()
bf := bufio.NewReader(f)
var line string
for lnum := 0; lnum < n; lnum++ {
line, err = bf.ReadString('\n')
if err == io.EOF {
switch lnum {
case 0:
return "", errors.New("no lines in file")
case 1:
return "", errors.New("only 1 line")
default:
return "", fmt.Errorf("only%d lines", lnum)
}
}
if err != nil {
return "", err
}
}
if line == "" {
return "", fmt.Errorf("line%d empty", n)
}
return line, nil
} | 369Read a specific line from a file
| 0go
| ufwvt |
typedef struct { double x, y; } vec;
typedef struct { int n; vec* v; } polygon_t, *polygon;
BIN_V(sub, a.x - b.x, a.y - b.y);
BIN_V(add, a.x + b.x, a.y + b.y);
BIN_S(dot, a.x * b.x + a.y * b.y);
BIN_S(cross, a.x * b.y - a.y * b.x);
vec vmadd(vec a, double s, vec b)
{
vec c;
c.x = a.x + s * b.x;
c.y = a.y + s * b.y;
return c;
}
int intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)
{
vec dx = vsub(x1, x0), dy = vsub(y1, y0);
double d = vcross(dy, dx), a;
if (!d) return 0;
a = (vcross(x0, dx) - vcross(y0, dx)) / d;
if (sect)
*sect = vmadd(y0, a, dy);
if (a < -tol || a > 1 + tol) return -1;
if (a < tol || a > 1 - tol) return 0;
a = (vcross(x0, dy) - vcross(y0, dy)) / d;
if (a < 0 || a > 1) return -1;
return 1;
}
double dist(vec x, vec y0, vec y1, double tol)
{
vec dy = vsub(y1, y0);
vec x1, s;
int r;
x1.x = x.x + dy.y; x1.y = x.y - dy.x;
r = intersect(x, x1, y0, y1, tol, &s);
if (r == -1) return HUGE_VAL;
s = vsub(s, x);
return sqrt(vdot(s, s));
}
int inside(vec v, polygon p, double tol)
{
int i, k, crosses, intersectResult;
vec *pv;
double min_x, max_x, min_y, max_y;
for (i = 0; i < p->n; i++) {
k = (i + 1) % p->n;
min_x = dist(v, p->v[i], p->v[k], tol);
if (min_x < tol) return 0;
}
min_x = max_x = p->v[0].x;
min_y = max_y = p->v[1].y;
for_v(i, pv, p) {
if (pv->x > max_x) max_x = pv->x;
if (pv->x < min_x) min_x = pv->x;
if (pv->y > max_y) max_y = pv->y;
if (pv->y < min_y) min_y = pv->y;
}
if (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)
return -1;
max_x -= min_x; max_x *= 2;
max_y -= min_y; max_y *= 2;
max_x += max_y;
vec e;
while (1) {
crosses = 0;
e.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x;
e.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x;
for (i = 0; i < p->n; i++) {
k = (i + 1) % p->n;
intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);
if (!intersectResult) break;
if (intersectResult == 1) crosses++;
}
if (i == p->n) break;
}
return (crosses & 1) ? 1 : -1;
}
int main()
{
vec vsq[] = { {0,0}, {10,0}, {10,10}, {0,10},
{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};
polygon_t sq = { 4, vsq },
sq_hole = { 8, vsq };
vec c = { 10, 5 };
vec d = { 5, 5 };
printf(, inside(c, &sq, 1e-10));
printf(, inside(c, &sq_hole, 1e-10));
printf(, inside(d, &sq, 1e-10));
printf(, inside(d, &sq_hole, 1e-10));
return 0;
} | 370Ray-casting algorithm
| 5c
| d1unv |
def line = null
new File("lines.txt").eachLine { currentLine, lineNumber ->
if (lineNumber == 7) {
line = currentLine
}
}
println "Line 7 = $line" | 369Read a specific line from a file
| 7groovy
| 98bm4 |
main :: IO ()
main = do contents <- readFile filename
case drop 6 $ lines contents of
[] -> error "File has less than seven lines"
l:_ -> putStrLn l
where filename = "testfile" | 369Read a specific line from a file
| 8haskell
| w46ed |
require 'benchmark'
Document = Struct.new(:id,:a,:b,:c)
documents_a = []
documents_h = {}
1.upto(10_000) do |n|
d = Document.new(n)
documents_a << d
documents_h[d.id] = d
end
searchlist = Array.new(1000){ rand(10_000)+1 }
Benchmark.bm(10) do |x|
x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} }
x.report('hash'){searchlist.each{|el| documents_h.has_key?(el)} }
end | 368Rate counter
| 14ruby
| 98pmz |
typedef struct{
int score;
char name[100];
}entry;
void ordinalRanking(entry* list,int len){
int i;
printf();
for(i=0;i<len;i++)
printf(,i+1,list[i].score,list[i].name);
}
void standardRanking(entry* list,int len){
int i,j=1;
printf();
for(i=0;i<len;i++){
printf(,j,list[i].score,list[i].name);
if(list[i+1].score<list[i].score)
j = i+2;
}
}
void denseRanking(entry* list,int len){
int i,j=1;
printf();
for(i=0;i<len;i++){
printf(,j,list[i].score,list[i].name);
if(list[i+1].score<list[i].score)
j++;
}
}
void modifiedRanking(entry* list,int len){
int i,j,count;
printf();
for(i=0;i<len-1;i++){
if(list[i].score!=list[i+1].score){
printf(,i+1,list[i].score,list[i].name);
count = 1;
for(j=i+1;list[j].score==list[j+1].score && j<len-1;j++)
count ++;
for(j=0;j<count-1;j++)
printf(,i+count+1,list[i+j+1].score,list[i+j+1].name);
i += (count-1);
}
}
printf(,len,list[len-1].score,list[len-1].name);
}
void fractionalRanking(entry* list,int len){
int i,j,count;
float sum = 0;
printf();
for(i=0;i<len;i++){
if(i==len-1 || list[i].score!=list[i+1].score)
printf(,(float)(i+1),list[i].score,list[i].name);
else if(list[i].score==list[i+1].score){
sum = i;
count = 1;
for(j=i;list[j].score==list[j+1].score;j++){
sum += (j+1);
count ++;
}
for(j=0;j<count;j++)
printf(,sum/count + 1,list[i+j].score,list[i+j].name);
i += (count-1);
}
}
}
void processFile(char* fileName){
FILE* fp = fopen(fileName,);
entry* list;
int i,num;
fscanf(fp,,&num);
list = (entry*)malloc(num*sizeof(entry));
for(i=0;i<num;i++)
fscanf(fp,,&list[i].score,list[i].name);
fclose(fp);
ordinalRanking(list,num);
standardRanking(list,num);
denseRanking(list,num);
modifiedRanking(list,num);
fractionalRanking(list,num);
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf();
else
processFile(argV[1]);
return 0;
} | 371Ranking methods
| 5c
| e5tav |
def task(n: Int) = Thread.sleep(n * 1000)
def rate(fs: List[() => Unit]) = {
val jobs = fs map (f => scala.actors.Futures.future(f()))
val cnt1 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
val cnt2 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
val cnt3 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
println("%d jobs in 5 seconds" format cnt1)
println("%d jobs in 10 seconds" format cnt2)
println("%d jobs in 15 seconds" format cnt3)
}
rate(List.fill(30)(() => task(scala.util.Random.nextInt(10)+1))) | 368Rate counter
| 16scala
| vdw2s |
package linenbr7;
import java.io.*;
public class LineNbr7 {
public static void main(String[] args) throws Exception {
File f = new File(args[0]);
if (!f.isFile() || !f.canRead())
throw new IOException("can't read " + args[0]);
BufferedReader br = new BufferedReader(new FileReader(f));
try (LineNumberReader lnr = new LineNumberReader(br)) {
String line = null;
int lnum = 0;
while ((line = lnr.readLine()) != null
&& (lnum = lnr.getLineNumber()) < 7) {
}
switch (lnum) {
case 0:
System.out.println("the file has zero length");
break;
case 7:
boolean empty = "".equals(line);
System.out.println("line 7: " + (empty ? "empty" : line));
break;
default:
System.out.println("the file has only " + lnum + " line(s)");
}
}
}
} | 369Read a specific line from a file
| 9java
| kcnhm |
typedef struct range_tag {
double low;
double high;
} range_t;
void normalize_range(range_t* range) {
if (range->high < range->low) {
double tmp = range->low;
range->low = range->high;
range->high = tmp;
}
}
int range_compare(const void* p1, const void* p2) {
const range_t* r1 = p1;
const range_t* r2 = p2;
if (r1->low < r2->low)
return -1;
if (r1->low > r2->low)
return 1;
if (r1->high < r2->high)
return -1;
if (r1->high > r2->high)
return 1;
return 0;
}
void normalize_ranges(range_t* ranges, size_t count) {
for (size_t i = 0; i < count; ++i)
normalize_range(&ranges[i]);
qsort(ranges, count, sizeof(range_t), range_compare);
}
size_t consolidate_ranges(range_t* ranges, size_t count) {
normalize_ranges(ranges, count);
size_t out_index = 0;
for (size_t i = 0; i < count; ) {
size_t j = i;
while (++j < count && ranges[j].low <= ranges[i].high) {
if (ranges[i].high < ranges[j].high)
ranges[i].high = ranges[j].high;
}
ranges[out_index++] = ranges[i];
i = j;
}
return out_index;
}
void print_range(const range_t* range) {
printf(, range->low, range->high);
}
void print_ranges(const range_t* ranges, size_t count) {
if (count == 0)
return;
print_range(&ranges[0]);
for (size_t i = 1; i < count; ++i) {
printf();
print_range(&ranges[i]);
}
}
void test_consolidate_ranges(range_t* ranges, size_t count) {
print_ranges(ranges, count);
printf();
count = consolidate_ranges(ranges, count);
print_ranges(ranges, count);
printf();
}
int main() {
range_t test1[] = { {1.1, 2.2} };
range_t test2[] = { {6.1, 7.2}, {7.2, 8.3} };
range_t test3[] = { {4, 3}, {2, 1} };
range_t test4[] = { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} };
range_t test5[] = { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} };
test_consolidate_ranges(test1, LENGTHOF(test1));
test_consolidate_ranges(test2, LENGTHOF(test2));
test_consolidate_ranges(test3, LENGTHOF(test3));
test_consolidate_ranges(test4, LENGTHOF(test4));
test_consolidate_ranges(test5, LENGTHOF(test5));
return 0;
} | 372Range consolidation
| 5c
| xgzwu |
null | 369Read a specific line from a file
| 11kotlin
| g3s4d |
(defn normalize [r]
(let [[n1 n2] r]
[(min n1 n2) (max n1 n2)]))
(defn touch? [r1 r2]
(let [[lo1 hi1] (normalize r1)
[lo2 hi2] (normalize r2)]
(or (<= lo2 lo1 hi2)
(<= lo2 hi1 hi2))))
(defn consolidate-touching-ranges [rs]
(let [lows (map #(apply min %) rs)
highs (map #(apply max %) rs)]
[ (apply min lows) (apply max highs) ]))
(defn consolidate-ranges [rs]
(loop [res []
rs rs]
(if (empty? rs)
res
(let [r0 (first rs)
touching (filter #(touch? r0 %) rs)
remove-used (fn [rs used]
(remove #(contains? (set used) %) rs))]
(recur (conj res (consolidate-touching-ranges touching))
(remove-used (rest rs) touching)))))) | 372Range consolidation
| 6clojure
| ok98j |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.