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 <- s... | 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 conf... | 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 ... | 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 co... | 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)... | 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(b... | 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
netpbmMagicNumb... | 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;
... | 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 ++) {
... | 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 mul... | 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 = s... | 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, ... | 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... | 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 = in... | 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 getLong... | 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
... | 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) :: I... | 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!")))
}
}
boundryEr... | 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)
fo... | 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
... | 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
... | 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 a... | 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.print... | 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 Lond... | 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... | 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)... | 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,... | 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))
... | 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);
... | 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... | 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;
... | 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(gues... | 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)... | 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 =... | 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(... | 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 > m... | 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]
e... | 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... | 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)?.i... | 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()... | 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(" ... | 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 ... | 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... | 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(... | 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!("H... | 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) => ... | 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
en... | 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.... | 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, next... | 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++){
... | 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) = ${ha... | 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... | 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-... | 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 = hailst... | 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); {
... | 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... | 766Haversine formula | 17swift | yj96e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.