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 : -1 : 0; } my @mebius; push @mebius, ($_) for 1 .. (my $upto = 199); say "Mbius sequence - First $upto terms:\n" . (' 'x4 . sprintf "@{['%4d' x $upto]}", @mebius) =~ s/((.){80})/$1\n/gr;
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): ' De-ligature. De-accent a char' de = decomposition(c) if de: de = [d for d in de.split() if all(c.lower() in hexdigits for c in d)] n = name(c, c).upper() if len(de)> 1 and 'PRECEDE' in n: de[1], de[0] = de[0], de[1] tmp = [ unichr(int(k, 16)) for k in de] base, others = tmp[0], tmp[1:] if 'LIGATURE' in n: base += others.pop(0) else: base = c return base def sortkeygen(s): '''Generate 'natural' sort key for s Doctests: >>> sortkeygen(' some extra spaces ') [u'some extra spaces'] >>> sortkeygen('CasE InseNsItIve') [u'case insensitive'] >>> sortkeygen('The Wind in the Willows') [u'wind in the willows'] >>> sortkeygen(u'\462 ligature') [u'ij ligature'] >>> sortkeygen(u'\335\375 upper/lower case Y with acute accent') [u'yy upper/lower case y with acute accent'] >>> sortkeygen('foo9.txt') [u'foo', 9, u'.txt'] >>> sortkeygen('x9y99') [u'x', 9, u'y', 99] ''' s = unicode(s).strip() s = ' '.join(s.split()) s = s.lower() words = s.split() if len(words) > 1 and words[0] in commonleaders: s = ' '.join( words[1:]) s = ''.join(splitchar(c) for c in s) s = ''.join( replacements.get(ch, ch) for ch in s ) s = [ int(.join(g)) if isinteger else .join(g) for isinteger,g in groupby(s, lambda x: x in decdigits)] return s def naturalsort(items): ''' Naturally sort a series of strings Doctests: >>> naturalsort(['The Wind in the Willows','The 40th step more', 'The 39 steps', 'Wanda']) ['The 39 steps', 'The 40th step more', 'Wanda', 'The Wind in the Willows'] ''' return sorted(items, key=sortkeygen) if __name__ == '__main__': import string ns = naturalsort print '\n txt = ['%signore leading spaces: 2%+i'% (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted:'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['ignore m.a.s%s spaces: 2%+i'% (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted:'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['Equiv.%sspaces: 3%+i'% (ch, i-3) for i,ch in enumerate(reversed(string.whitespace))] print 'Text strings:'; pp(txt) print 'Normally sorted:'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n s = 'CASE INDEPENENT' txt = [s[:i].lower() + s[i:] + ': 3%+i'% (i-3) for i in range(1,5)] print 'Text strings:'; pp(txt) print 'Normally sorted:'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] print 'Text strings:'; pp(txt) print 'Normally sorted:'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['The Wind in the Willows','The 40th step more', 'The 39 steps', 'Wanda'] print 'Text strings:'; pp(txt) print 'Normally sorted:'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['Equiv.%s accents: 2%+i'% (ch, i-2) for i,ch in enumerate(u'\xfd\xddyY')] print 'Text strings:'; pp(txt) print 'Normally sorted:'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = [u'\462 ligatured ij', 'no ligature',] print 'Text strings:'; pp(txt) print 'Normally sorted:'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n s = u's' txt = ['Start with an%s: 2%+i'% (ch, i-2) for i,ch in enumerate(s)] print 'Text strings:'; pp(txt) print 'Normally sorted:'; print '\n'.join(sorted(txt)) print 'Naturally sorted:'; print '\n'.join(ns(txt))
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[] = { , , }; parse_sep(, seps, 3); return 0; }
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..$ shift @{$s[$_]} if $s[$_][0] == $n; push @{$s[$_]}, $n * $m[$_] } return $n } } sub abbrev { my($n) = @_; return $n if length($n) <= 50; substr($n,0,10) . "...(@{[length($n) - 2*10]} digits omitted)..." . substr($n, -10, 10) } my @primes = @{primes(10_000)}; my $start = 3000; my $cnt = 3; for my $n_smooth (0..9) { say "\nFirst 25, and ${start}th through @{[$start+2]}nd $primes[$n_smooth]-smooth numbers:"; my $s = smooth_numbers(@primes[0..$n_smooth]); my @S25; push @S25, $s->() for 1..25; say join ' ', @S25; my @Sm; my $c = 25; do { my $sn = $s->(); push @Sm, abbrev($sn) if ++$c >= $start; } until @Sm == $cnt; say join ' ', @Sm; } $start = 30000; $cnt = 20; for my $n_smooth (95..97) { say "\n${start}th through @{[$start+$cnt-1]}th $primes[$n_smooth]-smooth numbers:"; my $s = smooth_numbers(@primes[0..$n_smooth]); my(@Sm,$c); do { my $sn = $s->(); push @Sm, $sn if ++$c >= $start; } until @Sm == $cnt; say join ' ', @Sm; }
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+t2) if math.Abs(x-x0)*1e15 < x { break } } return 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 isPrime(i)): if (N% (i * i) == 0): return 0 else: p = p + 1 if(p% 2 != 0): return -1 else: return 1 print() for i in range(1, 100): print(f, end = '') if i% 20 == 0: print()
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 BigDecimal).setScale(7, HALF_UP) }
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: if isPrime(s - 1) and s - 1 > primes[-1]: primes.append(s - 1) if isPrime(s + 1) and s + 1 > primes[-1]: primes.append(s + 1) s += 6 def nsmooth(n, size): if n < 2 or n > 521: raise Exception() if size < 1: raise Exception() bn = n ok = False for prime in primes: if bn == prime: ok = True break if not ok: raise Exception() ns = [0] * size ns[0] = 1 next = [] for prime in primes: if prime > bn: break next.append(prime) indicies = [0] * len(next) for m in xrange(1, size): ns[m] = min(next) for i in xrange(0, len(indicies)): if ns[m] == next[i]: indicies[i] += 1 next[i] = primes[i] * ns[indicies[i]] return ns def main(): init() for p in primes: if p >= 30: break print , p, print nsmooth(p, 25) print for p in primes[1:]: if p >= 30: break print , p, print nsmooth(p, 3002)[2999:] print for p in [503, 509, 521]: print , p, print nsmooth(p, 30019)[29999:] print main()
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; break; default: i = 0; }; snprintf(buf, len, , num, suffixes[i]); return buf; } int main(void) { int i; printf(); for (i = 0; i < 26; i++) { char s[5]; printf(, addSuffix(i, s, 5)); } putchar('\n'); printf(); for (i = 250; i < 266; i++) { char s[6]; printf(, addSuffix(i, s, 6)); } putchar('\n'); printf(); for (i = 1000; i < 1026; i++) { char s[7]; printf(, addSuffix(i, s, 7)); } putchar('\n'); return 0; }
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(int y = 0; y < getHeight();y++){ for(int x = 0; x < getWidth();x++){ g.setColor(new Color(0, (x ^ y) % 256, 0)); g.drawLine(x, y, x, y); } } } }; add(xorPanel); setSize(300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args){ new XorPattern(); } }
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| pc if prime? pc } end def nsmooth(n, limit) raise if n < 2 || n > 521 || limit < 1 raise unless prime? n primes = gen_primes(2, n) ns = [0] * limit ns[0] = 1 nextp = primes[0..primes.index(n)] indices = [0] * nextp.size (1...limit).each do |m| ns[m] = nextp.min (0...indices.size).each do |i| if ns[m] == nextp[i] indices[i] += 1 nextp[i] = primes[i] * ns[indices[i]] end end end ns end gen_primes(2, 29).each do |prime| print print nsmooth(prime, 25) puts end puts gen_primes(3, 29).each do |prime| print print nsmooth(prime, 3002)[2999..-1] puts end puts gen_primes(503, 521).each do |prime| print print nsmooth(prime, 30019)[29999..-1] puts end
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 { return false; } p += 4; } true } fn find_primes(from: u32, to: u32) -> Vec<u32> { let mut primes: Vec<u32> = Vec::new(); for p in from..=to { if is_prime(p) { primes.push(p); } } primes } fn find_nsmooth_numbers(n: u32, count: usize) -> Vec<u128> { let primes = find_primes(2, n); let num_primes = primes.len(); let mut result = Vec::with_capacity(count); let mut queue = Vec::with_capacity(num_primes); let mut index = Vec::with_capacity(num_primes); for i in 0..num_primes { index.push(0); queue.push(primes[i] as u128); } result.push(1); for i in 1..count { for p in 0..num_primes { if queue[p] == result[i - 1] { index[p] += 1; queue[p] = result[index[p]] * primes[p] as u128; } } let mut min_index: usize = 0; for p in 1..num_primes { if queue[min_index] > queue[p] { min_index = p; } } result.push(queue[min_index]); } result } fn print_nsmooth_numbers(n: u32, begin: usize, count: usize) { let numbers = find_nsmooth_numbers(n, begin + count); print!("{}: {}", n, &numbers[begin]); for i in 1..count { print!(", {}", &numbers[begin + i]); } println!(); } fn main() { println!("First 25 n-smooth numbers for n = 2 -> 29:"); for n in 2..=29 { if is_prime(n) { print_nsmooth_numbers(n, 0, 25); } } println!(); println!("3 n-smooth numbers starting from 3000th for n = 3 -> 29:"); for n in 3..=29 { if is_prime(n) { print_nsmooth_numbers(n, 2999, 3); } } println!(); println!("20 n-smooth numbers starting from 30,000th for n = 503 -> 521:"); for n in 503..=521 { if is_prime(n) { print_nsmooth_numbers(n, 29999, 20); } } }
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 str (interpose " " (map n-th (range 1000 1026))))
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 self% i == 0 { return false } } return true } } @inlinable public func smoothN<T: BinaryInteger>(n: T, count: Int) -> [T] { let primes = stride(from: 2, to: n + 1, by: 1).filter({ $0.isPrime }) var next = primes var indices = [Int](repeating: 0, count: primes.count) var res = [T](repeating: 0, count: count) res[0] = 1 guard count > 1 else { return res } for m in 1..<count { res[m] = next.min()! for i in 0..<indices.count where res[m] == next[i] { indices[i] += 1 next[i] = primes[i] * res[indices[i]] } } return res } for n in 2...29 where n.isPrime { print("The first 25 \(n)-smooth numbers are: \(smoothN(n: n, count: 25))") } print() for n in 3...29 where n.isPrime { print("The 3000...3002 \(n)-smooth numbers are: \(smoothN(n: BigInt(n), count: 3002).dropFirst(2999).prefix(3))") } print() for n in 503...521 where n.isPrime { print("The 30,000...30,019 \(n)-smooth numbers are: \(smoothN(n: BigInt(n), count: 30_019).dropFirst(29999).prefix(20))") }
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) end function createPalette() for i = 0, 255 do clr[i] = {i*2.8%256, i*3.2%256, i*1.5%256} end end function love.load() wid, hei = 256, 256 love.window.setMode(wid, hei) canvas = love.graphics.newCanvas() love.graphics.setCanvas(canvas) createPalette() drawMSquares() love.graphics.setCanvas() end function love.draw() love.graphics.setColor(1,1,1) love.graphics.draw(canvas) end
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) { printf(, i); } } return 0; }
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 posMatch = p } } ans = append(ans, txt[:posMatch]) txt = txt[posMatch+len(sepMatch):] } return } func main() { fmt.Printf("%q\n", ms("a!===b=!=c", []string{"==", "!=", "="})) }
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(long x = 0, count = 0; count < 25; x++){ if(isNarc(x)){ System.out.print(x + " "); count++; } } } }
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 == 12) 1000 else 500)) println("That's all") }
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, String, Int)] multisplit list delims = let ms [] acc pos = [(acc, [], pos)] ms l@(s:sx) acc pos = case trysplit l delims of Nothing -> ms sx (s: acc) (pos + 1) Just (d, sxx) -> (acc, d, pos): ms sxx [] (pos + genericLength d) in ms list [] 0 main :: IO () main = do let parsed = multisplit "a!===b=!=c" ["==", "!=", "="] mapM_ putStrLn [ "split string:" , intercalate "," $ map (\(a, _, _) -> a) parsed , "with [(string, delimiter, offset)]:" , show parsed ]
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 x = 0, count = 0; count < 25; x++){ if (isNarc(x)){ n.push(x); count++; } } return n.join(' '); }
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... to a^a + b^b + c^c ..." (let [digits-pwr (fn [n] (apply + (map #(math/expt % %) digits)))] (digits-pwr digits))) (defn find-numbers [max-range] " Filters for Munchausen numbers " (->> (range 1 (inc max-range)) (filter #(= (sum-power (get-digits %)) %)))) (println (find-numbers 5000))
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(); return EXIT_SUCCESS; }
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[]{"==", "!=", "="})) System.out.printf("\"%s\" ", s); } static List<String> multiSplit(String txt, String[] separators) { List<String> result = new ArrayList<>(); int txtLen = txt.length(), from = 0; for (int to = 0; to < txtLen; to++) { for (String sep : separators) { int sepLen = sep.length(); if (txt.regionMatches(to, sep, 0, sepLen)) { result.add(txt.substring(from, to)); from = to + sepLen; to = from - 1;
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^$j]); } } imagepng($im); imagedestroy($im);
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 + 1 until count == 25
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) s <- strsplit(s,"")[[1]] res <- sapply(s, function(x) which(map==x)) res <- as.vector((res-1)%*% b^((length(res)-1):0)) return(res) } int2str(255, 16) str2int("1a", 16)
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_separators => 1; print "\n";
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, j); j++); if (j < col) continue; hist[col] = i; solve(n, col + 1, hist); } } int main(int n, char **argv) { if (n <= 1 || (n = atoi(argv[1])) <= 0) n = 8; int hist[n]; solve(n, 0, hist); }
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 - rgb1.blue) * i / size), ) end pixmap = new(width, height) pixmap.each_pixel do |x, y| pixmap[x,y] = colours[(x^y)%size] end pixmap end end img = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW) img.save_as_png('xorpattern.png')
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 = m; m = n % m; n = t; } return n; } ulong lcm(ulong m, ulong n) { ulong g = gcd(m, n); return m / g * n; } ulong multi_order_p(ulong a, ulong p, ulong e) { ulong fac[10000]; ulong m = ipow(p, e); ulong t = m / p * (p - 1); int i, len = get_factors(t, fac); for (i = 0; i < len; i++) if (mpow(a, fac[i], m) == 1) return fac[i]; return 0; } ulong multi_order(ulong a, ulong m) { prime_factor pf[100]; int i, len = get_prime_factors(m, pf); ulong res = 1; for (i = 0; i < len; i++) res = lcm(res, multi_order_p(a, pf[i].p, pf[i].e)); return res; } int main() { sieve(); printf(, multi_order(37, 1000)); printf(, multi_order(54, 100001)); return 0; }
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().collect() } #[cfg(test)] #[test] fn test() { for value in 0..100u32 { for radix in 2..=36 { let s = format_with_radix(value, radix); let v = u32::from_str_radix(s.as_str(), radix).unwrap(); assert_eq!(value, v); } } } fn main() -> Result<(), Box<dyn std::error::Error>> { println!("{}", format_with_radix(0xdeadbeef, 2)); println!("{}", format_with_radix(0xdeadbeef, 36)); println!("{}", format_with_radix(0xdeadbeef, 16)); println!("{}", u32::from_str_radix("DeadBeef", 16)?); Ok(()) }
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("output.png"); }
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 = new Panel { protected override def paintComponent(g: Graphics2D) = { super.paintComponent(g) for { y <- 0 until size.getHeight.toInt x <- 0 until size.getWidth.toInt } { g.setColor(new Color(0, (x ^ y) % 256, 0)) g.drawLine(x, y, x, y) } } } centerOnScreen() } }
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 (nth (iterate extend [[]]) size)) (doseq [s solutions] (println s)) (println (count solutions) "solutions")
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):]] return ans >>> ms2() ['a', (1, 1), '', (0, 3), 'b', (2, 6), '', (1, 7), 'c'] >>> ms2(txt=, sep=[, , ]) ['a', (1, 1), '', (0, 3), '', (0, 4), 'b', (0, 6), '', (1, 7), 'c']
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)] (if (= (mmath/expm a d m) 1) d (recur (next dv))))))) (defn ord [a n] (if (not= (gcd a n) 1) NaN (->> (factor/factorize n) (map (partial ord' a)) (reduce lcm))))
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" } } return fmt.Sprintf("%d%s", n, s) } func main() { for n := 0; n <= 25; n++ { fmt.Printf("%s ", ord(n)) } fmt.Println() for n := 250; n <= 265; n++ { fmt.Printf("%s ", ord(n)) } fmt.Println() for n := 1000; n <= 1025; n++ { fmt.Printf("%s ", ord(n)) } fmt.Println() }
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 = divmod(div, 10) digitpsum += digitpowers[mod] if n == digitpsum: yield n for i, n in enumerate(islice(narcissists(), 25), 1): print(n, end=' ') if i% 5 == 0: print() print()
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 = ordSuffs ! (m `rem` 10) printOrdSuffs :: [Integer] -> IO () printOrdSuffs = putStrLn . unwords . map ordSuff main :: IO () main = do printOrdSuffs [ 0.. 25] printOrdSuffs [ 250.. 265] printOrdSuffs [1000..1025]
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), nil), one), big.NewInt(22801763489)) moTest(big.NewInt(1511678068), big.NewInt(7379191741)) moTest(big.NewInt(3047753288), big.NewInt(2257683301)) } func moTest(a, n *big.Int) { if a.BitLen() < 100 { fmt.Printf("ord(%v)", a) } else { fmt.Print("ord([big])") } if n.BitLen() < 100 { fmt.Printf(" mod%v ", n) } else { fmt.Print(" mod [big] ") } if !n.ProbablyPrime(20) { fmt.Println("not computed. modulus must be prime for this algorithm.") return } fmt.Println("=", moBachShallit58(a, n, factor(new(big.Int).Sub(n, one)))) } var one = big.NewInt(1) var two = big.NewInt(2) var ten = big.NewInt(10) func moBachShallit58(a, n *big.Int, pf []pExp) *big.Int { n1 := new(big.Int).Sub(n, one) var x, y, o1, g big.Int mo := big.NewInt(1) for _, pe := range pf { y.Quo(n1, y.Exp(pe.prime, big.NewInt(pe.exp), nil)) var o int64 for x.Exp(a, &y, n); x.Cmp(one) > 0; o++ { x.Exp(&x, pe.prime, n) } o1.Exp(pe.prime, o1.SetInt64(o), nil) mo.Mul(mo, o1.Quo(&o1, g.GCD(nil, nil, mo, &o1))) } return mo } type pExp struct { prime *big.Int exp int64 } func factor(n *big.Int) (pf []pExp) { var e int64 for ; n.Bit(int(e)) == 0; e++ { } if e > 0 { n.Rsh(n, uint(e)) pf = []pExp{{big.NewInt(2), e}} } s := sqrt(n) q, r := new(big.Int), new(big.Int) for d := big.NewInt(3); n.Cmp(one) > 0; d.Add(d, two) { if d.Cmp(s) > 0 { d.Set(n) } for e = 0; ; e++ { q.QuoRem(n, d, r) if r.BitLen() > 0 { break } n.Set(q) } if e > 0 { pf = append(pf, pExp{new(big.Int).Set(d), e}) s = sqrt(n) } } return } func sqrt(n *big.Int) *big.Int { a := new(big.Int) for b := new(big.Int).Set(n); ; { a.Set(b) b.Rsh(b.Add(b.Quo(n, a), a), 1) if b.Cmp(a) >= 0 { return a } } return a.SetInt64(0) }
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 == n64 } func main() {
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 _ => nextSep(index + 1) } def getParts(start:Int, pos:(Int,Int)):List[String]={ val part=str slice (start, pos._1) if(pos._2==0) List(part) else part :: getParts(pos._1+pos._2, nextSep(pos._1+pos._2)) } getParts(0, nextSep(0)) } println(multiSplit("a!===b=!=c", Seq("!=", "==", "=")))
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