code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
echo time(), ;
161System time
12php
ixlov
(() => { "use strict";
162Sum of elements below main diagonal of matrix
10javascript
s16qz
let setA: Set<String> = ["John", "Bob", "Mary", "Serena"] let setB: Set<String> = ["Jim", "Mary", "John", "Bob"] println(setA.exclusiveOr(setB))
159Symmetric difference
17swift
juo74
>>> while True: k = float(input('K? ')) print( % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8)) K? 21.0 21 Kelvin = -252.15 Celsius = -421.87 Fahrenheit = 37.8 Rankine degrees. K? 222.2 222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees. K?
157Temperature conversion
3python
26wlz
convert_Kelvin <- function(K){ if (!is.numeric(K)) stop("\n Input has to be numeric") return(list( Kelvin = K, Celsius = K - 273.15, Fahreneit = K * 1.8 - 459.67, Rankine = K * 1.8 )) } convert_Kelvin(21)
157Temperature conversion
13r
mfpy4
use strict; use warnings; use List::Util qw( sum ); my $matrix = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]; my $lowersum = sum map @{ $matrix->[$_] }[0 .. $_ - 1], 1 .. $ print "lower sum = $lowersum\n";
162Sum of elements below main diagonal of matrix
2perl
zo5tb
package main import "fmt" type pair struct{ x, y int } func main() {
163Sum and product puzzle
0go
f02d0
import time print time.ctime()
161System time
3python
glx4h
import Data.List (intersect) s1, s2, s3, s4 :: [(Int, Int)] s1 = [(x, y) | x <- [1 .. 100], y <- [1 .. 100], 1 < x && x < y && x + y < 100] add, mul :: (Int, Int) -> Int add (x, y) = x + y mul (x, y) = x * y sumEq, mulEq :: (Int, Int) -> [(Int, Int)] sumEq p = filter (\q -> add q == add p) s1 mulEq p = filter (\q -> mul q == mul p) s1 s2 = filter (\p -> all (\q -> (length $ mulEq q) /= 1) (sumEq p)) s1 s3 = filter (\p -> length (mulEq p `intersect` s2) == 1) s2 s4 = filter (\p -> length (sumEq p `intersect` s3) == 1) s3 main = print s4
163Sum and product puzzle
8haskell
4ca5s
Sys.time()
161System time
13r
vy127
package org.rosettacode; import java.util.ArrayList; import java.util.List; public class SumAndProductPuzzle { private final long beginning; private final int maxSum; private static final int MIN_VALUE = 2; private List<int[]> firstConditionExcludes = new ArrayList<>(); private List<int[]> secondConditionExcludes = new ArrayList<>(); public static void main(String... args){ if (args.length == 0){ new SumAndProductPuzzle(100).run(); new SumAndProductPuzzle(1684).run(); new SumAndProductPuzzle(1685).run(); } else { for (String arg : args){ try{ new SumAndProductPuzzle(Integer.valueOf(arg)).run(); } catch (NumberFormatException e){ System.out.println("Please provide only integer arguments. " + "Provided argument " + arg + " was not an integer. " + "Alternatively, calling the program with no arguments " + "will run the puzzle where maximum sum equals 100, 1684, and 1865."); } } } } public SumAndProductPuzzle(int maxSum){ this.beginning = System.currentTimeMillis(); this.maxSum = maxSum; System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " started at " + String.valueOf(beginning) + "."); } public void run(){ for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){ for (int y = x + 1; y < maxSum - MIN_VALUE; y++){ if (isSumNoGreaterThanMax(x,y) && isSKnowsPCannotKnow(x,y) && isPKnowsNow(x,y) && isSKnowsNow(x,y) ){ System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) + " in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } } } System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } public boolean isSumNoGreaterThanMax(int x, int y){ return x + y <= maxSum; } public boolean isSKnowsPCannotKnow(int x, int y){ if (firstConditionExcludes.contains(new int[] {x, y})){ return false; } for (int[] addends : sumAddends(x, y)){ if ( !(productFactors(addends[0], addends[1]).size() > 1) ) { firstConditionExcludes.add(new int[] {x, y}); return false; } } return true; } public boolean isPKnowsNow(int x, int y){ if (secondConditionExcludes.contains(new int[] {x, y})){ return false; } int countSolutions = 0; for (int[] factors : productFactors(x, y)){ if (isSKnowsPCannotKnow(factors[0], factors[1])){ countSolutions++; } } if (countSolutions == 1){ return true; } else { secondConditionExcludes.add(new int[] {x, y}); return false; } } public boolean isSKnowsNow(int x, int y){ int countSolutions = 0; for (int[] addends : sumAddends(x, y)){ if (isPKnowsNow(addends[0], addends[1])){ countSolutions++; } } return countSolutions == 1; } public List<int[]> sumAddends(int x, int y){ List<int[]> list = new ArrayList<>(); int sum = x + y; for (int addend = MIN_VALUE; addend < sum - addend; addend++){ if (isSumNoGreaterThanMax(addend, sum - addend)){ list.add(new int[]{addend, sum - addend}); } } return list; } public List<int[]> productFactors(int x, int y){ List<int[]> list = new ArrayList<>(); int product = x * y; for (int factor = MIN_VALUE; factor < product / factor; factor++){ if (product % factor == 0){ if (isSumNoGreaterThanMax(factor, product / factor)){ list.add(new int[]{factor, product / factor}); } } } return list; } }
163Sum and product puzzle
9java
czj9h
from numpy import array, tril, sum A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]] print(sum(tril(A, -1)))
162Sum of elements below main diagonal of matrix
3python
3i4zc
mat <- rbind(c(1,3,7,8,10), c(2,4,16,14,4), c(3,1,9,18,11), c(12,14,17,18,20), c(7,1,3,9,5)) print(sum(mat[lower.tri(mat)]))
162Sum of elements below main diagonal of matrix
13r
ds2nt
(function () { 'use strict';
163Sum and product puzzle
10javascript
591ur
module TempConvert FROM_TEMP_SCALE_TO_K = {'kelvin' => lambda{|t| t}, 'celsius' => lambda{|t| t + 273.15}, 'fahrenheit' => lambda{|t| (t + 459.67) * 5/9.0}, 'rankine' => lambda{|t| t * 5/9.0}, 'delisle' => lambda{|t| 373.15 - t * 2/3.0}, 'newton' => lambda{|t| t * 100/33.0 + 273.15}, 'reaumur' => lambda{|t| t * 5/4.0 + 273.15}, 'roemer' => lambda{|t| (t - 7.5) * 40/21.0 + 273.15}} TO_TEMP_SCALE_FROM_K = {'kelvin' => lambda{|t| t}, 'celsius' => lambda{|t| t - 273.15}, 'fahrenheit' => lambda{|t| t * 9/5.0 - 459.67}, 'rankine' => lambda{|t| t * 9/5.0}, 'delisle' => lambda{|t| (373.15 - t) * 3/2.0}, 'newton' => lambda{|t| (t - 273.15) * 33/100.0}, 'reaumur' => lambda{|t| (t - 273.15) * 4/5.0}, 'roemer' => lambda{|t| (t - 273.15) * 21/40.0 + 7.5}} SUPPORTED_SCALES = FROM_TEMP_SCALE_TO_K.keys.join('|') def self.method_missing(meth, *args, &block) if valid_temperature_conversion?(meth) then convert_temperature(meth, *args) else super end end def self.respond_to_missing?(meth, include_private = false) valid_temperature_conversion?(meth) || super end def self.valid_temperature_conversion?(meth) !!(meth.to_s =~ /( end def self.convert_temperature(meth, temp) from_scale, to_scale = meth.to_s.split() return temp.to_f if from_scale == to_scale TO_TEMP_SCALE_FROM_K[to_scale].call(FROM_TEMP_SCALE_TO_K[from_scale].call(temp)).round(2) end end
157Temperature conversion
14ruby
umqvz
object TemperatureConversion extends App { def kelvinToCelsius(k: Double) = k + 273.15 def kelvinToFahrenheit(k: Double) = k * 1.8 - 459.67 def kelvinToRankine(k: Double) = k * 1.8 if (args.length == 1) { try { val kelvin = args(0).toDouble if (kelvin >= 0) { println(f"K $kelvin%2.2f") println(f"C ${kelvinToCelsius(kelvin)}%2.2f") println(f"F ${kelvinToFahrenheit(kelvin)}%2.2f") println(f"R ${kelvinToRankine(kelvin)}%2.2f") } else println("%2.2f K is below absolute zero", kelvin) } catch { case e: NumberFormatException => System.out.println(e) case e: Throwable => { println("Some other exception type:") e.printStackTrace() } } } else println("Temperature not given.") }
157Temperature conversion
16scala
r2ogn
arr = [ [ 1, 3, 7, 8, 10], [ 2, 4, 16, 14, 4], [ 3, 1, 9, 18, 11], [12, 14, 17, 18, 20], [ 7, 1, 3, 9, 5] ] p arr.each_with_index.sum {|row, x| row[0, x].sum}
162Sum of elements below main diagonal of matrix
14ruby
ydr6n
fn main() -> std::io::Result<()> { print!("Enter temperature in Kelvin to convert: "); let mut input = String::new(); std::io::stdin().read_line(&mut input)?; match input.trim().parse::<f32>() { Ok(kelvin) => { if kelvin < 0.0 { println!("Negative Kelvin values are not acceptable."); } else { println!("{} K", kelvin); println!("{} C", kelvin - 273.15); println!("{} F", kelvin * 1.8 - 459.67); println!("{} R", kelvin * 1.8); } } _ => println!("Could not parse the input to a number."), } Ok(()) }
157Temperature conversion
15rust
59suq
t = Time.now puts t puts t.to_i puts t.to_f puts Time.now.to_r
161System time
14ruby
7vsri
null
163Sum and product puzzle
11kotlin
3i5z5
null
161System time
15rust
ju072
println(new java.util.Date)
161System time
16scala
bgik6
function print_count(t) local cnt = 0 for k,v in pairs(t) do cnt = cnt + 1 end print(cnt .. ' candidates') end function make_pair(a,b) local t = {} table.insert(t, a)
163Sum and product puzzle
1lua
6n439
func KtoC(kelvin: Double)->Double{ return kelvin-273.15 } func KtoF(kelvin: Double)->Double{ return ((kelvin-273.15)*1.8)+32 } func KtoR(kelvin: Double)->Double{ return ((kelvin-273.15)*1.8)+491.67 } var k
157Temperature conversion
17swift
vyx2r
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func suffize(arg string) { fields := strings.Fields(arg) a := fields[0] if a == "" { a = "0" } var places, base int var frac, radix string switch len(fields) { case 1: places = -1 base = 10 case 2: places, _ = strconv.Atoi(fields[1]) base = 10 frac = strconv.Itoa(places) case 3: if fields[1] == "," { places = 0 frac = "," } else { places, _ = strconv.Atoi(fields[1]) frac = strconv.Itoa(places) } base, _ = strconv.Atoi(fields[2]) if base != 2 && base != 10 { base = 10 } radix = strconv.Itoa(base) } a = strings.Replace(a, ",", "", -1)
164Suffixation of decimal numbers
0go
mfgyi
use List::Util qw(min max first); sub sufficate { my($val, $type, $round) = @_; $type //= 'M'; if ($type =~ /^\d$/) { $round = $type; $type = 'M' } my $s = ''; if (substr($val,0,1) eq '-') { $s = '-'; $val = substr $val, 1 } $val =~ s/,//g; if ($val =~ m/e/i) { my ($m,$e) = split /[eE]/, $val; $val = ($e < 0) ? $m * 10**-$e : $m * 10**$e; } my %s; if ($type eq 'M') { my @x = qw<K M G T P E Z Y X W V U>; $s{$x[$_]} = 1000 * 10 ** ($_*3) for 0..$ } elsif ($type eq 'B') { my @x = qw<Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui>; $s{$x[$_]} = 2 ** (10*($_+1)) for 0..$ } elsif ($type eq 'G') { $s{'googol'} = 10**100 } else { return 'What we have here is a failure to communicate...' } my $k; if (abs($val) < (my $m = min values %s)) { $k = first { $s{$_} == $m } keys %s; } elsif (abs($val) > (my $x = max values %s)) { $k = first { $s{$_} == $x } keys %s; } else { for my $key (sort { $s{$a} <=> $s{$b} } keys %s) { next unless abs($val)/$s{$key} < min values %s; $k = $key; last; } } my $final = abs($val)/$s{$k}; $final = round($final,$round) if defined $round; $s . $final . $k } sub round { my($num,$dig) = @_; if ($dig == 0) { int 0.5 + $num } elsif ($dig < 0) { 10**-$dig * int(0.5 + $num/10**-$dig) } else { my $fmt = '%.' . $dig . 'f'; sprintf $fmt, $num } } sub comma { my($i) = @_; my ($whole, $frac) = split /\./, $i; (my $s = reverse $whole) =~ s/(.{3})/$1,/g; ($s = reverse $s) =~ s/^,//; $frac = $frac.defined ? ".$frac" : ''; return "$s$frac"; } my @tests = ( '87,654,321', '-998,877,665,544,332,211,000 3', '+112,233 0', '16,777,216 1', '456,789,100,000,000', '456,789,100,000,000 M 2', '456,789,100,000,000 B 5', '456,789,100,000.000e+00 M 0', '+16777216 B', '1.2e101 G', '347,344 M -2', '1122334455 Q', ); printf "%33s:%s\n", $_, sufficate(split ' ', $_) for @tests;
164Suffixation of decimal numbers
2perl
qptx6
use List::Util qw(none); sub grep_unique { my($by, @list) = @_; my @seen; for (@list) { my $x = &$by(@$_); $seen[$x]= defined $seen[$x] ? 0 : join ' ', @$_; } grep { $_ } @seen; } sub sums { my($n) = @_; my @sums; push @sums, [$_, $n - $_] for 2 .. int $n/2; @sums; } sub sum { $_[0] + $_[1] } sub product { $_[0] * $_[1] } for $i (2..97) { push @all_pairs, map { [$i, $_] } $i + 1..98 } %p_unique = map { $_ => 1 } grep_unique(\&product, @all_pairs); for my $p (@all_pairs) { push @s_pairs, [@$p] if none { $p_unique{join ' ', @$_} } sums sum @$p; } @p_pairs = map { [split ' ', $_] } grep_unique(\&product, @s_pairs); @final_pair = grep_unique(\&sum, @p_pairs); printf "X =%d, Y =%d\n", split ' ', $final_pair[0];
163Sum and product puzzle
2perl
prob0
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) if base == 10 and num >= 1e100: suffix_index = 13 num /= 1e100 elif num > 1: magnitude = math.floor(math.log(num, base)) suffix_index = min(math.floor(magnitude / exponent_distance), 12) num /= base ** (exponent_distance * suffix_index) else: suffix_index = 0 if digits is not None: num_str = f'{num:.{digits}f}' else: num_str = f'{num:.3f}'.strip('0').strip('.') return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '') tests = [('87,654,321',), ('-998,877,665,544,332,211,000', 3), ('+112,233', 0), ('16,777,216', 1), ('456,789,100,000,000', 2), ('456,789,100,000,000', 2, 10), ('456,789,100,000,000', 5, 2), ('456,789,100,000.000e+00', 0, 10), ('+16777216', None, 2), ('1.2e101',)] for test in tests: print(' '.join(str(i) for i in test) + ': ' + suffize(*test))
164Suffixation of decimal numbers
3python
s1zq9
import Foundation var = NSDate() println()
161System time
17swift
r2qgg
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_pairs = [(a,b) for a,b in all_pairs if all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))] product_counts = Counter(c*d for c,d in s_pairs) p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1] sum_counts = Counter(c+d for c,d in p_pairs) final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1] print(final_pairs)
163Sum and product puzzle
3python
17ipc
def add(x,y) x + y end def mul(x,y) x * y end def sumEq(s,p) s.select{|q| add(*p) == add(*q)} end def mulEq(s,p) s.select{|q| mul(*p) == mul(*q)} end s1 = (a = *2...100).product(a).select{|x,y| x<y && x+y<100} s2 = s1.select{|p| sumEq(s1,p).all?{|q| mulEq(s1,q).size!= 1} } s3 = s2.select{|p| (mulEq(s1,p) & s2).size == 1} p s3.select{|p| (sumEq(s1,p) & s3).size == 1}
163Sum and product puzzle
14ruby
ehdax
object ImpossiblePuzzle extends App { type XY = (Int, Int) val step0 = for { x <- 1 to 100 y <- 1 to 100 if 1 < x && x < y && x + y < 100 } yield (x, y) def sum(xy: XY) = xy._1 + xy._2 def prod(xy: XY) = xy._1 * xy._2 def sumEq(xy: XY) = step0 filter { sum(_) == sum(xy) } def prodEq(xy: XY) = step0 filter { prod(_) == prod(xy) } val step2 = step0 filter { sumEq(_) forall { prodEq(_).size != 1 }} val step3 = step2 filter { prodEq(_).intersect(step2).size == 1 } val step4 = step3 filter { sumEq(_).intersect(step3).size == 1 } println(step4) }
163Sum and product puzzle
16scala
s13qo
enum OP { ADD, SUB, JOIN }; typedef int (*cmp)(const void*, const void*); struct Expression{ int sum; int code; }expressions[NUMBER_OF_EXPRESSIONS]; int expressionsLength = 0; int compareExpressionBySum(const struct Expression* a, const struct Expression* b){ return a->sum - b->sum; } struct CountSum{ int counts; int sum; }countSums[NUMBER_OF_EXPRESSIONS]; int countSumsLength = 0; int compareCountSumsByCount(const struct CountSum* a, const struct CountSum* b){ return a->counts - b->counts; } int evaluate(int code){ int value = 0, number = 0, power = 1; for ( int k = 9; k >= 1; k-- ){ number = power*k + number; switch( code % 3 ){ case ADD: value = value + number; number = 0; power = 1; break; case SUB: value = value - number; number = 0; power = 1; break; case JOIN: power = power * 10 ; break; } code /= 3; } return value; } void print(int code){ static char s[19]; char* p = s; int a = 19683, b = 6561; for ( int k = 1; k <= 9; k++ ){ switch((code % a) / b){ case ADD: if ( k > 1 ) *p++ = '+'; break; case SUB: *p++ = '-'; break; } a = b; b = b / 3; *p++ = '0' + k; } *p = 0; printf(, evaluate(code), s); } void comment(char* string){ printf(, string); } void init(void){ for ( int i = 0; i < NUMBER_OF_EXPRESSIONS; i++ ){ expressions[i].sum = evaluate(i); expressions[i].code = i; } expressionsLength = NUMBER_OF_EXPRESSIONS; qsort(expressions,expressionsLength,sizeof(struct Expression),(cmp)compareExpressionBySum); int j = 0; countSums[0].counts = 1; countSums[0].sum = expressions[0].sum; for ( int i = 0; i < expressionsLength; i++ ){ if ( countSums[j].sum != expressions[i].sum ){ j++; countSums[j].counts = 1; countSums[j].sum = expressions[i].sum; } else countSums[j].counts++; } countSumsLength = j + 1; qsort(countSums,countSumsLength,sizeof(struct CountSum),(cmp)compareCountSumsByCount); } int main(void){ init(); comment(); const int givenSum = 100; struct Expression ex = { givenSum, 0 }; struct Expression* found; if ( found = bsearch(&ex,expressions,expressionsLength, sizeof(struct Expression),(cmp)compareExpressionBySum) ){ while ( found != expressions && (found-1)->sum == givenSum ) found--; while ( found != &expressions[expressionsLength] && found->sum == givenSum ) print(found++->code); } comment(); int maxSumIndex = countSumsLength - 1; while( countSums[maxSumIndex].sum < 0 ) maxSumIndex--; printf(, countSums[maxSumIndex].sum, countSums[maxSumIndex].counts); comment(); for ( int value = 0; ; value++ ){ struct Expression ex = { value, 0 }; if (!bsearch(&ex,expressions,expressionsLength, sizeof(struct Expression),(cmp)compareExpressionBySum)){ printf(, value); break; } } comment(); for ( int i = expressionsLength-1; i >= expressionsLength-10; i-- ) print(expressions[i].code); return 0; }
165Sum to 100
5c
ixyo2
double squaredsum(double *l, int e) { int i; double sum = 0.0; for(i = 0 ; i < e ; i++) sum += l[i]*l[i]; return sum; } int main() { double list[6] = {3.0, 1.0, 4.0, 1.0, 5.0, 9.0}; printf(, squaredsum(list, 6)); printf(, squaredsum(list, 0)); printf(, squaredsum(NULL, 0)); return 0; }
166Sum of squares
5c
vyj2o
unsigned long long sum35(unsigned long long limit) { unsigned long long sum = 0; for (unsigned long long i = 0; i < limit; i++) if (!(i % 3) || !(i % 5)) sum += i; return sum; } int main(int argc, char **argv) { unsigned long long limit; if (argc == 2) limit = strtoull(argv[1], NULL, 10); else limit = 1000; printf(, sum35(limit)); return 0; }
167Sum multiples of 3 and 5
5c
9t5m1
(defn sum-of-squares [v] (reduce #(+ %1 (* %2 %2)) 0 v))
166Sum of squares
6clojure
r21g2
int wideStrLen(wchar_t* str){ int i = 0; while(str[i++]!=00); return i; } void processFile(char* fileName,char plainKey, char cipherKey,int flag){ FILE* inpFile = fopen(fileName,); FILE* outFile; int i,len, diff = (flag==ENCRYPT)?(int)cipherKey - (int)plainKey:(int)plainKey - (int)cipherKey; wchar_t str[1000], *outStr; char* outFileName = (char*)malloc((strlen(fileName)+5)*sizeof(char)); sprintf(outFileName,,fileName,(flag==ENCRYPT)?:); outFile = fopen(outFileName,); while(fgetws(str,1000,inpFile)!=NULL){ len = wideStrLen(str); outStr = (wchar_t*)malloc((len + 1)*sizeof(wchar_t)); for(i=0;i<len;i++){ if((int)str[i]>=ALPHA && (int)str[i]<=OMEGA && flag == ENCRYPT) outStr[i] = (wchar_t)((int)str[i]+diff); else if((int)str[i]-diff>=ALPHA && (int)str[i]-diff<=OMEGA && flag == DECRYPT) outStr[i] = (wchar_t)((int)str[i]-diff); else outStr[i] = str[i]; } outStr[i]=str[i]; fputws(outStr,outFile); free(outStr); } fclose(inpFile); fclose(outFile); } int main(int argC,char* argV[]){ if(argC!=5) printf(,argV[0]); else{ processFile(argV[1],argV[2][0],argV[3][0],(argV[4][0]=='E'||argV[4][0]=='e')?ENCRYPT:DECRYPT); printf(,argV[1],(argV[4][0]=='E'||argV[4][0]=='e')?:); } return 0; }
168Substitution cipher
5c
mfvys
int SumDigits(unsigned long long n, const int base) { int sum = 0; for (; n; n /= base) sum += n % base; return sum; } int main() { printf(, SumDigits(1, 10), SumDigits(12345, 10), SumDigits(123045, 10), SumDigits(0xfe, 16), SumDigits(0xf0e, 16) ); return 0; }
169Sum digits of an integer
5c
4cj5t
(defn sum-mults [n & mults] (let [pred (apply some-fn (map #(fn [x] (zero? (mod x %))) mults))] (->> (range n) (filter pred) (reduce +)))) (println (sum-mults 1000 3 5))
167Sum multiples of 3 and 5
6clojure
umjvi
int arg[] = { 1,2,3,4,5 }; int arg_length = sizeof(arg)/sizeof(arg[0]); int *end = arg+arg_length; int sum = 0, prod = 1; int *p; for (p = arg; p!=end; ++p) { sum += *p; prod *= *p; }
170Sum and product of an array
5c
59ruk
double Invsqr(double n) { return 1 / (n*n); } int main (int argc, char *argv[]) { int i, start = 1, end = 1000; double sum = 0.0; for( i = start; i <= end; i++) sum += Invsqr((double)i); printf(, sum); return 0; }
171Sum of a series
5c
qp0xc
(defn sum-digits [n base] (let [number (if-not (string? n) (Long/toString n base) n)] (reduce + (map #(Long/valueOf (str %) base) number))))
169Sum digits of an integer
6clojure
h51jr
sumOfSquares(list) { var sum=0; list.forEach((var n) { sum+=(n*n); }); return sum; } main() { print(sumOfSquares([])); print(sumOfSquares([1,2,3])); print(sumOfSquares([10])); }
166Sum of squares
18dart
ydu65
package main import ( "fmt" "strings" ) var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ" func encode(s string) string { bs := []byte(s) for i := 0; i < len(bs); i++ { bs[i] = key[int(bs[i]) - 32] } return string(bs) } func decode(s string) string { bs := []byte(s) for i := 0; i < len(bs); i++ { bs[i] = byte(strings.IndexByte(key, bs[i]) + 32) } return string(bs) } func main() { s := "The quick brown fox jumps over the lazy dog, who barks VERY loudly!" enc := encode(s) fmt.Println("Encoded: ", enc) fmt.Println("Decoded: ", decode(enc)) }
168Substitution cipher
0go
ajs1f
(defn sum [vals] (reduce + vals)) (defn product [vals] (reduce * vals))
170Sum and product of an array
6clojure
jub7m
(reduce + (map #(/ 1.0 % %) (range 1 1001)))
171Sum of a series
6clojure
ixdom
int state[55], si = 0, sj = 0; int subrand(); void subrand_seed(int p1) { int i, j, p2 = 1; state[0] = p1 % MOD; for (i = 1, j = 21; i < 55; i++, j += 21) { if (j >= 55) j -= 55; state[j] = p2; if ((p2 = p1 - p2) < 0) p2 += MOD; p1 = state[j]; } si = 0; sj = 24; for (i = 0; i < 165; i++) subrand(); } int subrand() { int x; if (si == sj) subrand_seed(0); if (!si--) si = 54; if (!sj--) sj = 54; if ((x = state[si] - state[sj]) < 0) x += MOD; return state[si] = x; } int main() { subrand_seed(292929); int i; for (i = 0; i < 10; i++) printf(, subrand()); return 0; }
172Subtractive generator
5c
3i6za
import Data.Char (chr) import Data.Maybe (fromMaybe) import Data.Tuple (swap) import System.Environment (getArgs) data Command = Cipher String | Decipher String | Invalid alphabet :: String alphabet = chr <$> [32..126] cipherMap :: [(Char, Char)] cipherMap = zip alphabet (shuffle 20 alphabet) shuffle :: Int -> [a] -> [a] shuffle n xs = iterate go xs !! n where go [] = [] go xs = go (drop 2 xs) <> take 2 xs convert :: Eq a => [(a, a)] -> [a] -> [a] convert m = map (\x -> fromMaybe x (lookup x m)) runCommand :: Command -> String runCommand (Cipher s) = convert cipherMap s runCommand (Decipher s) = convert (swap <$> cipherMap) s runCommand Invalid = "Invalid arguments. Usage: simplecipher c|d <text>" parseArgs :: [String] -> Command parseArgs (x:y:xs) | x == "c" = Cipher y | x == "d" = Decipher y | otherwise = Invalid parseArgs _ = Invalid main :: IO () main = parseArgs <$> getArgs >>= putStrLn . runCommand
168Substitution cipher
8haskell
zo9t0
public class SubstitutionCipher { final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N" + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"; static String text = "Here we have to do is there will be a input/source " + "file in which we are going to Encrypt the file by replacing every " + "upper/lower case alphabets of the source file with another " + "predetermined upper/lower case alphabets or symbols and save " + "it into another output/encrypted file and then again convert " + "that output/encrypted file into original/decrypted file. This " + "type of Encryption/Decryption scheme is often called a " + "Substitution Cipher."; public static void main(String[] args) { String enc = encode(text); System.out.println("Encoded: " + enc); System.out.println("\nDecoded: " + decode(enc)); } static String encode(String s) { StringBuilder sb = new StringBuilder(s.length()); for (char c : s.toCharArray()) sb.append(key.charAt((int) c - 32)); return sb.toString(); } static String decode(String s) { StringBuilder sb = new StringBuilder(s.length()); for (char c : s.toCharArray()) sb.append((char) (key.indexOf((int) c) + 32)); return sb.toString(); } }
168Substitution cipher
9java
owt8d
package main import ( "fmt" "sort" ) const pow3_8 = 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3
165Sum to 100
0go
gl14n
int64_t PRIMES[PRIME_COUNT]; size_t primeSize = 0; bool isPrime(int n) { size_t i = 0; for (i = 0; i < primeSize; i++) { int64_t p = PRIMES[i]; if (n == p) { return true; } if (n % p == 0) { return false; } if (p * p > n) { break; } } return true; } void initialize() { int i; PRIMES[primeSize++] = 2; PRIMES[primeSize++] = 3; PRIMES[primeSize++] = 5; PRIMES[primeSize++] = 7; PRIMES[primeSize++] = 11; PRIMES[primeSize++] = 13; PRIMES[primeSize++] = 17; PRIMES[primeSize++] = 19; for (i = 21; primeSize < PRIME_COUNT;) { if (isPrime(i)) { PRIMES[primeSize++] = i; } i += 2; if (primeSize < PRIME_COUNT && isPrime(i)) { PRIMES[primeSize++] = i; } i += 2; } } void diff1(size_t diff) { int64_t pm0, pm1; int64_t fg1 = 0, fg2 = 0, lg1 = 0, lg2 = 0; size_t pos, count = 0; if (diff == 0) { return; } pm0 = PRIMES[0]; for (pos = 1; pos < PRIME_COUNT; pos++) { pm1 = pm0; pm0 = PRIMES[pos]; if (pm0 > 1000000) { break; } if (pm0 - pm1 == diff) { count++; if (fg1 == 0) { fg1 = pm1; fg2 = pm0; } lg1 = pm1; lg2 = pm0; } } printf(, diff, count, fg1, fg2, lg1, lg2); } void diff2(size_t d0, size_t d1) { int64_t pm0, pm1, pm2; int64_t fg1 = 0, fg2, fg3, lg1, lg2, lg3; size_t pos, count = 0; if (d0 == 0 || d1 == 0) { return; } pm1 = PRIMES[0]; pm0 = PRIMES[1]; for (pos = 2; pos < PRIME_COUNT; pos++) { pm2 = pm1; pm1 = pm0; pm0 = PRIMES[pos]; if (pm0 > 1000000) { break; } if (pm1 - pm2 == d0 && pm0 - pm1 == d1) { count++; if (fg1 == 0) { fg1 = pm2; fg2 = pm1; fg3 = pm0; } lg1 = pm2; lg2 = pm1; lg3 = pm0; } } printf(, d0, d1, count, fg1, fg2, fg3, lg1, lg2, lg3); } void diff3(size_t d0, size_t d1, size_t d2) { int64_t pm0, pm1, pm2, pm3; int64_t fg1 = 0, fg2, fg3, fg4, lg1, lg2, lg3, lg4; size_t pos, count = 0; if (d0 == 0 || d1 == 0 || d2 == 0) { return; } pm2 = PRIMES[0]; pm1 = PRIMES[1]; pm0 = PRIMES[2]; for (pos = 3; pos < PRIME_COUNT; pos++) { pm3 = pm2; pm2 = pm1; pm1 = pm0; pm0 = PRIMES[pos]; if (pm0 > 1000000) { break; } if (pm2 - pm3 == d0 && pm1 - pm2 == d1 && pm0 - pm1 == d2) { count++; if (fg1 == 0) { fg1 = pm3; fg2 = pm2; fg3 = pm1; fg4 = pm0; } lg1 = pm3; lg2 = pm2; lg3 = pm1; lg4 = pm0; } } printf(, d0, d1, d2, count, fg1, fg2, fg3, fg4, lg1, lg2, lg3, lg4); } int main() { initialize(); printf(); diff1(2); diff1(1); diff2(2, 2); diff2(2, 4); diff2(4, 2); diff3(6, 4, 2); return 0; }
173Successive prime differences
5c
r2rg7
import Control.Monad (replicateM) import Data.Char (intToDigit) import Data.List ( find, group, intercalate, nub, sort, sortBy, ) import Data.Monoid ((<>)) import Data.Ord (comparing) data Sign = Unsigned | Plus | Minus deriving (Eq, Show) universe :: [[(Int, Sign)]] universe = zip [1 .. 9] <$> filter ((/= Plus) . head) (replicateM 9 [Unsigned, Plus, Minus]) allNonNegativeSums :: [Int] allNonNegativeSums = sort $ filter (>= 0) (asSum <$> universe) uniqueNonNegativeSums :: [Int] uniqueNonNegativeSums = nub allNonNegativeSums asSum :: [(Int, Sign)] -> Int asSum xs = n + ( case s of [] -> 0 _ -> read s :: Int ) where (n, s) = foldr readSign (0, []) xs readSign :: (Int, Sign) -> (Int, String) -> (Int, String) readSign (i, x) (n, s) | x == Unsigned = (n, intToDigit i: s) | otherwise = ( ( case x of Plus -> (+) _ -> (-) ) n (read (show i <> s) :: Int), [] ) asString :: [(Int, Sign)] -> String asString = foldr signedDigit [] where signedDigit (i, x) s | x == Unsigned = intToDigit i: s | otherwise = ( case x of Plus -> " +" _ -> " -" ) <> [intToDigit i] <> s main :: IO () main = putStrLn $ unlines [ "Sums to 100:", unlines (asString <$> filter ((100 ==) . asSum) universe), "\n10 commonest sums (sum, number of routes to it):", show ( ((,) <$> head <*> length) <$> take 10 ( sortBy (flip (comparing length)) (group allNonNegativeSums) ) ), "\nFirst positive integer not expressible " <> "as a sum of this kind:", maybeReport ( find (uncurry (/=)) (zip [0 ..] uniqueNonNegativeSums) ), "\n10 largest sums:", show ( take 10 ( sortBy (flip compare) uniqueNonNegativeSums ) ) ] where maybeReport :: Show a => Maybe (a, b) -> String maybeReport (Just (x, _)) = show x maybeReport _ = "No gaps found"
165Sum to 100
8haskell
s1tqk
(defn xpat2-with-seed "produces an xpat2 function initialized from seed" [seed] (let [e9 1000000000 fs (fn [[i j]] [j (mod (- i j) e9)]) s (->> [seed 1] (iterate fs) (map first) (take 55) vec) rinit (map #(-> % inc (* 34) (mod 55) s) (range 55)) r-atom (atom [54 (int-array rinit)]) update (fn [[nprev r]] (let [n (-> nprev inc (mod 55)) rx #(get r (-> n (- %) (mod 55))) rn (-> (rx 55) (- (rx 24)) (mod e9)) _ (aset-int r n rn)] [n r])) xpat2 #(let [[n r] (swap! r-atom update)] (get r n)) _ (dotimes [_ 165] (xpat2))] xpat2)) (def xpat2 (xpat2-with-seed 292929)) (println (xpat2) (xpat2) (xpat2))
172Subtractive generator
6clojure
czl9b
null
168Substitution cipher
11kotlin
xbows
null
168Substitution cipher
1lua
qpix0
package rosettacode; import java.io.PrintStream; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; public class SumTo100 implements Runnable { public static void main(String[] args) { new SumTo100().run(); } void print(int givenSum) { Expression expression = new Expression(); for (int i = 0; i < Expression.NUMBER_OF_EXPRESSIONS; i++, expression.next()) { if (expression.toInt() == givenSum) { expression.print(); } } } void comment(String commentString) { System.out.println(); System.out.println(commentString); System.out.println(); } @Override public void run() { final Stat stat = new Stat(); comment("Show all solutions that sum to 100"); final int givenSum = 100; print(givenSum); comment("Show the sum that has the maximum number of solutions"); final int maxCount = Collections.max(stat.sumCount.keySet()); int maxSum; Iterator<Integer> it = stat.sumCount.get(maxCount).iterator(); do { maxSum = it.next(); } while (maxSum < 0); System.out.println(maxSum + " has " + maxCount + " solutions"); comment("Show the lowest positive number that can't be expressed"); int value = 0; while (stat.countSum.containsKey(value)) { value++; } System.out.println(value); comment("Show the ten highest numbers that can be expressed"); final int n = stat.countSum.keySet().size(); final Integer[] sums = stat.countSum.keySet().toArray(new Integer[n]); Arrays.sort(sums); for (int i = n - 1; i >= n - 10; i--) { print(sums[i]); } } private static class Expression { private final static int NUMBER_OF_DIGITS = 9; private final static byte ADD = 0; private final static byte SUB = 1; private final static byte JOIN = 2; final byte[] code = new byte[NUMBER_OF_DIGITS]; final static int NUMBER_OF_EXPRESSIONS = 2 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3; Expression next() { for (int i = 0; i < NUMBER_OF_DIGITS; i++) { if (++code[i] > JOIN) { code[i] = ADD; } else { break; } } return this; } int toInt() { int value = 0; int number = 0; int sign = (+1); for (int digit = 1; digit <= 9; digit++) { switch (code[NUMBER_OF_DIGITS - digit]) { case ADD: value += sign * number; number = digit; sign = (+1); break; case SUB: value += sign * number; number = digit; sign = (-1); break; case JOIN: number = 10 * number + digit; break; } } return value + sign * number; } @Override public String toString() { StringBuilder s = new StringBuilder(2 * NUMBER_OF_DIGITS + 1); for (int digit = 1; digit <= NUMBER_OF_DIGITS; digit++) { switch (code[NUMBER_OF_DIGITS - digit]) { case ADD: if (digit > 1) { s.append('+'); } break; case SUB: s.append('-'); break; } s.append(digit); } return s.toString(); } void print() { print(System.out); } void print(PrintStream printStream) { printStream.format("%9d", this.toInt()); printStream.println(" = " + this); } } private static class Stat { final Map<Integer, Integer> countSum = new HashMap<>(); final Map<Integer, Set<Integer>> sumCount = new HashMap<>(); Stat() { Expression expression = new Expression(); for (int i = 0; i < Expression.NUMBER_OF_EXPRESSIONS; i++, expression.next()) { int sum = expression.toInt(); countSum.put(sum, countSum.getOrDefault(sum, 0) + 1); } for (Map.Entry<Integer, Integer> entry : countSum.entrySet()) { Set<Integer> set; if (sumCount.containsKey(entry.getValue())) { set = sumCount.get(entry.getValue()); } else { set = new HashSet<>(); } set.add(entry.getKey()); sumCount.put(entry.getValue(), set); } } } }
165Sum to 100
9java
178p2
(function () { 'use strict';
165Sum to 100
10javascript
qpfx8
const int PRIMES[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163 }; bool isPrime(int n) { int i; if (n < 2) { return false; } for (i = 0; i < PRIME_LENGTH; ++i) { if (n == PRIMES[i]) { return true; } if (n % PRIMES[i] == 0) { return false; } if (n < PRIMES[i] * PRIMES[i]) { break; } } return true; } int main() { const int MAX_LENGTH = 700000; int i, n, c1, c2; int *primePtr = calloc(MAX_LENGTH, sizeof(int)); if (primePtr == 0) { return EXIT_FAILURE; } for (i = 0; i < PRIME_LENGTH; i++) { primePtr[i] = PRIMES[i]; } i--; for (n = PRIMES[i] + 4; n < 10000100;) { if (isPrime(n)) { primePtr[i++] = n; } n += 2; if (isPrime(n)) { primePtr[i++] = n; } n += 4; if (i >= MAX_LENGTH) { printf(); return EXIT_FAILURE; } } printf(); c1 = 0; c2 = 0; for (n = 0, i = 1; i < MAX_LENGTH - 1; i++) { if (2 * primePtr[i] > primePtr[i - 1] + primePtr[i + 1]) { if (n < 36) { printf(, primePtr[i]); n++; } if (primePtr[i] < 1000000) { c1++; c2++; } else if (primePtr[i] < 10000000) { c2++; } else break; } } printf(, c1); printf(, c2); printf(); c1 = 0; c2 = 0; for (n = 0, i = 1; i < MAX_LENGTH - 1; i++) { if (2 * primePtr[i] < primePtr[i - 1] + primePtr[i + 1]) { if (n < 37) { printf(, primePtr[i]); n++; } if (primePtr[i] < 1000000) { c1++; c2++; } else if (primePtr[i] < 10000000) { c2++; } else break; } } printf(, c1); printf(, c2); free(primePtr); return EXIT_SUCCESS; }
174Strong and weak primes
5c
8as04
sub encode { my $source = shift; my $key = shift; my $out = q(); @ka = split //, $key; foreach $ch (split //, $source) { $idx = ord($ch) - 32; $out .= $ka[$idx]; } return $out; } sub decode { my $source = shift; my $key = shift; my $out = q(); foreach $ch (split //, $source) { $idx = index $key, $ch; $val = chr($idx + 32); $out .= $val; } return $out; } my $key = q(]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[ my $text = "Here we have to do is there will be a input/source " . "file in which we are going to Encrypt the file by replacing every " . "upper/lower case alphabets of the source file with another " . "predetermined upper/lower case alphabets or symbols and save " . "it into another output/encrypted file and then again convert " . "that output/encrypted file into original/decrypted file. This " . "type of Encryption/Decryption scheme is often called a " . "Substitution Cipher."; my $ct = encode($text, $key); print "Encoded: $ct\n"; my $pt = decode($ct, $key); print "Decoded: $pt\n";
168Substitution cipher
2perl
26glf
main() { var list = new List<int>.generate(1000, (i) => i + 1); num sum = 0; (list.map((x) => 1.0 / (x * x))).forEach((num e) { sum += e; }); print(sum); }
171Sum of a series
18dart
prab8
<?php $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $key = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq'; file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key)); $source = file_get_contents('input.txt'); $encoded = file_get_contents('output.txt'); $decoded = strtr($encoded, $key, $alphabet); echo '== SOURCE ==', PHP_EOL, $source, PHP_EOL, PHP_EOL, '== ENCODED ==', PHP_EOL, $encoded, PHP_EOL, PHP_EOL, '== DECODED ==', PHP_EOL, $decoded, PHP_EOL, PHP_EOL;
168Substitution cipher
12php
s1nqs
null
165Sum to 100
11kotlin
juw7r
local expressionsLength = 0 function compareExpressionBySum(a, b) return a.sum - b.sum end local countSumsLength = 0 function compareCountSumsByCount(a, b) return a.counts - b.counts end function evaluate(code) local value = 0 local number = 0 local power = 1 for k=9,1,-1 do number = power*k + number local mod = code % 3 if mod == 0 then
165Sum to 100
1lua
h5xj8
package main import "fmt" func sieve(limit int) []int { primes := []int{2} c := make([]bool, limit+1)
173Successive prime differences
0go
nqni1
int main( int argc, char ** argv ){ const char * str_a = ; const char * str_b = ; const char * str_c = ; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( , new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
175Substring/Top and tail
5c
spwq5
package main import ( "fmt" "os" )
172Subtractive generator
0go
bgpkh
package main import "fmt" func sieve(limit int) []bool { limit++
174Strong and weak primes
0go
5mvul
void show(int *x) { int i, j; for (i = 0; i < 9; i++) { if (!(i % 3)) putchar('\n'); for (j = 0; j < 9; j++) printf(j % 3 ? : , *x++); putchar('\n'); } } int trycell(int *x, int pos) { int row = pos / 9; int col = pos % 9; int i, j, used = 0; if (pos == 81) return 1; if (x[pos]) return trycell(x, pos + 1); for (i = 0; i < 9; i++) used |= 1 << (x[i * 9 + col] - 1); for (j = 0; j < 9; j++) used |= 1 << (x[row * 9 + j] - 1); row = row / 3 * 3; col = col / 3 * 3; for (i = row; i < row + 3; i++) for (j = col; j < col + 3; j++) used |= 1 << (x[i * 9 + j] - 1); for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1) if (!(used & 1) && trycell(x, pos + 1)) return 1; x[pos] = 0; return 0; } void solve(const char *s) { int i, x[81]; for (i = 0; i < 81; i++) x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0; if (trycell(x, 0)) show(x); else puts(); } int main(void) { solve( ); return 0; }
176Sudoku
5c
oeq80
import Data.Numbers.Primes (primes) type Result = [(String, [Int])] oneMillionPrimes :: Integral p => [p] oneMillionPrimes = takeWhile (<1_000_000) primes getGroups :: [Int] -> Result getGroups [] = [] getGroups ps@(n:x:y:z:xs) | x-n == 6 && y-x == 4 && z-y == 2 = ("(6 4 2)", [n, x, y, z]) : getGroups (tail ps) | x-n == 4 && y-x == 2 = ("(4 2)", [n, x, y]) : getGroups (tail ps) | x-n == 2 && y-x == 4 = ("(2 4)", [n, x, y]): ("2", [n, x]): getGroups (tail ps) | x-n == 2 && y-x == 2 = ("(2 2)", [n, x, y]): ("2", [n, x]): getGroups (tail ps) | x-n == 2 = ("2", [n, x]) : getGroups (tail ps) | x-n == 1 = ("1", [n, x]) : getGroups (tail ps) | otherwise = getGroups (tail ps) getGroups (x:xs) = getGroups xs groups :: Result groups = getGroups oneMillionPrimes showGroup :: String -> IO () showGroup group = do putStrLn $ "Differences of " ++ group ++ ": " ++ show (length r) putStrLn $ "First: " ++ show (head r) ++ "\nLast: " ++ show (last r) ++ "\n" where r = foldr (\(a, b) c -> if a == group then b: c else c) [] groups main :: IO () main = showGroup "2" >> showGroup "1" >> showGroup "(2 2)" >> showGroup "(2 4)" >> showGroup "(4 2)" >> showGroup "(6 4 2)"
173Successive prime differences
8haskell
umuv2
subtractgen :: Int -> [Int] subtractgen seed = drop 220 out where out = mmod $ r <> zipWith (-) out (drop 31 out) where r = take 55 $ shuffle $ cycle $ take 55 s shuffle x = (:) . head <*> shuffle $ drop 34 x s = mmod $ seed: 1: zipWith (-) s (tail s) mmod = fmap (`mod` 10 ^ 9) main :: IO () main = mapM_ print $ take 10 $ subtractgen 292929
172Subtractive generator
8haskell
dsfn4
from string import printable import random EXAMPLE_KEY = ''.join(sorted(printable, key=lambda _:random.random())) def encode(plaintext, key): return ''.join(key[printable.index(char)] for char in plaintext) def decode(plaintext, key): return ''.join(printable[key.index(char)] for char in plaintext) original = encoded = encode(original, EXAMPLE_KEY) decoded = decode(encoded, EXAMPLE_KEY) print(.format( original, EXAMPLE_KEY, encoded, decoded))
168Substitution cipher
3python
vyr29
const char *ca = , *cb = ; int al = 2, bl = 2; char *loadfile(const char *fn) { FILE *f = fopen(fn, ); int l; char *s; if (f != NULL) { fseek(f, 0, SEEK_END); l = ftell(f); s = malloc(l+1); rewind(f); if (s) fread(s, 1, l, f); fclose(f); } return s; } void stripcomments(char *s) { char *a, *b; int len = strlen(s) + 1; while ((a = strstr(s, ca)) != NULL) { b = strstr(a+al, cb); if (b == NULL) break; b += bl; memmove(a, b, len-(b-a)); } } int main(int argc, char **argv) { const char *fn = ; char *s; if (argc >= 2) fn = argv[1]; s = loadfile(fn); if (argc == 4) { al = strlen(ca = argv[2]); bl = strlen(cb = argv[3]); } stripcomments(s); puts(s); free(s); return 0; }
177Strip block comments
5c
1rjpj
package main import "fmt" var v = []float32{1, 2, .5} func main() { var sum float32 for _, x := range v { sum += x * x } fmt.Println(sum) }
166Sum of squares
0go
s1fqa
import Text.Printf (printf) import Data.Numbers.Primes (primes) xPrimes :: (Real a, Fractional b) => (b -> b -> Bool) -> [a] -> [a] xPrimes op ps@(p1:p2:p3:xs) | realToFrac p2 `op` (realToFrac (p1 + p3) / 2) = p2: xPrimes op (tail ps) | otherwise = xPrimes op (tail ps) main :: IO () main = do printf "First 36 strong primes:%s\n" . show . take 36 $ strongPrimes printf "Strong primes below 1,000,000:%d\n" . length . takeWhile (<1000000) $ strongPrimes printf "Strong primes below 10,000,000:%d\n\n" . length . takeWhile (<10000000) $ strongPrimes printf "First 37 weak primes:%s\n" . show . take 37 $ weakPrimes printf "Weak primes below 1,000,000:%d\n" . length . takeWhile (<1000000) $ weakPrimes printf "Weak primes below 10,000,000:%d\n\n" . length . takeWhile (<10000000) $ weakPrimes where strongPrimes = xPrimes (>) primes weakPrimes = xPrimes (<) primes
174Strong and weak primes
8haskell
xkew4
void subleq(int *code) { int ip = 0, a, b, c, nextIP; char ch; while(0 <= ip) { nextIP = ip + 3; a = code[ip]; b = code[ip + 1]; c = code[ip + 2]; if(a == -1) { scanf(, &ch); code[b] = (int)ch; } else if(b == -1) { printf(, (char)code[a]); } else { code[b] -= code[a]; if(code[b] <= 0) nextIP = c; } ip = nextIP; } } void processFile(char *fileName) { int *dataSet, i, num; FILE *fp = fopen(fileName, ); fscanf(fp, , &num); dataSet = (int *)malloc(num * sizeof(int)); for(i = 0; i < num; i++) fscanf(fp, , &dataSet[i]); fclose(fp); subleq(dataSet); } int main(int argC, char *argV[]) { if(argC != 2) printf(, argV[0]); else processFile(argV[1]); return 0; }
178Subleq
5c
t08f4
def array = 1..3
166Sum of squares
7groovy
aj81p
public class StrongAndWeakPrimes { private static int MAX = 10_000_000 + 1000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { sieve(); System.out.println("First 36 strong primes:"); displayStrongPrimes(36); for ( int n : new int[] {1_000_000, 10_000_000}) { System.out.printf("Number of strong primes below%,d =%,d%n", n, strongPrimesBelow(n)); } System.out.println("First 37 weak primes:"); displayWeakPrimes(37); for ( int n : new int[] {1_000_000, 10_000_000}) { System.out.printf("Number of weak primes below%,d =%,d%n", n, weakPrimesBelow(n)); } } private static int weakPrimesBelow(int maxPrime) { int priorPrime = 2; int currentPrime = 3; int count = 0; while ( currentPrime < maxPrime ) { int nextPrime = getNextPrime(currentPrime); if ( currentPrime * 2 < priorPrime + nextPrime ) { count++; } priorPrime = currentPrime; currentPrime = nextPrime; } return count; } private static void displayWeakPrimes(int maxCount) { int priorPrime = 2; int currentPrime = 3; int count = 0; while ( count < maxCount ) { int nextPrime = getNextPrime(currentPrime); if ( currentPrime * 2 < priorPrime + nextPrime) { count++; System.out.printf("%d ", currentPrime); } priorPrime = currentPrime; currentPrime = nextPrime; } System.out.println(); } private static int getNextPrime(int currentPrime) { int nextPrime = currentPrime + 2; while ( ! primes[nextPrime] ) { nextPrime += 2; } return nextPrime; } private static int strongPrimesBelow(int maxPrime) { int priorPrime = 2; int currentPrime = 3; int count = 0; while ( currentPrime < maxPrime ) { int nextPrime = getNextPrime(currentPrime); if ( currentPrime * 2 > priorPrime + nextPrime ) { count++; } priorPrime = currentPrime; currentPrime = nextPrime; } return count; } private static void displayStrongPrimes(int maxCount) { int priorPrime = 2; int currentPrime = 3; int count = 0; while ( count < maxCount ) { int nextPrime = getNextPrime(currentPrime); if ( currentPrime * 2 > priorPrime + nextPrime) { count++; System.out.printf("%d ", currentPrime); } priorPrime = currentPrime; currentPrime = nextPrime; } System.out.println(); } private static final void sieve() {
174Strong and weak primes
9java
b4hk3
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SuccessivePrimeDifferences { private static Integer[] sieve(int limit) { List<Integer> primes = new ArrayList<>(); primes.add(2); boolean[] c = new boolean[limit + 1];
173Successive prime differences
9java
mfmym
user=> (subs "knight" 1) "night" user=> (subs "socks" 0 4) "sock" user=> (.substring "brooms" 1 5) "room" user=> (apply str (rest "knight")) "night" user=> (apply str (drop-last "socks")) "sock" user=> (apply str (rest (drop-last "brooms"))) "room"
175Substring/Top and tail
6clojure
nx8ik
import java.util.function.IntSupplier; import static java.util.stream.IntStream.generate; public class SubtractiveGenerator implements IntSupplier { static final int MOD = 1_000_000_000; private int[] state = new int[55]; private int si, sj; public SubtractiveGenerator(int p1) { subrandSeed(p1); } void subrandSeed(int p1) { int p2 = 1; state[0] = p1 % MOD; for (int i = 1, j = 21; i < 55; i++, j += 21) { if (j >= 55) j -= 55; state[j] = p2; if ((p2 = p1 - p2) < 0) p2 += MOD; p1 = state[j]; } si = 0; sj = 24; for (int i = 0; i < 165; i++) getAsInt(); } @Override public int getAsInt() { if (si == sj) subrandSeed(0); if (si-- == 0) si = 54; if (sj-- == 0) sj = 54; int x = state[si] - state[sj]; if (x < 0) x += MOD; return state[si] = x; } public static void main(String[] args) { generate(new SubtractiveGenerator(292_929)).limit(10) .forEach(System.out::println); } }
172Subtractive generator
9java
s10q0
(defn comment-strip [txt & args] (let [args (conj {:delim ["/*" "*/"]} (apply hash-map args)) [opener closer] (:delim args)] (loop [out "", txt txt, delim-count 0] (let [[hdtxt resttxt] (split-at (count opener) txt)] (printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count) (cond (empty? hdtxt) (str out (apply str txt)) (= (apply str hdtxt) opener) (recur out resttxt (inc delim-count)) (= (apply str hdtxt) closer) (recur out resttxt (dec delim-count)) (= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count) true (recur out (rest txt) delim-count))))))
177Strip block comments
6clojure
qb1xt
versions :: [[Int] -> Int] versions = [ sum . fmap (^ 2) , sum . ((^ 2) <$>) , foldr ((+) . (^ 2)) 0 ] main :: IO () main = mapM_ print ((`fmap` [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]]) <$> versions)
166Sum of squares
8haskell
9t4mo
private const val MAX = 10000000 + 1000 private val primes = BooleanArray(MAX) fun main() { sieve() println("First 36 strong primes:") displayStrongPrimes(36) for (n in intArrayOf(1000000, 10000000)) { System.out.printf("Number of strong primes below%,d =%,d%n", n, strongPrimesBelow(n)) } println("First 37 weak primes:") displayWeakPrimes(37) for (n in intArrayOf(1000000, 10000000)) { System.out.printf("Number of weak primes below%,d =%,d%n", n, weakPrimesBelow(n)) } } private fun weakPrimesBelow(maxPrime: Int): Int { var priorPrime = 2 var currentPrime = 3 var count = 0 while (currentPrime < maxPrime) { val nextPrime = getNextPrime(currentPrime) if (currentPrime * 2 < priorPrime + nextPrime) { count++ } priorPrime = currentPrime currentPrime = nextPrime } return count } private fun displayWeakPrimes(maxCount: Int) { var priorPrime = 2 var currentPrime = 3 var count = 0 while (count < maxCount) { val nextPrime = getNextPrime(currentPrime) if (currentPrime * 2 < priorPrime + nextPrime) { count++ print("$currentPrime ") } priorPrime = currentPrime currentPrime = nextPrime } println() } private fun getNextPrime(currentPrime: Int): Int { var nextPrime = currentPrime + 2 while (!primes[nextPrime]) { nextPrime += 2 } return nextPrime } private fun strongPrimesBelow(maxPrime: Int): Int { var priorPrime = 2 var currentPrime = 3 var count = 0 while (currentPrime < maxPrime) { val nextPrime = getNextPrime(currentPrime) if (currentPrime * 2 > priorPrime + nextPrime) { count++ } priorPrime = currentPrime currentPrime = nextPrime } return count } private fun displayStrongPrimes(maxCount: Int) { var priorPrime = 2 var currentPrime = 3 var count = 0 while (count < maxCount) { val nextPrime = getNextPrime(currentPrime) if (currentPrime * 2 > priorPrime + nextPrime) { count++ print("$currentPrime ") } priorPrime = currentPrime currentPrime = nextPrime } println() } private fun sieve() {
174Strong and weak primes
11kotlin
rl4go
(ns rosettacode.sudoku (:use [clojure.pprint:only (cl-format)])) (defn- compatible? [m x y n] (let [n= #(= n (get-in m [%1 %2]))] (or (n= y x) (let [c (count m)] (and (zero? (get-in m [y x])) (not-any? #(or (n= y %) (n= % x)) (range c)) (let [zx (* c (quot x c)), zy (* c (quot y c))] (every? false? (map n= (range zy (+ zy c)) (range zx (+ zx c)))))))))) (defn solve [m] (let [c (count m)] (loop [m m, x 0, y 0] (if (= y c) m (let [ng (->> (range 1 c) (filter #(compatible? m x y %)) first (assoc-in m [y x]))] (if (= x (dec c)) (recur ng 0 (inc y)) (recur ng (inc x) y)))))))
176Sudoku
6clojure
t0ifv
use warnings; use strict; use feature qw{ say }; my $string = '123456789'; my $length = length $string; my @possible_ops = ("" , '+', '-'); { my @ops; sub Next { return @ops = (0) x ($length) unless @ops; my $i = 0; while ($i < $length) { if ($ops[$i]++ > $ $ops[$i++] = 0; next } next if 0 == $i && '+' eq $possible_ops[ $ops[0] ]; return @ops } return } } sub evaluate { my ($expression) = @_; my $sum; $sum += $_ for $expression =~ /([-+]?[0-9]+)/g; return $sum } my %count = ( my $max_count = 0 => 0 ); say 'Show all solutions that sum to 100'; while (my @ops = Next()) { my $expression = ""; for my $i (0 .. $length - 1) { $expression .= $possible_ops[ $ops[$i] ]; $expression .= substr $string, $i, 1; } my $sum = evaluate($expression); ++$count{$sum}; $max_count = $sum if $count{$sum} > $count{$max_count}; say $expression if 100 == $sum; } say 'Show the sum that has the maximum number of solutions'; say "sum: $max_count; solutions: $count{$max_count}"; my $n = 1; ++$n until ! exists $count{$n}; say "Show the lowest positive sum that can't be expressed"; say $n; say 'Show the ten highest numbers that can be expressed'; say for (sort { $b <=> $a } keys %count)[0 .. 9];
165Sum to 100
2perl
t8lfg
int main() { char str[100]=; char *cstr=; char *dup; sprintf(str,,cstr,(dup=strdup(str))); free(dup); printf(,str); return 0; }
179String prepend
5c
233lo
int ascii (const unsigned char c); int ascii_ext (const unsigned char c); unsigned char* strip(unsigned char* str, const size_t n, int ext ); int ascii (const unsigned char c) { unsigned char min = 32; unsigned char max = 126; if ( c>=min && c<=max ) return 1; return 0; } int ascii_ext (const unsigned char c) { unsigned char min_ext = 128; unsigned char max_ext = 255; if ( c>=min_ext && c<=max_ext ) return 1; return 0; } unsigned char* strip( unsigned char* str, const size_t n, int ext) { unsigned char buffer[MAXBUF] = {'\0'}; size_t i = 0; size_t j = 0; size_t max = (n<MAXBUF)? n : MAXBUF -1; while (i < max ) { if ( (ext && ascii_ext(str[i]) ) || (ascii(str[i]) ) ) { buffer[j++] = str[i]; } i++; } memset(str, '\0', max); i = 0; while( i < j) { str[i] = buffer[i]; i++; } str[j] = '\0'; return str; } int main( int argc, char** argv) { enum {ASCII=0, EXT=1}; unsigned int seed = 134529; unsigned char badstring[STR_SZ] = {'\0'}; unsigned char bs_2[STR_SZ] = {'\0'}; unsigned char* goodstring = NULL; unsigned char* goodstring_ext = NULL; size_t i = 0; srand(seed); fprintf(stdout, ); for (i = 0; i < STR_SZ; i++) { badstring[i] = (unsigned char) ( rand () & (unsigned char)0xFF ); fprintf(stdout, , badstring[i] ); } fprintf(stdout, ); memcpy(bs_2, badstring, STR_SZ * sizeof(unsigned char) ); goodstring_ext = strip( badstring, STR_SZ, EXT); fprintf(stdout, , goodstring_ext ); goodstring = strip( bs_2, STR_SZ, ASCII); fprintf(stdout, , goodstring ); return 0; }
180Strip control codes and extended characters from a string
5c
pg4by
char *rtrim(const char *s) { while( isspace(*s) || !isprint(*s) ) ++s; return strdup(s); } char *ltrim(const char *s) { char *r = strdup(s); if (r != NULL) { char *fr = r + strlen(s) - 1; while( (isspace(*fr) || !isprint(*fr) || *fr == 0) && fr >= r) --fr; *++fr = 0; } return r; } char *trim(const char *s) { char *r = rtrim(s); char *f = ltrim(r); free(r); return f; } const char *a = ; int main() { char *b = rtrim(a); char *c = ltrim(a); char *d = trim(a); printf(, b, c, d); free(b); free(c); free(d); return 0; }
181Strip whitespace from a string/Top and tail
5c
wh7ec
null
174Strong and weak primes
1lua
72gru
null
172Subtractive generator
11kotlin
aje13
Alphabet = Key = def encrypt(str) = str.tr(Alphabet, Key) def decrypt(str) = str.tr(Key, Alphabet) str = 'All is lost, he thought. Everything is ruined. Its ten past three.' p encrypted = encrypt(str) p decrypt(encrypted)
168Substitution cipher
14ruby
59juj
object SubstitutionCipher extends App { private val key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N" + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ" private val text = """"It was still dark, in the early morning hours of the twenty-second of December | 1946, on the second floor of the house at Schilderskade 66 in our town, | when the hero of this story, Frits van Egters, awoke."""".stripMargin val enc = encode(text) println("Encoded: " + enc) println("Decoded: " + decode(enc)) private def encode(s: String) = { val sb = new StringBuilder(s.length) s.map { case c if (' ' to '~').contains(c) => sb.append(key(c.toInt - 32)) case _ => } sb.toString } private def decode(s: String) = { val sb = new StringBuilder(s.length) s.map { case c if (' ' to '~').contains(c) => sb.append((key.indexOf(c.toInt) + 32).toChar) case _ => } sb.toString } }
168Substitution cipher
16scala
7vpr9
int main() { char ch, str[100]; int i; do{ printf(); fgets(str,100,stdin); for(i=0;str[i]!=00;i++) { if(str[i]==' { str[i]=00; break; } } printf(,str); printf(); scanf(,&ch); fflush(stdin); }while(ch=='y'||ch=='Y'); return 0; }
182Strip comments from a string
5c
ctn9c
function findspds(primelist, diffs) local results = {} for i = 1, #primelist-#diffs do result = {primelist[i]} for j = 1, #diffs do if primelist[i+j] - primelist[i+j-1] == diffs[j] then result[j+1] = primelist[i+j] else result = nil break end end results[#results+1] = result end return results end primegen:generate(nil, 1000000) for _,diffs in ipairs{{2}, {1}, {2,2}, {2,4}, {4,2}, {6,4,2}} do spdlist = findspds(primegen.primelist, diffs) print("DIFFS: ["..table.concat(diffs," ").."]") print("COUNT: "..#spdlist) print("FIRST: ["..table.concat(spdlist[1]," ").."]") print("LAST: ["..table.concat(spdlist[#spdlist]," ").."]") print() end
173Successive prime differences
1lua
zozty
function SubGen(seed) local n, r, s = 54, {}, { [0]=seed, 1 } for n = 2,54 do s[n] = (s[n-2] - s[n-1]) % 1e9 end for n = 0,54 do r[n] = s[(34*(n+1))%55] end local next = function() n = (n+1) % 55 r[n] = (r[(n-55)%55] - r[(n-24)%55]) % 1e9 return r[n] end for n = 55,219 do next() end return next end subgen = SubGen(292929) for n = 220,229 do print(n,subgen()) end
172Subtractive generator
1lua
ehwac
(defn str-prepend [a-string, to-prepend] (str to-prepend a-string))
179String prepend
6clojure
gcc4f
package main import "fmt" func main() { fmt.Println(s35(1000)) } func s35(n int) int { n-- threes := n / 3 fives := n / 5 fifteen := n / 15 threes = 3 * threes * (threes + 1) fives = 5 * fives * (fives + 1) fifteen = 15 * fifteen * (fifteen + 1) n = (threes + fives - fifteen) / 2 return n }
167Sum multiples of 3 and 5
0go
eh8a6
null
169Sum digits of an integer
0go
owf8q
public class SumSquares { public static void main(final String[] args) { double sum = 0; int[] nums = {1,2,3,4,5}; for (int i: nums) sum += i * i; System.out.println("The sum of the squares is: " + sum); } }
166Sum of squares
9java
t8cf9
(use 'clojure.string) (triml " my string ") => "my string " (trimr " my string ") => " my string" (trim " \t\r\n my string \t\r\n ") => "my string"
181Strip whitespace from a string/Top and tail
6clojure
8ap05