code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use std::env;
fn main() {
let mut args = env::args().skip(1).flat_map(|num| num.parse());
let rows = args.next().expect("Expected number of rows as first argument");
let cols = args.next().expect("Expected number of columns as second argument");
assert_ne!(rows, 0, "rows were zero");
assert_ne!(cols, 0, "cols were zero"); | 986Create a two-dimensional array at runtime
| 15rust
| he2j2 |
object Array2D{
def main(args: Array[String]): Unit = {
val x = Console.readInt
val y = Console.readInt
val a=Array.fill(x, y)(0)
a(0)(0)=42
println("The number at (0, 0) is "+a(0)(0))
}
} | 986Create a two-dimensional array at runtime
| 16scala
| pq5bj |
def countChange(amount: Int, coins:List[Int]) = {
val ways = Array.fill(amount + 1)(0)
ways(0) = 1
coins.foreach (coin =>
for (j<-coin to amount)
ways(j) = ways(j) + ways(j - coin)
)
ways(amount)
}
countChange (15, List(1, 5, 10, 25)) | 989Count the coins
| 16scala
| bxlk6 |
sub countSubstring {
my $str = shift;
my $sub = quotemeta(shift);
my $count = () = $str =~ /$sub/g;
return $count;
}
print countSubstring("the three truths","th"), "\n";
print countSubstring("ababababab","abab"), "\n"; | 992Count occurrences of a substring
| 2perl
| qn5x6 |
use ntheory qw/factor/;
print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010; | 991Count in factors
| 2perl
| pqcb0 |
use HTML::Entities;
sub row {
my $elem = shift;
my @cells = map {"<$elem>$_</$elem>"} split ',', shift;
print '<tr>', @cells, "</tr>\n";
}
my ($first, @rest) = map
{my $x = $_; chomp $x; encode_entities $x}
<STDIN>;
print "<table>\n";
row @ARGV ? 'th' : 'td', $first;
row 'td', $_ foreach @rest;
print "</table>\n"; | 987CSV to HTML translation
| 2perl
| rpmgd |
<?php
echo substr_count(, ), PHP_EOL;
echo substr_count(, ), PHP_EOL; | 992Count occurrences of a substring
| 12php
| v7o2v |
import sys
for n in xrange(sys.maxint):
print oct(n) | 993Count in octal
| 3python
| zcptt |
import os
for directory in ['/', './']:
open(directory + 'output.txt', 'w').close()
os.mkdir(directory + 'docs') | 988Create a file
| 3python
| kwlhf |
f <- file("output.txt", "w")
close(f)
f <- file("/output.txt", "w")
close(f)
success <- dir.create("docs")
success <- dir.create("/docs") | 988Create a file
| 13r
| rpygj |
<?php
$csv = <<<EOT
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
EOT;
function convert($csv)
{
$out = [];
array_map(function($ln) use(&$out) {
$ln = htmlentities($ln);
$out[] = count($out) == 0
? '<thead><tr><th>'.implode('</th><th>',explode(',',$ln)).
: '<tr><td>'.implode('</td><td>',explode(',',$ln)).;
}, explode(,$csv));
return '<table>'.implode('',$out).'</table>';
}
echo convert($csv); | 987CSV to HTML translation
| 12php
| dyen8 |
class StdDevAccumulator
def initialize
@n, @sum, @sumofsquares = 0, 0.0, 0.0
end
def <<(num)
@n += 1
@sum += num
@sumofsquares += num**2
self
end
def stddev
Math.sqrt( (@sumofsquares / @n) - (@sum / @n)**2 )
end
def to_s
stddev.to_s
end
end
sd = StdDevAccumulator.new
i = 0
[2,4,4,4,5,5,7,9].each {|n| puts } | 982Cumulative standard deviation
| 14ruby
| mutyj |
import BigInt
func countCoins(amountCents cents: Int, coins: [Int]) -> BigInt {
let cycle = coins.filter({ $0 <= cents }).map({ $0 + 1 }).max()! * coins.count
var table = [BigInt](repeating: 0, count: cycle)
for x in 0..<coins.count {
table[x] = 1
}
var pos = coins.count
for s in 1..<cents+1 {
for i in 0..<coins.count {
if i == 0 && pos >= cycle {
pos = 0
}
if coins[i] <= s {
let q = pos - coins[i] * coins.count
table[pos] = q >= 0? table[q]: table[q + cycle]
}
if i!= 0 {
table[pos] += table[pos - 1]
}
pos += 1
}
}
return table[pos - 1]
}
let usCoins = [100, 50, 25, 10, 5, 1]
let euCoins = [200, 100, 50, 20, 10, 5, 2, 1]
for set in [usCoins, euCoins] {
print(countCoins(amountCents: 100, coins: Array(set.dropFirst(2))))
print(countCoins(amountCents: 100000, coins: set))
print(countCoins(amountCents: 1000000, coins: set))
print(countCoins(amountCents: 10000000, coins: set))
print()
} | 989Count the coins
| 17swift
| rp6gg |
from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i%5s%s'% (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info()) | 991Count in factors
| 3python
| 1slpc |
import Foundation
print("Enter the dimensions of the array seperated by a space (width height): ")
let fileHandle = NSFileHandle.fileHandleWithStandardInput()
let dims = NSString(data: fileHandle.availableData, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString(" ")
if let dims = dims where dims.count == 2{
let w = dims[0].integerValue
let h = dims[1].integerValue
if let w = w, h = h where w > 0 && h > 0 {
var array = Array<[Int!]>(count: h, repeatedValue: Array<Int!>(count: w, repeatedValue: nil))
array[0][0] = 2
println(array[0][0])
println(array)
}
} | 986Create a two-dimensional array at runtime
| 17swift
| 71crq |
n = 0
loop do
puts % n
n += 1
end
for n in 0..Float::INFINITY
puts n.to_s(8)
end
0.upto(1/0.0) do |n|
printf , n
end
0.step do |n|
puts format(, n)
end | 993Count in octal
| 14ruby
| 62a3t |
findfactors <- function(num) {
x <- c()
p1<- 2
p2 <- 3
everyprime <- num
while( everyprime!= 1 ) {
while( everyprime%%p1 == 0 ) {
x <- c(x, p1)
everyprime <- floor(everyprime/ p1)
}
p1 <- p2
p2 <- p2 + 2
}
x
}
count_in_factors=function(x){
primes=findfactors(x)
x=c(1)
for (i in 1:length(primes)) {
x=paste(primes[i],"x",x)
}
return(x)
}
count_in_factors(72) | 991Count in factors
| 13r
| heyjj |
pub struct CumulativeStandardDeviation {
n: f64,
sum: f64,
sum_sq: f64
}
impl CumulativeStandardDeviation {
pub fn new() -> Self {
CumulativeStandardDeviation {
n: 0.,
sum: 0.,
sum_sq: 0.
}
}
fn push(&mut self, x: f64) -> f64 {
self.n += 1.;
self.sum += x;
self.sum_sq += x * x;
(self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt()
}
}
fn main() {
let nums = [2, 4, 4, 4, 5, 5, 7, 9];
let mut cum_stdev = CumulativeStandardDeviation::new();
for num in nums.iter() {
println!("{}", cum_stdev.push(*num as f64));
}
} | 982Cumulative standard deviation
| 15rust
| 95zmm |
>>> .count()
3
>>> .count()
2 | 992Count occurrences of a substring
| 3python
| sd4q9 |
fn main() {
for i in 0..std::usize::MAX {
println!("{:o}", i);
}
} | 993Count in octal
| 15rust
| yve68 |
['/', './'].each{|dir|
Dir.mkdir(dir + 'docs')
File.open(dir + 'output.txt', 'w') {}
} | 988Create a file
| 14ruby
| pqvbh |
csvtxt = '''\
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!\
'''
from cgi import escape
def _row2tr(row, attr=None):
cols = escape(row).split(',')
return ('<TR>'
+ ''.join('<TD>%s</TD>'% data for data in cols)
+ '</TR>')
def csv2html(txt):
htmltxt = '<TABLE summary=>\n'
for rownum, row in enumerate(txt.split('\n')):
htmlrow = _row2tr(row)
htmlrow = ' <TBODY>%s</TBODY>\n'% htmlrow
htmltxt += htmlrow
htmltxt += '</TABLE>\n'
return htmltxt
htmltxt = csv2html(csvtxt)
print(htmltxt) | 987CSV to HTML translation
| 3python
| 719rm |
count = function(haystack, needle)
{v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length")
if (identical(v, -1L)) 0 else length(v)}
print(count("hello", "l")) | 992Count occurrences of a substring
| 13r
| e82ad |
Stream from 0 foreach (i => println(i.toOctalString)) | 993Count in octal
| 16scala
| c4q93 |
use std::io::{self, Write};
use std::fs::{DirBuilder, File};
use std::path::Path;
use std::{process,fmt};
const FILE_NAME: &'static str = "output.txt";
const DIR_NAME: &'static str = "docs";
fn main() {
create(".").and(create("/"))
.unwrap_or_else(|e| error_handler(e,1));
}
fn create<P>(root: P) -> io::Result<File>
where P: AsRef<Path>
{
let f_path = root.as_ref().join(FILE_NAME);
let d_path = root.as_ref().join(DIR_NAME);
DirBuilder::new().create(d_path).and(File::create(f_path))
}
fn error_handler<E: fmt::Display>(error: E, code: i32) ->! {
let _ = writeln!(&mut io::stderr(), "Error: {}", error);
process::exit(code)
} | 988Create a file
| 15rust
| 1supu |
File <- "~/test.csv"
Opened <- readLines(con = File)
Size <- length(Opened)
HTML <- "~/test.html"
Table <- list()
for(i in 1:Size)
{
Split <- unlist(strsplit(Opened[i],split = ","))
Table[i] <- paste0("<td>",Split,"</td>",collapse = "")
Table[i] <- paste0("<tr>",Table[i],"</tr>")
}
Table[1] <- paste0("<table>",Table[1])
Table[length(Table)] <- paste0(Table[length(Table)],"</table>")
writeLines(as.character(Table), HTML) | 987CSV to HTML translation
| 13r
| 5h3uy |
import scala.math.sqrt
object StddevCalc extends App {
def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
def avg(ts: Iterable[T])(implicit num: Fractional[T]): T =
num.div(ts.sum, num.fromInt(ts.size)) | 982Cumulative standard deviation
| 16scala
| 2rylb |
require 'optparse'
require 'prime'
maximum = 10
OptionParser.new do |o|
o.banner =
o.on(, Integer,
) { |m| maximum = m }
o.parse! rescue ($stderr.puts $!, o; exit 1)
($stderr.puts o; exit 1) unless ARGV.size == 0
end
puts unless maximum < 1
2.upto(maximum) do |i|
f = i.prime_division.map! do |factor, exponent|
([factor] * exponent).join
end.join
puts
end | 991Count in factors
| 14ruby
| e8vax |
import java.io.File
object CreateFile extends App {
try { new File("output.txt").createNewFile() }
catch { case e: Exception => println(s"Exception caught: $e with creating output.txt") }
try { new File(s"${File.separator}output.txt").createNewFile() }
catch { case e: Exception => println(s"Exception caught: $e with creating ${File.separator}output.txt") }
try { new File("docs").mkdir() }
catch { case e: Exception => println(s"Exception caught: $e with creating directory docs") }
try { new File(s"${File.separator}docs").mkdir() }
catch { case e: Exception => println(s"Exception caught: $e with creating directory ${File.separator}docs") }
} | 988Create a file
| 16scala
| woges |
use std::env;
fn main() {
let args: Vec<_> = env::args().collect();
let n = if args.len() > 1 {
args[1].parse().expect("Not a valid number to count to")
}
else {
20
};
count_in_factors_to(n);
}
fn count_in_factors_to(n: u64) {
println!("1");
let mut primes = vec![];
for i in 2..=n {
let fs = factors(&primes, i);
if fs.len() <= 1 {
primes.push(i);
println!("{}", i);
}
else {
println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x "));
}
}
}
fn factors(primes: &[u64], mut n: u64) -> Vec<u64> {
let mut result = Vec::new();
for p in primes {
while n% p == 0 {
result.push(*p);
n /= p;
}
if n == 1 {
return result;
}
}
vec![n]
} | 991Count in factors
| 15rust
| woue4 |
def countSubstrings str, subStr
str.scan(subStr).length
end
p countSubstrings ,
p countSubstrings , | 992Count occurrences of a substring
| 14ruby
| 8tr01 |
import Foundation
func octalSuccessor(value: String) -> String {
if value.isEmpty {
return "1"
} else {
let i = value.startIndex, j = value.endIndex.predecessor()
switch (value[j]) {
case "0": return value[i..<j] + "1"
case "1": return value[i..<j] + "2"
case "2": return value[i..<j] + "3"
case "3": return value[i..<j] + "4"
case "4": return value[i..<j] + "5"
case "5": return value[i..<j] + "6"
case "6": return value[i..<j] + "7"
case "7": return octalSuccessor(value[i..<j]) + "0"
default:
NSException(name:"InvalidDigit", reason: "InvalidOctalDigit", userInfo: nil).raise();
return ""
}
}
}
var n = "0"
while strtoul(n, nil, 8) < UInt.max {
println(n)
n = octalSuccessor(n)
} | 993Count in octal
| 17swift
| 3l1z2 |
object CountInFactors extends App {
def primeFactors(n: Int): List[Int] = {
def primeStream(s: LazyList[Int]): LazyList[Int] = {
s.head #:: primeStream(s.tail filter {
_ % s.head != 0
})
}
val primes = primeStream(LazyList.from(2))
def factors(n: Int): List[Int] = primes.takeWhile(_ <= n).find(n % _ == 0) match {
case None => Nil
case Some(p) => p :: factors(n / p)
}
if (n == 1) List(1) else factors(n)
} | 991Count in factors
| 16scala
| sdgqo |
fn main() {
println!("{}","the three truths".matches("th").count());
println!("{}","ababababab".matches("abab").count());
} | 992Count occurrences of a substring
| 15rust
| oz783 |
import scala.annotation.tailrec
def countSubstring(str1:String, str2:String):Int={
@tailrec def count(pos:Int, c:Int):Int={
val idx=str1 indexOf(str2, pos)
if(idx == -1) c else count(idx+str2.size, c+1)
}
count(0,0)
} | 992Count occurrences of a substring
| 16scala
| dykng |
my @heading = qw(X Y Z);
my $rows = 5;
print '<table><thead><td>',
(map { "<th>$_</th>" } @heading),
"</thead><tbody>";
for (1 .. $rows) {
print "<tr><th>$_</th>",
(map { "<td>".int(rand(10000))."</td>" } @heading),
"</tr>";
}
print "</tbody></table>"; | 990Create an HTML table
| 2perl
| zcetb |
-- the minimal table
CREATE TABLE IF NOT EXISTS teststd (n DOUBLE PRECISION NOT NULL);
-- code modularity with view, we could have used a common table expression instead
CREATE VIEW vteststd AS
SELECT COUNT(n) AS cnt,
SUM(n) AS tsum,
SUM(POWER(n,2)) AS tsqr
FROM teststd;
-- you can of course put this code into every query
CREATE OR REPLACE FUNCTION std_dev() RETURNS DOUBLE PRECISION AS $$
SELECT SQRT(tsqr/cnt - (tsum/cnt)^2) FROM vteststd;
$$ LANGUAGE SQL;
-- test data is: 2,4,4,4,5,5,7,9
INSERT INTO teststd VALUES (2);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (4);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (5);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (5);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (7);
SELECT std_dev() AS std_deviation;
INSERT INTO teststd VALUES (9);
SELECT std_dev() AS std_deviation;
-- cleanup test data
DELETE FROM teststd; | 982Cumulative standard deviation
| 19sql
| 5hcu3 |
extension BinaryInteger {
@inlinable
public func primeDecomposition() -> [Self] {
guard self > 1 else { return [] }
func step(_ x: Self) -> Self {
return 1 + (x << 2) - ((x >> 1) << 1)
}
let maxQ = Self(Double(self).squareRoot())
var d: Self = 1
var q: Self = self & 1 == 0? 2: 3
while q <= maxQ && self% q!= 0 {
q = step(d)
d += 1
}
return q <= maxQ? [q] + (self / q).primeDecomposition(): [self]
}
}
for i in 1...20 {
if i == 1 {
print("1 = 1")
} else {
print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " x "))")
}
} | 991Count in factors
| 17swift
| a021i |
ruby csv2html.rb header | 987CSV to HTML translation
| 14ruby
| heljx |
import Darwin
class stdDev{
var n:Double = 0.0
var sum:Double = 0.0
var sum2:Double = 0.0
init(){
let testData:[Double] = [2,4,4,4,5,5,7,9];
for x in testData{
var a:Double = calcSd(x)
println("value \(Int(x)) SD = \(a)");
}
}
func calcSd(x:Double)->Double{
n += 1
sum += x
sum2 += x*x
return sqrt( sum2 / n - sum*sum / n / n)
}
}
var aa = stdDev() | 982Cumulative standard deviation
| 17swift
| yvf6e |
<?php
$cols = array('', 'X', 'Y', 'Z');
$rows = 3;
$html = '<html><body><table><colgroup>';
foreach($cols as $col)
{
$html .= '<col style= />';
}
unset($col);
$html .= '</colgroup><thead><tr>';
foreach($cols as $col)
{
$html .= ;
}
unset($col);
$html .= '</tr></thead><tbody>';
for($r = 1; $r <= $rows; $r++)
{
$html .= '<tr>';
foreach($cols as $key => $col)
{
$html .= '<td>' . (($key > 0)? rand(1, 9999) : $r) . '</td>';
}
unset($col);
$html .= '</tr>';
}
$html .= '</tbody></table></body></html>';
echo $html; | 990Create an HTML table
| 12php
| bxck9 |
static INPUT: &'static str =
"Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!";
fn main() {
print!("<table>\n<tr><td>");
for c in INPUT.chars() {
match c {
'\n' => print!("</td></tr>\n<tr><td>"),
',' => print!("</td><td>"),
'<' => print!("<"),
'>' => print!(">"),
'&' => print!("&"),
_ => print!("{}", c)
}
}
println!("</td></tr>\n</table>");
} | 987CSV to HTML translation
| 15rust
| kw2h5 |
object CsvToHTML extends App {
val header = <head>
<title>CsvToHTML</title>
<style type="text/css">
td {{background-color:#ddddff; }} thead td {{background-color:#ddffdd; text-align:center; }}
</style>
</head>
val csv =
"""Character,Speech
|The multitude,The messiah! Show us the messiah!
|Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
|The multitude,Who are you?
|Brians mother,I'm his mother; that's who!
|The multitude,Behold his mother! Behold his mother!""".stripMargin
def csv2html(csv: String, withHead: Boolean) = {
def processRow(text: String) = <tr>
{text.split(',').map(s => <td>
{s}
</td>)}
</tr>
val (first :: rest) = csv.lines.toList | 987CSV to HTML translation
| 16scala
| 1s5pf |
import Foundation
func countSubstring(str: String, substring: String) -> Int {
return str.components(separatedBy: substring).count - 1
}
print(countSubstring(str: "the three truths", substring: "th"))
print(countSubstring(str: "ababababab", substring: "abab")) | 992Count occurrences of a substring
| 17swift
| 0fgs6 |
import random
def rand9999():
return random.randint(1000, 9999)
def tag(attr='', **kwargs):
for tag, txt in kwargs.items():
return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())
if __name__ == '__main__':
header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n'
rows = '\n'.join(tag(tr=tag(' style=', td=i)
+ ''.join(tag(td=rand9999())
for j in range(3)))
for i in range(1, 6))
table = tag(table='\n' + header + rows + '\n')
print(table) | 990Create an HTML table
| 3python
| 3lwzc |
int main(){
char c;
while ( (c=getchar()) != EOF ){
putchar(c);
}
return 0;
} | 994Copy stdin to stdout
| 5c
| v702o |
import 'dart:io';
void main() {
var line = stdin.readLineSync();
stdout.write(line);
} | 994Copy stdin to stdout
| 18dart
| yva65 |
def r
rand(10000)
end
STDOUT << .tap do |html|
html <<
[
['X', 'Y', 'Z'],
[r ,r ,r],
[r ,r ,r],
[r ,r ,r],
[r ,r ,r]
].each_with_index do |row, index|
html <<
html <<
html << row.map { |e| }.join
html <<
end
html <<
end | 990Create an HTML table
| 14ruby
| yvq6n |
package main
import (
"bufio"
"io"
"os"
)
func main() {
r := bufio.NewReader(os.Stdin)
w := bufio.NewWriter(os.Stdout)
for {
b, err := r.ReadByte()
if err == io.EOF {
return
}
w.WriteByte(b)
w.Flush()
}
} | 994Copy stdin to stdout
| 0go
| sduqa |
class StdInToStdOut {
static void main(args) {
try (def reader = System.in.newReader()) {
def line
while ((line = reader.readLine()) != null) {
println line
}
}
}
} | 994Copy stdin to stdout
| 7groovy
| a091p |
extern crate rand;
use rand::Rng;
fn random_cell<R: Rng>(rng: &mut R) -> u32 { | 990Create an HTML table
| 15rust
| musya |
main = interact id | 994Copy stdin to stdout
| 8haskell
| 95wmo |
import java.util.Scanner;
public class CopyStdinToStdout {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in);) {
String s;
while ( (s = scanner.nextLine()).compareTo("") != 0 ) {
System.out.println(s);
}
}
}
} | 994Copy stdin to stdout
| 9java
| t9kf9 |
process.stdin.resume();
process.stdin.pipe(process.stdout); | 994Copy stdin to stdout
| 10javascript
| mueyv |
object TableGenerator extends App {
val data = List(List("X", "Y", "Z"), List(11, 12, 13), List(12, 22, 23), List(13, 32, 33))
def generateTable(data: List[List[Any]]) = {
<table>
{data.zipWithIndex.map { case (row, rownum) => (if (rownum == 0) Nil else rownum) +: row}.
map(row => <tr>
{row.map(cell =>
<td>
{cell}
</td>)}
</tr>)}
</table>
}
println(generateTable(data))
} | 990Create an HTML table
| 16scala
| lgocq |
fun main() {
var c: Int
do {
c = System.`in`.read()
System.out.write(c)
} while (c >= 0)
} | 994Copy stdin to stdout
| 11kotlin
| ozg8z |
lua -e 'for x in io.lines() do print(x) end' | 994Copy stdin to stdout
| 1lua
| i3rot |
perl -pe '' | 994Copy stdin to stdout
| 2perl
| gbn4e |
python -c 'import sys; sys.stdout.write(sys.stdin.read())' | 994Copy stdin to stdout
| 3python
| rpdgq |
Rscript -e 'cat(readLines(file("stdin")))' | 994Copy stdin to stdout
| 13r
| uj8vx |
use std::io;
fn main() {
io::copy(&mut io::stdin().lock(), &mut io::stdout().lock());
} | 994Copy stdin to stdout
| 15rust
| hezj2 |
object CopyStdinToStdout extends App {
io.Source.fromInputStream(System.in).getLines().foreach(println)
} | 994Copy stdin to stdout
| 16scala
| pqybj |
typedef struct{
int num,den;
}fraction;
fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}};
fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}};
fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}};
int r2cf(int *numerator,int *denominator)
{
int quotient=0,temp;
if(denominator != 0)
{
quotient = *numerator / *denominator;
temp = *numerator;
*numerator = *denominator;
*denominator = temp % *denominator;
}
return quotient;
}
int main()
{
int i;
printf();
for(i=0;i<sizeof(examples)/sizeof(fraction);i++)
{
printf(,examples[i].num,examples[i].den);
while(examples[i].den != 0){
printf(,r2cf(&examples[i].num,&examples[i].den));
}
}
printf(,251);
for(i=0;i<sizeof(sqrt2)/sizeof(fraction);i++)
{
printf(,sqrt2[i].num,sqrt2[i].den);
while(sqrt2[i].den != 0){
printf(,r2cf(&sqrt2[i].num,&sqrt2[i].den));
}
}
printf(,227);
for(i=0;i<sizeof(pi)/sizeof(fraction);i++)
{
printf(,pi[i].num,pi[i].den);
while(pi[i].den != 0){
printf(,r2cf(&pi[i].num,&pi[i].den));
}
}
return 0;
} | 995Continued fraction/Arithmetic/Construct from rational number
| 5c
| 95em1 |
void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom)
{
int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 };
int64_t x, d, n = 1;
int i, neg = 0;
if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }
if (f < 0) { neg = 1; f = -f; }
while (f != floor(f)) { n <<= 1; f *= 2; }
d = f;
for (i = 0; i < 64; i++) {
a = n ? d / n : 0;
if (i && !a) break;
x = d; d = n; n = x % n;
x = a;
if (k[1] * a + k[0] >= md) {
x = (md - k[0]) / k[1];
if (x * 2 >= a || k[1] >= md)
i = 65;
else
break;
}
h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];
k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];
}
*denom = k[1];
*num = neg ? -h[1] : h[1];
}
int main()
{
int i;
int64_t d, n;
double f;
printf(, f = 1.0/7);
for (i = 1; i <= 20000000; i *= 16) {
printf(, i);
rat_approx(f, i, &n, &d);
printf(, n, d);
}
printf(, f = atan2(1,1) * 4);
for (i = 1; i <= 20000000; i *= 16) {
printf(, i);
rat_approx(f, i, &n, &d);
printf(, n, d);
}
return 0;
} | 996Convert decimal number to rational
| 5c
| mu1ys |
(defn r2cf [n d]
(if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d))))))
(def demo '((1 2)
(3 1)
(23 8)
(13 11)
(22 7)
(-151 77)
(14142 10000)
(141421 100000)
(1414214 1000000)
(14142136 10000000)
(31 10)
(314 100)
(3142 1000)
(31428 10000)
(314285 100000)
(3142857 1000000)
(31428571 10000000)
(314285714 100000000)
(3141592653589793 1000000000000000)))
(doseq [inputs demo
:let [outputs (r2cf (first inputs) (last inputs))]]
(println inputs " | 995Continued fraction/Arithmetic/Construct from rational number
| 6clojure
| uj0vi |
user=> (rationalize 0.1)
1/10
user=> (rationalize 0.9054054)
4527027/5000000
user=> (rationalize 0.518518)
259259/500000
user=> (rationalize Math/PI)
3141592653589793/1000000000000000 | 996Convert decimal number to rational
| 6clojure
| v7q2f |
package cf
import (
"fmt"
"strings"
) | 995Continued fraction/Arithmetic/Construct from rational number
| 0go
| e89a6 |
import Data.Ratio ((%))
real2cf :: (RealFrac a, Integral b) => a -> [b]
real2cf x =
let (i, f) = properFraction x
in i:
if f == 0
then []
else real2cf (1 / f)
main :: IO ()
main =
mapM_
print
[ real2cf (13 % 11)
, take 20 $ real2cf (sqrt 2)
] | 995Continued fraction/Arithmetic/Construct from rational number
| 8haskell
| 3lbzj |
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ConstructFromRationalNumber {
private static class R2cf implements Iterator<Integer> {
private int num;
private int den;
R2cf(int num, int den) {
this.num = num;
this.den = den;
}
@Override
public boolean hasNext() {
return den != 0;
}
@Override
public Integer next() {
int div = num / den;
int rem = num % den;
num = den;
den = rem;
return div;
}
}
private static void iterate(R2cf generator) {
generator.forEachRemaining(n -> System.out.printf("%d ", n));
System.out.println();
}
public static void main(String[] args) {
List<Map.Entry<Integer, Integer>> fracs = List.of(
Map.entry(1, 2),
Map.entry(3, 1),
Map.entry(23, 8),
Map.entry(13, 11),
Map.entry(22, 7),
Map.entry(-151, 77)
);
for (Map.Entry<Integer, Integer> frac : fracs) {
System.out.printf("%4d /%-2d = ", frac.getKey(), frac.getValue());
iterate(new R2cf(frac.getKey(), frac.getValue()));
}
System.out.println("\nSqrt(2) ->");
List<Map.Entry<Integer, Integer>> root2 = List.of(
Map.entry( 14_142, 10_000),
Map.entry( 141_421, 100_000),
Map.entry( 1_414_214, 1_000_000),
Map.entry(14_142_136, 10_000_000)
);
for (Map.Entry<Integer, Integer> frac : root2) {
System.out.printf("%8d /%-8d = ", frac.getKey(), frac.getValue());
iterate(new R2cf(frac.getKey(), frac.getValue()));
}
System.out.println("\nPi ->");
List<Map.Entry<Integer, Integer>> pi = List.of(
Map.entry( 31, 10),
Map.entry( 314, 100),
Map.entry( 3_142, 1_000),
Map.entry( 31_428, 10_000),
Map.entry( 314_285, 100_000),
Map.entry( 3_142_857, 1_000_000),
Map.entry( 31_428_571, 10_000_000),
Map.entry(314_285_714, 100_000_000)
);
for (Map.Entry<Integer, Integer> frac : pi) {
System.out.printf("%9d /%-9d = ", frac.getKey(), frac.getValue());
iterate(new R2cf(frac.getKey(), frac.getValue()));
}
}
} | 995Continued fraction/Arithmetic/Construct from rational number
| 9java
| i3gos |
package main
import (
"fmt"
"math/big"
)
func main() {
for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
if r, ok := new(big.Rat).SetString(d); ok {
fmt.Println(d, "=", r)
} else {
fmt.Println(d, "invalid decimal number")
}
}
} | 996Convert decimal number to rational
| 0go
| a0y1f |
null | 995Continued fraction/Arithmetic/Construct from rational number
| 11kotlin
| qn2x1 |
Number.metaClass.mixin RationalCategory
[
0.9054054, 0.518518, 0.75, Math.E, -0.423310825, Math.PI, 0.111111111111111111111111
].each{
printf "%30.27f%s\n", it, it as Rational
} | 996Convert decimal number to rational
| 7groovy
| hefj9 |
Prelude> map (\d -> Ratio.approxRational d 0.0001) [0.9054054, 0.518518, 0.75]
[67 % 74,14 % 27,3 % 4]
Prelude> [0.9054054, 0.518518, 0.75] :: [Rational]
[4527027 % 5000000,259259 % 500000,3 % 4]
Prelude> map (fst . head . Numeric.readFloat) ["0.9054054", "0.518518", "0.75"] :: [Rational]
[4527027 % 5000000,259259 % 500000,3 % 4] | 996Convert decimal number to rational
| 8haskell
| zcht0 |
import org.apache.commons.math3.fraction.BigFraction;
public class Test {
public static void main(String[] args) {
double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,
3.141592654, 2.718281828, -0.423310825, 31.415926536};
for (double d : n)
System.out.printf("%-12s:%s%n", d, new BigFraction(d, 0.00000002D, 10000));
}
} | 996Convert decimal number to rational
| 9java
| oz58d |
(() => {
'use strict';
const main = () =>
showJSON(
map( | 996Convert decimal number to rational
| 10javascript
| t9jfm |
$|=1;
sub rc2f {
my($num, $den) = @_;
return sub { return unless $den;
my $q = int($num/$den);
($num, $den) = ($den, $num - $q*$den);
$q; };
}
sub rcshow {
my $sub = shift;
print "[";
my $n = $sub->();
print "$n" if defined $n;
print "; $n" while defined($n = $sub->());
print "]\n";
}
rcshow(rc2f(@$_))
for ([1,2],[3,1],[23,8],[13,11],[22,7],[-151,77]);
print "\n";
rcshow(rc2f(@$_))
for ([14142,10000],[141421,100000],[1414214,1000000],[14142136,10000000]);
print "\n";
rcshow(rc2f(314285714,100000000)); | 995Continued fraction/Arithmetic/Construct from rational number
| 2perl
| v7s20 |
null | 996Convert decimal number to rational
| 11kotlin
| xicws |
def r2cf(n1,n2):
while n2:
n1, (t1, n2) = n2, divmod(n1, n2)
yield t1
print(list(r2cf(1,2)))
print(list(r2cf(3,1)))
print(list(r2cf(23,8)))
print(list(r2cf(13,11)))
print(list(r2cf(22,7)))
print(list(r2cf(14142,10000)))
print(list(r2cf(141421,100000)))
print(list(r2cf(1414214,1000000)))
print(list(r2cf(14142136,10000000))) | 995Continued fraction/Arithmetic/Construct from rational number
| 3python
| uj0vd |
for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do
local n, d, dmax, eps = 1, 1, 1e7, 1e-15
while math.abs(n/d-v)>eps and d<dmax do d=d+1 n=math.floor(v*d) end
print(string.format("%15.13f | 996Convert decimal number to rational
| 1lua
| qnlx0 |
def r2cf(n1,n2)
while n2 > 0
n1, (t1, n2) = n2, n1.divmod(n2)
yield t1
end
end | 995Continued fraction/Arithmetic/Construct from rational number
| 14ruby
| 4ko5p |
struct R2cf {
n1: i64,
n2: i64
} | 995Continued fraction/Arithmetic/Construct from rational number
| 15rust
| gbi4o |
sub gcd {
my ($m, $n) = @_;
($m, $n) = ($n, $m % $n) while $n;
return $m
}
sub rat_machine {
my $n = shift;
my $denom = 1;
while ($n != int $n) {
$n *= 2;
$denom <<= 1;
}
if ($n) {
my $g = gcd($n, $denom);
$n /= $g;
$denom /= $g;
}
return $n, $denom;
}
sub get_denom {
my ($num, $denom) = (1, pop @_);
for (reverse @_) {
($num, $denom) = ($denom, $_ * $denom + $num);
}
wantarray ? ($num, $denom) : $denom
}
sub best_approx {
my ($n, $limit) = @_;
my ($denom, $neg);
if ($n < 0) {
$neg = 1;
$n = -$n;
}
my $int = int($n);
my ($num, $denom, @coef) = (1, $n - $int);
while (1) {
last if $limit * $denom < 1;
my $i = int($num / $denom);
push @coef, $i;
if (get_denom(@coef) > $limit) {
pop @coef;
last;
}
($num, $denom) = ($denom, $num - $i * $denom);
}
($num, $denom) = get_denom @coef;
$num += $denom * $int;
return $neg ? -$num : $num, $denom;
}
sub rat_string {
my $n = shift;
my $denom = 1;
my $neg;
$n =~ s/\.0+$//;
return $n, 1 unless $n =~ /\./;
if ($n =~ /^-/) {
$neg = 1;
$n =~ s/^-//;
}
$denom *= 10 while $n =~ s/\.(\d)/$1\./;
$n =~ s/\.$//;
$n =~ s/^0*//;
if ($n) {
my $g = gcd($n, $denom);
$n /= $g;
$denom /= $g;
}
return $neg ? -$n : $n, $denom;
}
my $limit = 1e8;
my $x = 3/8;
print "3/8 = $x:\n";
printf "machine:%d/%d\n", rat_machine $x;
printf "string: %d/%d\n", rat_string $x;
printf "approx below $limit: %d/%d\n", best_approx $x, $limit;
$x = 137/4291;
print "\n137/4291 = $x:\n";
printf "machine:%d/%d\n", rat_machine $x;
printf "string: %d/%d\n", rat_string $x;
printf "approx below $limit: %d/%d\n", best_approx $x, $limit;
$x = sqrt(1/2);
print "\n1/sqrt(2) = $x\n";
printf "machine:%d/%d\n", rat_machine $x;
printf "string: %d/%d\n", rat_string $x;
printf "approx below 10: %d/%d\n", best_approx $x, 10;
printf "approx below 100: %d/%d\n", best_approx $x, 100;
printf "approx below 1000: %d/%d\n", best_approx $x, 1000;
printf "approx below 10000: %d/%d\n", best_approx $x, 10000;
printf "approx below 100000: %d/%d\n", best_approx $x, 100000;
printf "approx below $limit: %d/%d\n", best_approx $x, $limit;
$x = -4 * atan2(1,1);
print "\n-Pi = $x\n";
printf "machine:%d/%d\n", rat_machine $x;
printf "string: %d/%d\n", rat_string $x;
for (map { 10 ** $_ } 1 .. 10) {
printf "approx below%g:%d /%d\n", $_, best_approx($x, $_)
} | 996Convert decimal number to rational
| 2perl
| 2rxlf |
int
main()
{
size_t len;
char src[] = ;
char dst1[80], dst2[80];
char *dst3, *ref;
strcpy(dst1, src);
len = strlen(src);
if (len >= sizeof dst2) {
fputs(, stderr);
exit(1);
}
memcpy(dst2, src, len + 1);
dst3 = strdup(src);
if (dst3 == NULL) {
perror();
exit(1);
}
ref = src;
memset(src, '-', 5);
printf(, src);
printf(, dst1);
printf(, dst2);
printf(, dst3);
printf(, ref);
free(dst3);
return 0;
} | 997Copy a string
| 5c
| 4k05t |
function asRational($val, $tolerance = 1.e-6)
{
if ($val == (int) $val) {
return $val;
}
$h1=1;
$h2=0;
$k1=0;
$k2=1;
$b = 1 / $val;
do {
$b = 1 / $b;
$a = floor($b);
$aux = $h1;
$h1 = $a * $h1 + $h2;
$h2 = $aux;
$aux = $k1;
$k1 = $a * $k1 + $k2;
$k2 = $aux;
$b = $b - $a;
} while (abs($val-$h1/$k1) > $val * $tolerance);
return $h1.'/'.$k1;
}
echo asRational(1/5).;
echo asRational(1/4).;
echo asRational(1/3).;
echo asRational(5).; | 996Convert decimal number to rational
| 12php
| sd2qs |
(let [s "hello"
s1 s]
(println s s1)) | 997Copy a string
| 6clojure
| hedjr |
>>> from fractions import Fraction
>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))
0.9054054 67/74
0.518518 14/27
0.75 3/4
>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))
0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
>>> | 996Convert decimal number to rational
| 3python
| v7q29 |
ratio<-function(decimal){
denominator=1
while(nchar(decimal*denominator)!=nchar(round(decimal*denominator))){
denominator=denominator+1
}
str=paste(decimal*denominator,"/",sep="")
str=paste(str,denominator,sep="")
return(str)
} | 996Convert decimal number to rational
| 13r
| 95amg |
> '0.9054054 0.518518 0.75'.split.each { |d| puts % [d, Rational(d)] }
0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
=> [, , ] | 996Convert decimal number to rational
| 14ruby
| 5h0uj |
extern crate rand;
extern crate num;
use num::Integer;
use rand::Rng;
fn decimal_to_rational (mut n: f64) -> [isize;2] { | 996Convert decimal number to rational
| 15rust
| 4k85u |
import org.apache.commons.math3.fraction.BigFraction
object Number2Fraction extends App {
val n = Array(0.750000000, 0.518518000, 0.905405400,
0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536)
for (d <- n)
println(f"$d%-12s: ${new BigFraction(d, 0.00000002D, 10000)}%s")
} | 996Convert decimal number to rational
| 16scala
| 71nr9 |
char* seconds2string(unsigned long seconds)
{
int i;
const unsigned long s = 1;
const unsigned long m = 60 * s;
const unsigned long h = 60 * m;
const unsigned long d = 24 * h;
const unsigned long w = 7 * d;
const unsigned long coeff[5] = { w, d, h, m, s };
const char units[5][4] = { , , , , };
static char buffer[256];
char* ptr = buffer;
for ( i = 0; i < 5; i++ )
{
unsigned long value;
value = seconds / coeff[i];
seconds = seconds % coeff[i];
if ( value )
{
if ( ptr != buffer )
ptr += sprintf(ptr, );
ptr += sprintf(ptr,,value,units[i]);
}
}
return buffer;
}
int main(int argc, char argv[])
{
unsigned long seconds;
if ( (argc < 2) && scanf( , &seconds )
|| (argc >= 2) && sscanf( argv[1], , & seconds ) )
{
printf( , seconds2string(seconds) );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
} | 998Convert seconds to compound duration
| 5c
| 5hquk |
type eatable interface {
eat()
} | 999Constrained genericity
| 0go
| 2ral7 |
class Eatable a where
eat :: a -> String | 999Constrained genericity
| 8haskell
| a0z1g |
package main
import (
"fmt"
"rcu"
)
const LIMIT = 999999
var primes = rcu.Primes(LIMIT)
func longestSeq(dir string) {
pd := 0
longSeqs := [][]int{{2}}
currSeq := []int{2}
for i := 1; i < len(primes); i++ {
d := primes[i] - primes[i-1]
if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) {
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
currSeq = []int{primes[i-1], primes[i]}
} else {
currSeq = append(currSeq, primes[i])
}
pd = d
}
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":")
for _, ls := range longSeqs {
var diffs []int
for i := 1; i < len(ls); i++ {
diffs = append(diffs, ls[i]-ls[i-1])
}
for i := 0; i < len(ls)-1; i++ {
fmt.Print(ls[i], " (", diffs[i], ") ")
}
fmt.Println(ls[len(ls)-1])
}
fmt.Println()
}
func main() {
fmt.Println("For primes < 1 million:\n")
for _, dir := range []string{"ascending", "descending"} {
longestSeq(dir)
}
} | 1,000Consecutive primes with ascending or descending differences
| 0go
| bxnkh |
typedef double (*coeff_func)(unsigned n);
double calc(coeff_func f_a, coeff_func f_b, unsigned expansions)
{
double a, b, r;
a = b = r = 0.0;
unsigned i;
for (i = expansions; i > 0; i--) {
a = f_a(i);
b = f_b(i);
r = b / (a + r);
}
a = f_a(0);
return a + r;
}
double sqrt2_a(unsigned n)
{
return n ? 2.0 : 1.0;
}
double sqrt2_b(unsigned n)
{
return 1.0;
}
double napier_a(unsigned n)
{
return n ? n : 2.0;
}
double napier_b(unsigned n)
{
return n > 1.0 ? n - 1.0 : 1.0;
}
double pi_a(unsigned n)
{
return n ? 6.0 : 3.0;
}
double pi_b(unsigned n)
{
double c = 2.0 * n - 1.0;
return c * c;
}
int main(void)
{
double sqrt2, napier, pi;
sqrt2 = calc(sqrt2_a, sqrt2_b, 1000);
napier = calc(napier_a, napier_b, 1000);
pi = calc(pi_a, pi_b, 1000);
printf(, sqrt2, napier, pi);
return 0;
} | 1,001Continued fraction
| 5c
| rpqg7 |
(require '[clojure.string:as string])
(def seconds-in-minute 60)
(def seconds-in-hour (* 60 seconds-in-minute))
(def seconds-in-day (* 24 seconds-in-hour))
(def seconds-in-week (* 7 seconds-in-day))
(defn seconds->duration [seconds]
(let [weeks ((juxt quot rem) seconds seconds-in-week)
wk (first weeks)
days ((juxt quot rem) (last weeks) seconds-in-day)
d (first days)
hours ((juxt quot rem) (last days) seconds-in-hour)
hr (first hours)
min (quot (last hours) seconds-in-minute)
sec (rem (last hours) seconds-in-minute)]
(string/join ", "
(filter #(not (string/blank? %))
(conj []
(when (> wk 0) (str wk " wk"))
(when (> d 0) (str d " d"))
(when (> hr 0) (str hr " hr"))
(when (> min 0) (str min " min"))
(when (> sec 0) (str sec " sec")))))))
(seconds->duration 7259)
(seconds->duration 86400)
(seconds->duration 6000000) | 998Convert seconds to compound duration
| 6clojure
| jai7m |
interface Eatable
{
void eat();
} | 999Constrained genericity
| 9java
| jao7c |
null | 999Constrained genericity
| 11kotlin
| 5hxua |
import Data.Numbers.Primes (primes)
consecutives equiv = filter ((> 1) . length) . go []
where
go r [] = [r]
go [] (h: t) = go [h] t
go (y: ys) (h: t)
| y `equiv` h = go (h: y: ys) t
| otherwise = (y: ys): go [h] t
maximumBy g (h: t) = foldr f h t
where
f r x = if g r < g x then x else r
task ord n = reverse $ p + s: p: (fst <$> rest)
where
(p, s): rest =
maximumBy length $
consecutives (\(_, a) (_, b) -> a `ord` b) $
differences $
takeWhile (< n) primes
differences l = zip l $ zipWith (-) (tail l) l | 1,000Consecutive primes with ascending or descending differences
| 8haskell
| dyun4 |
function findcps(primelist, fcmp)
local currlist = {primelist[1]}
local longlist, prevdiff = currlist, 0
for i = 2, #primelist do
local diff = primelist[i] - primelist[i-1]
if fcmp(diff, prevdiff) then
currlist[#currlist+1] = primelist[i]
if #currlist > #longlist then
longlist = currlist
end
else
currlist = {primelist[i-1], primelist[i]}
end
prevdiff = diff
end
return longlist
end
primegen:generate(nil, 1000000)
cplist = findcps(primegen.primelist, function(a,b) return a>b end)
print("ASC ("..#cplist.."): ["..table.concat(cplist, " ").."]")
cplist = findcps(primegen.primelist, function(a,b) return a<b end)
print("DESC ("..#cplist.."): ["..table.concat(cplist, " ").."]") | 1,000Consecutive primes with ascending or descending differences
| 1lua
| e8zac |
Subsets and Splits