code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
library(gWidgets) options(guiToolkit="RGtk2") w <- gwindow("Interaction") g <- ggroup(cont=w, horizontal=FALSE) e <- gedit(0, cont=g, coerce.with=as.numeric) bg <- ggroup(cont=g) inc_btn <- gbutton("increment", cont=bg) rdm_btn <- gbutton("random", cont=bg) addHandlerChanged(e, handler=function(h,...) { val <- svalue(e) if(is.na(val)) galert("You need to enter a number", parent=w) }) addHandlerChanged(inc_btn, handler=function(h,...) { val <- svalue(e) if(is.na(val)) galert("Can't increment if not a number", parent=w) else svalue(e) <- val + 1 }) addHandlerChanged(rdm_btn, handler=function(h,...) { if(gconfirm("Really replace value?")) svalue(e) <- sample(1:1000, 1) })
770GUI component interaction
13r
ualvx
Shoes.app(title: ) do stack do textbox = edit_line textbox.change do textbox.text = textbox.text.gsub(/[^\d]/, '') and alert if textbox.text!~ /^\d*$/ end flow do button do textbox.text = textbox.text.to_i + 1 end button do textbox.text = rand 5000 if confirm end end end end
770GUI component interaction
14ruby
j0g7x
char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len) { ptrdiff_t i; char *start = buf; while (start + len < buf_end) { for (i = 0; i < len; i++) if (start[i] != pat[i]) break; if (i == len) return (char *)start; start++; } return 0; } int replace(const char *from, const char *to, const char *fname) { struct stat st; int ret = 0; char *buf = 0, *start, *end; size_t len = strlen(from), nlen = strlen(to); int fd = open(fname, O_RDWR); if (fd == -1) bail(); if (fstat(fd, &st) == -1) bail(); if (!(buf = malloc(st.st_size))) bail(); if (read(fd, buf, st.st_size) != st.st_size) bail(); start = buf; end = find_match(start, buf + st.st_size, from, len); if (!end) goto done; ftruncate(fd, 0); lseek(fd, 0, 0); do { write(fd, start, end - start); write(fd, to, nlen); start = end + len; end = find_match(start, buf + st.st_size, from, len); } while (end); if (start < buf + st.st_size) write(fd, start, buf + st.st_size - start); done: if (fd != -1) close(fd); if (buf) free(buf); return ret; } int main() { const char *from = ; const char *to = ; const char * files[] = { , , }; int i; for (i = 0; i < sizeof(files)/sizeof(char*); i++) replace(from, to, files[i]); return 0; }
781Globally replace text in several files
5c
4wf5t
package raster import ( "math" "math/rand" )
775Grayscale image
0go
fuqd0
#!/usr/bin/perl use strict; # https:
778Go Fish
9java
t5wf9
import scala.swing._ class GreyscaleBars extends Component { override def paintComponent(g:Graphics2D)={ val barHeight=size.height>>2 for(run <- 0 to 3; colCount=8<<run){ val deltaX=size.width.toDouble/colCount val colBase=if (run%2==0) -255 else 0 for(x <- 0 until colCount){ val col=(colBase+(255.0/(colCount-1)*x).toInt).abs g.setColor(new Color(col,col,col)) val startX=(deltaX*x).toInt val endX=(deltaX*(x+1)).toInt g.fillRect(startX, barHeight*run, endX-startX, barHeight) } } } }
772Greyscale bars/Display
16scala
wzbes
my $min = 1; my $max = 99; my $guess = int(rand $max) + $min; my $tries = 0; print "=>> Think of a number between $min and $max and I'll guess it!\n Press <ENTER> when are you ready... "; <STDIN>; { do { $tries++; print "\n=>> My guess is: $guess Is your number higher, lower, or equal? (h/l/e)\n> "; my $score = <STDIN>; if ($max <= $min) { print "\nI give up...\n" and last; } elsif ($score =~ /^h/i) { $min = $guess + 1; } elsif ($score =~ /^l/i) { $max = $guess; } elsif ($score =~ /^e/i) { print "\nI knew it! It took me only $tries tries.\n" and last; } else { print "error: invalid score\n"; } $guess = int(($max + $min) / 2); } while(1); }
769Guess the number/With feedback (player)
2perl
lb9c5
import java.awt.* import javax.swing.* fun main(args: Array<String>) { JOptionPane.showMessageDialog(null, "Goodbye, World!")
767Hello world/Graphical
11kotlin
21vli
import scala.swing._ import scala.swing.Swing._ import scala.swing.event._ object Interact extends SimpleSwingApplication { def top = new MainFrame { title = "Rosetta Code >>> Task: component interaction | Language: Scala" val numberField = new TextField { text = "0"
770GUI component interaction
16scala
pnhbj
int main(int argc, char **argv) { if (argc < 2) return 1; FILE *fd; fd = popen(argv[1], ); if (!fd) return 1; char buffer[256]; size_t chread; size_t comalloc = 256; size_t comlen = 0; char *comout = malloc(comalloc); while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) { if (comlen + chread >= comalloc) { comalloc *= 2; comout = realloc(comout, comalloc); } memmove(comout + comlen, buffer, chread); comlen += chread; } fwrite(comout, 1, comlen, stdout); free(comout); pclose(fd); return 0; }
782Get system command output
5c
5enuk
module Bitmap.Gray(module Bitmap.Gray) where import Bitmap import Control.Monad.ST newtype Gray = Gray Int deriving (Eq, Ord) instance Color Gray where luminance (Gray x) = x black = Gray 0 white = Gray 255 toNetpbm = map $ toEnum . luminance fromNetpbm = map $ Gray . fromEnum netpbmMagicNumber _ = "P5" netpbmMaxval _ = "255" toGrayImage :: Color c => Image s c -> ST s (Image s Gray) toGrayImage = mapImage $ Gray . luminance
775Grayscale image
8haskell
4wm5s
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
783Gray code
5c
q6uxc
(defn hello-goodbye [& more] (doseq [file more] (spit file (.replace (slurp file) "Goodbye London!" "Hello New York!"))))
781Globally replace text in several files
6clojure
h8yjr
void convertToGrayscale(final BufferedImage image){ for(int i=0; i<image.getWidth(); i++){ for(int j=0; j<image.getHeight(); j++){ int color = image.getRGB(i,j); int alpha = (color >> 24) & 255; int red = (color >> 16) & 255; int green = (color >> 8) & 255; int blue = (color) & 255; final int lum = (int)(0.2126 * red + 0.7152 * green + 0.0722 * blue); alpha = (alpha << 24); red = (lum << 16); green = (lum << 8); blue = lum; color = alpha + red + green + blue; image.setRGB(i,j,color); } } }
775Grayscale image
9java
ckf9h
function toGray(img) { let cnv = document.getElementById("canvas"); let ctx = cnv.getContext('2d'); let imgW = img.width; let imgH = img.height; cnv.width = imgW; cnv.height = imgH; ctx.drawImage(img, 0, 0); let pixels = ctx.getImageData(0, 0, imgW, imgH); for (let y = 0; y < pixels.height; y ++) { for (let x = 0; x < pixels.width; x ++) { let i = (y * 4) * pixels.width + x * 4; let avg = (pixels.data[i] + pixels.data[i + 1] + pixels.data[i + 2]) / 3; pixels.data[i] = avg; pixels.data[i + 1] = avg; pixels.data[i + 2] = avg; } } ctx.putImageData(pixels, 0, 0, 0, 0, pixels.width, pixels.height); return cnv.toDataURL(); }
775Grayscale image
10javascript
5eyur
#!/usr/bin/perl use strict; # https:
778Go Fish
11kotlin
ocb8z
import 'dart:math'; final lb2of2 = 1.0; final lb2of3 = log(3.0) / log(2.0); final lb2of5 = log(5.0) / log(2.0); class Trival { final double log2; final int twos; final int threes; final int fives; Trival mul2() { return Trival(this.log2 + lb2of2, this.twos + 1, this.threes, this.fives); } Trival mul3() { return Trival(this.log2 + lb2of3, this.twos, this.threes + 1, this.fives); } Trival mul5() { return Trival(this.log2 + lb2of5, this.twos, this.threes, this.fives + 1); } @override String toString() { return this.log2.toString() + " " + this.twos.toString() + " " + this.threes.toString() + " " + this.fives.toString(); } const Trival(this.log2, this.twos, this.threes, this.fives); } Iterable<Trival> makeHammings() sync* { var one = Trival(0.0, 0, 0, 0); yield(one); var s532 = one.mul2(); var mrg = one.mul3(); var s53 = one.mul3().mul3();
780Hamming numbers
18dart
fu1dz
use ntheory qw/Pi/; sub asin { my $x = shift; atan2($x, sqrt(1-$x*$x)); } sub surfacedist { my($lat1, $lon1, $lat2, $lon2) = @_; my $radius = 6372.8; my $radians = Pi() / 180;; my $dlat = ($lat2 - $lat1) * $radians; my $dlon = ($lon2 - $lon1) * $radians; $lat1 *= $radians; $lat2 *= $radians; my $a = sin($dlat/2)**2 + cos($lat1) * cos($lat2) * sin($dlon/2)**2; my $c = 2 * asin(sqrt($a)); return $radius * $c; } my @BNA = (36.12, -86.67); my @LAX = (33.94, -118.4); printf "Distance:%.3f km\n", surfacedist(@BNA, @LAX);
766Haversine formula
2perl
3ryzs
(use '[clojure.java.shell:only [sh]]) (sh "echo" "Hello")
782Get system command output
6clojure
j037m
null
775Grayscale image
11kotlin
3g8z5
#!/usr/bin/perl use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle ); my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9; my $mebooks = my $youbooks = 0; my $me = substr $deck, 0, 2 * 9, ''; my $mepicks = join '', $me =~ /$pat/g; arrange($me); $mebooks++ while $me =~ s/($pat).\1.\1.\1.//; my $you = substr $deck, 0, 2 * 9, ''; my $youpicks = join '', $you =~ /$pat/g; arrange($you); $youbooks++ while $you =~ s/($pat).\1.\1.\1.//; while( $mebooks + $youbooks < 13 ) { play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 ); $mebooks + $youbooks == 13 and last; play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 ); } print "me $mebooks you $youbooks\n"; sub arrange { $_[0] = join '', sort $_[0] =~ /../g } sub human { my $have = shift =~ s/($pat).\K(?!\1)/ /gr; local $| = 1; my $pick; do { print "You have $have, enter request: "; ($pick) = lc(<STDIN>) =~ /$pat/g; } until $pick and $have =~ /$pick/; return $pick; } sub play { my ($me, $mb, $lastpicks, $you, $yb, $human) = @_; my $more = 1; while( arrange( $$me ), $more and $$mb + $$yb < 13 ) { # use Data::Dump 'dd'; dd \@_, "deck $deck"; if( $$me =~ s/($pat).\1.\1.\1.// ) { print "book of $&\n"; $$mb++; } elsif( $$me ) { my $pick = $human ? do { human($$me) } : do { my %picks; $picks{$_}++ for my @picks = $$me =~ /$pat/g; my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks; print "pick $pick\n"; $$lastpicks =~ s/$pick//g; $$lastpicks .= $pick; $pick; }; if( $$you =~ s/(?:$pick.)+// ) { $$me .= $&; } else { print "GO FISH!!\n"; $$me .= substr $deck, 0, 2, ''; $more = 0; } } elsif( $deck ) { $$me .= substr $deck, 0, 2, ''; } else { $more = 0; } } arrange( $$me ); }
778Go Fish
1lua
ilpot
package main import ( "fmt" "math/rand" "time" ) func main() { fmt.Print("Guess number from 1 to 10: ") rand.Seed(time.Now().Unix()) n := rand.Intn(10) + 1 for guess := n; ; fmt.Print("No. Try again: ") { switch _, err := fmt.Scan(&guess); { case err != nil: fmt.Println("\n", err, "\nSo, bye.") return case guess == n: fmt.Println("Well guessed!") return } } }
773Guess the number
0go
q6pxz
def random = new Random() def keyboard = new Scanner(System.in) def number = random.nextInt(10) + 1 println "Guess the number which is between 1 and 10: " def guess = keyboard.nextInt() while (number != guess) { println "Guess again: " guess = keyboard.nextInt() } println "Hurray! You guessed correctly!"
773Guess the number
7groovy
1d7p6
inclusive_range = mn, mx = (1, 10) print('''\ Think of a number between%i and%i and wait for me to guess it. On every guess of mine you should state whether the guess was too high, too low, or equal to your number by typing h, l, or = '''% inclusive_range) i = 0 while True: i += 1 guess = (mn+mx) txt = input( % (i, guess)).strip().lower()[0] if txt not in 'hl=': print(% txt) continue if txt == 'h': mx = guess-1 if txt == 'l': mn = guess+1 if txt == '=': print() break if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]): print() break print()
769Guess the number/With feedback (player)
3python
2pclz
class POI { private $latitude; private $longitude; public function __construct($latitude, $longitude) { $this->latitude = deg2rad($latitude); $this->longitude = deg2rad($longitude); } public function getLatitude() { return $this->latitude; } public function getLongitude() { return $this->longitude; } public function getDistanceInMetersTo(POI $other) { $radiusOfEarth = 6371; $diffLatitude = $other->getLatitude() - $this->latitude; $diffLongitude = $other->getLongitude() - $this->longitude; $a = sin($diffLatitude / 2) ** 2 + cos($this->latitude) * cos($other->getLatitude()) * sin($diffLongitude / 2) ** 2; $c = 2 * asin(sqrt($a)); $distance = $radiusOfEarth * $c; return $distance; } }
766Haversine formula
12php
pdaba
package main import "fmt" func main() { fmt.Println("Hello world!") }
755Hello world/Text
0go
qyyxz
require "iuplua" dlg = iup.dialog{iup.label{title="Goodbye, World!"}; title="test"} dlg:show() if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then iup.MainLoop() end
767Hello world/Graphical
1lua
vau2x
function ConvertToGrayscaleImage( bitmap ) local size_x, size_y = #bitmap, #bitmap[1] local gray_im = {} for i = 1, size_x do gray_im[i] = {} for j = 1, size_y do gray_im[i][j] = math.floor( 0.2126*bitmap[i][j][1] + 0.7152*bitmap[i][j][2] + 0.0722*bitmap[i][j][3] ) end end return gray_im end function ConvertToColorImage( gray_im ) local size_x, size_y = #gray_im, #gray_im[1] local bitmap = Allocate_Bitmap( size_x, size_y )
775Grayscale image
1lua
6ro39
import Control.Monad import System.Random until_ act pred = act >>= pred >>= flip unless (until_ act pred) answerIs ans guess | ans == guess = putStrLn "You got it!" >> return True | otherwise = putStrLn "Nope. Guess again." >> return False ask = liftM read getLine main = do ans <- randomRIO (1,10) :: IO Int putStrLn "Try to guess my secret number between 1 and 10." ask `until_` answerIs ans
773Guess the number
8haskell
mjfyf
guessANumberPlayer <- function(low, high) { boundryErrorCheck(low, high) repeat { guess <- floor(mean(c(low, high))) switch(guessResult(guess), l = low <- guess + 1, h = high <- guess - 1, c = return(paste0("Your number is ", guess, ".", " I win!"))) } } boundryErrorCheck <- function(low, high) { if(!is.numeric(low) || as.integer(low) != low) stop("Lower bound must be an integer. Try again.") if(!is.numeric(high) || as.integer(high) != high) stop("Upper bound must be an integer. Try again.") if(high < low) stop("Upper bound must be strictly greater than lower bound. Try again.") if(low == high) stop("This game is impossible to lose. Try again.") invisible() } guessResult <- function(guess) readline(paste0("My guess is ", guess, ". If it is too low, submit l. If it is too high, h. Otherwise, c. "))
769Guess the number/With feedback (player)
13r
mj6y4
package main import ( "fmt" "log" "os/exec" ) func main() { output, err := exec.Command("ls", "-l").CombinedOutput() if err != nil { log.Fatal(err) } fmt.Print(string(output)) }
782Get system command output
0go
89r0g
#!/usr/bin/env stack import System.Process (readProcess) main :: IO () main = do results <- lines <$> readProcess "hexdump" ["-C", "/etc/passwd"] "" mapM_ (putStrLn . reverse) results
782Get system command output
8haskell
lb0ch
package main import ( "bytes" "io/ioutil" "log" "os" ) func main() { gRepNFiles("Goodbye London!", "Hello New York!", []string{ "a.txt", "b.txt", "c.txt", }) } func gRepNFiles(olds, news string, files []string) { oldb := []byte(olds) newb := []byte(news) for _, fn := range files { if err := gRepFile(oldb, newb, fn); err != nil { log.Println(err) } } } func gRepFile(oldb, newb []byte, fn string) (err error) { var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } if bytes.Index(b, oldb) < 0 { return } r := bytes.Replace(b, oldb, newb, -1) if err = f.Truncate(0); err != nil { return } _, err = f.WriteAt(r, 0) return }
781Globally replace text in several files
0go
ocj8q
package main import "fmt" func gss(s []int) ([]int, int) { var best, start, end, sum, sumStart int for i, x := range s { sum += x switch { case sum > best: best = sum start = sumStart end = i + 1 case sum < 0: sum = 0 sumStart = i + 1 } } return s[start:end], best } var testCases = [][]int{ {-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1}, {-1, 1, 2, -5, -6}, {}, {-1, -2, -1}, } func main() { for _, c := range testCases { fmt.Println("Input: ", c) subSeq, sum := gss(c) fmt.Println("Sub seq:", subSeq) fmt.Println("Sum: ", sum, "\n") } }
774Greatest subsequential sum
0go
rqlgm
>>> import itertools >>> def harshad(): for n in itertools.count(1): if n% sum(int(ch) for ch in str(n)) == 0: yield n >>> list(itertools.islice(harshad(), 0, 20)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42] >>> for n in harshad(): if n > 1000: print(n) break 1002 >>>
762Harshad or Niven series
3python
4xk5k
import Data.List (tails, elemIndices, isPrefixOf) replace :: String -> String -> String -> String replace [] _ xs = xs replace _ [] xs = xs replace _ _ [] = [] replace a b xs = replAll where xtails = tails xs matches = elemIndices True $ map (isPrefixOf a) xtails repl ys n = take n ys ++ b ++ drop (n + length b) ys replAll = foldl repl xs matches replaceInFiles a1 a2 files = do f <- mapM readFile files return $ map (replace a1 a2) f
781Globally replace text in several files
8haskell
2poll
public class Guessing { public static void main(String[] args) throws NumberFormatException{ int n = (int)(Math.random() * 10 + 1); System.out.print("Guess the number between 1 and 10: "); while(Integer.parseInt(System.console().readLine()) != n){ System.out.print("Wrong! Guess again: "); } System.out.println("Well guessed!"); } }
773Guess the number
9java
fu0dv
import Data.List (inits, tails, maximumBy) import Data.Ord (comparing) subseqs :: [a] -> [[a]] subseqs = concatMap inits . tails maxsubseq :: (Ord a, Num a) => [a] -> [a] maxsubseq = maximumBy (comparing sum) . subseqs main = print $ maxsubseq [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
774Greatest subsequential sum
8haskell
0m1s7
println "Hello world!"
755Hello world/Text
7groovy
1ffp6
import java.io.*; import java.util.*; public class SystemCommand { public static void main(String args[]) throws IOException { String command = "cmd /c dir"; Process p = Runtime.getRuntime().exec(command); try (Scanner sc = new Scanner(p.getInputStream())) { System.out.printf("Output of the command:%s%n%n", command); while (sc.hasNext()) { System.out.println(sc.nextLine()); } } } }
782Get system command output
9java
3gazg
import java.io.*; import java.nio.file.*; public class GloballyReplaceText { public static void main(String[] args) throws IOException { for (String fn : new String[]{"test1.txt", "test2.txt"}) { String s = new String(Files.readAllBytes(Paths.get(fn))); s = s.replace("Goodbye London!", "Hello New York!"); try (FileWriter fw = new FileWriter(fn)) { fw.write(s); } } } }
781Globally replace text in several files
9java
6rw3z
use strict; use Image::Imlib2; sub tograyscale { my $img = shift; my $gimg = Image::Imlib2->new($img->width, $img->height); for ( my $x = 0; $x < $gimg->width; $x++ ) { for ( my $y = 0; $y < $gimg->height; $y++ ) { my ( $r, $g, $b, $a ) = $img->query_pixel($x, $y); my $gray = int(0.2126 * $r + 0.7152 * $g + 0.0722 * $b); $gimg->set_color($gray, $gray, $gray, 255); $gimg->draw_point($x, $y); } } return $gimg; } my $animage = Image::Imlib2->load("Lenna100.jpg"); my $gscale = tograyscale($animage); $gscale->set_quality(80); $gscale->save("Lennagray.jpg"); exit 0;
775Grayscale image
2perl
pn4b0
use strict; use warnings; use List::Util qw( first shuffle ); my $pat = qr/[atjqk2-9]/; my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9; my $mebooks = my $youbooks = 0; my $me = substr $deck, 0, 2 * 9, ''; my $mepicks = join '', $me =~ /$pat/g; arrange($me); $mebooks++ while $me =~ s/($pat).\1.\1.\1.//; my $you = substr $deck, 0, 2 * 9, ''; my $youpicks = join '', $you =~ /$pat/g; arrange($you); $youbooks++ while $you =~ s/($pat).\1.\1.\1.//; while( $mebooks + $youbooks < 13 ) { play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 ); $mebooks + $youbooks == 13 and last; play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 ); } print "me $mebooks you $youbooks\n"; sub arrange { $_[0] = join '', sort $_[0] =~ /../g } sub human { my $have = shift =~ s/($pat).\K(?!\1)/ /gr; local $| = 1; my $pick; do { print "You have $have, enter request: "; ($pick) = lc(<STDIN>) =~ /$pat/g; } until $pick and $have =~ /$pick/; return $pick; } sub play { my ($me, $mb, $lastpicks, $you, $yb, $human) = @_; my $more = 1; while( arrange( $$me ), $more and $$mb + $$yb < 13 ) { if( $$me =~ s/($pat).\1.\1.\1.// ) { print "book of $&\n"; $$mb++; } elsif( $$me ) { my $pick = $human ? do { human($$me) } : do { my %picks; $picks{$_}++ for my @picks = $$me =~ /$pat/g; my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks; print "pick $pick\n"; $$lastpicks =~ s/$pick//g; $$lastpicks .= $pick; $pick; }; if( $$you =~ s/(?:$pick.)+// ) { $$me .= $&; } else { print "GO FISH!!\n"; $$me .= substr $deck, 0, 2, ''; $more = 0; } } elsif( $deck ) { $$me .= substr $deck, 0, 2, ''; } else { $more = 0; } } arrange( $$me ); }
778Go Fish
2perl
gx64e
function guessNumber() {
773Guess the number
10javascript
y7d6r
def play(low, high, turns=1) num = (low + high) / 2 print case is_it?(num) when 1 puts play(low, num - 1, turns + 1) when -1 puts play(num + 1, high, turns + 1) else puts end end def is_it?(num) num <=> $number end low, high = 1, 100 $number = rand(low .. high) puts play(low, high)
769Guess the number/With feedback (player)
14ruby
ua2vz
from math import radians, sin, cos, sqrt, asin def haversine(lat1, lon1, lat2, lon2): R = 6372.8 dLat = radians(lat2 - lat1) dLon = radians(lon2 - lon1) lat1 = radians(lat1) lat2 = radians(lat2) a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2 c = 2 * asin(sqrt(a)) return R * c >>> haversine(36.12, -86.67, 33.94, -118.40) 2887.2599506071106 >>>
766Haversine formula
3python
67m3w
null
782Get system command output
11kotlin
n2hij
class BitmapGrayscale extends Bitmap { public function toGrayscale(){ for ($i = 0; $i < $this->h; $i++){ for ($j = 0; $j < $this->w; $j++){ $l = ($this->data[$j][$i][0] * 0.2126) + ($this->data[$j][$i][1] * 0.7152) + ($this->data[$j][$i][2] * 0.0722); $l = round($l); $this->data[$j][$i] = array($l,$l,$l); } } } } $b = new BitmapGrayscale(16,16); $b->fill(0,0,null,null, array(255,255,0)); $b->setPixel(0, 15, array(255,0,0)); $b->setPixel(0, 14, array(0,255,0)); $b->setPixel(0, 13, array(0,0,255)); $b->toGrayscale(); $b->writeP6('p6-grayscale.ppm');
775Grayscale image
12php
y7i61
Red [ Title: Author: ] chand: [] ;-- c and p = computer and player cguesses: [] phand: [] cbooks: 0 pbooks: 0 gf: { *************** * GO FISH * *************** } pip: [ ];-- suits are not relevant pile: [] ;-- where discarded cards go ;--------------------- ; Helper functions - ;--------------------- clear-screen: does [ call/console either system/platform = 'Linux [][] ] clear-and-show: func [duration str][ { Poor persons animation. Blips message to screen after a pause of duration length. } clear-screen print str wait duration clear-screen ] deal-cards: func [num hand][ loop num [ append hand rejoin [trim/all form take deck] ] ] find-in: func [blk str][ foreach i blk [if find i str [return i]] ] go-fish: func [num hand][ either not empty? deck [ deal-cards num hand ][ append hand rejoin [trim/all form take pile] ;-- take from pile if deck is empty ] ] guess-from: func [hand guessed][ { Randomly picks from hand minus guessed. Simulates a person asking for different cards on their next turn if their previous guess resulted in a Go Fish. } random/seed now/time either any [empty? guessed empty? exclude hand guessed][ random/only hand ][ random/only exclude hand guessed ] ] make-deck: function [] [ new-deck: make block! 52 foreach p pip [loop 4 [append/only new-deck p]] return new-deck ] show-cards: does [ clear-and-show 0 print [newline newline sort phand newline] print [ cbooks] print [ pbooks newline] ] shuffle: function [deck [block!]] [deck: random deck] ;------------- end of helper functions ----------------- check-for-books: func [ { Checks for a book in a players hand. Increments the players book score, and discards the book from the players hand } hand kind /local c ][ c: collect [ forall hand [keep find hand/1 kind] ] remove-each i c [none = i] if 4 = length? c [ either hand = phand [pbooks: pbooks + 1][cbooks: cbooks + 1] remove-each i hand [if find/only c i [i]] ;-- remove book from hand forall c [append pile c/1] ;-- append discarded book to the pile ] ] transfer-cards: func [ fhand thand kind /local c ][ c: collect [forall fhand [keep find fhand/1 kind]] remove-each i c [none = i] ;-- remove none values from collected forall c [append thand c/1];-- append remaining values to remove-each i fhand [if find/only c i [i]];-- remove those values from ] computer-turn: func [ fhand thand kind /local a ][ a: ask rejoin [ kind ] if a = [halt] either any [a = a = ][ check-for-books thand kind transfer-cards fhand thand kind show-cards computer-turn fhand thand guess-from thand cguesses ][ clear-and-show 0.4 gf go-fish 1 thand append cguesses kind ] ] player-turn: func [ fhand thand kind /local p ][ if empty? fhand [go-fish 3 fhand] if none? find-in thand kind [ ;-- player has to hold rank asked for clear-and-show 1.0 exit ] either find-in fhand kind [ check-for-books thand kind transfer-cards fhand thand kind show-cards if find-in thand kind [ p: ask either p = [halt][player-turn fhand thand p] check-for-books thand p ] ][ clear-and-show 0.4 gf go-fish 1 thand ] ] game-round: has [c p][ print { ------------------- - COMPUTER TURN - ------------------- } if empty? chand [ ; computer has no more cards? fish 3 cards. go-fish 3 chand show-cards ] computer-turn phand chand c: guess-from chand cguesses check-for-books chand c show-cards print { ------------------- - PLAYER TURN - ------------------- } if empty? phand [ ;-- player has no more cards? fish 3 cards. go-fish 3 phand show-cards ] p: ask either p = [halt][player-turn chand phand find-in phand p] check-for-books phand p show-cards ] main: does [ deck: shuffle make-deck deal-cards 9 chand deal-cards 9 phand show-cards while [cbooks + pbooks < 13][ game-round ] clear-and-show 0 print print [newline cbooks newline pbooks] ] main
778Go Fish
3python
rqygq
use std::io::stdin; const MIN: isize = 1; const MAX: isize = 100; fn main() { loop { let mut min = MIN; let mut max = MAX; let mut num_guesses = 1; println!("Please think of a number between {} and {}", min, max); loop { let guess = (min + max) / 2; println!("Is it {}?", guess); println!("(type h if my guess is too high, l if too low, e if equal and q to quit)"); let mut line = String::new(); stdin().read_line(&mut line).unwrap(); match Some(line.chars().next().unwrap().to_uppercase().next().unwrap()) { Some('H') => { max = guess - 1; num_guesses += 1; }, Some('L')=> { min = guess + 1; num_guesses += 1; }, Some('E') => { if num_guesses == 1 { println!("\n*** That was easy! Got it in one guess! ***\n"); } else { println!("\n*** I knew it! Got it in only {} guesses! ***\n", num_guesses); } break; }, Some('Q') => return, _ => println!("Sorry, I didn't quite get that. Please try again.") } } } }
769Guess the number/With feedback (player)
15rust
5evuq
object GuessNumber extends App { val n = 1 + scala.util.Random.nextInt(20) println("Guess which number I've chosen in the range 1 to 20\n") do println("Your guess, please: ") while (io.StdIn.readInt() match { case `n` => println("Correct, well guessed!"); false case guess if (n + 1 to 20).contains(guess) => println("Your guess is higher than the chosen number, try again"); true case guess if (1 until n).contains(guess) => println("Your guess is lower than the chosen number, try again"); true case _ => println("Your guess is inappropriate, try again"); true }) }
769Guess the number/With feedback (player)
16scala
rq4gn
dms_to_rad <- function(d, m, s) (d + m / 60 + s / 3600) * pi / 180 great_circle_distance <- function(lat1, long1, lat2, long2) { a <- sin(0.5 * (lat2 - lat1)) b <- sin(0.5 * (long2 - long1)) 12742 * asin(sqrt(a * a + cos(lat1) * cos(lat2) * b * b)) } great_circle_distance( dms_to_rad(36, 7, 28.10), dms_to_rad( 86, 40, 41.50), dms_to_rad(33, 56, 32.98), dms_to_rad(118, 24, 29.05))
766Haversine formula
13r
f5zdc
local output = io.popen("echo Hurrah!") print(output:read("*all"))
782Get system command output
1lua
dvknq
null
781Globally replace text in several files
11kotlin
dvbnz
null
773Guess the number
11kotlin
89e0q
import java.util.Scanner; import java.util.ArrayList; public class Sub{ private static int[] indices; public static void main(String[] args){ ArrayList<Long> array= new ArrayList<Long>();
774Greatest subsequential sum
9java
af71y
filenames = { "f1.txt", "f2.txt" } for _, fn in pairs( filenames ) do fp = io.open( fn, "r" ) str = fp:read( "*all" ) str = string.gsub( str, "Goodbye London!", "Hello New York!" ) fp:close() fp = io.open( fn, "w+" ) fp:write( str ) fp:close() end
781Globally replace text in several files
1lua
fupdp
import io ppmfileout = io.StringIO('') def togreyscale(self): for h in range(self.height): for w in range(self.width): r, g, b = self.get(w, h) l = int(0.2126 * r + 0.7152 * g + 0.0722 * b) self.set(w, h, Colour(l, l, l)) Bitmap.togreyscale = togreyscale bitmap = Bitmap(4, 4, white) bitmap.fillrect(1, 0, 1, 2, Colour(127, 0, 63)) bitmap.set(3, 3, Colour(0, 127, 31)) print('Colour:') bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) print('Grey:') bitmap.togreyscale() ppmfileout = io.StringIO('') bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ''' The print statement above produces the following output: Colour: P3 4 4 255 255 255 255 255 255 255 255 255 255 0 127 31 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 127 0 63 255 255 255 255 255 255 255 255 255 127 0 63 255 255 255 255 255 255 Grey: P3 4 4 254 254 254 254 254 254 254 254 254 254 93 93 93 254 254 254 254 254 254 254 254 254 254 254 254 254 254 254 31 31 31 254 254 254 254 254 254 254 254 254 31 31 31 254 254 254 254 254 254 '''
775Grayscale image
3python
1dgpc
setAs("pixmapGrey", "pixmapRGB", function(from, to){ z = new(to, as(from, "pixmap")) z@red = from@grey z@green = from@grey z@blue = from@grey z@channels = c("red", "green", "blue") z }) getMethods(addChannels) setMethod("addChannels", "pixmapRGB", function(object, coef=NULL){ if(is.null(coef)) coef = c(0.2126, 0.7152, 0.0722) z = new("pixmapGrey", object) z@grey = coef[1] * object@red + coef[2] * object@green + coef[3] * object@blue z@channels = "grey" z }) plot(p1 <- pixmapRGB(c(c(1,0,0,0,0,1), c(0,1,0,0,1,0), c(0,0,1,1,0,0)), nrow=6, ncol=6)) plot(p2 <- as(p1, "pixmapGrey")) plot(p3 <- as(p2, "pixmapRGB"))
775Grayscale image
13r
h8vjj
function MaximumSubsequence(population) { var maxValue = 0; var subsequence = []; for (var i = 0, len = population.length; i < len; i++) { for (var j = i; j <= len; j++) { var subsequence = population.slice(i, j); var value = sumValues(subsequence); if (value > maxValue) { maxValue = value; greatest = subsequence; }; } } return greatest; } function sumValues(arr) { var result = 0; for (var i = 0, len = arr.length; i < len; i++) { result += arr[i]; } return result; }
774Greatest subsequential sum
10javascript
sypqz
my @directories = grep { chomp; -d } `ls`; for (@directories) { chomp; ...; }
782Get system command output
2perl
7szrh
include Math Radius = 6371 def spherical_distance(start_coords, end_coords) lat1, long1 = deg2rad *start_coords lat2, long2 = deg2rad *end_coords 2 * Radius * asin(sqrt(sin((lat2-lat1)/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)/2)**2)) end def deg2rad(lat, long) [lat * PI / 180, long * PI / 180] end bna = [36.12, -86.67] lax = [33.94, -118.4] puts % spherical_distance(bna, lax)
766Haversine formula
14ruby
mhcyj
harshad = 1.step.lazy.select { |n| n % n.digits.sum == 0 } puts puts
762Harshad or Niven series
14ruby
rspgs
class RGBColour def to_grayscale luminosity = Integer(0.2126*@red + 0.7152*@green + 0.0722*@blue) self.class.new(luminosity, luminosity, luminosity) end end class Pixmap def to_grayscale gray = self.class.new(@width, @height) @width.times do |x| @height.times do |y| gray[x,y] = self[x,y].to_grayscale end end gray end end
775Grayscale image
14ruby
et7ax
null
774Greatest subsequential sum
11kotlin
h8uj3
import Cocoa var found = false let fh = NSFileHandle.fileHandleWithStandardInput() println("Enter an integer between 1 and 100 for me to guess: ") let data = fh.availableData var num:Int! var low = 0.0 var high = 100.0 var lastGuess:Double! if let numFromData = NSString(data: data, encoding: NSUTF8StringEncoding)?.intValue { num = Int(numFromData) } func guess() -> Double? { if (high - low == 1) { println("I can't guess it. I think you cheated."); return nil } return floor((low + high) / 2) } while (!found) { if let guess = guess() { lastGuess = guess } else { break } println("My guess is: \(Int(lastGuess))") println("How was my guess? Enter \"higher\" if it was higher, \"lower\" if it was lower, and \"correct\" if I got it") let data = fh.availableData let str = NSString(data: data, encoding: NSUTF8StringEncoding) if (str == nil) { continue } if (str! == "correct\n") { found = true println("I did it!") } else if (str! == "higher\n") { low = lastGuess } else if (str! == "lower\n") { high = lastGuess } }
769Guess the number/With feedback (player)
17swift
v1l2r
use std::f64; static R: f64 = 6372.8; struct Point { lat: f64, lon: f64, } fn haversine(mut origin: Point, mut destination: Point) -> f64 { origin.lon -= destination.lon; origin.lon = origin.lon.to_radians(); origin.lat = origin.lat.to_radians(); destination.lat = destination.lat.to_radians(); let dz: f64 = origin.lat.sin() - destination.lat.sin(); let dx: f64 = origin.lon.cos() * origin.lat.cos() - destination.lat.cos(); let dy: f64 = origin.lon.sin() * origin.lat.cos(); ((dx * dx + dy * dy + dz * dz).sqrt() / 2.0).asin() * 2.0 * R } fn main() { let origin: Point = Point { lat: 36.12, lon:-86.67 }; let destination: Point = Point { lat: 33.94, lon:-118.4 }; let d: f64 = haversine(origin, destination); println!("Distance: {} km ({} mi)", d, d / 1.609344); }
766Haversine formula
15rust
9klmm
main = putStrLn "Hello world!"
755Hello world/Text
8haskell
mhhyf
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
783Gray code
0go
2p0l7
>>> import subprocess >>> returned_text = subprocess.check_output(, shell=True, universal_newlines=True) >>> type(returned_text) <class 'str'> >>> print(returned_text) Volume in drive C is Windows Volume Serial Number is 44X7-73CE Directory of C:\Python33 04/07/2013 06:40 <DIR> . 04/07/2013 06:40 <DIR> .. 27/05/2013 07:10 <DIR> DLLs 27/05/2013 07:10 <DIR> Doc 27/05/2013 07:10 <DIR> include 27/05/2013 07:10 <DIR> Lib 27/05/2013 07:10 <DIR> libs 16/05/2013 00:15 33,326 LICENSE.txt 15/05/2013 22:49 214,554 NEWS.txt 16/05/2013 00:03 26,624 python.exe 16/05/2013 00:03 27,136 pythonw.exe 15/05/2013 22:49 6,701 README.txt 27/05/2013 07:10 <DIR> tcl 27/05/2013 07:10 <DIR> Tools 16/05/2013 00:02 43,008 w9xpopen.exe 6 File(s) 351,349 bytes 9 Dir(s) 46,326,947,840 bytes free >>>
782Get system command output
3python
j037p
perl -pi -e "s/Goodbye London\!/Hello New York\!/g;" a.txt b.txt c.txt
781Globally replace text in several files
2perl
j067f
object BitmapOps { def luminosity(c:Color)=(0.2126*c.getRed + 0.7152*c.getGreen + 0.0722*c.getBlue+0.5).toInt def grayscale(bm:RgbBitmap)={ val image=new RgbBitmap(bm.width, bm.height) for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y))) image.setPixel(x, y, new Color(l,l,l)) image } }
775Grayscale image
16scala
sybqo
math.randomseed( os.time() ) n = math.random( 1, 10 ) print( "I'm thinking of a number between 1 and 10. Try to guess it: " ) repeat x = tonumber( io.read() ) if x == n then print "Well guessed!" else print "Guess again: " end until x == n
773Guess the number
1lua
ocw8h
package main import "fmt" func happy(n int) bool { m := make(map[int]bool) for n > 1 { m[n] = true var x int for x, n = n, 0; x > 0; x /= 10 { d := x % 10 n += d * d } if m[n] { return false } } return true } func main() { for found, n := 0, 1; found < 8; n++ { if happy(n) { fmt.Print(n, " ") found++ } } fmt.Println() }
771Happy numbers
0go
0mwsk
fn is_harshad (n: u32) -> bool { let sum_digits = n.to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .fold(0, |a, b| a+b); n% sum_digits == 0 } fn main() { for i in (1u32..).filter(|num| is_harshad(*num)).take(20) { println!("Harshad: {}", i); } for i in (1_001u32..).filter(|num| is_harshad(*num)).take(1) { println!("First Harshad bigger than 1_000: {}", i); } }
762Harshad or Niven series
15rust
701rc
def grayEncode = { i -> i ^ (i >>> 1) } def grayDecode; grayDecode = { int code -> if(code <= 0) return 0 def h = grayDecode(code >>> 1) return (h << 1) + ((code ^ h) & 1) }
783Gray code
7groovy
y7e6o
import Data.Bits import Data.Char import Numeric import Control.Monad import Text.Printf grayToBin :: (Integral t, Bits t) => t -> t grayToBin 0 = 0 grayToBin g = g `xor` (grayToBin $ g `shiftR` 1) binToGray :: (Integral t, Bits t) => t -> t binToGray b = b `xor` (b `shiftR` 1) showBinary :: (Integral t, Show t) => t -> String showBinary n = showIntAtBase 2 intToDigit n "" showGrayCode :: (Integral t, Bits t, PrintfArg t, Show t) => t -> IO () showGrayCode num = do let bin = showBinary num let gray = showBinary (binToGray num) printf "int:%2d -> bin:%5s -> gray:%5s\n" num bin gray main = forM_ [0..31::Int] showGrayCode
783Gray code
8haskell
afc1g
system("wc -l /etc/passwd /etc/group", intern = TRUE)
782Get system command output
13r
4wd5y
function sumt(t, start, last) return start <= last and t[start] + sumt(t, start+1, last) or 0 end function maxsub(ary, idx) local idx = idx or 1 if not ary[idx] then return {} end local maxsum, last = 0, idx for i = idx, #ary do if sumt(ary, idx, i) > maxsum then maxsum, last = sumt(ary, idx, i), i end end local v = maxsub(ary, idx + 1) if maxsum < sumt(v, 1, #v) then return v end local ret = {} for i = idx, last do ret[#ret+1] = ary[i] end return ret end
774Greatest subsequential sum
1lua
ko5h2
Number.metaClass.isHappy = { def number = delegate as Long def cycle = new HashSet<Long>() while (number != 1 && !cycle.contains(number)) { cycle << number number = (number as String).collect { d = (it as Long); d * d }.sum() } number == 1 } def matches = [] for (int i = 0; matches.size() < 8; i++) { if (i.happy) { matches << i } } println matches
771Happy numbers
7groovy
etbal
import math._ object Haversine { val R = 6372.8
766Haversine formula
16scala
21ulb
object Harshad extends App { val harshads = Stream.from(1).filter(i => i % i.toString.map(_.asDigit).sum == 0) println(harshads.take(20).toList) println(harshads.filter(_ > 1000).head) }
762Harshad or Niven series
16scala
kiwhk
str = `ls` arr = `ls`.lines
782Get system command output
14ruby
koyhg
use std::process::Command; use std::io::{Write, self}; fn main() { let output = Command::new("/bin/cat") .arg("/etc/fstab") .output() .expect("failed to execute process"); io::stdout().write(&output.stdout); }
782Get system command output
15rust
bimkx
import scala.io.Source val command = "cmd /c echo Time at%DATE%%TIME%" val p = Runtime.getRuntime.exec(command) val sc = Source.fromInputStream(p.getInputStream) println(sc.mkString)
782Get system command output
16scala
afl1n
package main import ( "fmt" "math/big" ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func hamming(n int) []*big.Int { h := make([]*big.Int, n) h[0] = big.NewInt(1) two, three, five := big.NewInt(2), big.NewInt(3), big.NewInt(5) next2, next3, next5 := big.NewInt(2), big.NewInt(3), big.NewInt(5) i, j, k := 0, 0, 0 for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, next5))) if h[m].Cmp(next2) == 0 { i++; next2.Mul( two, h[i]) } if h[m].Cmp(next3) == 0 { j++; next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++; next5.Mul( five, h[k]) } } return h } func main() { h := hamming(1e6) fmt.Println(h[:20]) fmt.Println(h[1691-1]) fmt.Println(h[len(h)-1]) }
780Hamming numbers
0go
afv1f
public class Gray { public static long grayEncode(long n){ return n ^ (n >>> 1); } public static long grayDecode(long n) { long p = n; while ((n >>>= 1) != 0) p ^= n; return p; } public static void main(String[] args){ System.out.println("i\tBinary\tGray\tDecoded"); for(int i = -1; i < 32;i++){ System.out.print(i +"\t"); System.out.print(Integer.toBinaryString(i) + "\t"); System.out.print(Long.toBinaryString(grayEncode(i))+ "\t"); System.out.println(grayDecode(grayEncode(i))); } } }
783Gray code
9java
j0z7c
import Foundation let process = Process() process.launchPath = "/usr/bin/env" process.arguments = ["pwd"] let pipe = Pipe() process.standardOutput = pipe process.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String.init(data: data, encoding: String.Encoding.utf8) print(output!)
782Get system command output
17swift
h86j0
import fileinput for line in fileinput.input(inplace=True): print(line.replace('Goodbye London!', 'Hello New York!'), end='')
781Globally replace text in several files
3python
h8yjw
class Hamming { static final ONE = BigInteger.ONE static final THREE = BigInteger.valueOf(3) static final FIVE = BigInteger.valueOf(5) static void main(args) { print 'Hamming(1 .. 20) =' (1..20).each { print " ${hamming it}" } println "\nHamming(1691) = ${hamming 1691}" println "Hamming(1000000) = ${hamming 1000000}" } static hamming(n) { def priorityQueue = new PriorityQueue<BigInteger>() priorityQueue.add ONE def lowest n.times { lowest = priorityQueue.poll() while (priorityQueue.peek() == lowest) { priorityQueue.poll() } updateQueue(priorityQueue, lowest) } lowest } static updateQueue(priorityQueue, lowest) { priorityQueue.add(lowest.shiftLeft 1) priorityQueue.add(lowest.multiply THREE) priorityQueue.add(lowest.multiply FIVE) } }
780Hamming numbers
7groovy
h8mj9
import Data.Char (digitToInt) import Data.Set (member, insert, empty) isHappy :: Integer -> Bool isHappy = p empty where p _ 1 = True p s n | n `member` s = False | otherwise = p (insert n s) (f n) f = sum . fmap ((^ 2) . toInteger . digitToInt) . show main :: IO () main = mapM_ print $ take 8 $ filter isHappy [1 ..]
771Happy numbers
8haskell
ck694
export function encode (number) { return number ^ (number >> 1) } export function decode (encodedNumber) { let number = encodedNumber while (encodedNumber >>= 1) { number ^= encodedNumber } return number }
783Gray code
10javascript
1d9p7
hamming = 1: map (2*) hamming `union` map (3*) hamming `union` map (5*) hamming union a@(x:xs) b@(y:ys) = case compare x y of LT -> x: union xs b EQ -> x: union xs ys GT -> y: union a ys main = do print $ take 20 hamming print (hamming !! (1691-1), hamming !! (1692-1)) print $ hamming !! (1000000-1)
780Hamming numbers
8haskell
z4et0
null
783Gray code
11kotlin
5eiua
float max(unsigned int count, float values[]) { assert(count > 0); size_t idx; float themax = values[0]; for(idx = 1; idx < count; ++idx) { themax = values[idx] > themax ? values[idx] : themax; } return themax; }
784Greatest element of a list
5c
3gpza
ruby -pi -e a.txt b.txt c.txt
781Globally replace text in several files
14ruby
bi9kq
null
781Globally replace text in several files
15rust
pncbu
int hailstone(int n, int *arry) { int hs = 1; while (n!=1) { hs++; if (arry) *arry++ = n; n = (n&1) ? (3*n+1) : (n/2); } if (arry) *arry++ = n; return hs; } int main() { int j, hmax = 0; int jatmax, n; int *arry; for (j=1; j<100000; j++) { n = hailstone(j, NULL); if (hmax < n) { hmax = n; jatmax = j; } } n = hailstone(27, NULL); arry = malloc(n*sizeof(int)); n = hailstone(27, arry); printf(, arry[0],arry[1],arry[2],arry[3], arry[n-4], arry[n-3], arry[n-2], arry[n-1], n); printf(, hmax, jatmax); free(arry); return 0; }
785Hailstone sequence
5c
rqng7
package main import ( "fmt" "math/rand" "time" ) const lower, upper = 1, 100 func main() { fmt.Printf("Guess integer number from%d to%d: ", lower, upper) rand.Seed(time.Now().Unix()) n := rand.Intn(upper-lower+1) + lower for guess := n; ; { switch _, err := fmt.Scan(&guess); { case err != nil: fmt.Println("\n", err, "So, bye.") return case guess < n: fmt.Print("Too low. Try again: ") case guess > n: fmt.Print("Too high. Try again: ") default: fmt.Println("Well guessed!") return } } }
776Guess the number/With feedback
0go
mjiyi
import Foundation func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double { let lat1rad = lat1 * Double.pi/180 let lon1rad = lon1 * Double.pi/180 let lat2rad = lat2 * Double.pi/180 let lon2rad = lon2 * Double.pi/180 let dLat = lat2rad - lat1rad let dLon = lon2rad - lon1rad let a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad) let c = 2 * asin(sqrt(a)) let R = 6372.8 return R * c } print(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40))
766Haversine formula
17swift
yj96e