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/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.)
| #J | J | require 'plot'
plot }:+/\ 0,*/\(^~ 0j_1 0j1 $~ #)'0'=_1{::F_Words 20 |
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.)
| #Java | Java | import java.awt.*;
import javax.swing.*;
public class FibonacciWordFractal extends JPanel {
String wordFractal;
FibonacciWordFractal(int n) {
setPreferredSize(new Dimension(450, 620));
setBackground(Color.white);
wordFractal = wordFractal(n);
}
public String wordFractal(int n) {
if (n < 2)
return n == 1 ? "1" : "";
// we should really reserve fib n space here
StringBuilder f1 = new StringBuilder("1");
StringBuilder f2 = new StringBuilder("0");
for (n = n - 2; n > 0; n--) {
String tmp = f2.toString();
f2.append(f1);
f1.setLength(0);
f1.append(tmp);
}
return f2.toString();
}
void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) {
for (int n = 0; n < wordFractal.length(); n++) {
g.drawLine(x, y, x + dx, y + dy);
x += dx;
y += dy;
if (wordFractal.charAt(n) == '0') {
int tx = dx;
dx = (n % 2 == 0) ? -dy : dy;
dy = (n % 2 == 0) ? tx : -tx;
}
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawWordFractal(g, 20, 20, 1, 0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Fibonacci Word Fractal");
f.setResizable(false);
f.add(new FibonacciWordFractal(23), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write(lcdsubstr(["/home/user1/tmp/coverage/test","/home/user1/tmp/covert/operator","/home/user1/tmp/coven/members"]))
end
procedure lcdsubstr(sL,d) #: return the longest common sub-string of strings in the list sL delimited by d
local ss
/d := "/"
reverse(sL[1]) ? {
if tab(find(d)+*d) || allmatch(ss := reverse(tab(0)),sL) then
return ss
}
end
procedure allmatch(s,L) #: retrun s if it matches all strings in L
local x
every x := !L do
if not match(s,x) then fail
return s
end |
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.
| #Bracmat | Bracmat | ( :?odds
& ( 1 2 3 4 5 6 7 8 9 10 16 25 36 49 64 81 100:? (=.!sjt*1/2:/&!odds !sjt:?odds)$() ()
| !odds
)
)
|
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.
| #M2000_Interpreter | M2000 Interpreter |
Module checkit {
Global z
Function a {
z++
=a()
}
try {
m=a()
}
Print z
z<=0
Function a {
z++
call a()
}
try {
call a()
}
Print z
z<=0
Module m {
z++
Call m
}
try {
call m
}
Print z
z<=0
\\ without Call a module can't call itself
\\ but can call something global, and that global can call back
Module Global m1 {
z++
m2
}
Module Global m2 {
z++
m1
}
try {
call m1
}
Print z
}
Checkit
|
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | $RecursionLimit=10^6 |
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
| #Wren | Wren | import "/fmt" for Fmt
var isPalindrome2 = Fn.new { |n|
var x = 0
if (n % 2 == 0) return n == 0
while (x < n) {
x = x*2 + (n%2)
n = (n/2).floor
}
return n == x || n == (x/2).floor
}
var reverse3 = Fn.new { |n|
var x = 0
while (n != 0) {
x = x*3 + (n%3)
n = (n/3).floor
}
return x
}
var start
var show = Fn.new { |n|
Fmt.print("Decimal : $d", n)
Fmt.print("Binary : $b", n)
Fmt.print("Ternary : $t", n)
Fmt.print("Time : $0.3f ms\n", (System.clock - start)*1000)
}
var min = Fn.new { |a, b| (a < b) ? a : b }
var max = Fn.new { |a, b| (a > b) ? a : b }
start = System.clock
System.print("The first 6 numbers which are palindromic in both binary and ternary are :\n")
show.call(0)
var cnt = 1
var lo = 0
var hi = 1
var pow2 = 1
var pow3 = 1
while (true) {
var i = lo
while (i < hi) {
var n = (i*3+1)*pow3 + reverse3.call(i)
if (isPalindrome2.call(n)) {
show.call(n)
cnt = cnt + 1
if (cnt >= 6) return
}
i = i + 1
}
if (i == pow3) {
pow3 = pow3 * 3
} else {
pow2 = pow2 * 4
}
while (true) {
while (pow2 <= pow3) pow2 = pow2 * 4
var lo2 = (((pow2/pow3).floor - 1)/3).floor
var hi2 = (((pow2*2/pow3).floor-1)/3).floor + 1
var lo3 = (pow3/3).floor
var hi3 = pow3
if (lo2 >= hi3) {
pow3 = pow3 * 3
} else if (lo3 >= hi2) {
pow2 = pow2 * 4
} else {
lo = max.call(lo2, lo3)
hi = min.call(hi2, hi3)
break
}
}
} |
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
| #FreeBASIC | FreeBASIC | gen n word = cycle (take (n - 1) (repeat "") ++ [word])
pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz")
fizzbuzz = zipWith combine pattern [1..] where
combine word number = if null word
then show number
else word
show $ take 100 fizzbuzz |
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.
| #Fortran | Fortran |
use :: iso_fortran_env, only : FILE_STORAGE_SIZE
implicit none
character(len=*),parameter :: filename(*)=[character(len=256) :: 'input.txt', '/input.txt']
integer :: file_size, i
do i=1,size(filename)
INQUIRE(FILE=filename(i), SIZE=file_size) ! return -1 if cannot determine file size
write(*,*)'size of file '//trim(filename(i))//' is ',file_size * FILE_STORAGE_SIZE /8,' bytes'
enddo
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#include "file.bi"
Print FileLen("input.txt"), FileLen(Environ("SystemRoot") + "\input.txt")
Sleep |
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.
| #C.23 | C# | using System.IO;
using (var reader = new StreamReader("input.txt"))
using (var writer = new StreamWriter("output.txt"))
{
var text = reader.ReadToEnd();
writer.Write(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.
| #C.2B.2B | C++ | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream input ( "input.txt" );
ofstream output ("output.txt");
if (output.is_open()) {
if (input.is_open()){
while (getline (input,line)) {
output << line << endl;
}
input.close(); // Not necessary - will be closed when variable goes out of scope.
}
else {
cout << "input.txt cannot be opened!\n";
}
output.close(); // Not necessary - will be closed when variable goes out of scope.
}
else {
cout << "output.txt cannot be written to!\n";
}
return 0;
} |
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
| #C.23 | C# | using SYS = System;
using SCG = System.Collections.Generic;
//
// Basically a port of the C++ solution as posted
// 2017-11-12.
//
namespace FibonacciWord
{
class Program
{
static void Main( string[] args )
{
PrintHeading();
string firstString = "1";
int n = 1;
PrintLine( n, firstString );
string secondString = "0";
++n;
PrintLine( n, secondString );
while ( n < 37 )
{
string resultString = firstString + secondString;
firstString = secondString;
secondString = resultString;
++n;
PrintLine( n, resultString );
}
}
private static void PrintLine( int n, string result )
{
SYS.Console.Write( "{0,-5}", n );
SYS.Console.Write( "{0,12}", result.Length );
SYS.Console.WriteLine( " {0,-16}", GetEntropy( result ) );
}
private static double GetEntropy( string result )
{
SCG.Dictionary<char, int> frequencies = new SCG.Dictionary<char, int>();
foreach ( char c in result )
{
if ( frequencies.ContainsKey( c ) )
{
++frequencies[c];
}
else
{
frequencies[c] = 1;
}
}
int length = result.Length;
double entropy = 0;
foreach ( var keyValue in frequencies )
{
double freq = (double)keyValue.Value / length;
entropy += freq * SYS.Math.Log( freq, 2 );
}
return -entropy;
}
private static void PrintHeading()
{
SYS.Console.Write( "{0,-5}", "N" );
SYS.Console.Write( "{0,12}", "Length" );
SYS.Console.WriteLine( " {0,-16}", "Entropy" );
}
}
} |
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.
| #Action.21 | Action! | PROC ReadFastaFile(CHAR ARRAY fname)
CHAR ARRAY line(256)
CHAR ARRAY tmp(256)
BYTE newLine,dev=[1]
newLine=0
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
IF line(0)>0 AND line(1)='> THEN
IF newLine THEN
PutE()
FI
newLine=1
SCopyS(tmp,line,2,line(0))
Print(tmp) Print(": ")
ELSE
Print(line)
FI
OD
Close(dev)
RETURN
PROC Main()
CHAR ARRAY fname="H6:FASTA.TXT"
ReadFastaFile(fname)
RETURN |
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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Simple_FASTA is
Current: Character;
begin
Get(Current);
if Current /= '>' then
raise Constraint_Error with "'>' expected";
end if;
while not End_Of_File loop -- read name and string
Put(Get_Line & ": "); -- read name and write directly to output
Read_String:
loop
exit Read_String when End_Of_File; -- end of input
Get(Current);
if Current = '>' then -- next name
New_Line;
exit Read_String;
else
Put(Current & Get_Line);
-- read part of string and write directly to output
end if;
end loop Read_String;
end loop;
end Simple_FASTA; |
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
| #Factor | Factor | USING: formatting io kernel lists lists.lazy math math.functions
math.primes.factors sequences ;
: lfermats ( -- list )
0 lfrom [ [ 1 2 2 ] dip ^ ^ + ] lmap-lazy ;
CHAR: ₀ 10 lfermats ltake list>array [
"First 10 Fermat numbers:" print
[ dupd "F%c = %d\n" printf 1 + ] each drop nl
] [
"Factors of first few Fermat numbers:" print [
dupd factors dup length 1 = " (prime)" "" ?
"Factors of F%c: %[%d, %]%s\n" printf 1 +
] each drop
] 2bi |
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
| #Go | Go | package main
import (
"fmt"
"github.com/jbarham/primegen"
"math"
"math/big"
"math/rand"
"sort"
"time"
)
const (
maxCurves = 10000
maxRnd = 1 << 31
maxB1 = uint64(43 * 1e7)
maxB2 = uint64(2 * 1e10)
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
two = big.NewInt(2)
three = big.NewInt(3)
four = big.NewInt(4)
five = big.NewInt(5)
)
// Uses algorithm in Wikipedia article, including speed-up.
func pollardRho(n *big.Int) (*big.Int, error) {
// g(x) = (x^2 + 1) mod n
g := func(x, n *big.Int) *big.Int {
x2 := new(big.Int)
x2.Mul(x, x)
x2.Add(x2, one)
return x2.Mod(x2, n)
}
x, y, d := new(big.Int).Set(two), new(big.Int).Set(two), new(big.Int).Set(one)
t, z := new(big.Int), new(big.Int).Set(one)
count := 0
for {
x = g(x, n)
y = g(g(y, n), n)
t.Sub(x, y)
t.Abs(t)
t.Mod(t, n)
z.Mul(z, t)
count++
if count == 100 {
d.GCD(nil, nil, z, n)
if d.Cmp(one) != 0 {
break
}
z.Set(one)
count = 0
}
}
if d.Cmp(n) == 0 {
return nil, fmt.Errorf("Pollard's rho failure")
}
return d, nil
}
// Gets all primes under 'n' - uses a Sieve of Atkin under the hood.
func getPrimes(n uint64) []uint64 {
pg := primegen.New()
var primes []uint64
for {
prime := pg.Next()
if prime < n {
primes = append(primes, prime)
} else {
break
}
}
return primes
}
// Computes Stage 1 and Stage 2 bounds.
func computeBounds(n *big.Int) (uint64, uint64) {
le := len(n.String())
var b1, b2 uint64
switch {
case le <= 30:
b1, b2 = 2000, 147396
case le <= 40:
b1, b2 = 11000, 1873422
case le <= 50:
b1, b2 = 50000, 12746592
case le <= 60:
b1, b2 = 250000, 128992510
case le <= 70:
b1, b2 = 1000000, 1045563762
case le <= 80:
b1, b2 = 3000000, 5706890290
default:
b1, b2 = maxB1, maxB2
}
return b1, b2
}
// Adds two specified P and Q points (in Montgomery form). Assumes R = P - Q.
func pointAdd(px, pz, qx, qz, rx, rz, n *big.Int) (*big.Int, *big.Int) {
t := new(big.Int).Sub(px, pz)
u := new(big.Int).Add(qx, qz)
u.Mul(t, u)
t.Add(px, pz)
v := new(big.Int).Sub(qx, qz)
v.Mul(t, v)
upv := new(big.Int).Add(u, v)
umv := new(big.Int).Sub(u, v)
x := new(big.Int).Mul(upv, upv)
x.Mul(x, rz)
if x.Cmp(n) >= 0 {
x.Mod(x, n)
}
z := new(big.Int).Mul(umv, umv)
z.Mul(z, rx)
if z.Cmp(n) >= 0 {
z.Mod(z, n)
}
return x, z
}
// Doubles a point P (in Montgomery form).
func pointDouble(px, pz, n, a24 *big.Int) (*big.Int, *big.Int) {
u2 := new(big.Int).Add(px, pz)
u2.Mul(u2, u2)
v2 := new(big.Int).Sub(px, pz)
v2.Mul(v2, v2)
t := new(big.Int).Sub(u2, v2)
x := new(big.Int).Mul(u2, v2)
if x.Cmp(n) >= 0 {
x.Mod(x, n)
}
z := new(big.Int).Mul(a24, t)
z.Add(v2, z)
z.Mul(t, z)
if z.Cmp(n) >= 0 {
z.Mod(z, n)
}
return x, z
}
// Multiplies a specified point P (in Montgomery form) by a specified scalar.
func scalarMultiply(k, px, pz, n, a24 *big.Int) (*big.Int, *big.Int) {
sk := fmt.Sprintf("%b", k)
lk := len(sk)
qx := new(big.Int).Set(px)
qz := new(big.Int).Set(pz)
rx, rz := pointDouble(px, pz, n, a24)
for i := 1; i < lk; i++ {
if sk[i] == '1' {
qx, qz = pointAdd(rx, rz, qx, qz, px, pz, n)
rx, rz = pointDouble(rx, rz, n, a24)
} else {
rx, rz = pointAdd(qx, qz, rx, rz, px, pz, n)
qx, qz = pointDouble(qx, qz, n, a24)
}
}
return qx, qz
}
// Lenstra's two-stage ECM algorithm.
func ecm(n *big.Int) (*big.Int, error) {
if n.Cmp(one) == 0 || n.ProbablyPrime(10) {
return n, nil
}
b1, b2 := computeBounds(n)
dd := uint64(math.Sqrt(float64(b2)))
beta := make([]*big.Int, dd+1)
for i := 0; i < len(beta); i++ {
beta[i] = new(big.Int)
}
s := make([]*big.Int, 2*dd+2)
for i := 0; i < len(s); i++ {
s[i] = new(big.Int)
}
// stage 1 and stage 2 precomputations
curves := 0
logB1 := math.Log(float64(b1))
primes := getPrimes(b2)
numPrimes := len(primes)
idxB1 := sort.Search(len(primes), func(i int) bool { return primes[i] >= b1 })
// compute a B1-powersmooth integer 'k'
k := big.NewInt(1)
for i := 0; i < idxB1; i++ {
p := primes[i]
bp := new(big.Int).SetUint64(p)
t := uint64(logB1 / math.Log(float64(p)))
bt := new(big.Int).SetUint64(t)
bt.Exp(bp, bt, nil)
k.Mul(k, bt)
}
g := big.NewInt(1)
for (g.Cmp(one) == 0 || g.Cmp(n) == 0) && curves <= maxCurves {
curves++
st := int64(6 + rand.Intn(maxRnd-5))
sigma := big.NewInt(st)
// generate a new random curve in Montgomery form with Suyama's parameterization
u := new(big.Int).Mul(sigma, sigma)
u.Sub(u, five)
u.Mod(u, n)
v := new(big.Int).Mul(four, sigma)
v.Mod(v, n)
vmu := new(big.Int).Sub(v, u)
a := new(big.Int).Mul(vmu, vmu)
a.Mul(a, vmu)
t := new(big.Int).Mul(three, u)
t.Add(t, v)
a.Mul(a, t)
t.Mul(four, u)
t.Mul(t, u)
t.Mul(t, u)
t.Mul(t, v)
a.Quo(a, t)
a.Sub(a, two)
a.Mod(a, n)
a24 := new(big.Int).Add(a, two)
a24.Quo(a24, four)
// stage 1
px := new(big.Int).Mul(u, u)
px.Mul(px, u)
t.Mul(v, v)
t.Mul(t, v)
px.Quo(px, t)
px.Mod(px, n)
pz := big.NewInt(1)
qx, qz := scalarMultiply(k, px, pz, n, a24)
g.GCD(nil, nil, n, qz)
// if stage 1 is successful, return a non-trivial factor else
// move on to stage 2
if g.Cmp(one) != 0 && g.Cmp(n) != 0 {
return g, nil
}
// stage 2
s[1], s[2] = pointDouble(qx, qz, n, a24)
s[3], s[4] = pointDouble(s[1], s[2], n, a24)
beta[1].Mul(s[1], s[2])
beta[1].Mod(beta[1], n)
beta[2].Mul(s[3], s[4])
beta[2].Mod(beta[2], n)
for d := uint64(3); d <= dd; d++ {
d2 := 2 * d
s[d2-1], s[d2] = pointAdd(s[d2-3], s[d2-2], s[1], s[2], s[d2-5], s[d2-4], n)
beta[d].Mul(s[d2-1], s[d2])
beta[d].Mod(beta[d], n)
}
g.SetUint64(1)
b := new(big.Int).SetUint64(b1 - 1)
rx, rz := scalarMultiply(b, qx, qz, n, a24)
t.Mul(two, new(big.Int).SetUint64(dd))
t.Sub(b, t)
tx, tz := scalarMultiply(t, qx, qz, n, a24)
q, step := idxB1, 2*dd
for r := b1 - 1; r < b2; r += step {
alpha := new(big.Int).Mul(rx, rz)
alpha.Mod(alpha, n)
limit := r + step
for q < numPrimes && primes[q] <= limit {
d := (primes[q] - r) / 2
t := new(big.Int).Sub(rx, s[2*d-1])
f := new(big.Int).Add(rz, s[2*d])
f.Mul(t, f)
f.Sub(f, alpha)
f.Add(f, beta[d])
g.Mul(g, f)
g.Mod(g, n)
q++
}
trx := new(big.Int).Set(rx)
trz := new(big.Int).Set(rz)
rx, rz = pointAdd(rx, rz, s[2*dd-1], s[2*dd], tx, tz, n)
tx.Set(trx)
tz.Set(trz)
}
g.GCD(nil, nil, n, g)
}
// no non-trivial factor found, return an error
if curves > maxCurves {
return zero, fmt.Errorf("maximum curves exceeded before a factor was found")
}
return g, nil
}
// find prime factors of 'n' using an appropriate method.
func primeFactors(n *big.Int) ([]*big.Int, error) {
var res []*big.Int
if n.ProbablyPrime(10) {
return append(res, n), nil
}
le := len(n.String())
var factor1 *big.Int
var err error
if le > 20 && le <= 60 {
factor1, err = ecm(n)
} else {
factor1, err = pollardRho(n)
}
if err != nil {
return nil, err
}
if !factor1.ProbablyPrime(10) {
return nil, fmt.Errorf("first factor is not prime")
}
factor2 := new(big.Int)
factor2.Quo(n, factor1)
if !factor2.ProbablyPrime(10) {
return nil, fmt.Errorf("%d (second factor is not prime)", factor1)
}
return append(res, factor1, factor2), nil
}
func fermatNumbers(n int) (res []*big.Int) {
f := new(big.Int).SetUint64(3) // 2^1 + 1
for i := 0; i < n; i++ {
t := new(big.Int).Set(f)
res = append(res, t)
f.Sub(f, one)
f.Mul(f, f)
f.Add(f, one)
}
return res
}
func main() {
start := time.Now()
rand.Seed(time.Now().UnixNano())
fns := fermatNumbers(10)
fmt.Println("First 10 Fermat numbers:")
for i, f := range fns {
fmt.Printf("F%c = %d\n", 0x2080+i, f)
}
fmt.Println("\nFactors of first 10 Fermat numbers:")
for i, f := range fns {
fmt.Printf("F%c = ", 0x2080+i)
factors, err := primeFactors(f)
if err != nil {
fmt.Println(err)
continue
}
for _, factor := range factors {
fmt.Printf("%d ", factor)
}
if len(factors) == 1 {
fmt.Println("- prime")
} else {
fmt.Println()
}
}
fmt.Printf("\nTook %s\n", time.Since(start))
} |
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
| #ACL2 | ACL2 | (defun sum (xs)
(if (endp xs)
0
(+ (first xs)
(sum (rest xs)))))
(defun n-bonacci (prevs limit)
(if (zp limit)
nil
(let ((next (append (rest prevs)
(list (sum prevs)))))
(cons (first next)
(n-bonacci next (1- limit)))))) |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Fortran | Fortran | program feigenbaum
implicit none
integer i, j, k
real ( KIND = 16 ) x, y, a, b, a1, a2, d1
print '(a4,a13)', 'i', 'd'
a1 = 1.0;
a2 = 0.0;
d1 = 3.2;
do i=2,20
a = a1 + (a1 - a2) / d1;
do j=1,10
x = 0
y = 0
do k=1,2**i
y = 1 - 2 * y * x;
x = a - x**2;
end do
a = a - x / y;
end do
d1 = (a1 - a2) / (a - a1);
a2 = a1;
a1 = a;
print '(i4,f13.10)', i, d1
end do
end |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #FreeBASIC | FreeBASIC | ' version 25-0-2019
' compile with: fbc -s console
Dim As UInteger i, j, k, maxit = 13, maxitj = 13
Dim As Double x, y, a, a1 = 1, a2, d, d1 = 3.2
Print "Feigenbaum constant calculation:"
Print
Print " i d"
Print "==================="
For i = 2 To maxIt
a = a1 + (a1 - a2) / d1
For j = 1 To maxItJ
x = 0 : y = 0
For k = 1 To 2 ^ i
y = 1 - 2 * y * x
x = a - x * x
Next
a = a - x / y
Next
d = (a1 - a2) / (a - a1)
Print Using "### ##.#########"; i; d
d1 = d
a2 = a1
a1 = a
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
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
| #Kotlin | Kotlin | // version 1.1
/* implicitly allows for extensions containing dots */
fun String.isFileExtensionListed(extensions: List<String>): Boolean {
return extensions.any { toLowerCase().endsWith("." + it.toLowerCase()) }
}
fun main(args: Array<String>) {
val extensions = listOf("zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2")
val fileNames = listOf(
"MyData.a##",
"MyData.tar.Gz",
"MyData.gzip",
"MyData.7z.backup",
"MyData...",
"MyData",
"MyData_v1.0.tar.bz2",
"MyData_v1.0.bz2"
)
for (fileName in fileNames) {
println("${fileName.padEnd(19)} -> ${fileName.isFileExtensionListed(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
| #Lua | Lua | -- Data declarations
local extentions = {"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}
local testCases = {
"MyData.a##",
"MyData.tar.Gz",
"MyData.gzip",
"MyData.7z.backup",
"MyData...",
"MyData",
"MyData_v1.0.tar.bz2",
"MyData_v1.0.bz2"
}
-- Return boolean of whether example has a file extension found in extList
function extMatch (extList, example)
for _, extension in pairs(extList) do
if example:lower():match("%." .. extension:lower() .. "$") then
return true
end
end
return false
end
-- Main procedure
for _, case in pairs(testCases) do
print(case .. ": " .. tostring(extMatch(extentions, case)))
end |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
\\ without *for wide output* we open for ANSI (1 byte per character)
\\ but here we need it only for the creation of a file
Open "afile" for output as #f
Close #f
Print file.stamp("afile") 'it is a number in VB6 date format.
\\ day format as for Greece
Print Str$(File.Stamp("afile"),"hh:nn:ss dd/mm/yyyy") , "utc write time - by default"
Print Str$(File.Stamp("afile" ,1),"hh:nn:ss dd/mm/yyyy") , "utc write time, 1"
Print Str$(File.Stamp("afile" ,-1),"hh:nn:ss dd/mm/yyyy"), "local write time, -1"
Print Str$(File.Stamp("afile" ,2),"hh:nn:ss dd/mm/yyyy"), "utc creation time, 2"
Print Str$(File.Stamp("afile" ,-2),"hh:nn:ss dd/mm/yyyy"), "local creation time, -2"
}
Checkit
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | FileDate["file","Modification"] |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #MATLAB_.2F_Octave | MATLAB / Octave | f = dir('output.txt'); % struct f contains file information
f.date % is string containing modification time
f.datenum % numerical format (number of days)
datestr(f.datenum) % is the same as f.date
% see also: stat, lstat |
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.)
| #JavaScript | JavaScript |
// Plot Fibonacci word/fractal
// FiboWFractal.js - 6/27/16 aev
function pFibowFractal(n,len,canvasId,color) {
// DCLs
var canvas = document.getElementById(canvasId);
var ctx = canvas.getContext("2d");
var w = canvas.width; var h = canvas.height;
var fwv,fwe,fn,tx,x=10,y=10,dx=len,dy=0,nr;
// Cleaning canvas, setting plotting color, etc
ctx.fillStyle="white"; ctx.fillRect(0,0,w,h);
ctx.beginPath();
ctx.moveTo(x,y);
fwv=fibword(n); fn=fwv.length;
// MAIN LOOP
for(var i=0; i<fn; i++) {
ctx.lineTo(x+dx,y+dy); fwe=fwv[i];
if(fwe=="0") {tx=dx; nr=i%2;
if(nr==0) {dx=-dy;dy=tx} else {dx=dy;dy=-tx}};
x+=dx; y+=dy;
}//fend i
ctx.strokeStyle = color; ctx.stroke();
}//func end
// Create and return Fibonacci word
function fibword(n) {
var f1="1",f2="0",fw,fwn,n2,i;
if (n<5) {n=5}; n2=n+2;
for (i=0; i<n2; i++) {fw=f2+f1;f1=f2;f2=fw};
return(fw)
}
|
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
| #J | J | parseDirs =: = <;.2 ]
getCommonPrefix =: {. ;@{.~ 0 i.~ *./@(="1 {.)
getCommonDirPath=: [: getCommonPrefix parseDirs&> |
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
| #Java | Java | public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/"); //split on file separator
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j]; //grab the next folder name in the first path
boolean allMatched = true; //assume all have matched in case there are no more paths
for(int i = 1; i < folders.length && allMatched; i++){ //look at the other paths
if(folders[i].length < j){ //if there is no folder here
allMatched = false; //no match
break; //stop looking because we've gone as far as we can
}
//otherwise
allMatched &= folders[i][j].equals(thisFolder); //check if it matched
}
if(allMatched){ //if they all matched this folder name
commonPath += thisFolder + "/"; //add it to the answer
}else{//otherwise
break;//stop looking
}
}
return commonPath;
}
public static void main(String[] args){
String[] paths = { "/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths));
String[] paths2 = { "/hame/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths2));
}
} |
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.
| #Brat | Brat | #Prints [2, 4, 6, 8, 10]
p 1.to(10).select { x | x % 2 == 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.
| #MATLAB_.2F_Octave | MATLAB / Octave | >> get(0,'RecursionLimit')
ans =
500
>> set(0,'RecursionLimit',2500)
>> get(0,'RecursionLimit')
ans =
2500 |
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.
| #Maxima | Maxima | f(p) := f(n: p + 1)$
f(0);
Maxima encountered a Lisp error:
Error in PROGN [or a callee]: Bind stack overflow.
Automatically continuing.
To enable the Lisp debugger set *debugger-hook* to nil.
n;
406 |
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
| #zkl | zkl | fcn pal23W{ //--> iterator returning (index,palindromic number)
Walker.tweak(fcn(ri,r){ // references to loop start and count of palindromes
foreach i in ([ri.value..*]){
n3:=i.toString(3);
n:=String(n3,"1",n3.reverse()).toInt(3); // create base 3 palindrome
n2:= n.toString(2);
if(n2.len().isOdd and n2==n2.reverse()){ // stop here, return answer
ri.set(i+1); // continue loop from this value at next iteration
return(r.inc(),n);
}
}
}.fp(Ref(3),Ref(3))).push(T(1,0),T(2,1)) // seed with first two results
} |
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
| #Frege | Frege | gen n word = cycle (take (n - 1) (repeat "") ++ [word])
pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz")
fizzbuzz = zipWith combine pattern [1..] where
combine word number = if null word
then show number
else word
show $ take 100 fizzbuzz |
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.
| #Frink | Frink | println[newJava["java.io.File", "input.txt"].length[]]
println[newJava["java.io.File", "/input.txt"].length[]] |
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.
| #Gambas | Gambas | Public Sub Main()
Dim stInfo As Stat = Stat(User.home &/ "input.txt")
Dim stInfo1 As Stat = Stat("/input.txt")
Print User.Home &/ "input.txt = " & stInfo.Size & " bytes"
Print "/input.txt = " & stInfo1.Size & " bytes"
End |
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.
| #Clean | Clean | import StdEnv
copyFile fromPath toPath world
# (ok, fromFile, world) = fopen fromPath FReadData world
| not ok = abort ("Cannot open " +++ fromPath +++ " for reading")
# (ok, toFile, world) = fopen toPath FWriteData world
| not ok = abort ("Cannot open " +++ toPath +++ " for writing")
# (fromFile, toFile) = copyData 1024 fromFile toFile
# (ok, world) = fclose fromFile world
| not ok = abort ("Cannot close " +++ fromPath +++ " after reading")
# (ok, world) = fclose toFile world
| not ok = abort ("Cannot close " +++ toPath +++ " after writing")
= world
where
copyData bufferSize fromFile toFile
# (buffer, fromFile) = freads fromFile bufferSize
# toFile = fwrites buffer toFile
| size buffer < bufferSize = (fromFile, toFile) // we're done
= copyData bufferSize fromFile toFile // continue recursively |
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.
| #Clojure | Clojure |
(use 'clojure.java.io)
(copy (file "input.txt") (file "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
| #C.2B.2B | C++ | #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
double log2( double number ) {
return ( log( number ) / log( 2 ) ) ;
}
double find_entropy( std::string & fiboword ) {
std::map<char , int> frequencies ;
std::for_each( fiboword.begin( ) , fiboword.end( ) ,
[ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ;
int numlen = fiboword.length( ) ;
double infocontent = 0 ;
for ( std::pair<char , int> p : frequencies ) {
double freq = static_cast<double>( p.second ) / numlen ;
infocontent += freq * log2( freq ) ;
}
infocontent *= -1 ;
return infocontent ;
}
void printLine( std::string &fiboword , int n ) {
std::cout << std::setw( 5 ) << std::left << n ;
std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;
std::cout << " " << std::setw( 16 ) << std::setprecision( 13 )
<< std::left << find_entropy( fiboword ) ;
std::cout << "\n" ;
}
int main( ) {
std::cout << std::setw( 5 ) << std::left << "N" ;
std::cout << std::setw( 12 ) << std::right << "length" ;
std::cout << " " << std::setw( 16 ) << std::left << "entropy" ;
std::cout << "\n" ;
std::string firststring ( "1" ) ;
int n = 1 ;
printLine( firststring , n ) ;
std::string secondstring( "0" ) ;
n++ ;
printLine( secondstring , n ) ;
while ( n < 37 ) {
std::string resultstring = firststring + secondstring ;
firststring.assign( secondstring ) ;
secondstring.assign( resultstring ) ;
n++ ;
printLine( resultstring , n ) ;
}
return 0 ;
} |
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.
| #Aime | Aime | file f;
text n, s;
f.affix(argv(1));
while (f.line(s) ^ -1) {
if (s[0] == '>') {
o_(n, s, ": ");
n = "\n";
} else {
o_(s);
}
}
o_(n); |
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.
| #ALGOL_W | ALGOL W | begin
% reads FASTA format data from standard input and write the results to standard output %
% only handles the ">" line start %
string(256) line;
% allow the program to continue after reaching end-of-file %
ENDFILE := EXCEPTION( false, 1, 0, false, "EOF" );
% handle the input %
readcard( line );
while not XCPNOTED(ENDFILE) do begin
% strings are fixed length in Algol W - we need to find the line lengh with trailing spaces removed %
integer len;
len := 255;
while len > 0 and line( len // 1 ) = " " do len := len - 1;
if len > 0 then begin % non-empty line %
integer pos;
pos := 0;
if line( 0 // 1 ) = ">" then begin % header line %
write();
pos := 1;
end if_header_line ;
for cPos := pos until len do writeon( line( cPos // 1 ) );
if line( 0 // 1 ) = ">" then writeon( ": " )
end if_non_empty_line ;
readcard( line );
end while_not_eof
end. |
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.
| #Arturo | Arturo | parseFasta: function [data][
result: #[]
current: ø
loop split.lines data 'line [
if? `>` = first line [
current: slice line 1 (size line)-1
set result current ""
]
else ->
set result current (get result current)++line
]
return result
]
text: {
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
}
inspect.muted parseFasta text |
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
| #Haskell | Haskell | import Data.Numbers.Primes (primeFactors)
import Data.Bool (bool)
fermat :: Integer -> Integer
fermat = succ . (2 ^) . (2 ^)
fermats :: [Integer]
fermats = fermat <$> [0 ..]
--------------------------- TEST ---------------------------
main :: IO ()
main =
mapM_
putStrLn
[ fTable "First 10 Fermats:" show show fermat [0 .. 9]
, fTable
"Factors of first 7:"
show
showFactors
primeFactors
(take 7 fermats)
]
------------------------- DISPLAY --------------------------
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
fTable s xShow fxShow f xs =
unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs
where
rjust n c = drop . length <*> (replicate n c ++)
w = maximum (length . xShow <$> xs)
showFactors :: [Integer] -> String
showFactors x
| 1 < length x = show x
| otherwise = "(prime)" |
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
| #Action.21 | Action! | DEFINE MAX="15"
PROC GenerateSeq(CARD ARRAY init BYTE nInit CARD ARRAY seq BYTE nSeq)
CARD next
BYTE i,j,n
IF nInit<nSeq THEN
n=nInit
ELSE
n=nSeq
FI
FOR i=0 TO n-1
DO
seq(i)=init(i)
OD
FOR i=n TO nSeq-1
DO
next=0
FOR j=i-nInit TO i-1
DO
next==+seq(j)
OD
seq(i)=next
OD
RETURN
PROC PrintSeq(CHAR ARRAY name CARD ARRAY seq BYTE n)
BYTE i
PrintF("%S=[",name)
FOR i=0 TO n-1
DO
PrintC(seq(i))
IF i<n-1 THEN
Print(" ")
ELSE
PrintE("]")
FI
OD
RETURN
PROC SetInverseVideo(CHAR ARRAY text)
BYTE i
FOR i=1 TO text(0)
DO
text(i)=text(i) OR $80
OD
RETURN
PROC Test(CHAR ARRAY name CARD ARRAY init CARD ARRAY nInit BYTE nSeq)
CARD ARRAY seq(MAX)
SetInverseVideo(name)
GenerateSeq(init,nInit,seq,nSeq)
PrintSeq(name,seq,nSeq)
RETURN
PROC Main()
CARD ARRAY fibInit=[1 1 2 4 8 16 32 64 128 256 512]
CARD ARRAY lucInit=[2 1]
Test("lucas",lucInit,2,MAX)
Test("fibonacci",fibInit,2,MAX)
Test("tribonacci",fibInit,3,MAX)
Test("tetranacci",fibInit,4,MAX)
Test("pentanacci",fibInit,5,MAX)
Test("hexanacci",fibInit,6,MAX)
Test("heptanacci",fibInit,7,MAX)
Test("octanacci",fibInit,8,MAX)
Test("nonanacci",fibInit,9,MAX)
Test("decanacci",fibInit,10,MAX)
RETURN |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ |
window 1, @"Feignenbaum Constant", ( 0, 0, 200, 300 )
_maxIt = 13
_maxItJ = 10
void local fn Feignenbaum
NSUInteger i, j, k
double a1 = 1.0, a2 = 0.0, d1 = 3.2
print "Feignenbaum Constant"
print " i d"
for i = 2 to _maxIt
double a = a1 + ( a1 - a2 ) / d1
for j = 1 to _maxItJ
double x = 0, y = 0
for k = 1 to fn pow( 2, i )
y = 1 - 2 * y * x
x = a - x * x
next
a = a - x / y
next
double d = ( a1 - a2 ) / ( a - a1 )
printf @"%2d. %.8f", i, d
d1 = d
a2 = a1
a1 = a
next
end fn
fn Feignenbaum
HandleEvents
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #FutureBasic | FutureBasic |
window 1, @"Feignenbaum Constant", ( 0, 0, 200, 300 )
_maxIt = 13
_maxItJ = 10
void local fn Feignenbaum
NSUInteger i, j, k
double a1 = 1.0, a2 = 0.0, d1 = 3.2
print "Feignenbaum Constant"
print " i d"
for i = 2 to _maxIt
double a = a1 + ( a1 - a2 ) / d1
for j = 1 to _maxItJ
double x = 0, y = 0
for k = 1 to fn pow( 2, i )
y = 1 - 2 * y * x
x = a - x * x
next
a = a - x / y
next
double d = ( a1 - a2 ) / ( a - a1 )
printf @"%2d. %.8f", i, d
d1 = d
a2 = a1
a1 = a
next
end fn
fn Feignenbaum
HandleEvents
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Go | Go | package main
import "fmt"
func feigenbaum() {
maxIt, maxItJ := 13, 10
a1, a2, d1 := 1.0, 0.0, 3.2
fmt.Println(" i d")
for i := 2; i <= maxIt; i++ {
a := a1 + (a1-a2)/d1
for j := 1; j <= maxItJ; j++ {
x, y := 0.0, 0.0
for k := 1; k <= 1<<uint(i); k++ {
y = 1.0 - 2.0*y*x
x = a - x*x
}
a -= x / y
}
d := (a1 - a2) / (a - a1)
fmt.Printf("%2d %.8f\n", i, d)
d1, a2, a1 = d, a1, a
}
}
func main() {
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[CheckExtension]
CheckExtension[fn_String, e : {_String ..}] := StringMatchQ[ToLowerCase[FileExtension[fn]], Alternatives @@ ToLowerCase[e]]
exts = {"zip", "rar", "7z", "gz", "archive", "A##"};
CheckExtension["MyData.a##", exts]
CheckExtension["MyData.tar.gz", exts]
CheckExtension["MyData.gzip", exts]
CheckExtension["MyData.7z.backup", exts]
CheckExtension["MyData..", exts]
CheckExtension["MyData", exts] |
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
| #Nim | Nim | import os, strutils
let fileNameList = ["MyData.a##", "MyData.tar.Gz", "MyData.gzip",
"MyData.7z.backup", "MyData...", "MyData"]
func buildExtensionList(extensions: varargs[string]): seq[string] {.compileTime.} =
for ext in extensions:
result.add('.' & ext.toLowerAscii())
const ExtList = buildExtensionList("zip", "rar", "7z", "gz", "archive", "A##")
for fileName in fileNameList:
echo fileName, " → ", fileName.splitFile().ext.toLowerAscii() in ExtList |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #MAXScript | MAXScript | -- Returns a string containing the mod date for the file, e.g. "1/29/99 1:52:05 PM"
getFileModDate "C:\myFile.txt" |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Modula-3 | Modula-3 | MODULE ModTime EXPORTS Main;
IMPORT IO, Fmt, File, FS, Date, OSError;
TYPE dateArray = ARRAY [0..5] OF TEXT;
VAR
file: File.Status;
date: Date.T;
PROCEDURE DateArray(date: Date.T): dateArray =
BEGIN
RETURN
dateArray{Fmt.Int(date.year), Fmt.Int(ORD(date.month) + 1), Fmt.Int(date.day),
Fmt.Int(date.hour), Fmt.Int(date.minute), Fmt.Int(date.second)};
END DateArray;
BEGIN
TRY
file := FS.Status("test.txt");
date := Date.FromTime(file.modificationTime);
IO.Put(Fmt.FN("%s-%02s-%02s %02s:%02s:%02s", DateArray(date)));
IO.Put("\n");
EXCEPT
| OSError.E => IO.Put("Error: Failed to get file status.\n");
END;
END ModTime. |
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.)
| #Julia | Julia | using Luxor, Colors
function fwfractal!(word::AbstractString, t::Turtle)
left = 90
right = -90
for (n, c) in enumerate(word)
Forward(t)
if c == '0'
Turn(t, ifelse(iseven(n), left, right))
end
end
return t
end
word = last(fiboword(25))
touch("data/fibonaccifractal.png")
Drawing(800, 800, "data/fibonaccifractal.png");
background(colorant"white")
t = Turtle(100, 300)
fwfractal!(word, t)
finish()
preview() |
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.)
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import javax.swing.*
class FibonacciWordFractal(n: Int) : JPanel() {
private val wordFractal: String
init {
preferredSize = Dimension(450, 620)
background = Color.black
wordFractal = wordFractal(n)
}
fun wordFractal(i: Int): String {
if (i < 2) return if (i == 1) "1" else ""
val f1 = StringBuilder("1")
val f2 = StringBuilder("0")
for (j in i - 2 downTo 1) {
val tmp = f2.toString()
f2.append(f1)
f1.setLength(0)
f1.append(tmp)
}
return f2.toString()
}
private fun drawWordFractal(g: Graphics2D, x: Int, y: Int, dx: Int, dy: Int) {
var x2 = x
var y2 = y
var dx2 = dx
var dy2 = dy
for (i in 0 until wordFractal.length) {
g.drawLine(x2, y2, x2 + dx2, y2 + dy2)
x2 += dx2
y2 += dy2
if (wordFractal[i] == '0') {
val tx = dx2
dx2 = if (i % 2 == 0) -dy2 else dy2
dy2 = if (i % 2 == 0) tx else -tx
}
}
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.color = Color.green
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
drawWordFractal(g, 20, 20, 1, 0)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
with(f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
title = "Fibonacci Word Fractal"
isResizable = false
add(FibonacciWordFractal(23), BorderLayout.CENTER)
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
} |
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
| #JavaScript | JavaScript |
/**
* Given an array of strings, return an array of arrays, containing the
* strings split at the given separator
* @param {!Array<!string>} a
* @param {string} sep
* @returns {!Array<!Array<string>>}
*/
const splitStrings = (a, sep = '/') => a.map(i => i.split(sep));
/**
* Given an index number, return a function that takes an array and returns the
* element at the given index
* @param {number} i
* @return {function(!Array<*>): *}
*/
const elAt = i => a => a[i];
/**
* Transpose an array of arrays:
* Example:
* [['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3]] ->
* [['a', 'A', 1], ['b', 'B', 2], ['c', 'C', 3]]
* @param {!Array<!Array<*>>} a
* @return {!Array<!Array<*>>}
*/
const rotate = a => a[0].map((e, i) => a.map(elAt(i)));
/**
* Checks of all the elements in the array are the same.
* @param {!Array<*>} arr
* @return {boolean}
*/
const allElementsEqual = arr => arr.every(e => e === arr[0]);
const commonPath = (input, sep = '/') => rotate(splitStrings(input, sep))
.filter(allElementsEqual).map(elAt(0)).join(sep);
const cdpInput = [
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
];
console.log(`Common path is: ${commonPath(cdpInput)}`);
|
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.
| #Burlesque | Burlesque |
blsq ) 1 13r@{2.%n!}f[
{2 4 6 8 10 12}
|
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.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П2 ПП 05 ИП1 С/П
ИП0 ИП2 - x<0 20 ИП0 1 + П0 ПП 05
ИП1 1 + П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.
| #Modula-2 | Modula-2 | MODULE recur;
IMPORT InOut;
PROCEDURE recursion (a : CARDINAL);
BEGIN
InOut.Write ('.'); (* just count the dots.... *)
recursion (a + 1)
END recursion;
BEGIN
recursion (0)
END recur. |
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
| #Frink | Frink | for i = 1 to 100
{
flag = false
if i mod 3 == 0
{
flag = true
print["Fizz"]
}
if i mod 5 == 0
{
flag = true
print["Buzz"]
}
if flag == false
print[i]
println[]
} |
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.
| #Go | Go | package main
import "fmt"
import "os"
func printFileSize(f string) {
if stat, err := os.Stat(f); err != nil {
fmt.Println(err)
} else {
fmt.Println(stat.Size())
}
}
func main() {
printFileSize("input.txt")
printFileSize("/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.
| #Groovy | Groovy | println new File('index.txt').length();
println new File('/index.txt').length(); |
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.
| #COBOL | COBOL | $set ans85 flag"ans85" flagas"s" sequential"line"
|
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.
| #ColdFusion | ColdFusion | <cfif fileExists(expandPath("input.txt"))>
<cffile action="read" file="#expandPath('input.txt')#" variable="inputContents">
<cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#">
</cfif> |
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
| #Clojure | Clojure | (defn entropy [s]
(let [len (count s), log-2 (Math/log 2)]
(->> (frequencies s)
(map (fn [[_ v]]
(let [rf (/ v len)]
(-> (Math/log rf) (/ log-2) (* rf) Math/abs))))
(reduce +))))
(defn fibonacci [cat a b]
(lazy-seq
(cons a (fibonacci b (cat a b)))))
; you could also say (fibonacci + 0 1) or (fibonacci concat '(0) '(1))
(printf "%2s %10s %17s %s%n" "N" "Length" "Entropy" "Fibword")
(doseq [i (range 1 38)
w (take 37 (fibonacci str "1" "0"))]
(printf "%2d %10d %.15f %s%n" i (count w) (entropy w) (if (<= i 8) w "...")))) |
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.
| #AutoHotkey | AutoHotkey | Data =
(
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
)
Data := RegExReplace(RegExReplace(Data, ">\V+\K\v+", ": "), "\v+(?!>)")
Gui, add, Edit, w700, % Data
Gui, show
return |
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.
| #AWK | AWK |
# syntax: GAWK -f FASTA_FORMAT.AWK filename
# stop processing each file when an error is encountered
{ if (FNR == 1) {
header_found = 0
if ($0 !~ /^[;>]/) {
error("record is not valid")
nextfile
}
}
if ($0 ~ /^;/) { next } # comment begins with a ";"
if ($0 ~ /^>/) { # header
if (header_found > 0) {
printf("\n") # EOL for previous sequence
}
printf("%s: ",substr($0,2))
header_found = 1
next
}
if ($0 ~ /[ \t]/) { next } # ignore records with whitespace
if ($0 ~ /\*$/) { # sequence may end with an "*"
if (header_found > 0) {
printf("%s\n",substr($0,1,length($0)-1))
header_found = 0
next
}
else {
error("end of sequence found but header is missing")
nextfile
}
}
if (header_found > 0) {
printf("%s",$0)
}
else {
error("header not found")
nextfile
}
}
ENDFILE {
if (header_found > 0) {
printf("\n")
}
}
END {
exit (errors == 0) ? 0 : 1
}
function error(message) {
printf("error: FILENAME=%s, FNR=%d, %s, %s\n",FILENAME,FNR,message,$0) >"con"
errors++
return
}
|
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
| #J | J | fermat =: 1 1 p. 2 ^ 2 ^ x:
(,. fermat)i.10
0 3
1 5
2 17
3 257
4 65537
5 4294967297
6 18446744073709551617
7 340282366920938463463374607431768211457
8 115792089237316195423570985008687907853269984665640564039457584007913129639937
9 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084097
(; q:@:fermat)&>i.7
+-+---------------------+
|0|3 |
+-+---------------------+
|1|5 |
+-+---------------------+
|2|17 |
+-+---------------------+
|3|257 |
+-+---------------------+
|4|65537 |
+-+---------------------+
|5|641 6700417 |
+-+---------------------+
|6|274177 67280421310721|
+-+---------------------+
|
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
| #Java | Java |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class FermatNumbers {
public static void main(String[] args) {
System.out.println("First 10 Fermat numbers:");
for ( int i = 0 ; i < 10 ; i++ ) {
System.out.printf("F[%d] = %s\n", i, fermat(i));
}
System.out.printf("%nFirst 12 Fermat numbers factored:%n");
for ( int i = 0 ; i < 13 ; i++ ) {
System.out.printf("F[%d] = %s\n", i, getString(getFactors(i, fermat(i))));
}
}
private static String getString(List<BigInteger> factors) {
if ( factors.size() == 1 ) {
return factors.get(0) + " (PRIME)";
}
return factors.stream().map(v -> v.toString()).map(v -> v.startsWith("-") ? "(C" + v.replace("-", "") + ")" : v).collect(Collectors.joining(" * "));
}
private static Map<Integer, String> COMPOSITE = new HashMap<>();
static {
COMPOSITE.put(9, "5529");
COMPOSITE.put(10, "6078");
COMPOSITE.put(11, "1037");
COMPOSITE.put(12, "5488");
COMPOSITE.put(13, "2884");
}
private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) {
List<BigInteger> factors = new ArrayList<>();
BigInteger factor = BigInteger.ONE;
while ( true ) {
if ( n.isProbablePrime(100) ) {
factors.add(n);
break;
}
else {
if ( COMPOSITE.containsKey(fermatIndex) ) {
String stop = COMPOSITE.get(fermatIndex);
if ( n.toString().startsWith(stop) ) {
factors.add(new BigInteger("-" + n.toString().length()));
break;
}
}
factor = pollardRhoFast(n);
if ( factor.compareTo(BigInteger.ZERO) == 0 ) {
factors.add(n);
break;
}
else {
factors.add(factor);
n = n.divide(factor);
}
}
}
return factors;
}
private static final BigInteger TWO = BigInteger.valueOf(2);
private static BigInteger fermat(int n) {
return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE);
}
// See: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
@SuppressWarnings("unused")
private static BigInteger pollardRho(BigInteger n) {
BigInteger x = BigInteger.valueOf(2);
BigInteger y = BigInteger.valueOf(2);
BigInteger d = BigInteger.ONE;
while ( d.compareTo(BigInteger.ONE) == 0 ) {
x = pollardRhoG(x, n);
y = pollardRhoG(pollardRhoG(y, n), n);
d = x.subtract(y).abs().gcd(n);
}
if ( d.compareTo(n) == 0 ) {
return BigInteger.ZERO;
}
return 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 static BigInteger pollardRhoFast(BigInteger n) {
long start = System.currentTimeMillis();
BigInteger x = BigInteger.valueOf(2);
BigInteger y = BigInteger.valueOf(2);
BigInteger d = BigInteger.ONE;
int count = 0;
BigInteger z = BigInteger.ONE;
while ( true ) {
x = pollardRhoG(x, n);
y = pollardRhoG(pollardRhoG(y, n), n);
d = x.subtract(y).abs();
z = z.multiply(d).mod(n);
count++;
if ( count == 100 ) {
d = z.gcd(n);
if ( d.compareTo(BigInteger.ONE) != 0 ) {
break;
}
z = BigInteger.ONE;
count = 0;
}
}
long end = System.currentTimeMillis();
System.out.printf(" Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n", n, (end-start), d);
if ( d.compareTo(n) == 0 ) {
return BigInteger.ZERO;
}
return d;
}
private static BigInteger pollardRhoG(BigInteger x, BigInteger n) {
return x.multiply(x).add(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
| #Ada | Ada | package Bonacci is
type Sequence is array(Positive range <>) of Positive;
function Generate(Start: Sequence; Length: Positive := 10) return Sequence;
Start_Fibonacci: constant Sequence := (1, 1);
Start_Tribonacci: constant Sequence := (1, 1, 2);
Start_Tetranacci: constant Sequence := (1, 1, 2, 4);
Start_Lucas: constant Sequence := (2, 1);
end Bonacci; |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Groovy | Groovy | class Feigenbaum {
static void main(String[] args) {
int max_it = 13
int max_it_j = 10
double a1 = 1.0
double a2 = 0.0
double d1 = 3.2
double a
println(" i d")
for (int i = 2; i <= max_it; i++) {
a = a1 + (a1 - a2) / d1
for (int j = 0; j < max_it_j; j++) {
double x = 0.0
double y = 0.0
for (int k = 0; k < 1 << i; k++) {
y = 1.0 - 2.0 * y * x
x = a - x * x
}
a -= x / y
}
double d = (a1 - a2) / (a - a1)
printf("%2d %.8f\n", i, d)
d1 = d
a2 = a1
a1 = a
}
}
} |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Haskell | Haskell | import Data.List (mapAccumL)
feigenbaumApprox :: Int -> [Double]
feigenbaumApprox mx = snd $ mitch mx 10
where
mitch :: Int -> Int -> ((Double, Double, Double), [Double])
mitch mx mxj =
mapAccumL
(\(a1, a2, d1) i ->
let a =
iterate
(\a ->
let (x, y) =
iterate
(\(x, y) -> (a - (x * x), 1.0 - ((2.0 * x) * y)))
(0.0, 0.0) !!
(2 ^ i)
in a - (x / y))
(a1 + (a1 - a2) / d1) !!
mxj
d = (a1 - a2) / (a - a1)
in ((a, a1, d), d))
(1.0, 0.0, 3.2)
[2 .. (1 + mx)]
-- TEST ------------------------------------------------------------------
main :: IO ()
main =
(putStrLn . unlines) $
zipWith
(\i s -> justifyRight 2 ' ' (show i) ++ '\t' : s)
[1 ..]
(show <$> feigenbaumApprox 13)
where
justifyRight n c s = drop (length s) (replicate n c ++ s) |
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
| #Objeck | Objeck |
class FileExtension {
function : Main(args : String[]) ~ Nil {
files := ["MyData.a##", "MyData.tar.Gz", "MyData.gzip",
"MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2"];
exts := ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"];
each(i : files) {
HasExt(files[i], exts);
};
}
function : HasExt(file : String, exts : String[]) ~ Nil {
full_file := file->ToLower();
each(i : exts) {
full_ext := ".";
full_ext += exts[i]->ToLower();
if(full_file->EndsWith(full_ext)) {
IO.Console->Print(file)->Print(" has extension \"")->Print(exts[i])->PrintLine("\"");
return;
};
};
IO.Console->Print(file)->PrintLine(" does not have an extension in the list");
}
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
parse arg fileName
if fileName = '' then fileName = 'data/tempfile01'
mfile = File(fileName)
mtime = mfile.lastModified()
dtime = Date(mtime).toString()
say 'File' fileName 'last modified at' dtime
say
if mfile.setLastModified(0) then do
dtime = Date(mfile.lastModified()).toString()
say 'File modification time altered...'
say 'File' fileName 'now last modified at' dtime
say
say 'Resetting...'
mfile.setLastModified(mtime)
dtime = Date(mfile.lastModified()).toString()
say 'File' fileName 'reset to last modified at' dtime
end
else do
say 'Unable to modify time for file' fileName
end
return
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #NewLISP | NewLISP | ;; print modification time
(println (date (file-info "input.txt" 6)))
;; set modification time to now (Unix)
(! "touch -m input.txt") |
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.)
| #Logo | Logo | ; Return the low 1-bits of :n
; For example if n = binary 10110111 = 183
; then return binary 111 = 7
to low.ones :n
output ashift (bitxor :n (:n+1)) -1
end
; :fibbinary should be a fibbinary value
; return the next larger fibbinary value
to fibbinary.next :fibbinary
localmake "filled bitor :fibbinary (ashift :fibbinary -1)
localmake "mask low.ones :filled
output (bitor :fibbinary :mask) + 1
end
to fibonacci.word.fractal :steps
localmake "step.length 5 ; length of each step
localmake "fibbinary 0
repeat :steps [
forward :step.length
if (bitand 1 :fibbinary) = 0 [
ifelse (bitand repcount 1) = 1 [right 90] [left 90]
]
make "fibbinary fibbinary.next :fibbinary
]
end
setheading 0 ; initial line North
fibonacci.word.fractal 377 |
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.)
| #Lua | Lua |
RIGHT, LEFT, UP, DOWN = 1, 2, 4, 8
function drawFractals( w )
love.graphics.setCanvas( canvas )
love.graphics.clear()
love.graphics.setColor( 255, 255, 255 )
local dir, facing, lineLen, px, py, c = RIGHT, UP, 1, 10, love.graphics.getHeight() - 20, 1
local x, y = 0, -lineLen
local pts = {}
table.insert( pts, px + .5 ); table.insert( pts, py + .5 )
for i = 1, #w do
px = px + x; table.insert( pts, px + .5 )
py = py + y; table.insert( pts, py + .5 )
if w:sub( i, i ) == "0" then
if c % 2 == 1 then dir = RIGHT else dir = LEFT end
if facing == UP then
if dir == RIGHT then x = lineLen; facing = RIGHT
else x = -lineLen; facing = LEFT end; y = 0
elseif facing == RIGHT then
if dir == RIGHT then y = lineLen; facing = DOWN
else y = -lineLen; facing = UP end; x = 0
elseif facing == DOWN then
if dir == RIGHT then x = -lineLen; facing = LEFT
else x = lineLen; facing = RIGHT end; y = 0
elseif facing == LEFT then
if dir == RIGHT then y = -lineLen; facing = UP
else y = lineLen; facing = DOWN end; x = 0
end
end
c = c + 1
end
love.graphics.line( pts )
love.graphics.setCanvas()
end
function createWord( wordLen )
local a, b, w = "1", "0"
repeat
w = b .. a; a = b; b = w; wordLen = wordLen - 1
until wordLen == 0
return w
end
function love.load()
wid, hei = love.graphics.getWidth(), love.graphics.getHeight()
canvas = love.graphics.newCanvas( wid, hei )
drawFractals( createWord( 21 ) )
end
function love.draw()
love.graphics.draw( canvas )
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
| #jq | jq | # maximal_initial_subarray takes as input an array of arrays:
def maximal_initial_subarray:
(map( .[0] ) | unique) as $u
| if $u == [ null ] then []
elif ($u|length) == 1
then $u + ( map( .[1:] ) | maximal_initial_subarray)
else []
end ;
# Solution: read in the strings, convert to an array of arrays, and proceed:
def common_path(slash):
[.[] | split(slash)] | maximal_initial_subarray | join(slash) ;
common_path("/") |
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
| #Julia | Julia | function commonpath(ds::Vector{<:AbstractString}, dlm::Char='/')
0 < length(ds) || return ""
1 < length(ds) || return String(ds[1])
p = split(ds[1], dlm)
mincnt = length(p)
for d in ds[2:end]
q = split(d, dlm)
mincnt = min(mincnt, length(q))
hits = findfirst(p[1:mincnt] .!= q[1:mincnt])
if hits != 0 mincnt = hits - 1 end
if mincnt == 0 return "" end
end
1 < mincnt || p[1] != "" || return convert(T, string(dlm))
return join(p[1:mincnt], dlm)
end
test = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"]
println("Comparing:\n - ", join(test, "\n - "))
println("for their common directory path yields:\n", commonpath(test)) |
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.
| #BQN | BQN | _filter ← {(𝔽𝕩)/𝕩}
Odd ← 2⊸|
Odd _filter 1‿2‿3‿4‿5 |
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.
| #MUMPS | MUMPS | RECURSE
IF $DATA(DEPTH)=1 SET DEPTH=1+DEPTH
IF $DATA(DEPTH)=0 SET DEPTH=1
WRITE !,DEPTH_" levels down"
DO RECURSE
QUIT |
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.
| #Nanoquery | Nanoquery | def recurse(counter)
println counter
counter += 1
recurse(counter)
end
recurse(1) |
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
| #FutureBasic | FutureBasic | include "NSLog.incl"
long fizz, buzz, i
for i = 1 to 100
fizz = (i mod 3 )
buzz = (i mod 5 )
if fizz + buzz == 0 then NSLog(@"FizzBuzz") : continue
if fizz == 0 then NSLog(@"Fizz") : continue
if buzz == 0 then NSLog(@"Buzz") : continue
NSLog(@"%ld",i)
next i
HandleEvents |
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.
| #Haskell | Haskell | import System.IO
printFileSize filename = withFile filename ReadMode hFileSize >>= print
main = mapM_ printFileSize ["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.
| #HicEst | HicEst | READ(FILE="input.txt", LENgth=bytes) ! bytes = -1 if not existent
READ(FILE="C:\input.txt", LENgth=bytes) ! bytes = -1 if not existent |
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.
| #Icon_and_Unicon | Icon and Unicon | every dir := !["./","/"] do {
write("Size of ",f := dir || "input.txt"," = ",stat(f).size) |stop("failure for to stat ",f)
} |
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.
| #Common_Lisp | Common Lisp | (with-open-file (in #p"input.txt" :direction :input)
(with-open-file (out #p"output.txt" :direction :output)
(loop for line = (read-line in nil 'foo)
until (eq line 'foo)
do (write-line line out)))) |
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.
| #D | D | import std.file: copy;
void main() {
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
| #CLU | CLU | % NOTE: when compiling with Portable CLU,
% this program needs to be merged with 'useful.lib' to get log()
%
% pclu -merge $CLUHOME/lib/useful.lib -compile fib_words.clu
% Yield pairs of (zeroes, ones) for each Fibonacci word
% We don't generate the whole words, as that would take too much
% memory.
fib_words = iter () yields (int,int)
az: int := 0 ao: int := 1
bz: int := 1 bo: int := 0
while true do
yield(az, ao)
az, ao, bz, bo := bz, bo, az+bz, ao+bo
end
end fib_words
fib_entropy = proc (zeroes, ones: int) returns (real)
rsize: real := real$i2r(zeroes + ones)
zeroes_frac: real := real$i2r(zeroes)/rsize
ones_frac: real := real$i2r(ones)/rsize
return(-zeroes_frac*log(zeroes_frac)/log(2.0)
-ones_frac*log(ones_frac)/log(2.0))
except when undefined: return(0.0) end
end fib_entropy
start_up = proc ()
max = 37
po: stream := stream$primary_output()
stream$putl(po, " # Length Entropy")
num: int := 0
for zeroes, ones: int in fib_words() do
num := num + 1
stream$putright(po, int$unparse(num), 2)
stream$putright(po, int$unparse(zeroes+ones), 10)
stream$putright(po, f_form(fib_entropy(zeroes, ones), 1, 6), 10)
stream$putl(po, "")
if num=max then break end
end
end start_up |
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
| #Common_Lisp | Common Lisp | (defun make-fibwords (array)
(loop for i from 0 below 37
for j = "0" then (concatenate 'string j k)
and k = "1" then j
do (setf (aref array i) k))
array)
(defvar *fib* (make-fibwords (make-array 37)))
(defun entropy (string)
(let ((table (make-hash-table :test 'eql))
(entropy 0d0)
(n (length string)))
(mapc (lambda (c)
(setf (gethash c table) (+ (gethash c table 0) 1)))
(coerce string 'list))
(maphash (lambda (k v)
(declare (ignore k))
(decf entropy (* (/ v n) (log (/ v n) 2))))
table)
entropy))
(defun string-or-dots (string)
(if (> (length string) 40)
"..."
string))
(format t "~2A ~10A ~17A ~A~%" "N" "Length" "Entropy" "Fibword")
(loop for i below 37
for n = (aref *fib* i) do
(format t "~2D ~10D ~17,15F ~A~%"
(1+ i) (length n) (entropy n) (string-or-dots n))) |
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.
| #BASIC | BASIC | FUNCTION checkNoSpaces (s$)
FOR i = 1 TO LEN(s$) - 1
IF MID$(s$, i, 1) = CHR$(32) OR MID$(s$, i, 1) = CHR$(9) THEN checkNoSpaces = 0
NEXT i
checkNoSpaces = 1
END FUNCTION
OPEN "input.fasta" FOR INPUT AS #1
first = 1
DO WHILE NOT EOF(1)
LINE INPUT #1, ln$
IF LEFT$(ln$, 1) = ">" THEN
IF NOT first THEN PRINT
PRINT MID$(ln$, 2); ": ";
IF first THEN first = 0
ELSEIF first THEN
PRINT : PRINT "Error : File does not begin with '>'"
EXIT DO
ELSE
IF checkNoSpaces(ln$) THEN
PRINT ln$;
ELSE
PRINT : PRINT "Error : Sequence contains space(s)"
EXIT DO
END IF
END IF
LOOP
CLOSE #1 |
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 | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.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) {
printf("%d", f.num);
if (f.denom != 1) {
printf("/%d", f.denom);
}
}
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 coeff, q;
int j, pwr, sign;
printf("%d : ", p);
q = makeFrac(1, p + 1);
sign = -1;
for (j = 0; j <= p; ++j) {
sign = -1 * sign;
coeff = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));
if (equalFrac(coeff, makeFrac(0, 1))) {
continue;
}
if (j == 0) {
if (!equalFrac(coeff, makeFrac(1, 1))) {
if (equalFrac(coeff, makeFrac(-1, 1))) {
printf("-");
} else {
printFrac(coeff);
}
}
} else {
if (equalFrac(coeff, makeFrac(1, 1))) {
printf(" + ");
} else if (equalFrac(coeff, makeFrac(-1, 1))) {
printf(" - ");
} else if (lessFrac(makeFrac(0, 1), coeff)) {
printf(" + ");
printFrac(coeff);
} else {
printf(" - ");
printFrac(negateFrac(coeff));
}
}
pwr = p + 1 - j;
if (pwr > 1) {
printf("n^%d", pwr);
} else {
printf("n");
}
}
printf("\n");
}
int main() {
int i;
for (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
| #jq | jq | # To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
def gcd(a; b):
# subfunction expects [a,b] as input
# i.e. a ~ .[0] and b ~ .[1]
def rgcd: if .[1] == 0 then .[0]
else [.[1], .[0] % .[1]] | rgcd
end;
[a,b] | rgcd;
# This is fast because the state of `until` is just a number
def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17
elif ($n % 19 == 0) then $n == 19
elif ($n % 23 == 0) then $n == 23
elif ($n % 29 == 0) then $n == 29
elif ($n % 31 == 0) then $n == 31
elif ($n % 37 == 0) then $n == 37
elif ($n % 41 == 0) then $n == 41
else 43
| until( (. * .) > $n or ($n % . == 0); . + 2)
| . * . > $n
end; |
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
| #Julia | Julia | using Primes
fermat(n) = BigInt(2)^(BigInt(2)^n) + 1
prettyprint(fdict) = replace(replace(string(fdict), r".+\(([^)]+)\)" => s"\1"), r"\=\>" => "^")
function factorfermats(max, nofactor=false)
for n in 0:max
fm = fermat(n)
if nofactor
println("Fermat number F($n) is $fm.")
continue
end
factors = factor(fm)
println("Fermat number F($n), $fm, ",
length(factors) < 2 ? "is prime." : "factors to $(prettyprint(factors)).")
end
end
factorfermats(9, true)
factorfermats(10)
|
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
| #ALGOL_68 | ALGOL 68 | # returns an array of the first required count elements of an a n-step fibonacci sequence #
# the initial values are taken from the init array #
PROC n step fibonacci sequence = ( []INT init, INT required count )[]INT:
BEGIN
[ 1 : required count ]INT result;
[]INT initial values = init[ AT 1 ];
INT step = UPB initial values;
# install the initial values #
FOR n TO step DO result[ n ] := initial values[ n ] OD;
# calculate the rest of the sequence #
FOR n FROM step + 1 TO required count DO
result[ n ] := 0;
FOR p FROM n - step TO n - 1 DO result[ n ] +:= result[ p ] OD
OD;
result
END; # required count #
# prints the elements of a sequence #
PROC print sequence = ( STRING legend, []INT sequence )VOID:
BEGIN
print( ( legend, ":" ) );
FOR e FROM LWB sequence TO UPB sequence DO print( ( " ", whole( sequence[ e ], 0 ) ) ) OD;
print( ( newline ) )
END; # print sequence #
# print some sequences #
print sequence( "fibonacci ", n step fibonacci sequence( ( 1, 1 ), 10 ) );
print sequence( "tribonacci ", n step fibonacci sequence( ( 1, 1, 2 ), 10 ) );
print sequence( "tetrabonacci", n step fibonacci sequence( ( 1, 1, 2, 4 ), 10 ) );
print sequence( "lucus ", n step fibonacci sequence( ( 2, 1 ), 10 ) )
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #J | J | Feigenbaum =: conjunction define NB. use: n Feigenbaum m
irange=: <. + i.@:>:@:|@:- NB. inclusive range
a=. 0 1
delta=. , 3.2
for_i. 3 irange n do.
tmp=. ({: + ({:delta) *inv ({: - _2&{)) a
for. i. m do.
'b bp'=. 0
for. i. 2 ^ <: i do.
'b bp'=. (tmp - *: b) , 1 _2 p. b * bp
end.
tmp=. tmp - b % bp
end.
a=. a , tmp
delta=. delta , %/@:(-/"1) (- 2 3 ,: 1 2) { a
end.
2 14j6 14j6 ": (#\ i. # delta) ,. (}. a) ,. delta
)
8 Feigenbaum 13
1 1.000000 3.200000
2 1.310703 3.218511
3 1.381547 4.385678
4 1.396945 4.600949
5 1.400253 4.655130
6 1.400962 4.666112
7 1.401114 4.668549
8 1.401146 4.669061
9 1.401153 4.669172
10 1.401155 4.669195
11 1.401155 4.669200
12 1.401155 4.669201
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Java | Java | public class Feigenbaum {
public static void main(String[] args) {
int max_it = 13;
int max_it_j = 10;
double a1 = 1.0;
double a2 = 0.0;
double d1 = 3.2;
double a;
System.out.println(" i d");
for (int i = 2; i <= max_it; i++) {
a = a1 + (a1 - a2) / d1;
for (int j = 0; j < max_it_j; j++) {
double x = 0.0;
double y = 0.0;
for (int k = 0; k < 1 << i; k++) {
y = 1.0 - 2.0 * y * x;
x = a - x * x;
}
a -= x / y;
}
double d = (a1 - a2) / (a - a1);
System.out.printf("%2d %.8f\n", i, d);
d1 = d;
a2 = a1;
a1 = a;
}
}
} |
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
| #PARI.2FGP | PARI/GP | lower(s)=
{
my(v=Vecsmall(s));
for(i=1,#v,
if(v[i]<91 && v[i]>64, v[i]+=32)
);
\\Strchr(v); \\ Use to return a string rather than a t_VECSMALL
v;
}
checkExt(ext, file)=
{
ext=apply(lower,ext);
my(v=lower(file),e);
for(i=1,#ext,
e=ext[i];
if(#v>#e && v[#v-#e+1..#v]==e && v[#v-#e]==46,
return(1)
)
);
}
ext=["txt","gz","bat","c","c++","exe","pdf"];
filenames=["c:","txt","text.txt","text.TXT","test.tar.gz","test/test2.exe","test","foo.c","foo.C","foo.C++","foo.c#","foo.zkl","document.pdf"];
select(f -> checkExt(ext, f), filenames) |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Nim | Nim | import os, strutils, times
if paramCount() == 0: quit(QuitSuccess)
let fileName = paramStr(1)
# Get and display last modification time.
var mtime = fileName.getLastModificationTime()
echo "File \"$1\" last modification time: $2".format(fileName, mtime.format("YYYY-MM-dd HH:mm:ss"))
# Change last modification time to current time.
fileName.setLastModificationTime(now().toTime()) |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Objeck | Objeck | use System.IO.File;
class Program {
function : Main(args : String[]) ~ Nil {
File->ModifiedTime("file_mod.obs")->ToString()->PrintLine();
}
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Objective-C | Objective-C | NSFileManager *fm = [NSFileManager defaultManager];
// Pre-OS X 10.5
NSLog(@"%@", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileModificationDate]);
[fm changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
atPath:@"input.txt"];
// OS X 10.5+
NSLog(@"%@", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileModificationDate]);
[fm setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
ofItemAtPath:@"input.txt" error:NULL]; |
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.)
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | (*note, this usage of Module allows us to memoize FibonacciWord
without exposing it to the global scope*)
Module[{FibonacciWord, step},
FibonacciWord[1] = "1";
FibonacciWord[2] = "0";
FibonacciWord[n_Integer?(# > 2 &)] :=
(FibonacciWord[n] = FibonacciWord[n - 1] <> FibonacciWord[n - 2]);
step["0", {_?EvenQ}] = N@RotationTransform[Pi/2];
step["0", {_?OddQ}] = N@RotationTransform[-Pi/2];
step[___] = Identity;
FibonacciFractal[n_] := Module[{steps, dirs},
steps = MapIndexed[step, Characters[FibonacciWord[n]]];
dirs = ComposeList[steps, {0, 1}];
Graphics[Line[FoldList[Plus, {0, 0}, dirs]]]]]; |
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.)
| #Nim | Nim | import imageman
const
Width = 1000
Height = 1000
LineColor = ColorRGBU [byte 64, 192, 96]
Output = "fibword.png"
proc fibword(n: int): string =
## Return the nth fibword.
var a = "1"
result = "0"
for _ in 1..n:
a = result & a
swap a, result
proc drawFractal(image: var Image; fw: string) =
# Draw the fractal.
var
x = 0
y = image.h - 1
dx = 1
dy = 0
for i, ch in fw:
let (nextx, nexty) = (x + dx, y + dy)
image.drawLine((x, y), (nextx, nexty), LineColor)
(x, y) = (nextx, nexty)
if ch == '0':
if (i and 1) == 0:
(dx, dy) = (dy, -dx)
else:
(dx, dy) = (-dy, dx)
#———————————————————————————————————————————————————————————————————————————————————————————————————
var image = initImage[ColorRGBU](Width, Height)
image.fill(ColorRGBU [byte 0, 0, 0])
image.drawFractal(fibword(23))
# Save into a PNG file.
image.savePNG(Output, compression = 9) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.