task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | // version 1.1.51
fun findCommonDirPath(paths: List<String>, separator: Char): String {
if (paths.isEmpty()) return ""
if (paths.size == 1) return paths[0]
val splits = paths[0].split(separator)
val n = splits.size
val paths2 = paths.drop(1)
var k = 0
var common = ""
while (true) {
val prevCommon = common
common += if (k == 0) splits[0] else separator + splits[k]
if (!paths2.all { it.startsWith(common + separator) || it == common } ) return prevCommon
if (++k == n) return common
}
}
fun main(args: Array<String>) {
val paths = listOf(
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"
)
val pathsToPrint = paths.map { " '$it'" }.joinToString("\n")
println("The common directory path of:\n\n$pathsToPrint\n")
println("is '${findCommonDirPath(paths, '/')}'")
} |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #C | C | #include <stdio.h>
#include <stdlib.h>
int even_sel(int x) { return !(x & 1); }
int tri_sel(int x) { return x % 3; }
/* using a predicate function sel() to select elements */
int* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace)
{
int i, j, *out;
if (inplace) out = in;
else out = malloc(sizeof(int) * len);
for (i = j = 0; i < len; i++)
if (sel(in[i]))
out[j++] = in[i];
if (!inplace && j < len)
out = realloc(out, sizeof(int) * j);
*outlen = j;
return out;
}
int main()
{
int in[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int i, len;
int *even = grep(in, 10, &len, even_sel, 0);
printf("Filtered even:");
for (i = 0; i < len; i++) printf(" %d", even[i]);
printf("\n");
grep(in, 8, &len, tri_sel, 1);
printf("In-place filtered not multiple of 3:");
for (i = 0; i < len; i++) printf(" %d", in[i]);
printf("\n");
return 0;
} |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Neko | Neko | /**
Recursion limit, in Neko
*/
/* This version is effectively unlimited, (50 billion test before ctrl-c) */
sum = 0.0
counter = 0
tco = function(n) {
sum += n
counter += 1
if n > 10000000 return n else tco(n + 1)
}
try $print("Tail call recursion: ", tco(0), " sum: ", sum, "\n")
catch with $print("tco counter: ", counter, " ", with, "\n")
/* Code after tail, these accumulate stack, will run out of space */
sum = 0.0
counter = 0
recurse = function(n) {
sum += n
counter += 1
if n > 1000000 return n else recurse(n + 1)
return sum
}
try $print("Recurse: ", recurse(0), " sum: ", sum, "\n")
catch with $print("recurse limit exception: ", counter, " ", with, "\n") |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
import java.lang.management.
memoryInfo()
digDeeper(0)
/**
* Just keep digging
* @param level depth gauge
*/
method digDeeper(level = int) private static binary
do
digDeeper(level + 1)
catch ex = Error
System.out.println('Recursion got' level 'levels deep on this system.')
System.out.println('Recursion stopped by' ex.getClass.getName())
end
return
/**
* Display some memory usage from the JVM
* @see ManagementFactory
* @see MemoryMXBean
* @see MemoryUsage
*/
method memoryInfo() private static
mxBean = ManagementFactory.getMemoryMXBean() -- get the MemoryMXBean
hmMemoryUsage = mxBean.getHeapMemoryUsage() -- get the heap MemoryUsage object
nmMemoryUsage = mxBean.getNonHeapMemoryUsage() -- get the non-heap MemoryUsage object
say 'JVM Memory Information:'
say ' Heap:' hmMemoryUsage.toString()
say ' Non-Heap:' nmMemoryUsage.toString()
say '-'.left(120, '-')
say
return
|
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Main()
Dim siCount As Short
Dim sText As String
For siCount = 1 To 100
sText = ""
If siCount Mod 3 = 0 Then sText = "Fizz"
If siCount Mod 5 = 0 Then sText = "Buzz"
If siCount Mod 15 = 0 Then sText = "FizzBuzz"
If sText Then Print sText Else Print siCount
Next
End |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #J | J | require 'files'
fsize 'input.txt';'/input.txt' |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Java | Java | import java.io.File;
public class FileSize
{
public static void main ( String[] args )
{
System.out.println("input.txt : " + new File("input.txt").length() + " bytes");
System.out.println("/input.txt : " + new File("/input.txt").length() + " bytes");
}
}
|
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #DBL | DBL | ;
; File Input and output examples for DBL version 4 by Dario B.
;
RECORD CUSTOM
CUCOD, D5 ;customer code
CUNAM, A20 ;name
CUCIT, A20 ;city
, A55
;------- 100 bytes -------------
A80, A80
PROC
;--------------------------------------------------------------
XCALL FLAGS (0007000000,1) ;suppress STOP message
CLOSE 1
OPEN (1,O,'TT:') ;open video
CLOSE 2
OPEN (2,O,"CUSTOM.DDF") ;create file in output
;Add new record
CLEAR CUSTOM
CUCOD=1
CUNAM="Alan Turing"
CUCIT="London"
WRITES (2,CUSTOM)
;Add new record
CLEAR CUSTOM
CUCOD=2
CUNAM="Galileo Galilei"
CUCIT="Pisa"
WRITES (2,CUSTOM)
;Modify a record
CLOSE 2
OPEN (2,U,"CUSTOM.DDF") [ERR=NOCUS] ;open in update
READ (2,CUSTOM,2) [ERR=NOREC]
CUCIT="Pisa - Italy"
WRITE (2,CUSTOM,2) [ERR=NOWRI]
;Add new record
CLOSE 2
OPEN (2,A,"CUSTOM.DDF") [ERR=NOCUS] ;open in append
CLEAR CUSTOM
CUCOD=3
CUNAM="Kenneth Lane Thompson"
CUCIT="New Orleans"
WRITES (2,CUSTOM)
CLOSE 2
;Read file and display a video
CLOSE 2
OPEN (2,I,"CUSTOM.DDF") [ERR=NOCUS]
DO FOREVER
BEGIN
READS (2,CUSTOM,EOF) [ERR=NOREC]
DISPLAY (1,13,CUSTOM)
END
EOF, DISPLAY (1,10)
CLOSE 2
;Write/read a text file
CLOSE 3
OPEN (3,O,"FILE.TXT")
DISPLAY (3,"An Occurrence at Owl Creek Bridge",13,10)
DISPLAY (3,"A man stood upon a railroad bridge in northern Alabama,",13,10)
DISPLAY (3,"looking down into the swift water twenty feet below.",13,10)
DISPLAY (3,"The man's hands were behind his back, the wrists bound ")
DISPLAY (3,"with a cord.",13,10)
CLOSE 3
OPEN (3,I,"FILE.TXT")
DO FOREVER
BEGIN
READS (3,A80,EOFF)
DISPLAY (1,A80(1:%TRIM(A80)),10)
END
EOFF, CLOSE 3
DISPLAY (1,10)
GOTO QUIT
;---------------------------------------------------------------
NOCUS, DISPLAY (1,10,"File CUSTUM.DDF Not found!",10)
GOTO QUIT
NOREC, DISPLAY (1,10,"Read error!",10)
GOTO QUIT
NOWRI, DISPLAY (1,10,"Write error!",10)
GOTO QUIT
QUIT, CLOSE 1
STOP |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #DCL | DCL | $ open input input.txt
$ open /write output output.txt
$ loop:
$ read /end_of_file = done input line
$ write output line
$ goto loop
$ done:
$ close input
$ close output |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #D | D | import std.stdio, std.algorithm, std.math, std.string, std.range;
real entropy(T)(T[] s) pure nothrow
if (__traits(compiles, s.sort())) {
immutable sLen = s.length;
return s
.sort()
.group
.map!(g => g[1] / real(sLen))
.map!(p => -p * p.log2)
.sum;
}
void main() {
enum uint nMax = 37;
" N Length Entropy Fibword".writeln;
uint n = 1;
foreach (s; recurrence!q{a[n - 1] ~ a[n - 2]}("1", "0").take(nMax))
writefln("%3d %10d %2.19f %s", n++, s.length,
s.dup.representation.entropy.abs,
s.length < 25 ? s : "<too long>");
} |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #BASIC256 | BASIC256 | open 1, "input.fasta"
first = True
while not eof(1)
ln = readline(1)
if left(ln, 1) = ">" then
if not first then print
print mid(ln, 2, length(ln)-2) & ": ";
if first then first = False
else
if first then
print "Error : File does not begin with '>'"
exit while
else
if checkNoSpaces(ln) then
print left(ln, length(ln)-2);
else
print "Error : Sequence contains space(s)"
exit while
end if
end if
end if
end while
close 1
end
function checkNoSpaces(s)
for i = 1 to length(s) - 1
if chr(mid(s,i,1)) = 32 or chr(mid(s,i,1)) = 9 then return False
next i
return True
end function |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("fasta.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
int state = 0;
while ((read = getline(&line, &len, fp)) != -1) {
/* Delete trailing newline */
if (line[read - 1] == '\n')
line[read - 1] = 0;
/* Handle comment lines*/
if (line[0] == '>') {
if (state == 1)
printf("\n");
printf("%s: ", line+1);
state = 1;
} else {
/* Print everything else */
printf("%s", line);
}
}
printf("\n");
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
} |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #C.23 | C# | using System;
namespace FaulhabersFormula {
internal class Frac {
private long num;
private long denom;
public static readonly Frac ZERO = new Frac(0, 1);
public static readonly Frac ONE = new Frac(1, 1);
public Frac(long n, long d) {
if (d == 0) {
throw new ArgumentException("d must not be zero");
}
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
}
else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.Abs(Gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
private static long Gcd(long a, long b) {
if (b == 0) {
return a;
}
return Gcd(b, a % b);
}
public static Frac operator -(Frac self) {
return new Frac(-self.num, self.denom);
}
public static Frac operator +(Frac lhs, Frac rhs) {
return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);
}
public static Frac operator -(Frac lhs, Frac rhs) {
return lhs + -rhs;
}
public static Frac operator *(Frac lhs, Frac rhs) {
return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
public static bool operator <(Frac lhs, Frac rhs) {
double x = (double)lhs.num / lhs.denom;
double y = (double)rhs.num / rhs.denom;
return x < y;
}
public static bool operator >(Frac lhs, Frac rhs) {
double x = (double)lhs.num / lhs.denom;
double y = (double)rhs.num / rhs.denom;
return x > y;
}
public static bool operator ==(Frac lhs, Frac rhs) {
return lhs.num == rhs.num && lhs.denom == rhs.denom;
}
public static bool operator !=(Frac lhs, Frac rhs) {
return lhs.num != rhs.num || lhs.denom != rhs.denom;
}
public override string ToString() {
if (denom == 1) {
return num.ToString();
}
return string.Format("{0}/{1}", num, denom);
}
public override bool Equals(object obj) {
var frac = obj as Frac;
return frac != null &&
num == frac.num &&
denom == frac.denom;
}
public override int GetHashCode() {
var hashCode = 1317992671;
hashCode = hashCode * -1521134295 + num.GetHashCode();
hashCode = hashCode * -1521134295 + denom.GetHashCode();
return hashCode;
}
}
class Program {
static Frac Bernoulli(int n) {
if (n < 0) {
throw new ArgumentException("n may not be negative or zero");
}
Frac[] a = new Frac[n + 1];
for (int m = 0; m <= n; m++) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);
}
}
// returns 'first' Bernoulli number
if (n != 1) return a[0];
return -a[0];
}
static int Binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw new ArgumentException();
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num = num * i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom = denom * i;
}
return num / denom;
}
static void Faulhaber(int p) {
Console.Write("{0} : ", p);
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; j++) {
sign *= -1;
Frac coeff = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);
if (Frac.ZERO == coeff) continue;
if (j == 0) {
if (Frac.ONE != coeff) {
if (-Frac.ONE == coeff) {
Console.Write("-");
}
else {
Console.Write(coeff);
}
}
}
else {
if (Frac.ONE == coeff) {
Console.Write(" + ");
}
else if (-Frac.ONE == coeff) {
Console.Write(" - ");
}
else if (Frac.ZERO < coeff) {
Console.Write(" + {0}", coeff);
}
else {
Console.Write(" - {0}", -coeff);
}
}
int pwr = p + 1 - j;
if (pwr > 1) {
Console.Write("n^{0}", pwr);
}
else {
Console.Write("n");
}
}
Console.WriteLine();
}
static void Main(string[] args) {
for (int i = 0; i < 10; i++) {
Faulhaber(i);
}
}
}
} |
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #Kotlin | Kotlin | import java.math.BigInteger
import kotlin.math.pow
fun main() {
println("First 10 Fermat numbers:")
for (i in 0..9) {
println("F[$i] = ${fermat(i)}")
}
println()
println("First 12 Fermat numbers factored:")
for (i in 0..12) {
println("F[$i] = ${getString(getFactors(i, fermat(i)))}")
}
}
private fun getString(factors: List<BigInteger>): String {
return if (factors.size == 1) {
"${factors[0]} (PRIME)"
} else factors.map { it.toString() }
.joinToString(" * ") {
if (it.startsWith("-"))
"(C" + it.replace("-", "") + ")"
else it
}
}
private val COMPOSITE = mutableMapOf(
9 to "5529",
10 to "6078",
11 to "1037",
12 to "5488",
13 to "2884"
)
private fun getFactors(fermatIndex: Int, n: BigInteger): List<BigInteger> {
var n2 = n
val factors: MutableList<BigInteger> = ArrayList()
var factor: BigInteger
while (true) {
if (n2.isProbablePrime(100)) {
factors.add(n2)
break
} else {
if (COMPOSITE.containsKey(fermatIndex)) {
val stop = COMPOSITE[fermatIndex]
if (n2.toString().startsWith(stop!!)) {
factors.add(BigInteger("-" + n2.toString().length))
break
}
}
//factor = pollardRho(n)
factor = pollardRhoFast(n)
n2 = if (factor.compareTo(BigInteger.ZERO) == 0) {
factors.add(n2)
break
} else {
factors.add(factor)
n2.divide(factor)
}
}
}
return factors
}
private val TWO = BigInteger.valueOf(2)
private fun fermat(n: Int): BigInteger {
return TWO.pow(2.0.pow(n.toDouble()).toInt()).add(BigInteger.ONE)
}
// See: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
@Suppress("unused")
private fun pollardRho(n: BigInteger): BigInteger {
var x = BigInteger.valueOf(2)
var y = BigInteger.valueOf(2)
var d = BigInteger.ONE
while (d.compareTo(BigInteger.ONE) == 0) {
x = pollardRhoG(x, n)
y = pollardRhoG(pollardRhoG(y, n), n)
d = (x - y).abs().gcd(n)
}
return if (d.compareTo(n) == 0) {
BigInteger.ZERO
} else d
}
// Includes Speed Up of 100 multiples and 1 GCD, instead of 100 multiples and 100 GCDs.
// See Variants section of Wikipedia article.
// Testing F[8] = 1238926361552897 * Prime
// This variant = 32 sec.
// Standard algorithm = 107 sec.
private fun pollardRhoFast(n: BigInteger): BigInteger {
val start = System.currentTimeMillis()
var x = BigInteger.valueOf(2)
var y = BigInteger.valueOf(2)
var d: BigInteger
var count = 0
var z = BigInteger.ONE
while (true) {
x = pollardRhoG(x, n)
y = pollardRhoG(pollardRhoG(y, n), n)
d = (x - y).abs()
z = (z * d).mod(n)
count++
if (count == 100) {
d = z.gcd(n)
if (d.compareTo(BigInteger.ONE) != 0) {
break
}
z = BigInteger.ONE
count = 0
}
}
val end = System.currentTimeMillis()
println(" Pollard rho try factor $n elapsed time = ${end - start} ms (factor = $d).")
return if (d.compareTo(n) == 0) {
BigInteger.ZERO
} else d
}
private fun pollardRhoG(x: BigInteger, n: BigInteger): BigInteger {
return (x * x + BigInteger.ONE).mod(n)
} |
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences | Fibonacci n-step number sequences | These number series are an expansion of the ordinary Fibonacci sequence where:
For
n
=
2
{\displaystyle n=2}
we have the Fibonacci sequence; with initial values
[
1
,
1
]
{\displaystyle [1,1]}
and
F
k
2
=
F
k
−
1
2
+
F
k
−
2
2
{\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #APL | APL | nStep ← {⊃(1↓⊢,+/)⍣(⍺-1)⊢⍵}
nacci ← 2*0⌈¯2+⍳
↑((⍳10)nStep¨⊂)¨(nacci¨2 3 4),⊂2 1 |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #jq | jq | def feigenbaum_delta(imax; jmax):
def lpad: tostring | (" " * (4 - length)) + .;
def pp(i;x): "\(i|lpad) \(x)";
"Feigenbaum's delta constant incremental calculation:",
pp("i"; "δ"),
pp(1; "3.20"),
( foreach range(2; 1+imax) as $i (
{a1: 1.0, a2: 0.0, d1: 3.2};
.a = .a1 + (.a1 - .a2) / .d1
| reduce range(1; 1+jmax) as $j (.;
.x = 0 | .y = 0
| reduce range(1; 1+pow(2;$i)) as $k (.;
.y = (1 - 2 * .x * .y)
| .x = .a - (.x * .x) )
| .a -= (.x / .y) )
| .d = (.a1 - .a2) / (.a - .a1)
| .emit = pp($i; .d)
| .d1 = .d | .a2 = .a1 | .a1 = .a;
.emit ) ) ;
feigenbaum_delta(13; 10)
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Julia | Julia | # http://en.wikipedia.org/wiki/Feigenbaum_constant
function feigenbaum_delta(imax=23, jmax=20)
a1, a2, d1 = BigFloat(1.0), BigFloat(0.0), BigFloat(3.2)
println("Feigenbaum's delta constant incremental calculation:\ni δ\n1 3.20")
for i in 2:imax
a = a1 + (a1 - a2) / d1
for j in 1:jmax
x, y = 0, 0
for k in 1:2^i
y = 1 - 2 * x * y
x = a - x * x
end
a -= x / y
end
d = (a1 - a2) / (a - a1)
println(rpad(i, 4), lpad(d, 4))
d1, a2 = d, a1
a1 = a
end
end
feigenbaum_delta()
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Kotlin | Kotlin | // Version 1.2.40
fun feigenbaum() {
val maxIt = 13
val maxItJ = 10
var a1 = 1.0
var a2 = 0.0
var d1 = 3.2
println(" i d")
for (i in 2..maxIt) {
var a = a1 + (a1 - a2) / d1
for (j in 1..maxItJ) {
var x = 0.0
var y = 0.0
for (k in 1..(1 shl i)) {
y = 1.0 - 2.0 * y * x
x = a - x * x
}
a -= x / y
}
val d = (a1 - a2) / (a - a1)
println("%2d %.8f".format(i,d))
d1 = d
a2 = a1
a1 = a
}
}
fun main(args: Array<String>) {
feigenbaum()
} |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Perl | Perl | sub check_extension {
my ($filename, @extensions) = @_;
my $extensions = join '|', map quotemeta, @extensions;
scalar $filename =~ / \. (?: $extensions ) $ /xi
} |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #PHP | PHP |
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];
$lc_allowed = array_map('strtolower', $allowed);
$tests = [
['MyData.a##',true],
['MyData.tar.Gz',true],
['MyData.gzip',false],
['MyData.7z.backup',false],
['MyData...',false],
['MyData',false],
['archive.tar.gz', true]
];
foreach ($tests as $test) {
$ext = pathinfo($test[0], PATHINFO_EXTENSION);
if (in_array(strtolower($ext), $lc_allowed)) {
$result = 'true';
} else {
$result = 'false';
}
printf("%20s : %s \n", $test[0],$result);
}
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #OCaml | OCaml | #load "unix.cma";;
open Unix;;
let mtime = (stat filename).st_mtime;; (* seconds since the epoch *)
utimes filename (stat filename).st_atime (time ());;
(* keep atime unchanged
set mtime to current time *) |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Oforth | Oforth | File new("myfile.txt") modified |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #OpenEdge.2FProgress | OpenEdge/Progress | FILE-INFO:FILE-NAME = 'c:/temp'.
MESSAGE
STRING( FILE-INFO:FILE-MOD-TIME, 'HH:MM:SS' )
VIEW-AS ALERT-BOX |
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #PARI.2FGP | PARI/GP |
\\ Fibonacci word/fractals
\\ 4/25/16 aev
fibword(n)={
my(f1="1",f2="0",fw,fwn,n2);
if(n<=4, n=5);n2=n-2;
for(i=1,n2, fw=Str(f2,f1); f1=f2;f2=fw;); fwn=#fw;
fw=Vecsmall(fw);
for(i=1,fwn,fw[i]-=48);
return(fw);
}
nextdir(n,d)={
my(dir=-1);
if(d==0, if(n%2==0, dir=0,dir=1)); \\0-left,1-right
return(dir);
}
plotfibofract(n,sz,len)={
my(fwv,fn,dr,px=10,py=420,x=0,y=-len,g2=0,
ttl="Fibonacci word/fractal: n=");
plotinit(0); plotcolor(0,6); \\green
plotscale(0, -sz,sz, -sz,sz);
plotmove(0, px,py);
fwv=fibword(n); fn=#fwv;
for(i=1,fn,
plotrline(0,x,y);
dr=nextdir(i,fwv[i]);
if(dr==-1, next);
\\up
if(g2==0, y=0; if(dr, x=len;g2=1, x=-len;g2=3); next);
\\right
if(g2==1, x=0; if(dr, y=len;g2=2, y=-len;g2=0); next);
\\down
if(g2==2, y=0; if(dr, x=-len;g2=3, x=len;g2=1); next);
\\left
if(g2==3, x=0; if(dr, y=-len;g2=0, y=len;g2=2); next);
);\\fend i
plotdraw([0,-sz,-sz]);
print(" *** ",ttl,n," sz=",sz," len=",len," fw-len=",fn);
}
{\\ Executing:
plotfibofract(11,430,20); \\ Fibofrac1.png
plotfibofract(21,430,2); \\ Fibofrac2.png
}
|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lasso | Lasso | #!/usr/bin/lasso9
local(
path1 = '/home/user1/tmp/coverage/test' -> split('/'),
path2 = '/home/user1/tmp/covert/operator' -> split('/'),
path3 = '/home/user1/tmp/coven/members' -> split('/')
)
define commonpath(...) => {
local(shared = #rest -> get(1))
loop(#rest -> size - 1) => {
#shared = #shared -> intersection(#rest -> get(loop_count + 1))
}
return #shared -> join('/')
}
stdoutnl(commonpath(#path1, #path2, #path3)) |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Liberty_BASIC | Liberty BASIC | path$(1) = "/home/user1/tmp/coverage/test"
path$(2) = "/home/user1/tmp/covert/operator"
path$(3) = "/home/user1/tmp/coven/members"
print samepath$(3,"/")
end
function samepath$(paths,sep$)
d = 1 'directory depth
n = 2 'path$(number)
while 1
if word$(path$(1),d,sep$) <> word$(path$(n),d,sep$) or word$(path$(1),d,sep$) = "" then exit while
n = n + 1
if n > paths then
if right$(samepath$,1) <> sep$ and d<>1 then
samepath$ = samepath$ + sep$ + word$(path$(1),d,sep$)
else
samepath$ = samepath$ + word$(path$(1),d,sep$)
end if
n = 2
d = d + 1
end if
wend
end function |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #C.23 | C# | ArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } );
ArrayList evens = new ArrayList();
foreach( int i in array )
{
if( (i%2) == 0 )
evens.Add( i );
}
foreach( int i in evens )
System.Console.WriteLine( i.ToString() ); |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Nim | Nim | proc recurse(i: int): int =
echo i
recurse(i+1)
echo recurse(0) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #OCaml | OCaml | # let last = ref 0 ;;
val last : int ref = {contents = 0}
# let rec f i =
last := i;
i + (f (i+1))
;;
val f : int -> int = <fun>
# f 0 ;;
stack overflow during evaluation (looping recursion?).
# !last ;;
- : int = 262067 |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Gambas | Gambas | Public Sub Main()
Dim siCount As Short
Dim sText As String
For siCount = 1 To 100
sText = ""
If siCount Mod 3 = 0 Then sText = "Fizz"
If siCount Mod 5 = 0 Then sText = "Buzz"
If siCount Mod 15 = 0 Then sText = "FizzBuzz"
If sText Then Print sText Else Print siCount
Next
End |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.GetFile('input.txt').Size;
fso.GetFile('c:/input.txt').Size; |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #jq | jq | jq -Rs length input.txt
jq -Rs length /input.txt |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Julia | Julia | println(filesize("input.txt"))
println(filesize("/input.txt")) |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Delphi | Delphi | - Read(F,V1..Vn)
- ReadLn(F,V1..Vn)
- Write(F,V1[,V2..Vn])
- WriteLn(f,V1[,V2..Vn])
- BlockRead(F,Buff,BytesToRead[,BytesRead])
- BlockWrite(F,Buff,BytesToRead[,BytesWritten])
|
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #DIBOL-11 | DIBOL-11 |
START ;Simple File Input and Output
RECORD TEMP
INLINE, A72
PROC
OPEN (8,I,"input.txt")
OPEN (9,O,"output.txt")
LOOP,
READS(8,TEMP,END)
WRITES(9,TEMP)
GOTO LOOP
END,
CLOSE 8
CLOSE 9
END
|
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #Delphi | Delphi |
(lib 'struct)
(struct FW ( count0 count1 length string)) ;; a fibonacci word
(define (F-word n) ;; generator
(define a (F-word (1- n)))
(define b (F-word (- n 2)))
(FW
(+ (FW-count0 a) (FW-count0 b))
(+ (FW-count1 a) (FW-count1 b))
(+ (FW-length a) (FW-length b))
(if (> n 9) "..." (string-append (FW-string a) (FW-string b)))))
(remember 'F-word (vector 0 (FW 0 1 1 "1") (FW 1 0 1 "0")))
(define (entropy fw)
(define p (// (FW-count0 fw) (FW-length fw)))
(cond
((= p 0) 0)
((= p 1) 0)
(else (- 0 (* p (log2 p)) (* (- 1 p) (log2 (- 1 p)))))))
(define (task (n 38) (fw))
(for ((i (in-range 1 n)))
(set! fw (F-word i))
(printf "%3d %10d %24d %a"
i (FW-length fw) (entropy fw) (FW-string fw))))
|
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Program
{
public class FastaEntry
{
public string Name { get; set; }
public StringBuilder Sequence { get; set; }
}
static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)
{
FastaEntry f = null;
string line;
while ((line = fastaFile.ReadLine()) != null)
{
// ignore comment lines
if (line.StartsWith(";"))
continue;
if (line.StartsWith(">"))
{
if (f != null)
yield return f;
f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };
}
else if (f != null)
f.Sequence.Append(line);
}
yield return f;
}
static void Main(string[] args)
{
try
{
using (var fastaFile = new StreamReader("fasta.txt"))
{
foreach (FastaEntry f in ParseFasta(fastaFile))
Console.WriteLine("{0}: {1}", f.Name, f.Sequence);
}
}
catch (FileNotFoundException e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
} |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int binomial(int n, int k) {
int num, denom, i;
if (n < 0 || k < 0 || n < k) return -1;
if (n == 0 || k == 0) return 1;
num = 1;
for (i = k + 1; i <= n; ++i) {
num = num * i;
}
denom = 1;
for (i = 2; i <= n - k; ++i) {
denom *= i;
}
return num / denom;
}
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
typedef struct tFrac {
int num, denom;
} Frac;
Frac makeFrac(int n, int d) {
Frac result;
int g;
if (d == 0) {
result.num = 0;
result.denom = 0;
return result;
}
if (n == 0) {
d = 1;
} else if (d < 0) {
n = -n;
d = -d;
}
g = abs(gcd(n, d));
if (g > 1) {
n = n / g;
d = d / g;
}
result.num = n;
result.denom = d;
return result;
}
Frac negateFrac(Frac f) {
return makeFrac(-f.num, f.denom);
}
Frac subFrac(Frac lhs, Frac rhs) {
return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);
}
Frac multFrac(Frac lhs, Frac rhs) {
return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
bool equalFrac(Frac lhs, Frac rhs) {
return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);
}
bool lessFrac(Frac lhs, Frac rhs) {
return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);
}
void printFrac(Frac f) {
char buffer[7];
int len;
if (f.denom != 1) {
snprintf(buffer, 7, "%d/%d", f.num, f.denom);
} else {
snprintf(buffer, 7, "%d", f.num);
}
len = 7 - strlen(buffer);
while (len-- > 0) {
putc(' ', stdout);
}
printf(buffer);
}
Frac bernoulli(int n) {
Frac a[16];
int j, m;
if (n < 0) {
a[0].num = 0;
a[0].denom = 0;
return a[0];
}
for (m = 0; m <= n; ++m) {
a[m] = makeFrac(1, m + 1);
for (j = m; j >= 1; --j) {
a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));
}
}
if (n != 1) {
return a[0];
}
return negateFrac(a[0]);
}
void faulhaber(int p) {
Frac q, *coeffs;
int j, sign;
coeffs = malloc(sizeof(Frac)*(p + 1));
q = makeFrac(1, p + 1);
sign = -1;
for (j = 0; j <= p; ++j) {
sign = -1 * sign;
coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));
}
for (j = 0; j <= p; ++j) {
printFrac(coeffs[j]);
}
printf("\n");
free(coeffs);
}
int main() {
int i;
for (i = 0; i < 10; ++i) {
faulhaber(i);
}
return 0;
} |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #C.2B.2B | C++ | #include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
class Frac {
public:
Frac(long n, long d) {
if (d == 0) {
throw new std::runtime_error("d must not be zero");
}
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = abs(std::gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
Frac operator-() const {
return Frac(-num, denom);
}
Frac operator+(const Frac& rhs) const {
return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);
}
Frac operator-(const Frac& rhs) const {
return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);
}
Frac operator*(const Frac& rhs) const {
return Frac(num*rhs.num, denom*rhs.denom);
}
bool operator==(const Frac& rhs) const {
return num == rhs.num && denom == rhs.denom;
}
bool operator!=(const Frac& rhs) const {
return num != rhs.num || denom != rhs.denom;
}
bool operator<(const Frac& rhs) const {
if (denom == rhs.denom) {
return num < rhs.num;
}
return num * rhs.denom < rhs.num * denom;
}
friend std::ostream& operator<<(std::ostream&, const Frac&);
static Frac ZERO() {
return Frac(0, 1);
}
static Frac ONE() {
return Frac(1, 1);
}
private:
long num;
long denom;
};
std::ostream & operator<<(std::ostream & os, const Frac &f) {
if (f.num == 0 || f.denom == 1) {
return os << f.num;
}
std::stringstream ss;
ss << f.num << "/" << f.denom;
return os << ss.str();
}
Frac bernoulli(int n) {
if (n < 0) {
throw new std::runtime_error("n may not be negative or zero");
}
std::vector<Frac> a;
for (int m = 0; m <= n; m++) {
a.push_back(Frac(1, m + 1));
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * Frac(j, 1);
}
}
// returns 'first' Bernoulli number
if (n != 1) return a[0];
return -a[0];
}
int binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw new std::runtime_error("parameters are invalid");
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num *= i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom *= i;
}
return num / denom;
}
void faulhaber(int p) {
using namespace std;
cout << p << " : ";
auto q = Frac(1, p + 1);
int sign = -1;
for (int j = 0; j < p + 1; j++) {
sign *= -1;
auto coeff = q * Frac(sign, 1) * Frac(binomial(p + 1, j), 1) * bernoulli(j);
if (coeff == Frac::ZERO()) {
continue;
}
if (j == 0) {
if (coeff == -Frac::ONE()) {
cout << "-";
} else if (coeff != Frac::ONE()) {
cout << coeff;
}
} else {
if (coeff == Frac::ONE()) {
cout << " + ";
} else if (coeff == -Frac::ONE()) {
cout << " - ";
} else if (coeff < Frac::ZERO()) {
cout << " - " << -coeff;
} else {
cout << " + " << coeff;
}
}
int pwr = p + 1 - j;
if (pwr > 1) {
cout << "n^" << pwr;
} else {
cout << "n";
}
}
cout << endl;
}
int main() {
for (int i = 0; i < 10; i++) {
faulhaber(i);
}
return 0;
} |
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #langur | langur | val .fermat = f 2 ^ 2 ^ .n + 1
val .factors = f(var .x) {
for[.f=[]] .i, .s = 2, truncate .x ^/ 2; .i < .s; .i += 1 {
if .x div .i {
.f ~= [.i]
.x \= .i
.s = truncate .x ^/ 2
}
} ~ [.x]
}
writeln "first 10 Fermat numbers"
for .i in 0..9 {
writeln $"F\(.i + 16x2080:cp) = \(.fermat(.i))"
}
writeln()
writeln "factors of first few Fermat numbers"
for .i in 0..9 {
val .ferm = .fermat(.i)
val .fac = .factors(.ferm)
if len(.fac) == 1 {
writeln $"F\(.i + 16x2080:cp) is prime"
} else {
writeln $"F\(.i + 16x2080:cp) factors: ", .fac
}
}
|
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Fermat]
Fermat[n_] := 2^(2^n) + 1
Fermat /@ Range[0, 9]
Scan[FactorInteger /* Print, %] |
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences | Fibonacci n-step number sequences | These number series are an expansion of the ordinary Fibonacci sequence where:
For
n
=
2
{\displaystyle n=2}
we have the Fibonacci sequence; with initial values
[
1
,
1
]
{\displaystyle [1,1]}
and
F
k
2
=
F
k
−
1
2
+
F
k
−
2
2
{\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
-- Start sequence -> Number of terms -> terms
-- takeNFibs :: [Int] -> Int -> [Int]
on takeNFibs(xs, n)
script go
on |λ|(xs, n)
if 0 < n and 0 < length of xs then
cons(head(xs), ¬
|λ|(append(tail(xs), {sum(xs)}), n - 1))
else
{}
end if
end |λ|
end script
go's |λ|(xs, n)
end takeNFibs
-- fibInit :: Int -> [Int]
on fibInit(n)
script powerOfTwo
on |λ|(x)
2 ^ x as integer
end |λ|
end script
cons(1, map(powerOfTwo, enumFromToInt(0, n - 2)))
end fibInit
-- TEST ---------------------------------------------------
on run
set intTerms to 15
script series
on |λ|(s, n)
justifyLeft(12, space, s & "nacci") & " -> " & ¬
showJSON(takeNFibs(fibInit(n), intTerms))
end |λ|
end script
set strTable to unlines(zipWith(series, ¬
words of ("fibo tribo tetra penta hexa hepta octo nona deca"), ¬
enumFromToInt(2, 10)))
justifyLeft(12, space, "Lucas ") & " -> " & ¬
showJSON(takeNFibs({2, 1}, intTerms)) & linefeed & strTable
end run
-- GENERIC FUNCTIONS --------------------------------------
-- Append two lists.
-- append (++) :: [a] -> [a] -> [a]
-- append (++) :: String -> String -> String
on append(xs, ys)
xs & ys
end append
-- cons :: a -> [a] -> [a]
on cons(x, xs)
if list is class of xs then
{x} & xs
else
x & xs
end if
end cons
-- enumFromToInt :: Int -> Int -> [Int]
on enumFromToInt(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromToInt
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- head :: [a] -> a
on head(xs)
if xs = {} then
missing value
else
item 1 of xs
end if
end head
-- justifyLeft :: Int -> Char -> String -> String
on justifyLeft(n, cFiller, strText)
if n > length of strText then
text 1 thru n of (strText & replicate(n, cFiller))
else
strText
end if
end justifyLeft
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- showJSON :: a -> String
on showJSON(x)
set c to class of x
if (c is list) or (c is record) then
set ca to current application
set {json, e} to ca's NSJSONSerialization's ¬
dataWithJSONObject:x options:0 |error|:(reference)
if json is missing value then
e's localizedDescription() as text
else
(ca's NSString's alloc()'s ¬
initWithData:json encoding:(ca's NSUTF8StringEncoding)) as text
end if
else if c is date then
"\"" & ((x - (time to GMT)) as «class isot» as string) & ".000Z" & "\""
else if c is text then
"\"" & x & "\""
else if (c is integer or c is real) then
x as text
else if c is class then
"null"
else
try
x as text
on error
("«" & c as text) & "»"
end try
end if
end showJSON
-- sum :: [Num] -> Num
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
-- tail :: [a] -> [a]
on tail(xs)
set blnText to text is class of xs
if blnText then
set unit to ""
else
set unit to {}
end if
set lng to length of xs
if 1 > lng then
missing value
else if 2 > lng then
unit
else
if blnText then
text 2 thru -1 of xs
else
rest of xs
end if
end if
end tail
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
if 1 > lng then return {}
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Lambdatalk | Lambdatalk |
{feigenbaum 11} // on my computer stackoverflow for values greater than 11
-> [3.2185114220380866,4.3856775985683365,4.600949276538056,4.6551304953919646,4.666111947822846,
4.668548581451485,4.66906066077106,4.669171554514976,4.669195154039278,4.669200256503637]
with:
{def feigenbaum
{lambda {:maxi}
{f3 :maxi 10 1 0 3.2 0 {A.new} 2}}}
{def f3
{lambda {:maxi :maxj :a1 :a2 :d1 :a3 :s :i}
{if {< :i {+ :maxi 1}}
then {let { {:maxi :maxi} {:maxj :maxj} {:a1 :a1} {:a2 :a2}
{:a3 {f2 {+ :a1 {/ {- :a1 :a2} :d1}} :i :maxj 1} }
{:s :s} {:i :i}
} {f3 :maxi :maxj :a3 :a1 {/ {- :a1 :a2} {- :a3 :a1}} :a3
{A.addlast! {/ {- :a1 :a2} {- :a3 :a1}} :s} {+ :i 1}} }
else :s}}}
{def f2
{lambda {:a :i :maxj :j}
{if {< :j {+ :maxj 1}}
then {f2 {f1 :a :i 0 0 1} :i :maxj {+ :j 1}}
else :a}}}
{def f1
{lambda {:a :i :y :x :k}
{if {< :k {+ {pow 2 :i} 1}}
then {f1 :a :i {- 1 {* 2 :y :x}} {- :a {* :x :x}} {+ :k 1}}
else {- :a {/ :x :y}} }}}
|
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Phix | Phix | with javascript_semantics
constant extensions = lower({"zip","rar","7z","gz","archive","A##","tar.bz2"})
global function get_known_extension(string filename)
for i=1 to length(filename) do
if filename[i]='.' then
string extension = lower(filename[i+1..$])
if find(extension,extensions) then
return extension
end if
end if
end for
return ""
end function
constant tests = {"MyData.a##",
"MyData.tar.Gz",
"MyData.gzip",
"MyData.7z.backup",
"MyData...",
"MyData",
"MyData_v1.0.tar.bz2",
"MyData_v1.0.bz2"}
for i=1 to length(tests) do
string ti = tests[i],
ext = get_known_extension(ti)
printf(1,"%-20s %-10s %s\n",{ti,ext,{"true","false"}[2-(find(ext,extensions)!=0)]})
end for
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Oz | Oz | declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
Modified = {Path.mtime "input.txt"} %% posix time
in
{Show {OsTime.localtime Modified}} %% human readable record |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Pascal | Pascal | my $mtime = (stat($file))[9]; # seconds since the epoch
# you should use the more legible version below:
use File::stat qw(stat);
my $mtime = stat($file)->mtime; # seconds since the epoch
utime(stat($file)->atime, time, $file);
# keep atime unchanged
# set mtime to current time |
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #Perl | Perl | use strict;
use warnings;
use GD;
my @fword = ( undef, 1, 0 );
sub fword {
my $n = shift;
return $fword[$n] if $n<3;
return $fword[$n] //= fword($n-1).fword($n-2);
}
my $size = 3000;
my $im = new GD::Image($size,$size);
my $white = $im->colorAllocate(255,255,255);
my $black = $im->colorAllocate(0,0,0);
$im->transparent($white);
$im->interlaced('true');
my @pos = (0,0);
my @dir = (0,5);
my @steps = split //, fword 23;
my $i = 1;
for( @steps ) {
my @next = ( $pos[0]+$dir[0], $pos[1]+$dir[1] );
$im->line( @pos, @next, $black );
@dir = ( $dir[1], -$dir[0] ) if 0==$_ && 1==$i%2; # odd
@dir = ( -$dir[1], $dir[0] ) if 0==$_ && 0==$i%2; # even
$i++;
@pos = @next;
}
open my $out, ">", "fword.png" or die "Cannot open output file.\n";
binmode $out;
print $out $im->png;
close $out;
|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lingo | Lingo | on getCommonPath (pathes, sep)
_player.itemDelimiter = sep
-- find length of shortest path (in terms of items)
commonCnt = the maxInteger
repeat with p in pathes
if p.item.count<commonCnt then commonCnt=p.item.count
end repeat
pathCnt = pathes.count
repeat with i = 1 to commonCnt
repeat with j = 2 to pathCnt
if pathes[j].item[i]<>pathes[j-1].item[i] then
return pathes[1].item[1..i-1]
end if
end repeat
end repeat
return pathes[1].item[1..commonCnt]
end |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MapBasic | MapBasic | Include "MapBasic.def"
DECLARE SUB Main
DECLARE FUNCTION commonPath(paths() AS STRING, BYVAL pathSep AS STRING) AS STRING
FUNCTION commonPath(paths() AS STRING, BYVAL pathSep AS STRING) AS STRING
DIM tmpint1 AS INTEGER, tmpint2 AS INTEGER, tmpstr1 AS STRING, tmpstr2 AS STRING
DIM L0 AS INTEGER, L1 AS INTEGER, lowerbound AS INTEGER, upperbound AS INTEGER
lowerbound = 1
upperbound = UBOUND(paths)
IF (lowerbound) = upperbound THEN 'Some quick error checking...
commonPath = paths(lowerbound)
ELSEIF lowerbound > upperbound THEN 'How in the...?
commonPath = ""
ELSE
tmpstr1 = paths(lowerbound)
FOR L0 = (lowerbound) TO upperbound 'Find common strings.
tmpstr2 = paths(L0)
tmpint1 = LEN(tmpstr1)
tmpint2 = LEN(tmpstr2)
IF tmpint1 > tmpint2
THEN tmpint1 = tmpint2
FOR L1 = 1 TO tmpint1
IF MID$(tmpstr1, L1, 1) <> MID$(tmpstr2, L1, 1) THEN
tmpint1 = L1 - 1
EXIT FOR
END IF
NEXT
END IF
tmpstr1 = LEFT$(tmpstr1, tmpint1)
NEXT
IF RIGHT$(tmpstr1, 1) <> pathSep THEN
FOR L1 = tmpint1 TO 2 STEP -1
IF (pathSep) = MID$(tmpstr1, L1, 1) THEN
tmpstr1 = LEFT$(tmpstr1, L1 - 1)
EXIT FOR
END IF
NEXT
IF LEN(tmpstr1) = tmpint1
THEN tmpstr1 = ""
ELSEIF tmpint1 > 1
THEN
tmpstr1 = LEFT$(tmpstr1, tmpint1 - 1)
END IF
END IF
commonPath = tmpstr1
END IF
END FUNCTION
SUB Main()
DIM x(3) AS STRING
Define Sep "/"
x(1) = "/home/user1/tmp/"
x(2) = "/home/user1/tmp/covert/operator"
x(3) = "/home/user1/tmp/coven/members"
PRINT "Common path is " + commonPath(x(), Sep)
END SUB |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #C.2B.2B | C++ | #include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
#include <iostream>
int main() {
std::vector<int> ary;
for (int i = 0; i < 10; i++)
ary.push_back(i);
std::vector<int> evens;
std::remove_copy_if(ary.begin(), ary.end(), back_inserter(evens),
std::bind2nd(std::modulus<int>(), 2)); // filter copy
std::copy(evens.begin(), evens.end(),
std::ostream_iterator<int>(std::cout, "\n"));
return 0;
} |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Oforth | Oforth | : limit 1+ dup . limit ;
0 limit |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #ooRexx | ooRexx | Using ooRexx for the program shown under Rexx:
rexx pgm 1>x1 2>x2
puts the numbers in x1 and the error messages in x2
...
2785
2786
8 *-* call self
....
8 *-* call self
3 *-* call self
Error 11 running C:\work.ooRexx\wc\main.4.1.1.release\Win32Rel\StreamClasses.orx line 366: Control stack full
Error 11.1: Insufficient control stack space; cannot continue execution
|
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #GAP | GAP | FizzBuzz := function()
local i;
for i in [1 .. 100] do
if RemInt(i, 15) = 0 then
Print("FizzBuzz\n");
elif RemInt(i, 3) = 0 then
Print("Fizz\n");
elif RemInt(i, 5) = 0 then
Print("Buzz\n");
else
Print(i, "\n");
fi;
od;
end; |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #K | K | _size "input.txt"
_size "/input.txt" |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Kotlin | Kotlin | // version 1.0.6
import java.io.File
fun main(args: Array<String>) {
val paths = arrayOf("input.txt", "c:\\input.txt")
for (path in paths)
println("Length of $path is ${File(path).length()} bytes")
} |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Lasso | Lasso | // local to current directory
local(f = file('input.txt'))
handle => { #f->close }
#f->size
// file at file system root
local(f = file('//input.txt'))
handle => { #f->close }
#f->size
|
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #E | E | <file:output.txt>.setText(<file:input.txt>.getText()) |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Eiffel | Eiffel | class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
create input_file.make_open_read ("input.txt")
create output_file.make_open_write ("output.txt")
from
input_file.read_character
until
input_file.exhausted
loop
output_file.put (input_file.last_character)
input_file.read_character
end
input_file.close
output_file.close
end
feature -- Access
input_file: PLAIN_TEXT_FILE
output_file: PLAIN_TEXT_FILE
end |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #EchoLisp | EchoLisp |
(lib 'struct)
(struct FW ( count0 count1 length string)) ;; a fibonacci word
(define (F-word n) ;; generator
(define a (F-word (1- n)))
(define b (F-word (- n 2)))
(FW
(+ (FW-count0 a) (FW-count0 b))
(+ (FW-count1 a) (FW-count1 b))
(+ (FW-length a) (FW-length b))
(if (> n 9) "..." (string-append (FW-string a) (FW-string b)))))
(remember 'F-word (vector 0 (FW 0 1 1 "1") (FW 1 0 1 "0")))
(define (entropy fw)
(define p (// (FW-count0 fw) (FW-length fw)))
(cond
((= p 0) 0)
((= p 1) 0)
(else (- 0 (* p (log2 p)) (* (- 1 p) (log2 (- 1 p)))))))
(define (task (n 38) (fw))
(for ((i (in-range 1 n)))
(set! fw (F-word i))
(printf "%3d %10d %24d %a"
i (FW-length fw) (entropy fw) (FW-string fw))))
|
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #C.2B.2B | C++ | #include <iostream>
#include <fstream>
int main( int argc, char **argv ){
if( argc <= 1 ){
std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl;
return -1;
}
std::ifstream input(argv[1]);
if(!input.good()){
std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl;
return -1;
}
std::string line, name, content;
while( std::getline( input, line ).good() ){
if( line.empty() || line[0] == '>' ){ // Identifier marker
if( !name.empty() ){ // Print out what we read from the last entry
std::cout << name << " : " << content << std::endl;
name.clear();
}
if( !line.empty() ){
name = line.substr(1);
}
content.clear();
} else if( !name.empty() ){
if( line.find(' ') != std::string::npos ){ // Invalid sequence--no spaces allowed
name.clear();
content.clear();
} else {
content += line;
}
}
}
if( !name.empty() ){ // Print out what we read from the last entry
std::cout << name << " : " << content << std::endl;
}
return 0;
} |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #C.23 | C# | using System;
namespace FaulhabersTriangle {
internal class Frac {
private long num;
private long denom;
public static readonly Frac ZERO = new Frac(0, 1);
public static readonly Frac ONE = new Frac(1, 1);
public Frac(long n, long d) {
if (d == 0) {
throw new ArgumentException("d must not be zero");
}
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
}
else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.Abs(Gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
private static long Gcd(long a, long b) {
if (b == 0) {
return a;
}
return Gcd(b, a % b);
}
public static Frac operator -(Frac self) {
return new Frac(-self.num, self.denom);
}
public static Frac operator +(Frac lhs, Frac rhs) {
return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);
}
public static Frac operator -(Frac lhs, Frac rhs) {
return lhs + -rhs;
}
public static Frac operator *(Frac lhs, Frac rhs) {
return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
public static bool operator <(Frac lhs, Frac rhs) {
double x = (double)lhs.num / lhs.denom;
double y = (double)rhs.num / rhs.denom;
return x < y;
}
public static bool operator >(Frac lhs, Frac rhs) {
double x = (double)lhs.num / lhs.denom;
double y = (double)rhs.num / rhs.denom;
return x > y;
}
public static bool operator ==(Frac lhs, Frac rhs) {
return lhs.num == rhs.num && lhs.denom == rhs.denom;
}
public static bool operator !=(Frac lhs, Frac rhs) {
return lhs.num != rhs.num || lhs.denom != rhs.denom;
}
public override string ToString() {
if (denom == 1) {
return num.ToString();
}
return string.Format("{0}/{1}", num, denom);
}
public override bool Equals(object obj) {
var frac = obj as Frac;
return frac != null &&
num == frac.num &&
denom == frac.denom;
}
public override int GetHashCode() {
var hashCode = 1317992671;
hashCode = hashCode * -1521134295 + num.GetHashCode();
hashCode = hashCode * -1521134295 + denom.GetHashCode();
return hashCode;
}
}
class Program {
static Frac Bernoulli(int n) {
if (n < 0) {
throw new ArgumentException("n may not be negative or zero");
}
Frac[] a = new Frac[n + 1];
for (int m = 0; m <= n; m++) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);
}
}
// returns 'first' Bernoulli number
if (n != 1) return a[0];
return -a[0];
}
static int Binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw new ArgumentException();
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num = num * i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom = denom * i;
}
return num / denom;
}
static Frac[] FaulhaberTriangle(int p) {
Frac[] coeffs = new Frac[p + 1];
for (int i = 0; i < p + 1; i++) {
coeffs[i] = Frac.ZERO;
}
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; j++) {
sign *= -1;
coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);
}
return coeffs;
}
static void Main(string[] args) {
for (int i = 0; i < 10; i++) {
Frac[] coeffs = FaulhaberTriangle(i);
foreach (Frac coeff in coeffs) {
Console.Write("{0,5} ", coeff);
}
Console.WriteLine();
}
}
}
} |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #D | D | import std.algorithm : fold;
import std.exception : enforce;
import std.format : formattedWrite;
import std.numeric : cmp, gcd;
import std.range : iota;
import std.stdio;
import std.traits;
auto abs(T)(T val)
if (isNumeric!T) {
if (val < 0) {
return -val;
}
return val;
}
struct Frac {
long num;
long denom;
enum ZERO = Frac(0, 1);
enum ONE = Frac(1, 1);
this(long n, long d) in {
enforce(d != 0, "Parameter d may not be zero.");
} body {
auto nn = n;
auto dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
auto g = gcd(abs(nn), abs(dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
auto opBinary(string op)(Frac rhs) const {
static if (op == "+" || op == "-") {
return mixin("Frac(num*rhs.denom"~op~"denom*rhs.num, rhs.denom*denom)");
} else if (op == "*") {
return Frac(num*rhs.num, denom*rhs.denom);
}
}
auto opUnary(string op : "-")() const {
return Frac(-num, denom);
}
int opCmp(Frac rhs) const {
return cmp(cast(real) this, cast(real) rhs);
}
bool opEquals(Frac rhs) const {
return num == rhs.num && denom == rhs.denom;
}
void toString(scope void delegate(const(char)[]) sink) const {
if (denom == 1) {
formattedWrite(sink, "%d", num);
} else {
formattedWrite(sink, "%d/%s", num, denom);
}
}
T opCast(T)() const if (isFloatingPoint!T) {
return cast(T) num / denom;
}
}
auto abs(Frac f) {
if (f.num >= 0) {
return f;
}
return -f;
}
auto bernoulli(int n) in {
enforce(n >= 0, "Parameter n must not be negative.");
} body {
Frac[] a;
a.length = n+1;
a[0] = Frac.ZERO;
foreach (m; 0..n+1) {
a[m] = Frac(1, m+1);
foreach_reverse (j; 1..m+1) {
a[j-1] = (a[j-1] - a[j]) * Frac(j, 1);
}
}
if (n != 1) {
return a[0];
}
return -a[0];
}
auto binomial(int n, int k) in {
enforce(n>=0 && k>=0 && n>=k);
} body {
if (n==0 || k==0) return 1;
auto num = iota(k+1, n+1).fold!"a*b"(1);
auto den = iota(2, n-k+1).fold!"a*b"(1);
return num / den;
}
auto faulhaber(int p) {
write(p, " : ");
auto q = Frac(1, p+1);
auto sign = -1;
foreach (j; 0..p+1) {
sign *= -1;
auto coeff = q * Frac(sign, 1) * Frac(binomial(p+1, j), 1) * bernoulli(j);
if (coeff == Frac.ZERO) continue;
if (j == 0) {
if (coeff == -Frac.ONE) {
write("-");
} else if (coeff != Frac.ONE) {
write(coeff);
}
} else {
if (coeff == Frac.ONE) {
write(" + ");
} else if (coeff == -Frac.ONE) {
write(" - ");
} else if (coeff > Frac.ZERO) {
write(" + ", coeff);
} else {
write(" - ", -coeff);
}
}
auto pwr = p + 1 - j;
if (pwr > 1) {
write("n^", pwr);
} else {
write("n");
}
}
writeln;
}
void main() {
foreach (i; 0..10) {
faulhaber(i);
}
} |
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #Nim | Nim | import math
import bignum
import strformat
import strutils
import tables
import times
const Composite = {9: "5529", 10: "6078", 11: "1037", 12: "5488", 13: "2884"}.toTable
const Subscripts = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"]
let One = newInt(1)
#---------------------------------------------------------------------------------------------------
func fermat(n: int): Int {.inline.} = 2^(culong(2^n)) + 1
#---------------------------------------------------------------------------------------------------
template isProbablyPrime(n: Int): bool = n.probablyPrime(25) != 0
#---------------------------------------------------------------------------------------------------
func pollardRhoG(x, n: Int): Int {.inline.} = (x * x + 1) mod n
#---------------------------------------------------------------------------------------------------
proc pollardRhoFast(n: Int): Int =
let start = getTime()
var
x = newInt(2)
y = newInt(2)
count = 0
z = One
while true:
x = pollardRhoG(x, n)
y = pollardRhoG(pollardRhoG(y, n), n)
result = abs(x - y)
z = z * result mod n
inc count
if count == 100:
result = gcd(z, n)
if result != One: break
z = One
count = 0
let duration = (getTime() - start).inMilliseconds
echo fmt" Pollard rho try factor {n} elapsed time = {duration} ms (factor = {result})."
if result == n:
result = newInt(0)
#---------------------------------------------------------------------------------------------------
proc factors(fermatIndex: int; n: Int): seq[Int] =
var n = n
var factor: Int
while true:
if n.isProbablyPrime():
result.add(n)
break
if fermatIndex in Composite:
let stop = Composite[fermatIndex]
let s = $n
if s.startsWith(stop):
result.add(newInt(-s.len))
break
factor = pollardRhoFast(n)
if factor.isZero():
result.add(n)
break
result.add(factor)
n = n div factor
#---------------------------------------------------------------------------------------------------
func `$`(factors: seq[Int]): string =
if factors.len == 1:
result = fmt"{factors[0]} (PRIME)"
else:
result = $factors[0]
let start = result.high
for factor in factors[1..^1]:
result.addSep(" * ", start)
result.add(if factor < 0: fmt"(C{-factor})" else: $factor)
#---------------------------------------------------------------------------------------------------
func subscript(n: Natural): string =
var n = n
while true:
result.insert(Subscripts[n mod 10], 0)
n = n div 10
if n == 0: break
#———————————————————————————————————————————————————————————————————————————————————————————————————
echo "First 10 Fermat numbers:"
for i in 0..9:
echo fmt"F{subscript(i)} = {fermat(i)}"
echo ""
echo "First 12 Fermat numbers factored:"
for i in 0..12:
echo fmt"F{subscript(i)} = {factors(i, fermat(i))}" |
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use bigint try=>"GMP";
use ntheory qw<factor>;
my @Fermats = map { 2**(2**$_) + 1 } 0..9;
my $sub = 0;
say 'First 10 Fermat numbers:';
printf "F%s = %s\n", $sub++, $_ for @Fermats;
$sub = 0;
say "\nFactors of first few Fermat numbers:";
for my $f (map { [factor($_)] } @Fermats[0..8]) {
printf "Factors of F%s: %s\n", $sub++, @$f == 1 ? 'prime' : join ' ', @$f
} |
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences | Fibonacci n-step number sequences | These number series are an expansion of the ordinary Fibonacci sequence where:
For
n
=
2
{\displaystyle n=2}
we have the Fibonacci sequence; with initial values
[
1
,
1
]
{\displaystyle [1,1]}
and
F
k
2
=
F
k
−
1
2
+
F
k
−
2
2
{\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #AutoHotkey | AutoHotkey | for i, seq in ["nacci", "lucas"]
Loop, 9 {
Out .= seq "(" A_Index + 1 "): "
for key, val in NStepSequence(i, 1, A_Index + 1, 15)
Out .= val (A_Index = 15 ? "`n" : "`, ")
}
MsgBox, % Out
NStepSequence(v1, v2, n, k) {
a := [v1, v2]
Loop, % k - 2 {
a[j := A_Index + 2] := 0
Loop, % j < n + 2 ? j - 1 : n
a[j] += a[j - A_Index]
}
return, a
} |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Lua | Lua | function leftShift(n,p)
local r = n
while p>0 do
r = r * 2
p = p - 1
end
return r
end
-- main
local MAX_IT = 13
local MAX_IT_J = 10
local a1 = 1.0
local a2 = 0.0
local d1 = 3.2
print(" i d")
for i=2,MAX_IT do
local a = a1 + (a1 - a2) / d1
for j=1,MAX_IT_J do
local x = 0.0
local y = 0.0
for k=1,leftShift(1,i) do
y = 1.0 - 2.0 * y * x
x = a - x * x
end
a = a - x / y
end
d = (a1 - a2) / (a - a1)
print(string.format("%2d %.8f", i, d))
d1 = d
a2 = a1
a1 = a
end |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | maxit = 13;
maxitj = 10;
a1 = 1.0;
a2 = 0.0;
d1 = 3.2;
a = 0.0;
Table[
a = a1 + (a1 - a2)/d1;
Do[
x = 0.0;
y = 0.0;
Do[
y = 1.0 - 2.0 y x;
x = a - x x;
,
{k, 1, 2^i}
];
a = a - x/y
,
{j, maxitj}
];
d = (a1 - a2)/(a - a1);
d1 = d;
a2 = a1;
a1 = a;
{i, d}
,
{i, 2, maxit}
] // Grid |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Python | Python |
def isExt(fileName, extensions):
return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
|
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Racket | Racket |
#lang racket
(define extensions '(".zip"
".rar"
".7z"
".gz"
".archive"
".a##"
".tar.bz2"))
(define filenames '("MyData.a##"
"MyData.tar.Gz"
"MyData.gzip"
"MyData.7z.backup"
"MyData..."
"MyData"
"MyData_v1.0.tar.bz2"
"MyData_v1.0.bz2"))
(define (string-right s n)
(if (< (string-length s) n)
s
(substring s (- (string-length s) n))))
(define (file-extension-in-list? f lst)
(let ([lcase (string-downcase f)])
(ormap (lambda (x) (equal? (string-right lcase (string-length x)) x)) extensions)))
(for ((f (in-list filenames)))
(printf "~a ~a~%" (~a #:width 20 f) (file-extension-in-list? f extensions)))
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Perl | Perl | my $mtime = (stat($file))[9]; # seconds since the epoch
# you should use the more legible version below:
use File::stat qw(stat);
my $mtime = stat($file)->mtime; # seconds since the epoch
utime(stat($file)->atime, time, $file);
# keep atime unchanged
# set mtime to current time |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Phix | Phix | without js -- file i/o
-- (however get as per the JavaScript entry above might be doable if needed)
constant filename = "test.txt"
?get_file_date(filename)
include timedate.e
?format_timedate(get_file_date(filename))
bool res = set_file_date(filename)
?format_timedate(get_file_date(filename))
|
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #Phix | Phix | --
-- demo\rosetta\FibonacciFractal.exw
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
procedure drawFibonacci(integer x, y, dx, dy, n)
string prev = "1", word = "0"
for i=3 to n do {prev,word} = {word,word&prev} end for
for i=1 to length(word) do
cdCanvasLine(cddbuffer, x, y, x+dx, y+dy)
x += dx y += dy
if word[i]=='0' then
{dx,dy} = iff(remainder(i,2)?{dy,-dx}:{-dy,dx})
end if
end for
end procedure
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
cdCanvasActivate(cddbuffer)
cdCanvasClear(cddbuffer)
drawFibonacci(20, 20, 0, 1, 23)
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_GREEN)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas("RASTERSIZE=620x450")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas, `RESIZE=NO, TITLE="Fibonacci Fractal"`)
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Maple | Maple |
dirpath:=proc(a,b,c)
local dirtemp,dirnew,x;
use StringTools in
dirtemp:=LongestCommonSubString(c, LongestCommonSubString(a,b));
x:=FirstFromRight("/",dirtemp);
dirnew:=dirtemp[1..x];
return dirnew;
end use;
end proc;
|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FindCommonDirectory[x_] := If[StringTake[#, -1] != "/", StringTake[#, Max[StringPosition[#, "/"]]], #] &
[Fold[LongestCommonSubsequence, First[x] , Rest[x]]]
FindCommonDirectory[{"/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}]
->"/home/user1/tmp/" |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Clean | Clean | module SelectFromArray
import StdEnv |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Oz | Oz | declare
proc {Recurse Number}
{Show Number}
{Recurse Number+1}
end
in
{Recurse 1} |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #PARI.2FGP | PARI/GP | dive(n) = dive(n+1)
dive(0) |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Genyris | Genyris |
@prefix u "http://www.genyris.org/lang/utilities#"
def fizzbuzz (n)
map-left ^((3 = 'fizz') (5 = 'buzz'))
lambda (d)
cond
(equal? 0 (% n d!left))
d!right
else
''
for n in (range 1 100)
define fb (''(.join (fizzbuzz n)))
u:format "%a\n"
cond
(equal? fb '')
n
else
fb
|
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Liberty_BASIC | Liberty BASIC | 'input.txt in current directory
OPEN DefaultDir$ + "/input.txt" FOR input AS #m
PRINT "File size: "; lof(#m)
CLOSE #m
'input.txt in root
OPEN "c:/input.txt" FOR input AS #m
PRINT "File size: "; lof(#m)
CLOSE #m |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Lingo | Lingo | ----------------------------------------
-- Returns file size
-- @param {string} filename
-- @return {integer}
----------------------------------------
on getFileSize (filename)
fp = xtra("fileIO").new()
fp.openFile(filename, 1)
if fp.status() then return 0
len = fp.getLength()
fp.closeFile()
return len
end |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #LiveCode | LiveCode | // root folder
set the defaultfolder to "/"
repeat for each line fline in (the detailed files)
if item 1 of fline is "input.txt" then
put item 2 of fline --bytes
exit repeat
end if
end repeat
// current working dir of stack
put the effective filename of this stack into tPath
set the itemDelimiter to slash
delete last item of tPath
set the defaultfolder to tPath
repeat for each line fline in (the detailed files)
if item 1 of fline is "input.txt" then
put item 2 of fline
exit repeat
end if
end repeat |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Elena | Elena | import system'io;
public program()
{
var text := File.assign("input.txt").readContent();
File.assign("output.txt").saveContent(text);
} |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Elixir | Elixir | defmodule FileReadWrite do
def copy(path,new_path) do
case File.read(path) do
# In case of success, write to the new file
{:ok, body} ->
# Can replace with :write! to generate an error upon failure
File.write(new_path,body)
# If not successful, raise an error
{:error,reason} ->
# Using Erlang's format_error to generate error string
:file.format_error(reason)
end
end
end
FileReadWrite.copy("input.txt","output.txt") |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #Elixir | Elixir | defmodule RC do
def entropy(str) do
leng = String.length(str)
String.to_charlist(str)
|> Enum.reduce(Map.new, fn c,acc -> Map.update(acc, c, 1, &(&1+1)) end)
|> Map.values
|> Enum.reduce(0, fn count, entropy ->
freq = count / leng
entropy - freq * :math.log2(freq) # log2 was added with Erlang/OTP 18
end)
end
end
fibonacci_word = Stream.unfold({"1","0"}, fn{a,b} -> {a, {b, b<>a}} end)
IO.puts " N Length Entropy Fibword"
fibonacci_word |> Enum.take(37) |> Enum.with_index
|> Enum.each(fn {word,i} ->
len = String.length(word)
str = if len < 60, do: word, else: "<too long>"
:io.format "~3w ~8w ~17.15f ~s~n", [i+1, len, RC.entropy(word), str]
end) |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #F.23 | F# | // include the code from /wiki/Entropy#F.23 for the entropy function
let fiboword =
Seq.unfold
(fun (state : string * string) ->
Some (fst state, (snd state, (snd state) + (fst state)))) ("1", "0")
printfn "%3s %10s %10s %s" "#" "Length" "Entropy" "Word (if length < 40)"
Seq.iteri (fun i (s : string) ->
printfn "%3i %10i %10.7g %s" (i+1) s.Length (entropy s) (if s.Length < 40 then s else ""))
(Seq.take 37 fiboword) |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Clojure | Clojure | (defn fasta [pathname]
(with-open [r (clojure.java.io/reader pathname)]
(doseq [line (line-seq r)]
(if (= (first line) \>)
(print (format "%n%s: " (subs line 1)))
(print line))))) |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Common_Lisp | Common Lisp | ;; * The input file as a parameter
(defparameter *input* #p"fasta.txt"
"The input file name.")
;; * Reading the data
(with-open-file (data *input*)
(loop
:for line = (read-line data nil nil)
:while line
;; Check if we have a comment using a simple test instead of a RegEx
:if (char= #\> (char line 0))
:do (format t "~&~a: " (subseq line 1))
:else
:do (format t "~a" line))) |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #11l | 11l | F farey(n)
V a = 0
V b = 1
V c = 1
V d = n
V far = ‘0/1 ’
V farn = 1
L c <= n
V k = (n + b) I/ d
(a, b, c, d) = (c, d, k * c - a, k * d - b)
far ‘’= a‘/’b‘ ’
farn++
R (far, farn)
L(i) 1..11
print(i‘: ’farey(i)[0])
L(i) (100..1000).step(100)
print(i‘: ’farey(i)[1]‘ items’) |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #11l | 11l | F _basechange_int(=num, b)
‘
Return list of ints representing positive num in base b
’
I num == 0
R [0]
[Int] result
L num != 0
(num, V d) = divmod(num, b)
result.append(d)
R reversed(result)
F fairshare(b, n)
[Int] r
L(i) 0..
r [+]= sum(_basechange_int(i, b)) % b
I r.len == n
L.break
R r
L(b) (2, 3, 5, 11)
print(‘#2’.format(b)‘: ’String(fairshare(b, 25))[1 .< (len)-1]) |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #C.2B.2B | C++ | #include <exception>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
class Frac {
public:
Frac() : num(0), denom(1) {}
Frac(int n, int d) {
if (d == 0) {
throw std::runtime_error("d must not be zero");
}
int sign_of_d = d < 0 ? -1 : 1;
int g = std::gcd(n, d);
num = sign_of_d * n / g;
denom = sign_of_d * d / g;
}
Frac operator-() const {
return Frac(-num, denom);
}
Frac operator+(const Frac& rhs) const {
return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);
}
Frac operator-(const Frac& rhs) const {
return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);
}
Frac operator*(const Frac& rhs) const {
return Frac(num*rhs.num, denom*rhs.denom);
}
Frac operator*(int rhs) const {
return Frac(num * rhs, denom);
}
friend std::ostream& operator<<(std::ostream&, const Frac&);
private:
int num;
int denom;
};
std::ostream & operator<<(std::ostream & os, const Frac &f) {
if (f.num == 0 || f.denom == 1) {
return os << f.num;
}
std::stringstream ss;
ss << f.num << "/" << f.denom;
return os << ss.str();
}
Frac bernoulli(int n) {
if (n < 0) {
throw std::runtime_error("n may not be negative or zero");
}
std::vector<Frac> a;
for (int m = 0; m <= n; m++) {
a.push_back(Frac(1, m + 1));
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * j;
}
}
// returns 'first' Bernoulli number
if (n != 1) return a[0];
return -a[0];
}
int binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw std::runtime_error("parameters are invalid");
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num *= i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom *= i;
}
return num / denom;
}
std::vector<Frac> faulhaberTraingle(int p) {
std::vector<Frac> coeffs(p + 1);
Frac q{ 1, p + 1 };
int sign = -1;
for (int j = 0; j <= p; j++) {
sign *= -1;
coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);
}
return coeffs;
}
int main() {
for (int i = 0; i < 10; i++) {
std::vector<Frac> coeffs = faulhaberTraingle(i);
for (auto frac : coeffs) {
std::cout << std::right << std::setw(5) << frac << " ";
}
std::cout << std::endl;
}
return 0;
} |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #EchoLisp | EchoLisp |
(lib 'math) ;; for bernoulli numbers
(string-delimiter "")
;; returns list of polynomial coefficients
(define (Faulhaber p)
(cons 0
(for/list ([k (in-range p -1 -1)])
(* (Cnp (1+ p) k) (bernoulli k)))))
;; prints formal polynomial
(define (task (pmax 10))
(for ((p pmax))
(writeln p '→ (/ 1 (1+ p)) '* (poly->string 'n (Faulhaber p)))))
;; extra credit - compute sums
(define (Faulcomp n p)
(printf "Σ(1..%d) n^%d = %d" n p (/ (poly n (Faulhaber p)) (1+ p) )))
|
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #Phix | Phix | with javascript_semantics
-- demo\rosetta\Fermat.exw
include mpfr.e
procedure fermat(mpz res, integer n)
integer pn = power(2,n)
mpz_ui_pow_ui(res,2,pn)
mpz_add_si(res,res,1)
end procedure
mpz fn = mpz_init()
constant lim = iff(platform()=JS?18:29), -- (see note)
print_lim = iff(platform()=JS?16:20)
for i=0 to lim do
fermat(fn,i)
if i<=print_lim then
printf(1,"F%d = %s\n",{i,shorten(mpz_get_str(fn))})
else -- (since printing it takes too long...)
printf(1,"F%d has %,d digits\n",{i,mpz_sizeinbase(fn,10)})
end if
end for
printf(1,"\n")
constant flimit = iff(platform()=JS?11:13)
for i=0 to flimit do
atom t = time()
fermat(fn,i)
sequence f = mpz_prime_factors(fn, 200000)
t = time()-t
string fs = "",
ts = elapsed(t)
if length(f[$])=1 then -- (as per docs)
mpz_set_str(fn,f[$][1])
if not mpz_prime(fn) then
if length(f)=1 then
fs = " (not prime)"
else
fs = " (last factor is not prime)"
end if
end if
f = deep_copy(f)
f[$][1] = shorten(f[$][1])
elsif length(f)=1
and mpz_prime(fn) then
fs = " (prime)"
end if
fs = mpz_factorstring(f)&fs
printf(1,"Factors of F%d: %s [%s]\n",{i,fs,ts})
end for
|
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences | Fibonacci n-step number sequences | These number series are an expansion of the ordinary Fibonacci sequence where:
For
n
=
2
{\displaystyle n=2}
we have the Fibonacci sequence; with initial values
[
1
,
1
]
{\displaystyle [1,1]}
and
F
k
2
=
F
k
−
1
2
+
F
k
−
2
2
{\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #AWK | AWK |
function sequence(values, howmany) {
init_length = length(values)
for (i=init_length + 1; i<=howmany; i++) {
values[i] = 0
for (j=1; j<=init_length; j++) {
values[i] += values[i-j]
}
}
result = ""
for (i in values) {
result = result values[i] " "
}
delete values
return result
}
# print some sequences
END {
a[1] = 1; a[2] = 1
print("fibonacci :\t",sequence(a, 10))
a[1] = 1; a[2] = 1; a[3] = 2
print("tribonacci :\t",sequence(a, 10))
a[1] = 1 ; a[2] = 1 ; a[3] = 2 ; a[4] = 4
print("tetrabonacci :\t",sequence(a, 10))
a[1] = 2; a[2] = 1
print("lucas :\t\t",sequence(a, 10))
}
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Modula-2 | Modula-2 | MODULE Feigenbaum;
FROM FormatString IMPORT FormatString;
FROM LongStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
VAR
buf : ARRAY[0..63] OF CHAR;
i,j,k,max_it,max_it_j : INTEGER;
a,x,y,d,a1,a2,d1 : LONGREAL;
BEGIN
max_it := 13;
max_it_j := 10;
a1 := 1.0;
a2 := 0.0;
d1 := 3.2;
WriteString(" i d");
WriteLn;
FOR i:=2 TO max_it DO
a := a1 + (a1 - a2) / d1;
FOR j:=1 TO max_it_j DO
x := 0.0;
y := 0.0;
FOR k:=1 TO INT(1 SHL i) DO
y := 1.0 - 2.0 * y * x;
x := a - x * x
END;
a := a - x / y
END;
d := (a1 - a2) / (a - a1);
FormatString("%2i ", buf, i);
WriteString(buf);
RealToStr(d, buf);
WriteString(buf);
WriteLn;
d1 := d;
a2 := a1;
a1 := a
END;
ReadChar
END Feigenbaum. |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Nim | Nim | import strformat
iterator feigenbaum(): tuple[n: int; δ: float] =
## Yield successive approximations of Feigenbaum constant.
const
MaxI = 13
MaxJ = 10
var
a1 = 1.0
a2 = 0.0
δ = 3.2
for i in 2..MaxI:
var a = a1 + (a1 - a2) / δ
for j in 1..MaxJ:
var x, y = 0.0
for _ in 1..(1 shl i):
y = 1 - 2 * y * x
x = a - x * x
a -= x / y
δ = (a1 - a2) / (a - a1)
a2 = a1
a1 = a
yield (i, δ)
echo " i δ"
for n, δ in feigenbaum():
echo fmt"{n:2d} {δ:.8f}" |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Raku | Raku | sub check-extension ($filename, *@extensions) {
so $filename ~~ /:i '.' @extensions $/
}
# Testing:
my @extensions = <zip rar 7z gz archive A## tar.bz2>;
my @files= <
MyData.a## MyData.tar.Gz MyData.gzip MyData.7z.backup MyData... MyData
MyData_v1.0.tar.bz2 MyData_v1.0.bz2
>;
say "{$_.fmt: '%-19s'} - {check-extension $_, @extensions}" for @files; |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #REXX | REXX | /*REXX pgm displays if a filename has a known extension (as per a list of extensions). */
$= 'zip rar 7z gz archive A## tar.bz2'; upper $ /*a list of "allowable" file extensions*/
parse arg fn /*obtain optional argument from the CL.*/
@.= /*define the default for the @. array.*/
if fn\='' then @.1 = strip(fn) /*A filename specified? Then use it. */
else do; @.1 = "MyData.a##" /*No " " Else use list*/
@.2 = "MyData.tar.Gz"
@.3 = "MyData.gzip"
@.4 = "MyData.7z.backup"
@.5 = "MyData..."
@.6 = "MyData"
@.7 = "MyData_v1.0.tar.bz2"
@.8 = "MyData_v1.0.bz2"
end
#= words($)
do j=1 while @.j\==''; @@= @.j; upper @@ /*traipse through @ file extension list*/
do k=1 for # until right(@@, L)==x /*Search $ list, is extension in list? */
x= . || word($, k); L=length(x) /*construct the extension of the file. */
end /*k*/ /* [↓] display file, and a nay or yea.*/
say right(@.j, 40) ' ' right( word( "false true", 1 + (k<=#) ), 5)
end /*j*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #PHP | PHP | <?php
$filename = 'input.txt';
$mtime = filemtime($filename); // seconds since the epoch
touch($filename,
time(), // set mtime to current time
fileatime($filename)); // keep atime unchanged
?> |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #PicoLisp | PicoLisp | (let File "test.file"
(and
(info File)
(prinl (stamp (cadr @) (cddr @))) ) # Print date and time in UTC
(call 'touch File) ) # Set modification time to "now" |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Pop11 | Pop11 | ;;; Print modification time (seconds since Epoch)
sysmodtime('file') => |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.