code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
data X = X
data Y = Y
data Point = Point Int Int deriving Show
createPointAt :: X -> Int -> Y -> Int -> Point
createPointAt X x Y y = Point x y
main = print $ createPointAt X 5 Y 3 | 535Named parameters | 8haskell | ecuai |
function buildArray(size, value)
local tbl = {}
for i=1, size do
table.insert(tbl, value)
end
return tbl
end
MU_MAX = 1000000
sqroot = math.sqrt(MU_MAX)
mu = buildArray(MU_MAX, 1)
for i=2, sqroot do
if mu[i] == 1 then | 533Möbius function | 1lua | zbxty |
null | 528Non-decimal radices/Convert | 11kotlin | x2bws |
import java.math.BigInteger
var primes = mutableListOf<BigInteger>()
var smallPrimes = mutableListOf<Int>() | 534N-smooth numbers | 11kotlin | rd6go |
processNutritionFacts(new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build()); | 535Named parameters | 9java | hzmjm |
function example(options) { | 535Named parameters | 10javascript | a9v10 |
use utf8;
use strict;
use warnings;
use feature 'say';
use List::Util 'uniq';
sub prime_factors {
my ($n, $d, @factors) = (shift, 1);
while ($n > 1 and $d++) {
$n /= $d, push @factors, $d until $n % $d;
}
@factors
}
sub {
my @p = prime_factors(shift);
@p == uniq(@p) ? 0 == @p%2 ? 1 : ... | 533Möbius function | 2perl | k3lhc |
from itertools import groupby
from unicodedata import decomposition, name
from pprint import pprint as pp
commonleaders = ['the']
replacements = {u'': 'ss',
u'': 's',
u'': 's',
}
hexdigits = set('0123456789abcdef')
decdigits = set('0123456789')
def splitchar(c):
... | 530Natural sorting | 3python | jt27p |
package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
) | 537Musical scale | 0go | yaw64 |
null | 535Named parameters | 11kotlin | 4it57 |
function dec2base (base, n)
local result, digit = ""
while n > 0 do
digit = n % base
if digit > 9 then digit = string.char(digit + 87) end
n = math.floor(n / base)
result = digit .. result
end
return result
end
local x = dec2base(16, 26)
print(x) | 528Non-decimal radices/Convert | 1lua | qvpx0 |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sample Page</title>
</head>
<body>
Upon loading the page you should hear the scale.
<script type="text/javascript">
function musicalScale(freqArr){ | 537Musical scale | 10javascript | jt37n |
void parse_sep(const char *str, const char *const *pat, int len)
{
int i, slen;
while (*str != '\0') {
for (i = 0; i < len || !putchar(*(str++)); i++) {
slen = strlen(pat[i]);
if (strncmp(str, pat[i], slen)) continue;
printf(, slen, str);
str += slen;
break;
}
}
}
int main()
{
const char *seps[]... | 539Multisplit | 5c | 2sslo |
use strict;
use warnings;
use feature 'say';
use ntheory qw<primes>;
use List::Util qw<min>;
use Math::GMPz;
sub smooth_numbers {
my @m = map { Math::GMPz->new($_) } @_;
my @s;
push @s, [1] for 0..$
return sub {
my $n = $s[0][0];
$n = min $n, $s[$_][0] for 1..$
for (0..$
... | 534N-smooth numbers | 2perl | dj1nw |
func root(a float64, n int) float64 {
n1 := n - 1
n1f, rn := float64(n1), 1/float64(n)
x, x0 := 1., 0.
for {
potx, t2 := 1/x, a
for b := n1; b > 0; b >>= 1 {
if b&1 == 1 {
t2 *= potx
}
potx *= potx
}
x0, x = x, rn*(n1f*x... | 531Nth root | 0go | 2stl7 |
def isPrime(n):
if (n < 2):
return False
for i in range(2, n + 1):
if (i * i <= n and n% i == 0):
return False
return True
def mobius(N):
if (N == 1):
return 1
p = 0
for i in range(1, N + 1):
if (N% i == 0 and
is... | 533Möbius function | 3python | b62kr |
null | 537Musical scale | 11kotlin | cxs98 |
function CreatePet(options)
local name=options.name
local species=options.species
local breed=options.breed
print('Created a '..breed..' '..species..' named '..name)
end
CreatePet{name='Rex',species='Dog',breed='Irish Setter'} | 535Named parameters | 1lua | gnz4j |
import static Constants.tolerance
import static java.math.RoundingMode.HALF_UP
def root(double base, double n) {
double xOld = 1
double xNew = 0
while (true) {
xNew = ((n - 1) * xOld + base/(xOld)**(n - 1))/n
if ((xNew - xOld).abs() < tolerance) { break }
xOld = xNew
}
(xNew as ... | 531Nth root | 7groovy | yao6o |
ar.sort_by{|str| str.downcase.gsub(/\Athe |\Aa |\Aan /, ).lstrip.gsub(/\s+/, )} | 530Natural sorting | 14ruby | k3uhg |
package main
import (
"image"
"image/png"
"os"
)
func main() {
g := image.NewGray(image.Rect(0, 0, 256, 256))
for i := range g.Pix {
g.Pix[i] = uint8(i>>8 ^ i)
}
f, _ := os.Create("xor.png")
png.Encode(f, g)
f.Close()
} | 538Munching squares | 0go | hz3jq |
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
def isPrime(n):
if n < 2:
return False
for i in primes:
if n == i:
return True
if n% i == 0:
return False
if i * i > n:
return True
print , n,
def init():
s = 24
while s < 600:
i... | 534N-smooth numbers | 3python | fhade |
n `nthRoot` x = fst $ until (uncurry(==)) (\(_,x0) -> (x0,((n-1)*x0+x/x0**(n-1))/n)) (x,x/n) | 531Nth root | 8haskell | a9g1g |
require 'prime'
def (n)
pd = n.prime_division
return 0 unless pd.map(&:last).all?(1)
pd.size.even?? 1: -1
end
([] + (1..199).map{|n| % (n)}).each_slice(20){|line| puts line.join() } | 533Möbius function | 14ruby | 1mupw |
object NaturalSorting {
implicit object ArrayOrdering extends Ordering[Array[String]] { | 530Natural sorting | 16scala | a9r1n |
import qualified Data.ByteString as BY (writeFile, pack)
import Data.Bits (xor)
main :: IO ()
main =
BY.writeFile
"out.pgm"
(BY.pack
(fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++
[ x `xor` y
| x <- [0 .. 255]
, y <- [0 .. 255] ])) | 538Munching squares | 8haskell | ir7or |
c = string.char
midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96) | 537Musical scale | 1lua | lq0ck |
char* addSuffix(int num, char* buf, size_t len)
{
char *suffixes[4] = { , , , };
int i;
switch (num % 10)
{
case 1 : i = (num % 100 == 11) ? 0 : 1;
break;
case 2 : i = (num % 100 == 12) ? 0 : 2;
break;
case 3 : i = (num % 100 == 13) ? 0 : 3;
... | 540N'th | 5c | py6by |
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class XorPattern extends JFrame{
private JPanel xorPanel;
public XorPattern(){
xorPanel = new JPanel(){
@Override
public void paint(Graphics g) {
for(i... | 538Munching squares | 9java | x2vwy |
def prime?(n)
return n | 1 == 3 if n < 5
return false if n.gcd(6)!= 1
sqrtN = Integer.sqrt(n)
pc = -1
until (pc += 6) > sqrtN
return false if n % pc == 0 || n % (pc + 2) == 0
end
true
end
def gen_primes(a, b)
(a..b).select { |pc| p... | 534N-smooth numbers | 14ruby | zbwtw |
package main
import "fmt"
func narc(n int) []int {
power := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
limit := 10
result := make([]int, 0, n)
for x := 0; len(result) < n; x++ {
if x >= limit {
for i := range power {
power[i] *= i | 536Narcissistic decimal number | 0go | 4if52 |
null | 538Munching squares | 11kotlin | pymb6 |
use MIDI::Simple;
set_tempo 500_000;
n 60; n 62; n 64; n 65; n 67; n 69; n 71; n 72;
write_score 'scale.mid'; | 537Musical scale | 2perl | x2uw8 |
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n% 2 == 0 {
return n == 2;
}
if n% 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n% p == 0 {
return false;
}
p += 2;
if n% p == 0 {
... | 534N-smooth numbers | 15rust | 3pxz8 |
sub funkshun {
my %h = @_;
print qq(Argument "$_" has value "$h{$_}".\n)
foreach sort keys %h;
print "Verbosity specified as $h{verbosity}.\n" if exists $h{verbosity};
print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n";
} | 535Named parameters | 2perl | irko3 |
public static double nthroot(int n, double A) {
return nthroot(n, A, .001);
}
public static double nthroot(int n, double A, double p) {
if(A < 0) {
System.err.println("A < 0"); | 531Nth root | 9java | jtl7c |
(defn n-th [n]
(str n
(let [rem (mod n 100)]
(if (and (>= rem 11) (<= rem 13))
"th"
(condp = (mod n 10)
1 "st"
2 "nd"
3 "rd"
"th")))))
(apply str (interpose " " (map n-th (range 0 26))))
(apply str (interpose " " (map n-th (range 250 266))))
(apply st... | 540N'th | 6clojure | x2lwk |
import BigInt
import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) {
if s... | 534N-smooth numbers | 17swift | tkefl |
function named($args) {
$args += [ => 2,
=> ,
=> ];
echo $args[] . . $args['motor'] . . $args['teenage'];
}
named([ => , => 10]); | 535Named parameters | 12php | rd3ge |
function nthRoot(num, nArg, precArg) {
var n = nArg || 2;
var prec = precArg || 12;
var x = 1; | 531Nth root | 10javascript | 1m4p7 |
import Data.Char (digitToInt)
isNarcissistic :: Int -> Bool
isNarcissistic n = (sum ((^ digitCount) <$> digits) ==) n
where
digits = digitToInt <$> show n
digitCount = length digits
main :: IO ()
main = mapM_ print $ take 25 (filter isNarcissistic [0 ..]) | 536Narcissistic decimal number | 8haskell | qv4x9 |
local clr = {}
function drawMSquares()
local points = {}
for y = 0, hei-1 do
for x = 0, wid-1 do
local idx = bit.bxor(x, y)%256
local r, g, b = clr[idx][1], clr[idx][2], clr[idx][3]
local point = {x+1, y+1, r/255, g/255, b/255, 1}
table.insert (points, point)
end
end
love.graphics.points(points)
en... | 538Munching squares | 1lua | 1m9po |
int main() {
for (int i = 1; i < 5000; i++) {
int sum = 0;
for (int number = i; number > 0; number /= 10) {
int digit = number % 10;
sum += pow(digit, digit);
}
if (sum == i) {
... | 541Munchausen numbers | 5c | wl9ec |
>>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>> | 537Musical scale | 3python | qv5xi |
install.packages("audio")
library(audio)
hz=c(1635,1835,2060,2183,2450,2750,3087,3270)
for (i in 1:8){
play(audioSample(sin(1:1000), hz[i]))
Sys.sleep(.7)
} | 537Musical scale | 13r | a9l1z |
package main
import (
"fmt"
"strings"
)
func ms(txt string, sep []string) (ans []string) {
for txt > "" {
sepMatch := ""
posMatch := len(txt)
for _, s := range sep {
if p := strings.Index(txt, s); p >= 0 && p < posMatch {
sepMatch = s
pos... | 539Multisplit | 0go | qvvxz |
def subtract(x, y):
return x - y
subtract(5, 3)
subtract(y = 3, x = 5) | 535Named parameters | 3python | n7biz |
divide <- function(numerator, denominator) {
numerator / denominator
}
divide(3, 2)
divide(numerator=3, denominator=2)
divide(n=3, d=2)
divide(den=3, num=2)
divide(den=3, 2)
divide(3, num=2) | 535Named parameters | 13r | 057sg |
null | 531Nth root | 11kotlin | 5o6ua |
sub to2 { sprintf "%b", shift; }
sub to16 { sprintf "%x", shift; }
sub from2 { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
sub from16 { hex(shift); } | 528Non-decimal radices/Convert | 2perl | 2s6lf |
public class Narc{
public static boolean isNarc(long x){
if(x < 0) return false;
String xStr = Long.toString(x);
int m = xStr.length();
long sum = 0;
for(char c: xStr.toCharArray()){
sum += Math.pow(Character.digit(c, 10), m);
}
return sum == x;
}
public static void main(String[] args){
for(lon... | 536Narcissistic decimal number | 9java | pycb3 |
import net.java.dev.sna.SNA
object PlayMusicScale extends App with SNA {
snaLibrary = "Kernel32"
val Beep = SNA[Int, Int, Unit]
println("Please don't shoot the piano player, he's doing the best that he can!")
List(0, 2, 4, 5, 7, 9, 11, 12).
foreach(f => Beep((261.63 * math.pow(2, f / 12.0)).toInt, if (f ... | 537Musical scale | 16scala | n7hic |
import Data.List
(isPrefixOf, stripPrefix, genericLength, intercalate)
trysplit :: String -> [String] -> Maybe (String, String)
trysplit s delims =
case filter (`isPrefixOf` s) delims of
[] -> Nothing
(d:_) -> Just (d, (\(Just x) -> x) $ stripPrefix d s)
multisplit :: String -> [String] -> [(String, ... | 539Multisplit | 8haskell | meeyf |
function isNarc(x) {
var str = x.toString(),
i,
sum = 0,
l = str.length;
if (x < 0) {
return false;
} else {
for (i = 0; i < l; i++) {
sum += Math.pow(str.charAt(i), l);
}
}
return sum == x;
}
function main(){
var n = [];
for (var ... | 536Narcissistic decimal number | 10javascript | x25w9 |
(ns async-example.core
(:require [clojure.math.numeric-tower :as math])
(:use [criterium.core])
(:gen-class))
(defn get-digits [n]
" Convert number of a list of digits (e.g. 545 -> ((5), (4), (5)) "
(map #(Integer/valueOf (str %)) (String/valueOf n)))
(defn sum-power [digits]
" Convert digits such as abc... | 541Munchausen numbers | 6clojure | 84u05 |
def example(foo: 0, bar: 1, grill: )
puts
end
example(grill: , bar: 3.14) | 535Named parameters | 14ruby | fh1dr |
def add(x: Int, y: Int = 1) = x + y | 535Named parameters | 16scala | 61x31 |
base_convert(, 10, 16); | 528Non-decimal radices/Convert | 12php | su1qs |
use GD;
my $img = new GD::Image(256, 256, 1);
for my $y(0..255) {
for my $x(0..255) {
my $color = $img->colorAllocate( abs(255 - $x - $y), (255-$x) ^ $y , $x ^ (255-$y));
$img->setPixel($x, $y, $color);
}
}
print $img->png | 538Munching squares | 2perl | yae6u |
int F(const int n);
int M(const int n);
int F(const int n)
{
return (n == 0) ? 1 : n - M(F(n - 1));
}
int M(const int n)
{
return (n == 0) ? 0 : n - F(M(n - 1));
}
int main(void)
{
int i;
for (i = 0; i < 20; i++)
printf(, F(i));
printf();
for (i = 0; i < 20; i++)
printf(, M(i));
printf();
ret... | 542Mutual recursion | 5c | cxa9c |
null | 536Narcissistic decimal number | 11kotlin | 7f3r4 |
import java.util.*;
public class MultiSplit {
public static void main(String[] args) {
System.out.println("Regex split:");
System.out.println(Arrays.toString("a!===b=!=c".split("==|!=|=")));
System.out.println("\nManual split:");
for (String s : multiSplit("a!===b=!=c", new String... | 539Multisplit | 9java | fhhdv |
func greet(person: String, hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", hometown: "Cupertino")) | 535Named parameters | 17swift | djpnh |
header();
$w = 256;
$h = 256;
$im = imagecreate($w, $h)
or die();
$color = array();
for($i=0;$i<256;$i++)
{
array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14/256))*128+128,$i/2,$i));
}
for($i=0;$i<$w;$i++)
{
for($j=0;$j<$h;$j++)
{
imagesetpixel($im,$i,$j,$color[$i... | 538Munching squares | 12php | a9c12 |
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
multisplit = function(string, seps) {
var sep_regex = RegExp(_.map(seps, function(sep) { return RegExp.escape(sep); }).join('|'));
return string.split(sep_regex);
} | 539Multisplit | 10javascript | yaa6r |
function nroot(root, num)
return num^(1/root)
end | 531Nth root | 1lua | 4iy5c |
function isNarc (n)
local m, sum, digit = string.len(n), 0
for pos = 1, m do
digit = tonumber(string.sub(n, pos, pos))
sum = sum + digit^m
end
return sum == n
end
local n, count = 0, 0
repeat
if isNarc(n) then
io.write(n .. " ")
count = count + 1
end
n = n + ... | 536Narcissistic decimal number | 1lua | jt671 |
null | 539Multisplit | 11kotlin | 8440q |
i = int('1a',16) | 528Non-decimal radices/Convert | 3python | v0y29 |
(declare F)
(defn M [n]
(if (zero? n)
0
(- n (F (M (dec n))))))
(defn F [n]
(if (zero? n)
1
(- n (M (F (dec n)))))) | 542Mutual recursion | 6clojure | 5osuz |
null | 539Multisplit | 1lua | ogg8h |
int2str <- function(x, b) {
if(x==0) return("0")
if(x<0) return(paste0("-", base(-x,b)))
map <- c(as.character(0:9), letters)
res <- ""
while (x>0) {
res <- c(map[x%% b + 1], res)
x <- x%/% b
}
return(paste(res, collapse=""))
}
str2int <- function(s, b) {
map <- c(as.character(0:9), letters)
... | 528Non-decimal radices/Convert | 13r | 9wtmg |
import Image, ImageDraw
image = Image.new(, (256, 256))
drawingTool = ImageDraw.Draw(image)
for x in range(256):
for y in range(256):
drawingTool.point((x, y), (0, x^y, 0))
del drawingTool
image.save(, ) | 538Munching squares | 3python | mewyh |
sub multisplit {
my ($sep, $string, %opt) = @_ ;
$sep = join '|', map quotemeta($_), @$sep;
$sep = "($sep)" if $opt{keep_separators};
split /$sep/, $string, -1;
}
print "'$_' " for multisplit ['==','!=','='], "a!===b=!=c";
print "\n";
print "'$_' " for multisplit ['==','!=','='], "a!===b=!=c", keep_separa... | 539Multisplit | 2perl | 4ii5d |
class String
def convert_base(from, to)
Integer(self, from).to_s(to)
end
end
p .convert_base(10, 23)
p .convert_base(23, 7)
p .convert_base(7, 10)
p .convert_base(10, 36)
p .convert_base(15, 10) | 528Non-decimal radices/Convert | 14ruby | 5o9uj |
int count = 0;
void solve(int n, int col, int *hist)
{
if (col == n) {
printf(, ++count);
for (int i = 0; i < n; i++, putchar('\n'))
for (int j = 0; j < n; j++)
putchar(j == hist[i] ? 'Q' : ((i + j) & 1) ? ' ' : '.');
return;
}
for (int i = 0, j = 0; i < n; i++) {
for (j = 0; j < col && !attack(i, ... | 543N-queens problem | 5c | lqacy |
sub is_narcissistic {
my $n = shift;
my($k,$sum) = (length($n),0);
$sum += $_**$k for split(//,$n);
$n == $sum;
}
my $i = 0;
for (1..25) {
$i++ while !is_narcissistic($i);
say $i++;
} | 536Narcissistic decimal number | 2perl | fhpd7 |
load 'raster_graphics.rb'
class Pixmap
def self.xor_pattern(width, height, rgb1, rgb2)
size = 256
colours = Array.new(size) do |i|
RGBColour.new(
(rgb1.red + (rgb2.red - rgb1.red) * i / size),
(rgb1.green + (rgb2.green - rgb1.green) * i / size),
(rgb1.blue + (rgb2.blue - ... | 538Munching squares | 14ruby | cxq9k |
int M(int n) => n==0?1:n-F(M(n-1));
int F(int n) => n==0?0:n-M(F(n-1));
main() {
String f="",m="";
for(int i=0;i<20;i++) {
m+="${M(i)} ";
f+="${F(i)} ";
}
print("M: $m");
print("F: $f");
} | 542Mutual recursion | 18dart | zbjte |
ulong mpow(ulong a, ulong p, ulong m)
{
ulong r = 1;
while (p) {
if ((1 & p)) r = r * a % m;
a = a * a % m;
p >>= 1;
}
return r;
}
ulong ipow(ulong a, ulong p) {
ulong r = 1;
while (p) {
if ((1 & p)) r = r * a;
a *= a;
p >>= 1;
}
return r;
}
ulong gcd(ulong m, ulong n)
{
ulong t;
while (m) { t =... | 544Multiplicative order | 5c | zbrtx |
fn format_with_radix(mut n: u32, radix: u32) -> String {
assert!(2 <= radix && radix <= 36);
let mut result = String::new();
loop {
result.push(std::char::from_digit(n% radix, radix).unwrap());
n /= radix;
if n == 0 {
break;
}
}
result.chars().rev().col... | 528Non-decimal radices/Convert | 15rust | 4ic5u |
extern crate image;
use image::{ImageBuffer, Pixel, Rgb};
fn main() {
let mut img = ImageBuffer::new(256, 256);
for x in 0..256 {
for y in 0..256 {
let pixel = Rgb::from_channels(0, x as u8 ^ y as u8, 0, 0);
img.put_pixel(x, y, pixel);
}
}
let _ = img.save("ou... | 538Munching squares | 15rust | lqscc |
def backToBig(num: String, oldBase: Int): BigInt = BigInt(num, oldBase)
def bigToBase(num: BigInt, newBase: Int): String = num.toString(newBase) | 528Non-decimal radices/Convert | 16scala | 7fvr9 |
import scala.swing.Swing.pair2Dimension
import scala.swing.{Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication}
object XorPattern extends SimpleSwingApplication {
def top = new MainFrame {
preferredSize = (300, 300)
title = "Rosetta Code >>> Task: Munching squares | Language: Scala"
contents = ... | 538Munching squares | 16scala | u8ov8 |
(def size 8)
(defn extends? [v n]
(let [k (count v)]
(not-any? true?
(for [i (range k):let [vi (v i)]]
(or
(= vi n)
(= (- k i) (Math/abs (- n vi))))))))
(defn extend [vs]
(for [v vs
n (range 1 (inc size)):when (extends? v n)]
(conj v n)))
(def solutions
(nt... | 543N-queens problem | 6clojure | 4is5o |
>>> import re
>>> def ms2(txt=, sep=[, , ]):
if not txt or not sep:
return []
ans = m = []
for m in re.finditer('(.*?)(?:' + '|'.join('('+re.escape(s)+')' for s in sep) + ')', txt):
ans += [m.group(1), (m.lastindex-2, m.start(m.lastindex))]
if m and txt[m.end(m.lastindex):]:
ans += [txt[m.end(m.lastindex):]]
... | 539Multisplit | 3python | gnn4h |
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod a b))))
(defn lcm [a b]
(/ (* a b) (gcd a b)))
(def NaN (Math/log -1))
(defn ord' [a [p e]]
(let [m (imath/expt p e)
t (* (quot m p) (dec p))]
(loop [dv (factor/divisors t)]
(let [d (first dv)]
... | 544Multiplicative order | 6clojure | 9wbma |
package main
import "fmt"
func ord(n int) string {
s := "th"
switch c := n % 10; c {
case 1, 2, 3:
if n%100/10 == 1 {
break
}
switch c {
case 1:
s = "st"
case 2:
s = "nd"
case 3:
s = "rd"
}
}
re... | 540N'th | 0go | 61p3p |
from __future__ import print_function
from itertools import count, islice
def narcissists():
for digits in count(0):
digitpowers = [i**digits for i in range(10)]
for n in range(int(10**(digits-1)), 10**digits):
div, digitpsum = n, 0
while div:
div, mod = divm... | 536Narcissistic decimal number | 3python | tk1fw |
use strict;
sub nthroot ($$)
{
my ( $n, $A ) = @_;
my $x0 = $A / $n;
my $m = $n - 1.0;
while(1) {
my $x1 = ($m * $x0 + $A / ($x0 ** $m)) / $n;
return $x1 if abs($x1 - $x0) < abs($x0 * 1e-9);
$x0 = $x1;
}
} | 531Nth root | 2perl | og18x |
for (u in 1:10000000) {
j <- nchar(u)
set2 <- c()
for (i in 1:j) {
set2[i] <- as.numeric(substr(u, i, i))
}
control <- c()
for (k in 1:j) {
control[k] <- set2[k]^(j)
}
if (sum(control) == u) print(u)
} | 536Narcissistic decimal number | 13r | irho5 |
import Data.Array
ordSuffs :: Array Integer String
ordSuffs = listArray (0,9) ["th", "st", "nd", "rd", "th",
"th", "th", "th", "th", "th"]
ordSuff :: Integer -> String
ordSuff n = show n ++ suff n
where suff m | (m `rem` 100) >= 11 && (m `rem` 100) <= 13 = "th"
| otherwise... | 540N'th | 8haskell | jtf7g |
println(String(26, radix: 16)) | 528Non-decimal radices/Convert | 17swift | u8mvg |
text = 'a!===b=!=c'
separators = ['==', '!=', '=']
def multisplit_simple(text, separators)
text.split(Regexp.union(separators))
end
p multisplit_simple(text, separators) | 539Multisplit | 14ruby | 7ffri |
foo *foos = malloc(n * sizeof(*foos));
for (int i = 0; i < n; i++)
init_foo(&foos[i]); | 545Multiple distinct objects | 5c | 61732 |
package main
import (
"fmt"
"math/big"
)
func main() {
moTest(big.NewInt(37), big.NewInt(3343))
b := big.NewInt(100)
moTest(b.Add(b.Exp(ten, b, nil), one), big.NewInt(7919))
moTest(b.Add(b.Exp(ten, b.SetInt64(1000), nil), one), big.NewInt(15485863))
moTest(b.Sub(b.Exp(ten, b.SetInt64(10000... | 544Multiplicative order | 0go | k3nhz |
function nthroot($number, $root, $p = P)
{
$x[0] = $number;
$x[1] = $number/$root;
while(abs($x[1]-$x[0]) > $p)
{
$x[0] = $x[1];
$x[1] = (($root-1)*$x[1] + $number/pow($x[1], $root-1))/$root;
}
return $x[1];
} | 531Nth root | 12php | gnm42 |
package main
import(
"fmt"
"math"
)
var powers [10]int
func isMunchausen(n int) bool {
if n < 0 { return false }
n64 := int64(n)
nn := n64
var sum int64 = 0
for nn > 0 {
sum += int64(powers[nn % 10])
if sum > n64 { return false }
nn /= 10
}
return sum == n... | 541Munchausen numbers | 0go | cxe9g |
import scala.annotation.tailrec
def multiSplit(str:String, sep:Seq[String])={
def findSep(index:Int)=sep find (str startsWith (_, index))
@tailrec def nextSep(index:Int):(Int,Int)=
if(index>str.size) (index, 0) else findSep(index) match {
case Some(sep) => (index, sep.size)
case _ => nextS... | 539Multisplit | 16scala | b66k6 |
user> (take 3 (repeat (rand)))
(0.2787011365537204 0.2787011365537204 0.2787011365537204)
user> (take 3 (repeatedly rand))
(0.8334795669220695 0.08405601245793926 0.5795448744634744)
user> | 545Multiple distinct objects | 6clojure | lqpcb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.