code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
fn square_free(mut n: usize) -> bool {
if n & 3 == 0 {
return false;
}
let mut p: usize = 3;
while p * p <= n {
let mut count = 0;
while n% p == 0 {
count += 1;
if count > 1 {
return false;
}
n /= p;
}
... | 205Square-free integers | 15rust | pgebu |
import spire.math.SafeLong
import spire.implicits._
import scala.annotation.tailrec
object SquareFreeNums {
def main(args: Array[String]): Unit = {
println(
s"""|1 - 145:
|${formatTable(sqrFree.takeWhile(_ <= 145).toVector, 10)}
|
|1T - 1T+145:
|${formatTable(sqrFre... | 205Square-free integers | 16scala | ejqab |
use Speech::Synthesis;
($engine) = Speech::Synthesis->InstalledEngines();
($voice) = Speech::Synthesis->InstalledVoices(engine => $engine);
Speech::Synthesis
->new(engine => $engine, voice => $voice->{id})
->speak("This is an example of speech synthesis."); | 209Speech synthesis | 2perl | kujhc |
(defn print-cchanges [s]
(println (clojure.string/join ", " (map first (re-seq #"(.)\1*" s)))))
(print-cchanges "gHHH5YY++///\\") | 210Split a character string based on change of character | 6clojure | fqidm |
<?php
<?php
$mac_use_espeak = false;
$voice = ;
$statement = 'Hello World!';
$save_file_args = '-w HelloWorld.wav';
$OS = strtoupper(substr(PHP_OS, 0, 3));
elseif($OS === 'DAR' && $mac_use_espeak == false) {
$voice = ;
$save_file_args = '-o HelloWorld.wav';
}
exec();
exec(); | 209Speech synthesis | 12php | 38tzq |
import BigInt
import Foundation
extension BinaryInteger {
@inlinable
public var isSquare: Bool {
var x = self / 2
var seen = Set([x])
while x * x!= self {
x = (x + (self / x)) / 2
if seen.contains(x) {
return false
}
seen.insert(x)
}
return true
}
@inlin... | 205Square-free integers | 17swift | k51hx |
class StemLeafPlot
def initialize(data, options = {})
opts = {:leaf_digits => 1}.merge(options)
@leaf_digits = opts[:leaf_digits]
@multiplier = 10 ** @leaf_digits
@plot = generate_structure(data)
end
private
def generate_structure(data)
plot = Hash.new {|h,k| h[k] = []}
data.sort.each ... | 198Stem-and-leaf plot | 14ruby | yng6n |
import pyttsx
engine = pyttsx.init()
engine.say()
engine.runAndWait() | 209Speech synthesis | 3python | b5hkr |
my @histogram = (0) x 10;
my $sum = 0;
my $sum_squares = 0;
my $n = $ARGV[0];
for (1..$n) {
my $current = rand();
$sum+= $current;
$sum_squares+= $current ** 2;
$histogram[$current * @histogram]+= 1;
}
my $mean = $sum / $n;
print "$n numbers\n",
"Mean: $mean\n",
"Stddev: ", sqrt(($sum_squares... | 206Statistics/Basic | 2perl | 72hrh |
def stemAndLeaf(numbers: List[Int]) = {
val lineFormat = "%" + (numbers map (_.toString.length) max) + "d |%s"
val map = numbers groupBy (_ / 10)
for (stem <- numbers.min / 10 to numbers.max / 10) {
println(lineFormat format (stem, map.getOrElse(stem, Nil) map (_ % 10) sortBy identity mkString " "))
}
} | 198Stem-and-leaf plot | 16scala | lzhcq |
package main
import (
"fmt"
"time"
)
func main() {
a := `|/-\`
fmt.Printf("\033[?25l") | 211Spinning rod animation/Text | 0go | v392m |
module OperatingSystem
require 'rbconfig'
module_function
def operating_system
case RbConfig::CONFIG[]
when /linux/i
:linux
when /cygwin|mswin|mingw|windows/i
:windows
when /darwin/i
:mac
when /solaris/i
:solaris
else
nil
end
end
def linux?; operatin... | 209Speech synthesis | 14ruby | 1gbpw |
import javax.speech.Central
import javax.speech.synthesis.{Synthesizer, SynthesizerModeDesc}
object ScalaSpeaker extends App {
def speech(text: String) = {
if (!text.trim.isEmpty) {
val VOICENAME = "kevin16"
System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDir... | 209Speech synthesis | 16scala | xhewg |
import Control.Concurrent (threadDelay)
import Control.Exception (bracket_)
import Control.Monad (forM_)
import System.Console.Terminfo
import System.IO (hFlush, stdout)
runCapability :: Terminal -> String -> IO ()
runCapability term cap =
forM_ (getCapability term (tiGetOutput1 cap)) (runTermOutput term)
cursor... | 211Spinning rod animation/Text | 8haskell | e7bai |
import Foundation
let task = NSTask()
task.launchPath = "/usr/bin/say"
task.arguments = ["This is an example of speech synthesis."]
task.launch() | 209Speech synthesis | 17swift | p4kbl |
package main
import (
"fmt"
"math"
)
func main() {
for n, count := 1, 0; count < 30; n++ {
sq := n * n
cr := int(math.Cbrt(float64(sq)))
if cr*cr*cr != sq {
count++
fmt.Println(sq)
} else {
fmt.Println(sq, "is square and cube")
}
... | 208Square but not cube | 0go | b4bkh |
import Control.Monad (join)
import Data.List (partition, sortOn)
import Data.Ord (comparing)
isCube :: Int -> Bool
isCube n = n == round (fromIntegral n ** (1 / 3)) ^ 3
both, only :: [Int]
(both, only) = partition isCube $ join (*) <$> [1 ..]
main :: IO ()
main =
(putStrLn . unlines) $
uncurry ((<>) . sho... | 208Square but not cube | 8haskell | dqdn4 |
def stern_brocot(predicate=lambda series: len(series) < 20):
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first%i values:\n '% n_first,
... | 201Stern-Brocot sequence | 3python | z8ltt |
public class SpinningRod
{
public static void main(String[] args) throws InterruptedException {
String a = "|/-\\";
System.out.print("\033[2J"); | 211Spinning rod animation/Text | 9java | hvgjm |
const rod = (function rod() {
const chars = "|/-\\";
let i=0;
return function() {
i= (i+1) % 4; | 211Spinning rod animation/Text | 10javascript | ark10 |
typedef struct stk_
stk_
stk_
s = malloc(sizeof(struct stk_
if (!s) return 0; \
s->buf = malloc(sizeof(type) * init_size); \
if (!s->buf) { free(s); return 0; } \
s->len = 0, s->alloc = init_size; \
return s; } \
int stk_
type *tmp; \
if (s->len >= s->alloc) { \
tmp = realloc(s->... | 212Stack | 5c | oax80 |
typedef uint64_t integer;
typedef struct number_names_tag {
const char* cardinal;
const char* ordinal;
} number_names;
const number_names small[] = {
{ , }, { , }, { , },
{ , }, { , }, { , },
{ , }, { , }, { , },
{ , }, { , }, { , },
{ , }, { , },
{ , }, { , },
{ , ... | 213Spelling of ordinal numbers | 5c | 1g7pj |
public class SquaresCubes {
public static boolean isPerfectCube(long n) {
long c = (long)Math.cbrt((double)n);
return ((c * c * c) == n);
}
public static void main(String... args) {
long n = 1;
int squareOnlyCount = 0;
int squareCubeCount = 0;
while ((squareO... | 208Square but not cube | 9java | spsq0 |
def sd1(numbers):
if numbers:
mean = sum(numbers) / len(numbers)
sd = (sum((n - mean)**2 for n in numbers) / len(numbers))**0.5
return sd, mean
else:
return 0, 0
def sd2(numbers):
if numbers:
sx = sxx = n = 0
for x in numbers:
sx += x
... | 206Statistics/Basic | 3python | jvk7p |
SternBrocot <- function(n){
V <- 1; k <- n/2;
for (i in 1:k)
{ V[2*i] = V[i]; V[2*i+1] = V[i] + V[i+1];}
return(V);
}
require(pracma);
{
cat(" *** The first 15:",SternBrocot(15),"\n");
cat(" *** The first i@n:","\n");
V=SternBrocot(40);
for (i in 1:10) {j=match(i,V); cat(i,"@",j,",")}
V=SternBrocot(1200);
i... | 201Stern-Brocot sequence | 13r | nxyi2 |
null | 211Spinning rod animation/Text | 11kotlin | 4m257 |
null | 211Spinning rod animation/Text | 1lua | g9v4j |
(() => {
'use strict';
const main = () =>
unlines(map(
x => x.toString() + (
isCube(x) ? (
` (cube of ${cubeRootInt(x)} and square of ${
Math.pow(x, 1/2)
})`
) : ''
),
... | 208Square but not cube | 10javascript | nxniy |
a = runif(10,min=0,max=1)
b = runif(100,min=0,max=1)
c = runif(1000,min=0,max=1)
d = runif(10000,min=0,max=1)
cat("a = ",a)
cat("Mean of a: ",mean(a))
cat("Standard Deviation of a: ", sd(a))
cat("Mean of b: ",mean(b))
cat("Standard Deviation of b: ", sd(b))
cat("Mean of c: ",mean(c))
cat("Standard Deviation of c: "... | 206Statistics/Basic | 13r | 49r5y |
(def test-cases [1 2 3 4 5 11 65 100 101 272 23456 8007006005004003])
(pprint
(sort (zipmap test-cases (map #(clojure.pprint/cl-format nil "~:R" %) test-cases)))) | 213Spelling of ordinal numbers | 6clojure | qkpxt |
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(scc(`gHHH5YY++ | 210Split a character string based on change of character | 0go | 5y2ul |
import Data.List (group, intercalate)
main :: IO ()
main = putStrLn $ intercalate ", " (group "gHHH5YY++///\\") | 210Split a character string based on change of character | 8haskell | xhaw4 |
(deftype Stack [elements])
(def stack (Stack (ref ())))
(defn push-stack
"Pushes an item to the top of the stack."
[x] (dosync (alter (:elements stack) conj x)))
(defn pop-stack
"Pops an item from the top of the stack."
[] (let [fst (first (deref (:elements stack)))]
(dosync (alter (:elements stack) ... | 212Stack | 6clojure | tsofv |
import (
"fmt"
"strings"
)
func main() {
for _, n := range []int64{
1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
} {
fmt.Println(sayOrdinal(n))
}
}
var irregularOrdinals = map[string]string{
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth"... | 213Spelling of ordinal numbers | 0go | yid64 |
null | 208Square but not cube | 11kotlin | a7a13 |
def generate_statistics(n)
sum = sum2 = 0.0
hist = Array.new(10, 0)
n.times do
r = rand
sum += r
sum2 += r**2
hist[(10*r).to_i] += 1
end
mean = sum / n
stddev = Math::sqrt((sum2 / n) - mean**2)
puts
puts
puts
hist.each_with_index {|x,i| puts % [0.1*i, * (70*x/hist.max)]}
puts... | 206Statistics/Basic | 14ruby | k5phg |
spellOrdinal :: Integer -> String
spellOrdinal n
| n <= 0 = "not ordinal"
| n < 20 = small n
| n < 100 = case divMod n 10 of
(k, 0) -> spellInteger (10*k) ++ "th"
(k, m) -> spellInteger (10*k) ++ "-" ++ spellOrdinal m
| n < 1000 = case divMod n 100 of
(k, 0) -> spellInteger (100*k) ++ "th"
... | 213Spelling of ordinal numbers | 8haskell | hv5ju |
#![feature(iter_arith)]
extern crate rand;
use rand::distributions::{IndependentSample, Range};
pub fn mean(data: &[f32]) -> Option<f32> {
if data.is_empty() {
None
} else {
let sum: f32 = data.iter().sum();
Some(sum / data.len() as f32)
}
}
pub fn variance(data: &[f32]) -> Option... | 206Statistics/Basic | 15rust | b41kx |
package org.rosettacode;
import java.util.ArrayList;
import java.util.List;
public class SplitStringByCharacterChange {
public static void main(String... args){
for (String string : args){
List<String> resultStrings = splitStringByCharacter(string);
String output = formatList(r... | 210Split a character string based on change of character | 9java | b5jk3 |
$|= 1;
while () {
for (qw[ | / - \ ]) {
select undef, undef, undef, 0.25;
printf "\r ($_)";
}
} | 211Spinning rod animation/Text | 2perl | ieso3 |
import java.util.HashMap;
import java.util.Map;
public class SpellingOfOrdinalNumbers {
public static void main(String[] args) {
for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) {
System.out.printf("%d =%s%n", test, toOrdinal(test));
... | 213Spelling of ordinal numbers | 9java | 5y9uf |
function nthroot (x, n)
local r = 1
for i = 1, 16 do
r = (((n - 1) * r) + x / (r ^ (n - 1))) / n
end
return r
end
local i, count, sq, cbrt = 0, 0
while count < 30 do
i = i + 1
sq = i * i | 208Square but not cube | 1lua | ejeac |
def mean(a:Array[Double])=a.sum / a.size
def stddev(a:Array[Double])={
val sum = a.fold(0.0)((a, b) => a + math.pow(b,2))
math.sqrt((sum/a.size) - math.pow(mean(a),2))
}
def hist(a:Array[Double]) = {
val grouped=(SortedMap[Double, Array[Double]]() ++ (a groupBy (x => math.rint(x*10)/10)))
grouped.map(v => (... | 206Statistics/Basic | 16scala | a7w1n |
(() => {
"use strict"; | 210Split a character string based on change of character | 10javascript | wj1e2 |
def sb
return enum_for :sb unless block_given?
a=[1,1]
0.step do |i|
yield a[i]
a << a[i]+a[i+1] << a[i+1]
end
end
puts
[*1..10,100].each do |n|
puts
end
if sb.take(1000).each_cons(2).all? { |a,b| a.gcd(b) == 1 }
puts
else
puts
end | 201Stern-Brocot sequence | 14ruby | 6iv3t |
null | 213Spelling of ordinal numbers | 11kotlin | cfz98 |
lazy val sbSeq: Stream[BigInt] = {
BigInt("1") #::
BigInt("1") #::
(sbSeq zip sbSeq.tail zip sbSeq.tail).
flatMap{ case ((a,b),c) => List(a+b,c) }
} | 201Stern-Brocot sequence | 16scala | ctg93 |
from time import sleep
while True:
for rod in r'\|/-':
print(rod, end='\r')
sleep(0.25) | 211Spinning rod animation/Text | 3python | nw0iz |
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
, , , , , , , , , ,
, , , , , , , , ,
};
int pref[jan + 1][jon + 1] = {
{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },
{ cath, hope, ab... | 214Stable marriage problem | 5c | ts0f4 |
use Lingua::EN::Numbers 'num2en_ordinal';
printf "%16s:%s\n", $_, num2en_ordinal(0+$_) for
<1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 '00123.0' 1.23e2 '1.23e2'>; | 213Spelling of ordinal numbers | 2perl | xhbw8 |
null | 210Split a character string based on change of character | 11kotlin | rc5go |
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
this->i++;
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv;
std::cout << << sv.i << << sv2.i << ;
} | 215Special variables | 5c | 2zzlo |
function charSplit (inStr)
local outStr, nextChar = inStr:sub(1, 1)
for pos = 2, #inStr do
nextChar = inStr:sub(pos, pos)
if nextChar ~= outStr:sub(#outStr, #outStr) then
outStr = outStr .. ", "
end
outStr = outStr .. nextChar
end
return outStr
end
print(char... | 210Split a character string based on change of character | 1lua | 7l4ru |
(apply str (interpose " " (sort (filter #(.startsWith % "*") (map str (keys (ns-publics 'clojure.core))))))) | 215Special variables | 6clojure | g994f |
def spinning_rod
begin
printf()
%w[| / - \\].cycle do |rod|
print rod
sleep 0.25
print
end
ensure
printf()
end
end
puts
spinning_rod | 211Spinning rod animation/Text | 14ruby | fqodr |
fn main() {
let characters = ['|', '/', '-', '\\'];
let mut current = 0;
println!("{}[2J", 27 as char); | 211Spinning rod animation/Text | 15rust | tsifd |
irregularOrdinals = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit(, 1)
num = num.rsplit(, 1)
delim =
if len(num[-1]) > len(hyphen[-1]):
num = hyphen
delim =
if num[-1] ... | 213Spelling of ordinal numbers | 3python | qkpxi |
while ($cnt < 30) {
$n++;
$h{$n**2}++;
$h{$n**3}--;
$cnt++ if $h{$n**2} > 0;
}
print "First 30 positive integers that are a square but not a cube:\n";
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 1 } keys %h;
print "\n\nFirst 3 positive integers that are both a square and a cube:\n";
print "$_ ... | 208Square but not cube | 2perl | 9f9mn |
struct SternBrocot: Sequence, IteratorProtocol {
private var seq = [1, 1]
mutating func next() -> Int? {
seq += [seq[0] + seq[1], seq[1]]
return seq.removeFirst()
}
}
func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
guard a!= 0 else {
return b
}
return a < b? gcd(b% a, a): gcd(a% b, b)
}
p... | 201Stern-Brocot sequence | 17swift | 3o2z2 |
object SpinningRod extends App {
val start = System.currentTimeMillis
def a = "|/-\\"
print("\033[2J") | 211Spinning rod animation/Text | 16scala | 6of31 |
# &keyword # type returned(indicators) - brief description
# indicators:
# * - generates multiple values
# = - modifiable
# ? - may fail (e.g. status inquiry)
# U - Unicon
# G - Icon or Unicon with Graphics
#
&allocated # integer(*) - report memory allocated in total and by storage regions
&ascii ... | 215Special variables | 0go | qkkxz |
typedef struct node_t *node, node_t;
struct node_t { int v; node next; };
typedef struct { node head, tail; } slist;
void push(slist *l, node e) {
if (!l->head) l->head = e;
if (l->tail) l->tail->next = e;
l->tail = e;
}
node removehead(slist *l) {
node e = l->head;
if (e) {
l->head = e->next;
e->next = 0;
... | 216Sorting algorithms/Strand sort | 5c | p45by |
struct NumberNames {
cardinal: &'static str,
ordinal: &'static str,
}
impl NumberNames {
fn get_name(&self, ordinal: bool) -> &'static str {
if ordinal {
return self.ordinal;
}
self.cardinal
}
}
const SMALL_NAMES: [NumberNames; 20] = [
NumberNames {
card... | 213Spelling of ordinal numbers | 15rust | 81e07 |
# &keyword # type returned(indicators) - brief description
# indicators:
# * - generates multiple values
# = - modifiable
# ? - may fail (e.g. status inquiry)
# U - Unicon
# G - Icon or Unicon with Graphics
#
&allocated # integer(*) - report memory allocated in total and by storage regions
&ascii ... | 215Special variables | 8haskell | mnnyf |
int main(int argC,char* argV[])
{
double* arr,min,max;
char* str;
int i,len;
if(argC == 1)
printf(,argV[0]);
else{
arr = (double*)malloc((argC-1)*sizeof(double));
for(i=1;i<argC;i++){
len = strlen(argV[i]);
if(argV[i][len-1]==','){
str = (char*)malloc(len*sizeof(char));
strncpy(str,argV[i],len... | 217Sparkline in unicode | 5c | wjrec |
(ns rosettacode.strand-sort)
(defn merge-join
"Produces a globally sorted seq from two sorted seqables"
[[a & la:as all] [b & lb:as bll]]
(cond (nil? a) bll
(nil? b) all
(< a b) (cons a (lazy-seq (merge-join la bll)))
true (cons b (lazy-seq (merge-join all lb)))))
(defn unbraid
"Sep... | 216Sorting algorithms/Strand sort | 6clojure | xhjwk |
fileprivate class NumberNames {
let cardinal: String
let ordinal: String
init(cardinal: String, ordinal: String) {
self.cardinal = cardinal
self.ordinal = ordinal
}
func getName(_ ordinal: Bool) -> String {
return ordinal? self.ordinal: self.cardinal
}
class func n... | 213Spelling of ordinal numbers | 17swift | sb1qt |
def nonCubeSquares(n):
upto = enumFromTo(1)
ns = upto(n)
setCubes = set(x ** 3 for x in ns)
ms = upto(n + len(set(x * x for x in ns).intersection(
setCubes
)))
return list(tuple([x * x, x in setCubes]) for x in ms)
def squareListing(xs):
justifyIdx = justifyRight(len(str(1 + len(x... | 208Square but not cube | 3python | ctc9q |
use strict;
use warnings;
use feature 'say';
use utf8;
binmode(STDOUT, ':utf8');
for my $string (q[gHHH5YY++///\\], q[fffnnn ]) {
my @S;
my $last = '';
while ($string =~ /(\X)/g) {
if ($last eq $1) { $S[-1] .= $1 } else { push @S, $1 }
$last = $1;
}
say "Orginal: $string\n Split: ... | 210Split a character string based on change of character | 2perl | dxonw |
int main(int c, char **v)
{
int i, j, m = 0, n = 0;
if (c >= 2) m = atoi(v[1]);
if (c >= 3) n = atoi(v[2]);
if (m <= 0) m = 5;
if (n <= 0) n = m;
int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);
s[0] = (int*)(s + m);
for (i = 1; i < m; i++) s[i] = s[i - 1] + n;
int dx = 1, dy = 0, val = 0, t;... | 218Spiral matrix | 5c | cfi9c |
import java.util.Arrays;
public class SpecialVariables {
public static void main(String[] args) { | 215Special variables | 9java | fqqdv |
(defn sparkline [nums]
(let [sparks ""
high (apply max nums)
low (apply min nums)
spread (- high low)
quantize #(Math/round (* 7.0 (/ (- % low) spread)))]
(apply str (map #(nth sparks (quantize %)) nums))))
(defn spark [line]
(if line
(let [nums (read-string... | 217Sparkline in unicode | 6clojure | 81b05 |
package main
import "fmt" | 214Stable marriage problem | 0go | hvujq |
var obj = {
foo: 1,
bar: function () { return this.foo; }
};
obj.bar(); | 215Special variables | 10javascript | yii6r |
import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys ... | 214Stable marriage problem | 7groovy | 4m95f |
from itertools import groupby
def splitter(text):
return ', '.join(''.join(group) for key, group in groupby(text))
if __name__ == '__main__':
txt = 'gHHH5YY++
print(f'Input: {txt}\nSplit: {splitter(txt)}') | 210Split a character string based on change of character | 3python | fqide |
null | 215Special variables | 11kotlin | 8110q |
package main
import "fmt"
type link struct {
int
next *link
}
func linkInts(s []int) *link {
if len(s) == 0 {
return nil
}
return &link{s[0], linkInts(s[1:])}
}
func (l *link) String() string {
if l == nil {
return "nil"
}
r := fmt.Sprintf("[%d", l.int)
for l = l.... | 216Sorting algorithms/Strand sort | 0go | 6o83p |
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State | 214Stable marriage problem | 8haskell | iewor |
class PowIt
:next
def initialize
@next = 1;
end
end
class SquareIt < PowIt
def next
result = @next ** 2
@next += 1
return result
end
end
class CubeIt < PowIt
def next
result = @next ** 3
@next += 1
return result
end
end
squares = []
hexponents = []
squit = SquareIt.new
cuit = CubeIt.new
s = s... | 208Square but not cube | 14ruby | 232lw |
(defn spiral [n]
(let [cyc (cycle [1 n -1 (- n)])]
(->> (range (dec n) 0 -1)
(mapcat #(repeat 2 %))
(cons n)
(mapcat #(repeat %2 %) cyc)
(reductions +)
(map vector (range 0 (* n n)))
(sort-by second)
(map first)))
(let [n 5]
(clojure.pprint/cl-form... | 218Spiral matrix | 6clojure | 5yzuz |
Trigraph Replacement letter
??( [
??) ]
??< {
??> }
??/ \
??=
??' ^
??! |
??- ~ | 219Special characters | 5c | lticy |
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x: xs) (y: ys)
| x <= y = x: merge xs (y: ys)
| otherwise = y: merge (x: xs) ys
strandSort :: (Ord a) => [a] -> [a]
strandSort [] = []
strandSort (x: xs) = merge strand (strandSort rest) where
(strand, rest) = extractStrand x xs
extract... | 216Sorting algorithms/Strand sort | 8haskell | j2l7g |
fn main() {
let mut s = 1;
let mut c = 1;
let mut cube = 1;
let mut n = 0;
while n < 30 {
let square = s * s;
while cube < square {
c += 1;
cube = c * c * c;
}
if cube == square {
println!("{} is a square and a cube.", square);
... | 208Square but not cube | 15rust | v6v2t |
import spire.math.SafeLong
import spire.implicits._
def ncs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).flatMap(n => Iterator.iterate(n.pow(3).sqrt + 1)(_ + 1).map(i => i*i).takeWhile(_ < (n + 1).pow(3)))
def scs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).map(_.pow(3)).filter(n => n.sqrt... | 208Square but not cube | 16scala | 49450 |
for n in pairs(_G) do print(n) end | 215Special variables | 1lua | oaa8h |
? println(`1 + 1$\n= ${1 + 1}`)
1 + 1
= 2 | 219Special characters | 6clojure | 4mz5o |
function sleep_and_echo {
sleep "$1"
echo "$1"
}
for val in "$@"; do
sleep_and_echo "$val" &
done
wait | 220Sorting algorithms/Sleep sort | 4bash | fq1d8 |
import java.util.Arrays;
import java.util.LinkedList;
public class Strand{ | 216Sorting algorithms/Strand sort | 9java | u63vv |
var s = 1, c = 1, cube = 1, n = 0
while n < 30 {
let square = s * s
while cube < square {
c += 1
cube = c * c * c
}
if cube == square {
print("\(square) is a square and a cube.")
} else {
print(square)
n += 1
}
s += 1
} | 208Square but not cube | 17swift | lzlc2 |
def split(str)
puts
s = str.chars.chunk(&:itself).map{|_,a| a.join}.join()
puts
s
end
split() | 210Split a character string based on change of character | 14ruby | z0dtw |
import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "... | 214Stable marriage problem | 9java | xhkwy |
fn splitter(string: &str) -> String {
let chars: Vec<_> = string.chars().collect();
let mut result = Vec::new();
let mut last_mismatch = 0;
for i in 0..chars.len() {
if chars.len() == 1 {
return chars[0..1].iter().collect();
}
if i > 0 && chars[i-1]!= chars[i] {
... | 210Split a character string based on change of character | 15rust | 38fz8 |
null | 210Split a character string based on change of character | 16scala | mn3yc |
int main(int c, char **v)
{
while (--c > 1 && !fork());
sleep(c = atoi(v[c]));
printf(, c);
wait(0);
return 0;
} | 220Sorting algorithms/Sleep sort | 5c | z0etx |
package main
import (
"bufio"
"errors"
"fmt"
"math"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
fmt.Println("Numbers please separated by space/commas:")
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
s, n, min, max, err := spark(sc.Text())
if err != nil {
... | 217Sparkline in unicode | 0go | cfn9g |
null | 216Sorting algorithms/Strand sort | 11kotlin | 9dnmh |
function Person(name) {
var candidateIndex = 0;
this.name = name;
this.fiance = null;
this.candidates = [];
this.rank = function(p) {
for (i = 0; i < this.candidates.length; i++)
if (this.candidates[i] === p) return i;
return this.candidates.length + 1;
}
this... | 214Stable marriage problem | 10javascript | oae86 |
-- comment here until end of line
{- comment here -} | 219Special characters | 0go | xhgwf |
def sparkline(List<Number> list) {
def (min, max) = [list.min(), list.max()]
def div = (max - min) / 7
list.collect { (char)(0x2581 + (it-min) * div) }.join()
}
def sparkline(String text) { sparkline(text.split(/[ ,]+/).collect { it as Double }) } | 217Sparkline in unicode | 7groovy | 38szd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.