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; } p += 2; } true } fn print_square_free_numbers(from: usize, to: usize) { println!("Square-free numbers between {} and {}:", from, to); let mut line = String::new(); for i in from..=to { if square_free(i) { if!line.is_empty() { line.push_str(" "); } line.push_str(&i.to_string()); if line.len() >= 80 { println!("{}", line); line.clear(); } } } if!line.is_empty() { println!("{}", line); } } fn print_square_free_count(from: usize, to: usize) { let mut count = 0; for i in from..=to { if square_free(i) { count += 1; } } println!( "Number of square-free numbers between {} and {}: {}", from, to, count ) } fn main() { print_square_free_numbers(1, 145); print_square_free_numbers(1000000000000, 1000000000145); let mut n: usize = 100; while n <= 1000000 { print_square_free_count(1, n); n *= 10; } }
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(sqrFreeInit(1000000000000L).takeWhile(_ <= 1000000000145L).toVector, 6)} | |Square-Free Counts... |100: ${sqrFree.takeWhile(_ <= 100).length} |1000: ${sqrFree.takeWhile(_ <= 1000).length} |10000: ${sqrFree.takeWhile(_ <= 10000).length} |100000: ${sqrFree.takeWhile(_ <= 100000).length} |1000000: ${sqrFree.takeWhile(_ <= 1000000).length} |""".stripMargin) } def chkSqr(num: SafeLong): Boolean = !LazyList.iterate(SafeLong(2))(_ + 1).map(_.pow(2)).takeWhile(_ <= num).exists(num%_ == 0) def sqrFreeInit(init: SafeLong): LazyList[SafeLong] = LazyList.iterate(init)(_ + 1).filter(chkSqr) def sqrFree: LazyList[SafeLong] = sqrFreeInit(1) def formatTable(lst: Vector[SafeLong], rlen: Int): String = { @tailrec def fHelper(ac: Vector[String], src: Vector[String]): String = { if(src.nonEmpty) fHelper(ac :+ src.take(rlen).mkString, src.drop(rlen)) else ac.mkString("\n") } val maxLen = lst.map(n => f"${n.toBigInt}%,d".length).max val formatted = lst.map(n => s"%,${maxLen + 2}d".format(n.toBigInt)) fHelper(Vector[String](), formatted) } }
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 } @inlinable public var isSquareFree: Bool { return factors().dropFirst().reduce(true, { $0 &&!$1.isSquare }) } @inlinable public func factors() -> [Self] { let maxN = Self(Double(self).squareRoot()) var res = Set<Self>() for factor in stride(from: 1, through: maxN, by: 1) where self% factor == 0 { res.insert(factor) res.insert(self / factor) } return res.sorted() } } let sqFree1to145 = (1...145).filter({ $0.isSquareFree }) print("Square free numbers in range 1...145: \(sqFree1to145)") let sqFreeBig = (BigInt(1_000_000_000_000)...BigInt(1_000_000_000_145)).filter({ $0.isSquareFree }) print("Square free numbers in range 1_000_000_000_000...1_000_000_000_045: \(sqFreeBig)") var count = 0 for n in 1...1_000_000 { if n.isSquareFree { count += 1 } switch n { case 100, 1_000, 10_000, 100_000, 1_000_000: print("Square free numbers between 1...\(n): \(count)") case _: break } }
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 do |value| stem, leaf = parse(value) plot[stem] << leaf end plot end def parse(value) stem, leaf = value.abs.divmod(@multiplier) [Stem.get(stem, value), leaf.round] end public def print stem_width = Math.log10(@plot.keys.max_by {|s| s.value}.value).ceil + 1 Stem.get_range(@plot.keys).each do |stem| leaves = @plot[stem].inject() {|str,leaf| str << % [@leaf_digits, leaf]} puts % [stem_width, stem, leaves] end puts puts puts end end class Stem @@cache = {} def self.get(stem_value, datum) sign = datum < 0?:-::+ cache(stem_value, sign) end private def self.cache(value, sign) if @@cache[[value, sign]].nil? @@cache[[value, sign]] = self.new(value, sign) end @@cache[[value, sign]] end def initialize(value, sign) @value = value @sign = sign end public attr_accessor :value, :sign def negative? @sign ==:- end def <=>(other) if self.negative? if other.negative? other.value <=> self.value else -1 end else if other.negative? 1 else self.value <=> other.value end end end def to_s % [(self.negative?? '-': ' '), @value] end def self.get_range(array_of_stems) min, max = array_of_stems.minmax if min.negative? if max.negative? min.value.downto(max.value).collect {|n| cache(n,:-)} else min.value.downto(0).collect {|n| cache(n,:-)} + 0.upto(max.value).collect {|n| cache(n,:+)} end else min.value.upto(max.value).collect {|n| cache(n,:+)} end end end data = DATA.read.split.map {|s| Float(s)} StemLeafPlot.new(data).print __END__ 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
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 / $n) - ($mean ** 2)), "\n"; for my $i (0..$ printf "%.1f -%.1f: ", $i/@histogram, (1 + $i)/@histogram; print "*" x (30 * $histogram[$i] * @histogram/$n); print "\n"; }
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?; operating_system == :linux; end def windows?; operating_system == :windows; end def mac?; operating_system == :mac; end end
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.KevinVoiceDirectory") Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral") val synth = Central.createSynthesizer(null) synth.allocate() val desc = synth.getEngineModeDesc match {case g2: SynthesizerModeDesc => g2} synth.getSynthesizerProperties.setVoice(desc.getVoices.find(_.toString == VOICENAME).get) synth.speakPlainText(text, null) synth.waitEngineState(Synthesizer.QUEUE_EMPTY) synth.deallocate() } } speech( """Thinking of Holland |I see broad rivers |slowly chuntering |through endless lowlands, |rows of implausibly |airy poplars |standing like tall plumes |against the horizon; |and sunk in the unbounded |vastness of space |homesteads and boweries |dotted across the land, |copses, villages, |couchant towers, |churches and elm-trees, |bound in one great unity. |There the sky hangs low, |and steadily the sun |is smothered in a greyly |iridescent smirr, |and in every province |the voice of water |with its lapping disasters |is feared and hearkened.""".stripMargin) }
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) cursorOff, cursorOn :: Terminal -> IO () cursorOff term = runCapability term "civis" cursorOn term = runCapability term "cnorm" spin :: IO () spin = forM_ (cycle "|/-\\") $ \c -> putChar c >> putChar '\r' >> hFlush stdout >> threadDelay 250000 main :: IO () main = do putStrLn "Spinning rod demo. Hit ^C to stop it.\n" term <- setupTermFromEnv bracket_ (cursorOff term) (cursorOn term) spin
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 ((<>) . show) <$> sortOn fst ( ((," (also cube)") <$> take 3 both) <> ((,"") <$> take 30 only) )
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, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of%3i in the series:'% n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
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->buf, s->alloc*2*sizeof(type)); \ if (!tmp) return -1; s->buf = tmp; \ s->alloc *= 2; } \ s->buf[s->len++] = item; \ return s->len; } \ type stk_ type tmp; \ if (!s->len) abort(); \ tmp = s->buf[--s->len]; \ if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ s->alloc /= 2; \ s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ return tmp; } \ void stk_ free(s->buf); free(s); } DECL_STACK_TYPE(int, int) int main(void) { int i; stk_int stk = stk_int_create(0); printf(); for (i = 'a'; i <= 'z'; i++) { printf(, i); stk_int_push(stk, i); } printf(, stk_size(stk)); printf(, stk_empty(stk) ? : ); printf(); while (stk_size(stk)) printf(, stk_int_pop(stk)); printf(, stk_size(stk)); printf(, stk_empty(stk) ? : ); stk_int_delete(stk); return 0; }
212Stack
5c
oax80
typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , } }; const number_names tens[] = { { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { , , 100 }, { , , 1000 }, { , , 1000000 }, { , , 1000000000 }, { , , 1000000000000 }, { , , 1000000000000000ULL }, { , , 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } void append_number_name(GString* gstr, integer n, bool ordinal) { if (n < 20) g_string_append(gstr, get_small_name(&small[n], ordinal)); else if (n < 100) { if (n % 10 == 0) { g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal)); } else { g_string_append(gstr, get_small_name(&tens[n/10 - 2], false)); g_string_append_c(gstr, '-'); g_string_append(gstr, get_small_name(&small[n % 10], ordinal)); } } else { const named_number* num = get_named_number(n); integer p = num->number; append_number_name(gstr, n/p, false); g_string_append_c(gstr, ' '); if (n % p == 0) { g_string_append(gstr, get_big_name(num, ordinal)); } else { g_string_append(gstr, get_big_name(num, false)); g_string_append_c(gstr, ' '); append_number_name(gstr, n % p, ordinal); } } } GString* number_name(integer n, bool ordinal) { GString* result = g_string_sized_new(8); append_number_name(result, n, ordinal); return result; } void test_ordinal(integer n) { GString* name = number_name(n, true); printf(, n, name->str); g_string_free(name, TRUE); } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
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 ((squareOnlyCount < 30) || (squareCubeCount < 3)) { long sq = n * n; if (isPerfectCube(sq)) { squareCubeCount++; System.out.println("Square and cube: " + sq); } else { squareOnlyCount++; System.out.println("Square: " + sq); } n++; } } }
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 sxx += x*x n += 1 sd = (n * sxx - sx*sx)**0.5 / n return sd, sx / n else: return 0, 0 def histogram(numbers): h = [0] * 10 maxwidth = 50 for n in numbers: h[int(n*10)] += 1 mx = max(h) print() for n, i in enumerate(h): print('%3.1f:%s'% (n / 10, '+' * int(i / mx * maxwidth))) print() if __name__ == '__main__': import random for i in range(1, 6): n = [random.random() for j in range(10**i)] print(% 10**i) print(' Naive method: sd:%8.6f, mean:%8.6f'% sd1(n)) print(' Second method: sd:%8.6f, mean:%8.6f'% sd2(n)) histogram(n)
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=100; j=match(i,V); cat(i,"@",j,"\n"); V=SternBrocot(1000); j=1; for (i in 2:1000) {j=j*gcd(V[i-1],V[i])} if(j==1) {cat(" *** All GCDs=1!\n")} else {cat(" *** All GCDs!=1??\n")} }
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) })` ) : '' ), map(x => x * x, enumFromTo(1, 33)) ));
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: ", sd(c)) cat("Mean of d: ",mean(d)) cat("Standard Deviation of d: ", sd(d)) hist(d) cat("Mean of a trillion random values in the range [0,1]: ",mean(runif(10^12,min=0,max=1))) cat("Standard Deviation of a trillion random values in the range [0,1]: ", sd(runif(10^12,min=0,max=1)))
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) rest)) fst)) (defn top-stack "Shows what's on the top of the stack." [] (first (deref (:elements stack)))) (defn empty-stack? "Tests whether or not the stack is empty." [] (= () (deref (: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", "nine": "ninth", "twelve": "twelfth", } func sayOrdinal(n int64) string { s := say(n) i := strings.LastIndexAny(s, " -") i++
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 end [100, 1000, 10000].each {|n| generate_statistics n}
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" (k, m) -> spellInteger (100*k) ++ " and " ++ spellOrdinal m | otherwise = case divMod n 1000 of (k, 0) -> spellInteger (1000*k) ++ "th" (k, m) -> spellInteger (k*1000) ++ s ++ spellOrdinal m where s = if m < 100 then " and " else ", " where small = ([ undefined, "first", "second", "third", "fourth", "fifth" , "sixth", "seventh", "eighth", "nineth", "tenth", "eleventh" , "twelveth", "thirteenth", "fourteenth", "fifteenth", "sixteenth" , "seventeenth", "eighteenth", "nineteenth"] !!) . fromEnum
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<f32> { if data.is_empty() { None } else { let mean = mean(data).unwrap(); let mut sum = 0f32; for &x in data { sum += (x - mean).powi(2); } Some(sum / data.len() as f32) } } pub fn standard_deviation(data: &[f32]) -> Option<f32> { if data.is_empty() { None } else { let variance = variance(data).unwrap(); Some(variance.sqrt()) } } fn print_histogram(width: u32, data: &[f32]) { let mut histogram = [0; 10]; let len = histogram.len() as f32; for &x in data { histogram[(x * len) as usize] += 1; } let max_frequency = *histogram.iter().max().unwrap() as f32; for (i, &frequency) in histogram.iter().enumerate() { let bar_width = frequency as f32 * width as f32 / max_frequency; print!("{:3.1}: ", i as f32 / len); for _ in 0..bar_width as usize { print!("*"); } println!(""); } } fn main() { let range = Range::new(0f32, 1f32); let mut rng = rand::thread_rng(); for &number_of_samples in [1000, 10_000, 1_000_000].iter() { let mut data = vec![]; for _ in 0..number_of_samples { let x = range.ind_sample(&mut rng); data.push(x); } println!(" Statistics for sample size {}", number_of_samples); println!("Mean: {:?}", mean(&data)); println!("Variance: {:?}", variance(&data)); println!("Standard deviation: {:?}", standard_deviation(&data)); print_histogram(40, &data); } }
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(resultStrings); System.out.println(output); } } public static List<String> splitStringByCharacter(String string){ List<String> resultStrings = new ArrayList<>(); StringBuilder currentString = new StringBuilder(); for (int pointer = 0; pointer < string.length(); pointer++){ currentString.append(string.charAt(pointer)); if (pointer == string.length() - 1 || currentString.charAt(0) != string.charAt(pointer + 1)) { resultStrings.add(currentString.toString()); currentString = new StringBuilder(); } } return resultStrings; } public static String formatList(List<String> list){ StringBuilder output = new StringBuilder(); for (int pointer = 0; pointer < list.size(); pointer++){ output.append(list.get(pointer)); if (pointer != list.size() - 1){ output.append(", "); } } return output.toString(); } }
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)); } } private static Map<String,String> ordinalMap = new HashMap<>(); static { ordinalMap.put("one", "first"); ordinalMap.put("two", "second"); ordinalMap.put("three", "third"); ordinalMap.put("five", "fifth"); ordinalMap.put("eight", "eighth"); ordinalMap.put("nine", "ninth"); ordinalMap.put("twelve", "twelfth"); } private static String toOrdinal(long n) { String spelling = numToString(n); String[] split = spelling.split(" "); String last = split[split.length - 1]; String replace = ""; if ( last.contains("-") ) { String[] lastSplit = last.split("-"); String lastWithDash = lastSplit[1]; String lastReplace = ""; if ( ordinalMap.containsKey(lastWithDash) ) { lastReplace = ordinalMap.get(lastWithDash); } else if ( lastWithDash.endsWith("y") ) { lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth"; } else { lastReplace = lastWithDash + "th"; } replace = lastSplit[0] + "-" + lastReplace; } else { if ( ordinalMap.containsKey(last) ) { replace = ordinalMap.get(last); } else if ( last.endsWith("y") ) { replace = last.substring(0, last.length() - 1) + "ieth"; } else { replace = last + "th"; } } split[split.length - 1] = replace; return String.join(" ", split); } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String numToString(long n) { return numToStringHelper(n); } private static final String numToStringHelper(long n) { if ( n < 0 ) { return "negative " + numToStringHelper(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : ""); } }
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 => (v._1, v._2.size)) } def printHist(a:Array[Double])=for((g,v) <- hist(a)){ println(s"$g: ${"*"*(205*v/a.size)} $v") } for(n <- Seq(100,1000,10000)){ val a = Array.fill(n)(Random.nextDouble) println(s"$n numbers") println(s"Mean: ${mean(a)}") println(s"StdDev: ${stddev(a)}") printHist(a) println }
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, abi, dee, eve, fay, bea, jan, ivy, gay }, { hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan }, { ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi }, { jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay }, { bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay }, { gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay }, { abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee }, { hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve }, { abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope }, { bob, fred, jon, gav, ian, abe, dan, ed, col, hal }, { bob, abe, col, fred, gav, dan, ian, ed, jon, hal }, { fred, bob, ed, gav, hal, col, ian, abe, dan, jon }, { fred, jon, col, abe, ian, hal, gav, dan, bob, ed }, { jon, hal, fred, dan, abe, gav, col, ed, ian, bob }, { bob, abe, ed, ian, jon, dan, fred, gav, col, hal }, { jon, gav, hal, fred, bob, abe, col, ed, dan, ian }, { gav, jon, bob, abe, ian, dan, hal, ed, col, fred }, { ian, col, hal, gav, fred, bob, abe, ed, jon, dan }, { ed, hal, gav, abe, bob, jon, col, ian, fred, dan }, }; int pairs[jan + 1], proposed[jan + 1]; void engage(int man, int woman) { pairs[man] = woman; pairs[woman] = man; if (verbose) printf(, name[man], name[woman]); } void dump(int woman, int man) { pairs[man] = pairs[woman] = clown; if (verbose) printf(, name[woman], name[man]); } int rank(int this, int that) { int i; for (i = abe; i <= jon && pref[this][i] != that; i++); return i; } void propose(int man, int woman) { int fiance = pairs[woman]; if (verbose) printf(, name[man], name[woman]); if (fiance == clown) { engage(man, woman); } else if (rank(woman, man) < rank(woman, fiance)) { dump(woman, fiance); engage(man, woman); } } int covet(int man1, int wife2) { if (rank(man1, wife2) < rank(man1, pairs[man1]) && rank(wife2, man1) < rank(wife2, pairs[wife2])) { printf( , name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]] ); return 1; } return 0; } int thy_neighbors_wife(int man1, int man2) { return covet(man1, pairs[man2]) + covet(man2, pairs[man1]); } int unstable() { int i, j, bad = 0; for (i = abe; i < jon; i++) { for (j = i + 1; j <= jon; j++) if (thy_neighbors_wife(i, j)) bad = 1; } return bad; } int main() { int i, unengaged; for (i = abe; i <= jan; i++) pairs[i] = proposed[i] = clown; do { unengaged = 0; for (i = abe; i <= jon; i++) { if (pairs[i] != clown) continue; unengaged = 1; propose(i, pref[i][++proposed[i]]); } } while (unengaged); printf(); for (i = abe; i <= jon; i++) printf(, name[i], pairs[i] == clown ? : name[pairs[i]]); printf(unstable() ? : ); printf(); i = pairs[bob]; engage(bob, pairs[fred]); engage(fred, i); printf(unstable() ? : ); return 0; }
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(charSplit("gHHH5YY++///\\"))
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] in irregularOrdinals: num[-1] = delim + irregularOrdinals[num[-1]] elif num[-1].endswith(): num[-1] = delim + num[-1][:-1] + else: num[-1] = delim + num[-1] + return .join(num) if __name__ == : tests = .split() for num in tests: print(.format(num, num2ordinal(num))) TENS = [None, None, , , , , , , , ] SMALL = [, , , , , , , , , , , , , , , , , , , ] HUGE = [None, None] + [h + for h in (, , , , , , , , , )] def nonzero(c, n, connect=''): return if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + else: return spell_integer(n) + + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero(, b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + + nonzero(, b, ' and') else: num = .join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num)
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 "$_ " for sort { $a <=> $b } grep { $h{$_} == 0 } keys %h;
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) } print("First 15: \(Array(SternBrocot().prefix(15)))") var found = Set<Int>() for (i, val) in SternBrocot().enumerated() { switch val { case 1...10 where!found.contains(val), 100 where!found.contains(val): print("First \(val) at \(i + 1)") found.insert(val) case _: continue } if found.count == 11 { break } } let firstThousand = SternBrocot().prefix(1000) let gcdIsOne = zip(firstThousand, firstThousand.dropFirst()).allSatisfy({ gcd($0.0, $0.1) == 1 }) print("GCDs of all two consecutive members are \(gcdIsOne? "": "not")one")
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 # cset - ASCII character set &clock # string - time of day &col # integer(=G) - column location of pointer &collections # integer(*) - garbage collection activity in total and by storage region &column # integer(U) - source code column &control # null(?G) - control key state &cset # cset - universal character set &current # co-expression - current co-expression &date # string - today's date &dateline # string - time stamp &digits # cset - digit characters &dump # integer(=) - termination dump &e # real - natural log e &error # integer(=) - enable/disable error conversion/fail on error &errno # integer(?) - variable containing error number from previous posix command &errornumber # integer(?) - error number of last error converted to failure &errortext # string(?) - error message of last error converted to failure &errorvalue # any(?) - erroneous value of last error converted to failure &errout # file - standard error file &eventcode # integer(=U) - program execution event in monitored program &eventsource # co-expression(=U) - source of events in monitoring program &eventvalue # any(=U) - value from event in monitored program &fail # none - always fails &features # string(*) - identifying features in this version of Icon/Unicon &file # string - current source file &host # string - host machine name &input # file - standard input file &interval # integer(G) - time between input events &lcase # cset - lowercase letters &ldrag # integer(G) - left button drag &letters # cset - letters &level # integer - call depth &line # integer - current source line number &lpress # integer(G) - left button press &lrelease # integer(G) - left button release &main # co-expression - main task &mdrag # integer(G) - middle button drag &meta # null(?G) - meta key state &mpress # integer(G) - middle button press &mrelease # integer(G) - middle button release &now # integer(U) - current time &null # null - null value &output # file - standard output file &pick # string (U) - variable containing the result of 3D selection &phi # real - golden ratio &pos # integer(=) - string scanning position &progname # string(=) - program name &random # integer(=) - random number seed &rdrag # integer(G) - right button drag &regions # integer(*) - region sizes &resize # integer(G) - window resize &row # integer(=G) - row location of pointer &rpress # integer(G) - right button press &rrelease # integer(G) - right button release &shift # null(?G) - shift key state &source # co-expression - invoking co-expression &storage # integer(*) - memory in use in each region &subject # string - string scanning subject &syserr # integer - halt on system error &time # integer(=) - elapsed time in milliseconds &trace # integer(=) - trace program &ucase # cset - upper case letters &version # string - version &window # window(=G) - the current graphics rendering window &x # integer(=G) - pointer horizontal position &y # integer(=G) - pointer vertical position # keywords may also fail if the corresponding feature is not present. # Other variants of Icon (e.g. MT-Icon) will have different mixes of keywords.
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; } return e; } void join(slist *a, slist *b) { push(a, b->head); a->tail = b->tail; } void merge(slist *a, slist *b) { slist r = {0}; while (a->head && b->head) push(&r, removehead(a->head->v <= b->head->v ? a : b)); join(&r, a->head ? a : b); *a = r; b->head = b->tail = 0; } void sort(int *ar, int len) { node_t all[len]; for (int i = 0; i < len; i++) all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0; slist list = {all, all + len - 1}, rem, strand = {0}, res = {0}; for (node e = 0; list.head; list = rem) { rem.head = rem.tail = 0; while ((e = removehead(&list))) push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e); merge(&res, &strand); } for (int i = 0; res.head; i++, res.head = res.head->next) ar[i] = res.head->v; } void show(const char *title, int *x, int len) { printf(, title); for (int i = 0; i < len; i++) printf(, x[i]); putchar('\n'); } int main(void) { int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2}; show(, x, SIZE); sort(x, sizeof(x)/sizeof(int)); show(, x, SIZE); return 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 { cardinal: "zero", ordinal: "zeroth", }, NumberNames { cardinal: "one", ordinal: "first", }, NumberNames { cardinal: "two", ordinal: "second", }, NumberNames { cardinal: "three", ordinal: "third", }, NumberNames { cardinal: "four", ordinal: "fourth", }, NumberNames { cardinal: "five", ordinal: "fifth", }, NumberNames { cardinal: "six", ordinal: "sixth", }, NumberNames { cardinal: "seven", ordinal: "seventh", }, NumberNames { cardinal: "eight", ordinal: "eighth", }, NumberNames { cardinal: "nine", ordinal: "ninth", }, NumberNames { cardinal: "ten", ordinal: "tenth", }, NumberNames { cardinal: "eleven", ordinal: "eleventh", }, NumberNames { cardinal: "twelve", ordinal: "twelfth", }, NumberNames { cardinal: "thirteen", ordinal: "thirteenth", }, NumberNames { cardinal: "fourteen", ordinal: "fourteenth", }, NumberNames { cardinal: "fifteen", ordinal: "fifteenth", }, NumberNames { cardinal: "sixteen", ordinal: "sixteenth", }, NumberNames { cardinal: "seventeen", ordinal: "seventeenth", }, NumberNames { cardinal: "eighteen", ordinal: "eighteenth", }, NumberNames { cardinal: "nineteen", ordinal: "nineteenth", }, ]; const TENS: [NumberNames; 8] = [ NumberNames { cardinal: "twenty", ordinal: "twentieth", }, NumberNames { cardinal: "thirty", ordinal: "thirtieth", }, NumberNames { cardinal: "forty", ordinal: "fortieth", }, NumberNames { cardinal: "fifty", ordinal: "fiftieth", }, NumberNames { cardinal: "sixty", ordinal: "sixtieth", }, NumberNames { cardinal: "seventy", ordinal: "seventieth", }, NumberNames { cardinal: "eighty", ordinal: "eightieth", }, NumberNames { cardinal: "ninety", ordinal: "ninetieth", }, ]; struct NamedNumber { cardinal: &'static str, ordinal: &'static str, number: usize, } impl NamedNumber { fn get_name(&self, ordinal: bool) -> &'static str { if ordinal { return self.ordinal; } self.cardinal } } const N: usize = 7; const NAMED_NUMBERS: [NamedNumber; N] = [ NamedNumber { cardinal: "hundred", ordinal: "hundredth", number: 100, }, NamedNumber { cardinal: "thousand", ordinal: "thousandth", number: 1000, }, NamedNumber { cardinal: "million", ordinal: "millionth", number: 1000000, }, NamedNumber { cardinal: "billion", ordinal: "billionth", number: 1000000000, }, NamedNumber { cardinal: "trillion", ordinal: "trillionth", number: 1000000000000, }, NamedNumber { cardinal: "quadrillion", ordinal: "quadrillionth", number: 1000000000000000, }, NamedNumber { cardinal: "quintillion", ordinal: "quintillionth", number: 1000000000000000000, }, ]; fn big_name(n: usize) -> &'static NamedNumber { for i in 1..N { if n < NAMED_NUMBERS[i].number { return &NAMED_NUMBERS[i - 1]; } } &NAMED_NUMBERS[N - 1] } fn number_name(n: usize, ordinal: bool) -> String { if n < 20 { return String::from(SMALL_NAMES[n].get_name(ordinal)); } else if n < 100 { if n% 10 == 0 { return String::from(TENS[n / 10 - 2].get_name(ordinal)); } let s1 = TENS[n / 10 - 2].get_name(false); let s2 = SMALL_NAMES[n% 10].get_name(ordinal); return format!("{}-{}", s1, s2); } let big = big_name(n); let mut result = number_name(n / big.number, false); result.push(' '); if n% big.number == 0 { result.push_str(big.get_name(ordinal)); } else { result.push_str(big.get_name(false)); result.push(' '); result.push_str(&number_name(n% big.number, ordinal)); } result } fn test_ordinal(n: usize) { println!("{}: {}", n, number_name(n, true)); } fn main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003); }
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 # cset - ASCII character set &clock # string - time of day &col # integer(=G) - column location of pointer &collections # integer(*) - garbage collection activity in total and by storage region &column # integer(U) - source code column &control # null(?G) - control key state &cset # cset - universal character set &current # co-expression - current co-expression &date # string - today's date &dateline # string - time stamp &digits # cset - digit characters &dump # integer(=) - termination dump &e # real - natural log e &error # integer(=) - enable/disable error conversion/fail on error &errno # integer(?) - variable containing error number from previous posix command &errornumber # integer(?) - error number of last error converted to failure &errortext # string(?) - error message of last error converted to failure &errorvalue # any(?) - erroneous value of last error converted to failure &errout # file - standard error file &eventcode # integer(=U) - program execution event in monitored program &eventsource # co-expression(=U) - source of events in monitoring program &eventvalue # any(=U) - value from event in monitored program &fail # none - always fails &features # string(*) - identifying features in this version of Icon/Unicon &file # string - current source file &host # string - host machine name &input # file - standard input file &interval # integer(G) - time between input events &lcase # cset - lowercase letters &ldrag # integer(G) - left button drag &letters # cset - letters &level # integer - call depth &line # integer - current source line number &lpress # integer(G) - left button press &lrelease # integer(G) - left button release &main # co-expression - main task &mdrag # integer(G) - middle button drag &meta # null(?G) - meta key state &mpress # integer(G) - middle button press &mrelease # integer(G) - middle button release &now # integer(U) - current time &null # null - null value &output # file - standard output file &pick # string (U) - variable containing the result of 3D selection &phi # real - golden ratio &pos # integer(=) - string scanning position &progname # string(=) - program name &random # integer(=) - random number seed &rdrag # integer(G) - right button drag &regions # integer(*) - region sizes &resize # integer(G) - window resize &row # integer(=G) - row location of pointer &rpress # integer(G) - right button press &rrelease # integer(G) - right button release &shift # null(?G) - shift key state &source # co-expression - invoking co-expression &storage # integer(*) - memory in use in each region &subject # string - string scanning subject &syserr # integer - halt on system error &time # integer(=) - elapsed time in milliseconds &trace # integer(=) - trace program &ucase # cset - upper case letters &version # string - version &window # window(=G) - the current graphics rendering window &x # integer(=G) - pointer horizontal position &y # integer(=G) - pointer vertical position # keywords may also fail if the corresponding feature is not present. # Other variants of Icon (e.g. MT-Icon) will have different mixes of keywords.
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-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf(,max,min,max-min); setlocale(LC_ALL, ); for(i=1;i<argC;i++){ printf(, (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
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 "Separates a sorted list from a sequence" [u] (when (seq u) (loop [[x & xs] u u [] s [] e x] (if (nil? x) [s u] (if (>= x e) (recur xs u (conj s x) x) (recur xs (conj u x) s e)))))) (defn strand-sort "http://en.wikipedia.org/wiki/Strand_sort" [s] (loop [[s u] (unbraid s) m nil] (if s (recur (unbraid u) (merge-join m s)) m))) (strand-sort [1, 6, 3, 2, 1, 7, 5, 3])
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 numberName(number: Int, ordinal: Bool) -> String { guard number < 100 else { return "" } if number < 20 { return smallNames[number].getName(ordinal) } if number% 10 == 0 { return tens[number/10 - 2].getName(ordinal) } var result = tens[number/10 - 2].getName(false) result += "-" result += smallNames[number% 10].getName(ordinal) return result } static let smallNames = [ NumberNames(cardinal: "zero", ordinal: "zeroth"), NumberNames(cardinal: "one", ordinal: "first"), NumberNames(cardinal: "two", ordinal: "second"), NumberNames(cardinal: "three", ordinal: "third"), NumberNames(cardinal: "four", ordinal: "fourth"), NumberNames(cardinal: "five", ordinal: "fifth"), NumberNames(cardinal: "six", ordinal: "sixth"), NumberNames(cardinal: "seven", ordinal: "seventh"), NumberNames(cardinal: "eight", ordinal: "eighth"), NumberNames(cardinal: "nine", ordinal: "ninth"), NumberNames(cardinal: "ten", ordinal: "tenth"), NumberNames(cardinal: "eleven", ordinal: "eleventh"), NumberNames(cardinal: "twelve", ordinal: "twelfth"), NumberNames(cardinal: "thirteen", ordinal: "thirteenth"), NumberNames(cardinal: "fourteen", ordinal: "fourteenth"), NumberNames(cardinal: "fifteen", ordinal: "fifteenth"), NumberNames(cardinal: "sixteen", ordinal: "sixteenth"), NumberNames(cardinal: "seventeen", ordinal: "seventeenth"), NumberNames(cardinal: "eighteen", ordinal: "eighteenth"), NumberNames(cardinal: "nineteen", ordinal: "nineteenth") ] static let tens = [ NumberNames(cardinal: "twenty", ordinal: "twentieth"), NumberNames(cardinal: "thirty", ordinal: "thirtieth"), NumberNames(cardinal: "forty", ordinal: "fortieth"), NumberNames(cardinal: "fifty", ordinal: "fiftieth"), NumberNames(cardinal: "sixty", ordinal: "sixtieth"), NumberNames(cardinal: "seventy", ordinal: "seventieth"), NumberNames(cardinal: "eighty", ordinal: "eightieth"), NumberNames(cardinal: "ninety", ordinal: "ninetieth") ] } fileprivate class NamedPower { let cardinal: String let ordinal: String let number: UInt64 init(cardinal: String, ordinal: String, number: UInt64) { self.cardinal = cardinal self.ordinal = ordinal self.number = number } func getName(_ ordinal: Bool) -> String { return ordinal? self.ordinal: self.cardinal } class func getNamedPower(_ number: UInt64) -> NamedPower { for i in 1..<namedPowers.count { if number < namedPowers[i].number { return namedPowers[i - 1] } } return namedPowers[namedPowers.count - 1] } static let namedPowers = [ NamedPower(cardinal: "hundred", ordinal: "hundredth", number: 100), NamedPower(cardinal: "thousand", ordinal: "thousandth", number: 1000), NamedPower(cardinal: "million", ordinal: "millionth", number: 1000000), NamedPower(cardinal: "billion", ordinal: "billionth", number: 1000000000), NamedPower(cardinal: "trillion", ordinal: "trillionth", number: 1000000000000), NamedPower(cardinal: "quadrillion", ordinal: "quadrillionth", number: 1000000000000000), NamedPower(cardinal: "quintillion", ordinal: "quintillionth", number: 1000000000000000000) ] } public func numberName(number: UInt64, ordinal: Bool) -> String { if number < 100 { return NumberNames.numberName(number: Int(truncatingIfNeeded: number), ordinal: ordinal) } let p = NamedPower.getNamedPower(number) var result = numberName(number: number/p.number, ordinal: false) result += " " if number% p.number == 0 { result += p.getName(ordinal) } else { result += p.getName(false) result += " " result += numberName(number: number% p.number, ordinal: ordinal) } return result } func printOrdinal(_ number: UInt64) { print("\(number): \(numberName(number: number, ordinal: true))") } printOrdinal(1) printOrdinal(2) printOrdinal(3) printOrdinal(4) printOrdinal(5) printOrdinal(11) printOrdinal(15) printOrdinal(21) printOrdinal(42) printOrdinal(65) printOrdinal(98) printOrdinal(100) printOrdinal(101) printOrdinal(272) printOrdinal(300) printOrdinal(750) printOrdinal(23456) printOrdinal(7891233) printOrdinal(8007006005004003)
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(xs))))(' ') justifySqr = justifyRight(1 + len(str(xs[-1][0])))(' ') return list( '(' + str(1 + idx) + '^2 = ' + str(n) + ' = ' + str(round(n ** (1 / 3))) + '^3)' if bln else ( justifyIdx(1 + idx) + ' ->' + justifySqr(n) ) for idx, (n, bln) in enumerate(xs) ) def main(): print( unlines( squareListing( nonCubeSquares(30) ) ) ) def enumFromTo(m): return lambda n: list(range(m, 1 + n)) def justifyRight(n): return lambda cFiller: lambda a: ( ((n * cFiller) + str(a))[-n:] ) def unlines(xs): return '\n'.join(xs) main()
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: " . join(', ', @S) . "\n"; }
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; for (i = j = 0; valid(i, j); i += dy, j += dx ) { for (; valid(i, j); j += dx, i += dy) s[i][j] = ++val; j -= dx; i -= dy; t = dy; dy = dx; dx = -t; } for (t = 2; val /= 10; t++); for(i = 0; i < m; i++) for(j = 0; j < n || !putchar('\n'); j++) printf(, t, s[i][j]); return 0; }
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 (str "[" line "]"))] (println (sparkline nums)) (recur (read-line))))) (spark (read-line))
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 -= thisGuy List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] } for(Woman girl in guyChoices) { if(! engagedTo[girl]) { engagedTo[girl] = thisGuy break } else { Man thatGuy = engagedTo[girl] if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) { engagedTo[girl] = thisGuy freeGuys << thatGuy break } } } } engagedTo }
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.next; l != nil; l = l.next { r = fmt.Sprintf("%s%d", r, l.int) } return r + "]" } func main() { a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66}) fmt.Println("before:", a) b := strandSort(a) fmt.Println("after: ", b) } func strandSort(a *link) (result *link) { for a != nil {
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 = squit.next c = cuit.next while (squares.length < 30 || hexponents.length < 3) if s < c squares.push(s) if squares.length < 30 s = squit.next elsif s == c hexponents.push(s) if hexponents.length < 3 s = squit.next c = cuit.next else c = cuit.next end end puts puts squares.join() puts puts hexponents.join()
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-format true (str " ~{~<~%~," (* n 3) ": (spiral n)))
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 extractStrand x [] = ([x], []) extractStrand x (x1: xs) | x <= x1 = let (strand, rest) = extractStrand x1 xs in (x: strand, rest) | otherwise = let (strand, rest) = extractStrand x xs in (strand, x1: rest)
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); } else { println!("{}", square); n += 1; } s += 1; } }
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.pow(2) == n)
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", "gay", "hope", "ivy", "jan"}); static Map<String, List<String>> guyPrefers = new HashMap<String, List<String>>(){{ put("abe", Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay")); put("bob", Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay")); put("col", Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan")); put("dan", Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi")); put("ed", Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay")); put("fred", Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay")); put("gav", Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay")); put("hal", Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee")); put("ian", Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve")); put("jon", Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope")); }}; static Map<String, List<String>> girlPrefers = new HashMap<String, List<String>>(){{ put("abi", Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal")); put("bea", Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal")); put("cath", Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon")); put("dee", Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed")); put("eve", Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob")); put("fay", Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal")); put("gay", Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian")); put("hope", Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred")); put("ivy", Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan")); put("jan", Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan")); }}; public static void main(String[] args){ Map<String, String> matches = match(guys, guyPrefers, girlPrefers); for(Map.Entry<String, String> couple:matches.entrySet()){ System.out.println( couple.getKey() + " is engaged to " + couple.getValue()); } if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){ System.out.println("Marriages are stable"); }else{ System.out.println("Marriages are unstable"); } String tmp = matches.get(girls.get(0)); matches.put(girls.get(0), matches.get(girls.get(1))); matches.put(girls.get(1), tmp); System.out.println( girls.get(0) +" and " + girls.get(1) + " have switched partners"); if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){ System.out.println("Marriages are stable"); }else{ System.out.println("Marriages are unstable"); } } private static Map<String, String> match(List<String> guys, Map<String, List<String>> guyPrefers, Map<String, List<String>> girlPrefers){ Map<String, String> engagedTo = new TreeMap<String, String>(); List<String> freeGuys = new LinkedList<String>(); freeGuys.addAll(guys); while(!freeGuys.isEmpty()){ String thisGuy = freeGuys.remove(0);
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] { let temp_result: String = chars[last_mismatch..i].iter().collect(); result.push(temp_result); last_mismatch = i; } if i == chars.len() - 1 { let temp_result: String = chars[last_mismatch..chars.len()].iter().collect(); result.push(temp_result); } } result.join(", ") } fn main() { let test_string = "g"; println!("input string: {}", test_string); println!("output string: {}", splitter(test_string)); let test_string = ""; println!("input string: {}", test_string); println!("output string: {}", splitter(test_string)); let test_string = "gHHH5YY++
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 { fmt.Println(err) return } if n == 1 { fmt.Println("1 value =", min) } else { fmt.Println(n, "values. Min:", min, "Max:", max) } fmt.Println(s) } var sep = regexp.MustCompile(`[\s,]+`) func spark(s0 string) (sp string, n int, min, max float64, err error) { ss := sep.Split(s0, -1) n = len(ss) vs := make([]float64, n) var v float64 min = math.Inf(1) max = math.Inf(-1) for i, s := range ss { switch v, err = strconv.ParseFloat(s, 64); { case err != nil: case math.IsNaN(v): err = errors.New("NaN not supported.") case math.IsInf(v, 0): err = errors.New("Inf not supported.") default: if v < min { min = v } if v > max { max = v } vs[i] = v continue } return } if min == max { sp = strings.Repeat("", n) } else { rs := make([]rune, n) f := 8 / (max - min) for j, v := range vs { i := rune(f * (v - min)) if i > 7 { i = 7 } rs[j] = '' + i } sp = string(rs) } return }
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.prefers = function(p) { return this.rank(p) < this.rank(this.fiance); } this.nextCandidate = function() { if (candidateIndex >= this.candidates.length) return null; return this.candidates[candidateIndex++]; } this.engageTo = function(p) { if (p.fiance) p.fiance.fiance = null; p.fiance = this; if (this.fiance) this.fiance.fiance = null; this.fiance = p; } this.swapWith = function(p) { console.log("%s &%s swap partners", this.name, p.name); var thisFiance = this.fiance; var pFiance = p.fiance; this.engageTo(pFiance); p.engageTo(thisFiance); } } function isStable(guys, gals) { for (var i = 0; i < guys.length; i++) for (var j = 0; j < gals.length; j++) if (guys[i].prefers(gals[j]) && gals[j].prefers(guys[i])) return false; return true; } function engageEveryone(guys) { var done; do { done = true; for (var i = 0; i < guys.length; i++) { var guy = guys[i]; if (!guy.fiance) { done = false; var gal = guy.nextCandidate(); if (!gal.fiance || gal.prefers(guy)) guy.engageTo(gal); } } } while (!done); } function doMarriage() { var abe = new Person("Abe"); var bob = new Person("Bob"); var col = new Person("Col"); var dan = new Person("Dan"); var ed = new Person("Ed"); var fred = new Person("Fred"); var gav = new Person("Gav"); var hal = new Person("Hal"); var ian = new Person("Ian"); var jon = new Person("Jon"); var abi = new Person("Abi"); var bea = new Person("Bea"); var cath = new Person("Cath"); var dee = new Person("Dee"); var eve = new Person("Eve"); var fay = new Person("Fay"); var gay = new Person("Gay"); var hope = new Person("Hope"); var ivy = new Person("Ivy"); var jan = new Person("Jan"); abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]; bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]; col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]; dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]; ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]; fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]; gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]; hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]; ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]; jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]; abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]; bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]; cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]; dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]; eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]; fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]; gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]; hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]; ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]; jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]; var guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]; var gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]; engageEveryone(guys); for (var i = 0; i < guys.length; i++) { console.log("%s is engaged to%s", guys[i].name, guys[i].fiance.name); } console.log("Stable =%s", isStable(guys, gals) ? "Yes" : "No"); jon.swapWith(fred); console.log("Stable =%s", isStable(guys, gals) ? "Yes" : "No"); } doMarriage();
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