task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Find_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.
| #JavaScript | JavaScript |
function recurse(depth)
{
try
{
return recurse(depth + 1);
}
catch(ex)
{
return depth;
}
}
var maxRecursion = recurse(1);
document.write("Recursion depth on this system is " + maxRecursion); |
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.
| #Ring | Ring |
# Project: Find palindromic numbers in both binary and ternary bases
max = 6
nr = 0
pal = 0
see "working..." + nl
see "wait for done..." + nl
while true
binpal = basedigits(nr,2)
terpal = basedigits(nr,3)
bool1 = ispalindrome(binpal)
bool2 = ispalindrome(terpal)
if bool1 = 1 and bool2 = 1
pal = pal + 1
see string(nr) + " " + binpal + "(2) " + terpal + "(3)" + nl
if pal = max
exit
ok
ok
nr = nr + 1
end
see "done..." + nl
func basedigits(n,base)
if n = 0
return "0"
ok
result = ""
while n > 0
result = string(n % base) + result
n = floor(n/base)
end
return result
func ispalindrome(astring)
if astring = "0"
return 1
ok
bString = ""
for i=len(aString) to 1 step -1
bString = bString + aString[i]
next
if aString = bString
return 1
else
return 0
ok
|
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.
| #Ruby | Ruby | pal23 = Enumerator.new do |y|
y << 0
y << 1
for i in 1 .. 1.0/0.0 # 1.step do |i| (Ruby 2.1+)
n3 = i.to_s(3)
n = (n3 + "1" + n3.reverse).to_i(3)
n2 = n.to_s(2)
y << n if n2.size.odd? and n2 == n2.reverse
end
end
puts " decimal ternary binary"
6.times do |i|
n = pal23.next
puts "%2d: %12d %s %s" % [i, n, n.to_s(3).center(25), n.to_s(2).center(39)]
end |
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
| #Fennel | Fennel | (for [i 1 100]
(print (if (= (% i 15) 0) :FizzBuzz
(= (% i 3) 0) :Fizz
(= (% i 5) 0) :Buzz
i))) |
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.
| #Delphi | Delphi | program SizeOfFile;
{$APPTYPE CONSOLE}
uses SysUtils;
function CheckFileSize(const aFilename: string): Integer;
var
lFile: file of Byte;
begin
AssignFile(lFile, aFilename);
FileMode := 0; {Access file in read only mode}
Reset(lFile);
Result := FileSize(lFile);
CloseFile(lFile);
end;
begin
Writeln('input.txt ', CheckFileSize('input.txt'));
Writeln('\input.txt ', CheckFileSize('\input.txt'));
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.
| #E | E | for file in [<file:input.txt>, <file:///input.txt>] {
println(`The size of $file is ${file.length()} bytes.`)
} |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #BASIC | BASIC | OPEN "INPUT.TXT" FOR INPUT AS #1
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
LINE INPUT #1, DATA$
PRINT #2, DATA$
LOOP
CLOSE #1
CLOSE #2
SYSTEM |
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
| #Ada | Ada | with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO, Ada.Numerics.Long_Elementary_Functions,
Ada.Long_Float_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO, Ada.Numerics.Long_Elementary_Functions,
Ada.Long_Float_Text_IO;
procedure Fibonacci_Words is
function Entropy (S : Unbounded_String) return Long_Float is
CF : array (Character) of Natural := (others => 0);
Len : constant Natural := Length (S);
H : Long_Float := 0.0;
Ratio : Long_Float;
begin
for I in 1 .. Len loop
CF (Element (S, I)) := CF (Element (S, I)) + 1;
end loop;
for C in Character loop
Ratio := Long_Float (CF (C)) / Long_Float (Len);
if Ratio /= 0.0 then
H := H - Ratio * Log (Ratio, 2.0);
end if;
end loop;
return H;
end Entropy;
procedure Print_Line (Word : Unbounded_String; Number : Integer) is
begin
Put (Number, 4);
Put (Length (Word), 10);
Put (Entropy (Word), 2, 15, 0);
if Length (Word) < 35 then
Put (" " & Word);
end if;
New_Line;
end Print_Line;
First, Second, Result : Unbounded_String;
begin
Set_Col (4); Put ("N");
Set_Col (9); Put ("Length");
Set_Col (16); Put ("Entropy");
Set_Col (35); Put_Line ("Word");
First := To_Unbounded_String ("1");
Print_Line (First, 1);
Second := To_Unbounded_String ("0");
Print_Line (Second, 2);
for N in 3 .. 37 loop
Result := Second & First;
Print_Line (Result, N);
First := Second;
Second := Result;
end loop;
end Fibonacci_Words;
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
procedure feigenbaum is
subtype i_range is Integer range 2 .. 13;
subtype j_range is Integer range 1 .. 10;
-- the number of digits in type Real is reduced to 15 to produce the
-- results reported by C, C++, C# and Ring. Increasing the number of
-- digits in type Real produces the results reported by D.
type Real is digits 15;
package Real_Io is new Float_IO (Real);
use Real_Io;
a, x, y, d : Real;
a1 : Real := 1.0;
a2 : Real := 0.0;
d1 : Real := 3.2;
begin
Put_Line (" i d");
for i in i_range loop
a := a1 + (a1 - a2) / d1;
for j in j_range loop
x := 0.0;
y := 0.0;
for k in 1 .. 2**i loop
y := 1.0 - 2.0 * x * y;
x := a - x * x;
end loop;
a := a - x / y;
end loop;
d := (a1 - a2) / (a - a1);
Put (Item => i, Width => 2);
Put (Item => d, Fore => 5, Aft => 8, Exp => 0);
New_Line;
d1 := d;
a2 := a1;
a1 := a;
end loop;
end feigenbaum;
begin
feigenbaum;
end Main;
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #ALGOL_68 | ALGOL 68 | # Calculate the Feigenbaum constant #
print( ( "Feigenbaum constant calculation:", newline ) );
INT max it = 13;
INT max it j = 10;
REAL a1 := 1.0;
REAL a2 := 0.0;
REAL d1 := 3.2;
print( ( "i ", "d", newline ) );
FOR i FROM 2 TO max it DO
REAL a := a1 + (a1 - a2) / d1;
FOR j TO max it j DO
REAL x := 0;
REAL y := 0;
FOR k TO 2 ^ i DO
y := 1 - 2 * y * x;
x := a - x * x
OD;
a := a - x / y
OD;
REAL d = (a1 - a2) / (a - a1);
IF i < 10 THEN
print( ( whole( i, 0 ), " ", fixed( d, -10, 8 ), newline ) )
ELSE
print( ( whole( i, 0 ), " ", fixed( d, -10, 8 ), newline ) )
FI;
d1 := d;
a2 := a1;
a1 := a
OD |
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
| #Factor | Factor | USING: formatting kernel qw sequences splitting unicode ;
IN: rosetta-code.file-extension-list
CONSTANT: extensions qw{ zip rar 7z gz archive A## tar.bz2 }
CONSTANT: filenames qw{
MyData.a## MyData.tar.Gz MyData.gzip MyData.7z.backup
MyData... MyData MyData_v1.0.tar.bz2 MyData_v1.0.bz2
}
: ext-in-list? ( filename list -- ? )
[ >lower "." split ] dup [ map ] curry bi*
[ tail? t = ] with find nip >boolean ;
extensions "List of file extensions: %[%s, %]\n\n" printf
"File extension in extensions list?\n" printf
filenames [
dup extensions ext-in-list? "%19s %u\n" printf
] each |
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
| #Fortran | Fortran | IT = ICHAR(TEXT(I:I)) - ICHAR("a") !More symbols precede "a" than "A".
IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A")) !In a-z? Convert! |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Haskell | Haskell | import System.Posix.Files
import System.Posix.Time
do status <- getFileStatus filename
let atime = accessTime status
mtime = modificationTime status -- seconds since the epoch
curTime <- epochTime
setFileTimes filename atime curTime -- keep atime unchanged
-- set mtime to current time |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #HicEst | HicEst | CHARACTER timestamp*18
timestamp = ' ' ! blank timestamp will read:
SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp) ! 20100320141940.525
timestamp = '19991231235950' ! set timestamp to Millenium - 10 seconds
SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp) |
http://rosettacode.org/wiki/File_size_distribution | File size distribution | Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.
Don't forget that empty files may exist, to serve as a marker.
Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
| #zkl | zkl | pipe:=Thread.Pipe();
// hoover all files in tree, don't return directories
fcn(pipe,dir){ File.globular(dir,"*",True,8,pipe); }
.launch(pipe,vm.arglist[0]); // thread
dist,N,SZ,maxd:=List.createLong(50,0),0,0,0;
foreach fnm in (pipe){
sz,szd:=File.len(fnm), sz.numDigits;
dist[szd]+=1;
N+=1; SZ+=sz; maxd=maxd.max(szd);
}
println("Found %d files, %,d bytes, %,d mean.".fmt(N,SZ,SZ/N));
scale:=50.0/(0.0).max(dist);
szchrs,idx,comma:=",nnn"*20, -1, Walker.cycle(0,0,1).next;
println("%15s %s (* = %.2f)".fmt("File size","Number of files",1.0/scale));
foreach sz,cnt in ([0..].zip(dist[0,maxd])){
println("%15s : %s".fmt(szchrs[idx,*], "*"*(scale*cnt).round().toInt()));
idx-=1 + comma();
} |
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.)
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"github.com/fogleman/gg"
"strings"
)
func wordFractal(i int) string {
if i < 2 {
if i == 1 {
return "1"
}
return ""
}
var f1 strings.Builder
f1.WriteString("1")
var f2 strings.Builder
f2.WriteString("0")
for j := i - 2; j >= 1; j-- {
tmp := f2.String()
f2.WriteString(f1.String())
f1.Reset()
f1.WriteString(tmp)
}
return f2.String()
}
func draw(dc *gg.Context, x, y, dx, dy float64, wf string) {
for i, c := range wf {
dc.DrawLine(x, y, x+dx, y+dy)
x += dx
y += dy
if c == '0' {
tx := dx
dx = dy
if i%2 == 0 {
dx = -dy
}
dy = -tx
if i%2 == 0 {
dy = tx
}
}
}
}
func main() {
dc := gg.NewContext(450, 620)
dc.SetRGB(0, 0, 0)
dc.Clear()
wf := wordFractal(23)
draw(dc, 20, 20, 1, 0, wf)
dc.SetRGB(0, 1, 0)
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("fib_wordfractal.png")
} |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import (
"fmt"
"os"
"path"
)
func CommonPrefix(sep byte, paths ...string) string {
// Handle special cases.
switch len(paths) {
case 0:
return ""
case 1:
return path.Clean(paths[0])
}
// Note, we treat string as []byte, not []rune as is often
// done in Go. (And sep as byte, not rune). This is because
// most/all supported OS' treat paths as string of non-zero
// bytes. A filename may be displayed as a sequence of Unicode
// runes (typically encoded as UTF-8) but paths are
// not required to be valid UTF-8 or in any normalized form
// (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different
// file names.
c := []byte(path.Clean(paths[0]))
// We add a trailing sep to handle the case where the
// common prefix directory is included in the path list
// (e.g. /home/user1, /home/user1/foo, /home/user1/bar).
// path.Clean will have cleaned off trailing / separators with
// the exception of the root directory, "/" (in which case we
// make it "//", but this will get fixed up to "/" bellow).
c = append(c, sep)
// Ignore the first path since it's already in c
for _, v := range paths[1:] {
// Clean up each path before testing it
v = path.Clean(v) + string(sep)
// Find the first non-common byte and truncate c
if len(v) < len(c) {
c = c[:len(v)]
}
for i := 0; i < len(c); i++ {
if v[i] != c[i] {
c = c[:i]
break
}
}
}
// Remove trailing non-separator characters and the final separator
for i := len(c) - 1; i >= 0; i-- {
if c[i] == sep {
c = c[:i]
break
}
}
return string(c)
}
func main() {
c := CommonPrefix(os.PathSeparator,
//"/home/user1/tmp",
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members",
"/home//user1/tmp/coventry",
"/home/user1/././tmp/covertly/foo",
"/home/bob/../user1/tmp/coved/bar",
)
if c == "" {
fmt.Println("No common path")
} else {
fmt.Println("Common path:", c)
}
} |
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.
| #AWK | AWK | $ awk 'BEGIN{split("1 2 3 4 5 6 7 8 9",a);for(i in a)if(!(a[i]%2))r=r" "a[i];print r}' |
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle | Find if a point is within a triangle | Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
| #XPL0 | XPL0 | func real Dot(W,X,Y,Z); \Return the dot product of two 2D vectors
real W,X,Y,Z; \ (W-X) dot (Y-Z)
real WX(2), YZ(2);
[WX(0):= W(0)-X(0); WX(1):= W(1)-X(1);
YZ(0):= Y(0)-Z(0); YZ(1):= Y(1)-Z(1);
return WX(0)*YZ(0) + WX(1)*YZ(1);
];
real A,B,C; \triangle
func PointInTri(P); \Return 'true' if point P is inside triangle ABC
real P;
int S0,S1,S2; \signs
[S0:= Dot(P,A,B,A) >= 0.0;
S1:= Dot(P,B,C,B) >= 0.0;
S2:= Dot(P,C,A,C) >= 0.0;
return S0=S1 & S1=S2 & S2=S0;
];
[A:= [10.5, 6.3]; B:= [13.5, 3.6]; C:= [ 3.3, -1.6];
Text(0, if PointInTri([10.0, 3.0]) then "inside" else "outside"); CrLf(0);
Text(0, if PointInTri([-5.0,-2.2]) then "inside" else "outside"); CrLf(0);
Text(0, if PointInTri([10.5, 6.3]) then "inside" else "outside"); CrLf(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.
| #jq | jq | def zero_arity:
if (. % 1000000 == 0) then . else empty end, ((.+1)| zero_arity);
1|zero_arity |
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.
| #Julia | Julia |
function divedivedive(d::Int)
try
divedivedive(d+1)
catch
return d
end
end
|
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.
| #Scala | Scala | import scala.annotation.tailrec
import scala.compat.Platform.currentTime
object Palindrome23 extends App {
private val executionStartTime = currentTime
private val st: Stream[(Int, Long)] = (0, 1L) #:: st.map(xs => nextPalin3(xs._1))
@tailrec
private def nextPalin3(n: Int): (Int, Long) = {
@inline
def isPali2(i: BigInt): Boolean = {
val s = i.toString(2)
if ((s.length & 1) == 0) false else s == s.reverse
}
def palin3(i: BigInt): Long = {
val n3 = i.toString(3)
java.lang.Long.parseLong(n3 + "1" + n3.reverse, 3)
}
val actual: Long = palin3(n)
if (isPali2(actual)) (n + 1, actual) else nextPalin3(n + 1)
}
println(f"${"Decimal"}%18s${"Binary"}%35s${"Ternary"}%51s")
(Stream(0L) ++ st.map(_._2)).take(6).foreach(n => {
val bigN = BigInt(n)
val (bin, ter) = (bigN.toString(2), bigN.toString(3))
println(f"${n}%18d, ${
bin + " " * ((60 - bin.length) / 2)}%60s, ${
ter + " " * ((37 - ter.length) / 2)}%37s")
})
println(s"Successfully completed without errors. [total ${currentTime - executionStartTime} ms]")
} |
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
| #FOCAL | FOCAL | 01.10 FOR I=1,100; DO 2.0
01.20 QUIT
02.10 SET ZB=I/15 - FITR(I/15)
02.20 IF (ZB) 2.4, 2.3, 2.4
02.30 TYPE "FizzBuzz" !
02.35 RETURN
02.40 SET Z=I/3 - FITR(I/3)
02.50 IF (Z) 2.7, 2.6, 2.7
02.60 TYPE "Fizz" !
02.65 RETURN
02.70 SET B=I/5 - FITR(I/5)
02.80 IF (B) 2.99, 2.9, 2.99
02.90 TYPE "Buzz" !
02.95 RETURN
02.99 TYPE %3, I, ! |
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.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
create input_file.make_open_read ("input.txt")
print(input_file.count)
print("%N")
input_file.close
create environment
input_file.make_open_read(environment.root_directory_name + "input.txt")
print(input_file.count)
input_file.close
end
feature -- Access
input_file: PLAIN_TEXT_FILE
environment:EXECUTION_ENVIRONMENT
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.
| #Elena | Elena | import system'io;
import extensions;
public program()
{
console.printLine(File.assign("input.txt").Length);
console.printLine(File.assign("\input.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.
| #Batch_File | Batch File | 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
| #Aime | Aime | real
entropy(data b)
{
integer count, i;
real ones, zeros;
ones = zeros = 0;
i = -(count = ~b);
while (i) {
if (b[i] == '0') {
zeros += 1;
} else {
ones += 1;
}
i += 1;
}
return -(ones /= count) * log2(ones) - (zeros /= count) * log2(zeros);
}
integer
main(void)
{
data a, b;
integer i;
a = "1";
b = "0";
o_form("%2d %9d /w12p10d10/ ~\n", 1, ~a, 0r, a);
o_form("%2d %9d /w12p10d10/ ~\n", 2, ~b, 0r, b);
i = 3;
while (i <= 37) {
bu_copy(a, 0, b);
o_form("%2d %9d /w12p10d10/ ~\n", i, ~a, entropy(a),
i < 10 ? a.string : "");
i += 1;
b.swap(a);
}
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
| #ALGOL_68 | ALGOL 68 | # calculate some details of "Fibonacci Words" #
# fibonacci word 1 = "1" #
# fibonacci word 2 = "0" #
# 3 = word 2 cat word 1 = "01" #
# n = word n-1 cat word n-2 #
# note the words contain only the characters "0" and "1" #
# also #
# C(word n) = C(word n-1) + C(word n-2) #
# where C(x) = the number of characters in x #
# Similarly, #
# C0(word n) = C0(word n-1) + C0(word n-2) #
# and C1(word n) = C1(word n-1) + C1(word n-2) #
# where C0(x) = the number of "0"s in x and #
# C1(x) = the number of "1"s in x #
# we therefore don't have to calculate the words themselves #
# prints the statistics for the fibonacci words from 1 to max number #
PROC print fibonacci word stats = ( INT max number )VOID:
BEGIN
# prints some statistics for a fibonacci word: #
# the word number, its length and its entropy #
PROC print one words stats = ( INT word
, INT zeros
, INT ones
)VOID:
BEGIN
REAL probability := 0;
REAL entropy := 0;
INT word length = zeros + ones;
IF zeros > 0
THEN
# the word contains some zeros #
probability := zeros / word length;
entropy -:= probability * log( probability )
FI;
IF ones > 0
THEN
# the word contains some ones #
probability := ones / word length;
entropy -:= probability * log( probability )
FI;
# we want entropy in bits so convert to log base 2 #
entropy /:= log( 2 );
print( ( ( whole( word, -5 )
+ " "
+ whole( word length, -12 )
+ " "
+ fixed( entropy, -8, 4 )
)
, newline
)
)
END; # print one words stats #
INT zeros one = 0; # number of zeros in word 1 #
INT ones one = 1; # number of ones in word 1 #
INT zeros two = 1; # number of zeros in word 2 #
INT ones two = 0; # number of ones in word 2 #
print( ( " word length entropy", newline ) );
IF max number > 0
THEN
# we want at least one number's statistics #
print one words stats( 1, zeros one, ones one );
IF max number > 1
THEN
# we want at least 2 number's statistics #
print one words stats( 2, zeros two, ones two );
IF max number > 2
THEN
# we want more statistics #
INT zeros n minus 1 := zeros two;
INT ones n minus 1 := ones two;
INT zeros n minus 2 := zeros one;
INT ones n minus 2 := ones one;
FOR word FROM 3 TO max number DO
INT zeros n := zeros n minus 1 + zeros n minus 2;
INT ones n := ones n minus 1 + ones n minus 2;
print one words stats( word, zeros n, ones n );
zeros n minus 2 := zeros n minus 1;
ones n minus 2 := ones n minus 1;
zeros n minus 1 := zeros n;
ones n minus 1 := ones n
OD
FI
FI
FI
END; # print fibonacci word stats #
main:
(
# print the statistics for the first 37 fibonacci words #
print fibonacci word stats( 37 )
)
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #AWK | AWK |
# syntax: GAWK -f FEIGENBAUM_CONSTANT_CALCULATION.AWK
BEGIN {
a1 = 1
a2 = 0
d1 = 3.2
max_i = 13
max_j = 10
print(" i d")
for (i=2; i<=max_i; i++) {
a = a1 + (a1 - a2) / d1
for (j=1; j<=max_j; j++) {
x = y = 0
for (k=1; k<=2^i; k++) {
y = 1 - 2 * y * x
x = a - x * x
}
a -= x / y
}
d = (a1 - a2) / (a - a1)
printf("%2d %.8f\n",i,d)
d1 = d
a2 = a1
a1 = a
}
exit(0)
}
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #BASIC | BASIC | maxIt = 13 : maxItj = 13
a1 = 1.0 : a2 = 0.0 : d = 0.0 : 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.0 : y = 0.0
for k = 1 to 2 ^ i
y = 1 - 2 * y * x
x = a - x * x
next k
a -= x / y
next j
d = (a1 - a2) / (a - a1)
print rjust(i,3); chr(9); ljust(d,13,"0")
d1 = d
a2 = a1
a1 = a
next i |
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
| #Go | Go | package main
import (
"fmt"
"strings"
)
var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}
func fileExtInList(filename string) (bool, string) {
filename2 := strings.ToLower(filename)
for _, ext := range extensions {
ext2 := "." + strings.ToLower(ext)
if strings.HasSuffix(filename2, ext2) {
return true, ext
}
}
s := strings.Split(filename, ".")
if len(s) > 1 {
t := s[len(s)-1]
if t != "" {
return false, t
} else {
return false, "<empty>"
}
} else {
return false, "<none>"
}
}
func main() {
fmt.Println("The listed extensions are:")
fmt.Println(extensions, "\n")
tests := []string{
"MyData.a##", "MyData.tar.Gz", "MyData.gzip",
"MyData.7z.backup", "MyData...", "MyData",
"MyData_v1.0.tar.bz2", "MyData_v1.0.bz2",
}
for _, test := range tests {
ok, ext := fileExtInList(test)
fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext)
}
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Icon_and_Unicon | Icon and Unicon |
every dir := !["./","/"] do {
if i := stat(f := dir || "input.txt") then {
write("info for ",f ," mtime= ",ctime(i.mtime),", atime=",ctime(i.ctime), ", atime=",ctime(i.atime))
utime(f,i.atime,i.mtime-1024)
i := stat(f)
write("update for ",f ," mtime= ",ctime(i.mtime),", atime=",ctime(i.ctime), ", atime=",ctime(i.atime))
}
else stop("failure to stat ",f)
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #J | J | load 'files'
fstamp 'input.txt'
2009 8 24 20 34 30 |
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.)
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"strings"
)
func wordFractal(i int) string {
if i < 2 {
if i == 1 {
return "1"
}
return ""
}
var f1 strings.Builder
f1.WriteString("1")
var f2 strings.Builder
f2.WriteString("0")
for j := i - 2; j >= 1; j-- {
tmp := f2.String()
f2.WriteString(f1.String())
f1.Reset()
f1.WriteString(tmp)
}
return f2.String()
}
func draw(dc *gg.Context, x, y, dx, dy float64, wf string) {
for i, c := range wf {
dc.DrawLine(x, y, x+dx, y+dy)
x += dx
y += dy
if c == '0' {
tx := dx
dx = dy
if i%2 == 0 {
dx = -dy
}
dy = -tx
if i%2 == 0 {
dy = tx
}
}
}
}
func main() {
dc := gg.NewContext(450, 620)
dc.SetRGB(0, 0, 0)
dc.Clear()
wf := wordFractal(23)
draw(dc, 20, 20, 1, 0, wf)
dc.SetRGB(0, 1, 0)
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("fib_wordfractal.png")
} |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Groovy | Groovy | def commonPath = { delim, Object[] paths ->
def pathParts = paths.collect { it.split(delim) }
pathParts.transpose().inject([match:true, commonParts:[]]) { aggregator, part ->
aggregator.match = aggregator.match && part.every { it == part [0] }
if (aggregator.match) { aggregator.commonParts << part[0] }
aggregator
}.commonParts.join(delim)
} |
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.
| #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
set numberarray=1 2 3 4 5 6 7 8 9 10
for %%i in (%numberarray%) do (
set /a tempcount+=1
set numberarray!tempcount!=%%i
)
echo Filtering all even numbers from numberarray into newarray...
call:filternew numberarray
echo numberarray - %numberarray%
echo newarray -%newarray%
echo.
echo Filtering numberarray so that only even entries remain...
call:filterdestroy numberarray
echo numberarray -%numberarray%
pause>nul
exit /b
:filternew
set arrayname=%1
call:arraylength %arrayname%
set tempcount=0
for /l %%i in (1,1,%length%) do (
set /a cond=!%arrayname%%%i! %% 2
if !cond!==0 (
set /a tempcount+=1
set newarray!tempcount!=!%arrayname%%%i!
set newarray=!newarray! !%arrayname%%%i!
)
)
exit /b
:filterdestroy
set arrayname=%1
call:arraylength %arrayname%
set tempcount=0
set "%arrayname%="
for /l %%i in (1,1,%length%) do (
set /a cond=!%arrayname%%%i! %% 2
if !cond!==0 (
set /a tempcount+=1
set %arrayname%!tempcount!=!%arrayname%%%i!
set %arrayname%=!%arrayname%! !%arrayname%%%i!
)
)
exit /b
:arraylength
set tempcount=0
set lengthname=%1
set length=0
:lengthloop
set /a tempcount+=1
if "!%lengthname%%tempcount%!"=="" exit /b
set /a length+=1
goto lengthloop
|
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.
| #Kotlin | Kotlin | // version 1.1.2
fun recurse(i: Int) {
try {
recurse(i + 1)
}
catch(e: StackOverflowError) {
println("Limit of recursion is $i")
}
}
fun main(args: Array<String>) = recurse(0) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Liberty_BASIC | Liberty BASIC |
'subroutine recursion limit- end up on 475000
call test 1
sub test n
if n mod 1000 = 0 then locate 1,1: print n
call test n+1
end sub
|
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.
| #Scheme | Scheme | (import (scheme base)
(scheme write)
(srfi 1 lists)) ; use 'fold' from SRFI 1
;; convert number to a list of digits, in desired base
(define (r-number->list n base)
(let loop ((res '())
(num n))
(if (< num base)
(cons num res)
(loop (cons (remainder num base) res)
(quotient num base)))))
;; convert number to string, in desired base
(define (r-number->string n base)
(apply string-append
(map number->string
(r-number->list n base))))
;; test if a list of digits is a palindrome
(define (palindrome? lst)
(equal? lst (reverse lst)))
;; based on Perl/Ruby's insight
;; -- construct the ternary palindromes in order
;; using fact that their central number is always a 1
;; -- convert into binary, and test if result is a palindrome too
(define (get-series size)
(let loop ((results '(1 0))
(i 1))
(if (= size (length results))
(reverse results)
(let* ((n3 (r-number->list i 3))
(n3-list (append n3 (list 1) (reverse n3)))
(n10 (fold (lambda (d t) (+ d (* 3 t))) 0 n3-list))
(n2 (r-number->list n10 2)))
(loop (if (palindrome? n2)
(cons n10 results)
results)
(+ 1 i))))))
;; display final results, in bases 10, 2 and 3.
(for-each
(lambda (n)
(display
(string-append (number->string n)
" in base 2: "
(r-number->string n 2)
" in base 3: "
(r-number->string n 3)))
(newline))
(get-series 6)) |
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
| #Fermat | Fermat |
for i = 1 to 100 do if i|15=0 then !'FizzBuzz ' else if i|5=0 then !'Buzz ' else if i|3=0 then !'Fizz ' else !i;!' ' fi fi fi od |
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.
| #Elixir | Elixir | IO.puts File.stat!("input.txt").size
IO.puts File.stat!("/input.txt").size |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Emacs_Lisp | Emacs Lisp | (message "sizes are %s and %s"
(nth 7 (file-attributes "input.txt"))
(nth 7 (file-attributes "/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.
| #Erlang | Erlang | -module(file_size).
-export([file_size/0]).
-include_lib("kernel/include/file.hrl").
file_size() ->
print_file_size("input.txt"),
print_file_size("/input.txt").
print_file_size(Filename) ->
case file:read_file_info(Filename) of
{ok, FileInfo} ->
io:format("~s ~p~n", [Filename, FileInfo#file_info.size]);
{error, _} ->
io:format("~s could not be opened~n",[Filename])
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.
| #BBC_BASIC | BBC BASIC | *COPY input.txt output.txt |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #BCPL | BCPL | GET "libhdr"
LET start() BE $(
// Attempt to open the named files.
LET source = findinput("input.txt")
LET destination = findoutput("output.txt")
TEST source = 0 THEN
writes("Unable to open input.txt*N")
ELSE TEST destination = 0 THEN
writes("Unable to open output.txt*N")
ELSE $(
// The current character, initially unknown.
LET ch = ?
// Make the open files the current input and output streams.
selectinput(source)
selectoutput(destination)
// Copy the input to the output character by character until
// endstreamch is returned to indicate input is exhausted.
ch := rdch()
UNTIL ch = endstreamch DO $(
wrch(ch)
ch := rdch()
$)
// Close the currently selected streams.
endread()
endwrite()
$)
$) |
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
| #APL | APL |
F_WORD←{{⍵,,/⌽¯2↑⍵}⍣(0⌈⍺-2),¨⍵}
ENTROPY←{-+/R×2⍟R←(+⌿⍵∘.=∪⍵)÷⍴⍵}
FORMAT←{'N' 'LENGTH' 'ENTROPY'⍪(⍳⍵),↑{(⍴⍵),ENTROPY ⍵}¨⍵ F_WORD 1 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
| #Arturo | Arturo | entropy: function [s][
if 1 >= size s -> return 0.0
strlen: to :floating size s
count0: to :floating size match s "0"
count1: strlen - count0
return neg add (count0/strlen) * log count0/strlen 2 (count1/strlen) * log count1/strlen 2
]
fibwords: function [n][
x: 0
a: "1"
b: "0"
result: @[a b]
while [x<n][
a: b ++ a
tmp: b
b: a
a: tmp
result: result ++ b
x: x+1
]
return result
]
loop.with:'i fibwords 37 'w [
print [
pad to :string i+1 4
pad to :string size w 10
pad to :string entropy w 20
]
] |
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
| #Arturo | Arturo | nPowers: [1 2 4 8 16 32 64 128 256 512]
fermatSet: map 0..9 'x -> 1 + 2 ^ nPowers\[x]
loop 0..9 'i ->
print ["F(" i ") =" fermatSet\[i]]
print ""
loop 0..9 'i ->
print ["Prime factors of F(" i ") =" factors.prime fermatSet\[i]] |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #C | C | #include <stdio.h>
void feigenbaum() {
int i, j, k, max_it = 13, max_it_j = 10;
double a, x, y, d, a1 = 1.0, a2 = 0.0, d1 = 3.2;
printf(" i d\n");
for (i = 2; i <= max_it; ++i) {
a = a1 + (a1 - a2) / d1;
for (j = 1; j <= max_it_j; ++j) {
x = 0.0;
y = 0.0;
for (k = 1; k <= 1 << i; ++k) {
y = 1.0 - 2.0 * y * x;
x = a - x * x;
}
a -= x / y;
}
d = (a1 - a2) / (a - a1);
printf("%2d %.8f\n", i, d);
d1 = d;
a2 = a1;
a1 = a;
}
}
int main() {
feigenbaum();
return 0;
} |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #C.23 | C# | using System;
namespace FeigenbaumConstant {
class Program {
static void Main(string[] args) {
var maxIt = 13;
var maxItJ = 10;
var a1 = 1.0;
var a2 = 0.0;
var d1 = 3.2;
Console.WriteLine(" i d");
for (int i = 2; i <= maxIt; i++) {
var a = a1 + (a1 - a2) / d1;
for (int j = 1; j <= maxItJ; j++) {
var x = 0.0;
var y = 0.0;
for (int k = 1; k <= 1<<i; k++) {
y = 1.0 - 2.0 * y * x;
x = a - x * x;
}
a -= x / y;
}
var d = (a1 - a2) / (a - a1);
Console.WriteLine("{0,2:d} {1:f8}", 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
| #Haskell | Haskell | import Data.List
import qualified Data.Char as Ch
toLower :: String -> String
toLower = map Ch.toLower
isExt :: String -> [String] -> Bool
isExt filename extensions = any (`elem` (tails . toLower $ filename)) $ map toLower 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
| #J | J | isSuffix=: -~&# = {:@I.@E.
isExt=: ('.'&,&.>@[ ([: +./ isSuffix&(tolower@>)/) boxopen@]) |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Java | Java | import java.io.File;
import java.util.Date;
public class FileModificationTimeTest {
public static void test(String type, File file) {
long t = file.lastModified();
System.out.println("The following " + type + " called " + file.getPath() +
(t == 0 ? " does not exist." : " was modified at " + new Date(t).toString() )
);
System.out.println("The following " + type + " called " + file.getPath() +
(!file.setLastModified(System.currentTimeMillis()) ? " does not exist." : " was modified to current time." )
);
System.out.println("The following " + type + " called " + file.getPath() +
(!file.setLastModified(t) ? " does not exist." : " was modified to previous time." )
);
}
public static void main(String args[]) {
test("file", new File("output.txt"));
test("directory", new File("docs"));
}
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.GetFile('input.txt');
var mtime = f.DateLastModified; |
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.)
| #Icon_and_Unicon | Icon and Unicon | global width, height
procedure main(A)
n := integer(A[1]) | 25 # F_word to use
sl := integer(A[2]) | 1 # Segment length
width := integer(A[3]) | 1050 # Width of plot area
height := integer(A[4]) | 1050 # Height of plot area
w := fword(n)
drawFractal(n,w,sl)
end
procedure fword(n)
static fcache
initial fcache := table()
/fcache[n] := case n of {
1: "1"
2: "0"
default: fword(n-1)||fword(n-2)
}
return fcache[n]
end
record loc(x,y)
procedure drawFractal(n,w,sl)
static lTurn, rTurn
initial {
every (lTurn|rTurn) := table()
lTurn["north"] := "west"; lTurn["west"] := "south"
lTurn["south"] := "east"; lTurn["east"] := "north"
rTurn["north"] := "east"; rTurn["east"] := "south"
rTurn["south"] := "west"; rTurn["west"] := "north"
}
wparms := ["FibFractal "||n,"g","bg=white","canvas=normal",
"fg=black","size="||width||","||height,"dx=10","dy=10"]
&window := open!wparms | stop("Unable to open window")
p := loc(10,10)
d := "north"
every i := 1 to *w do {
p := draw(p,d,sl)
if w[i] == "0" then d := if i%2 = 0 then lTurn[d] else rTurn[d]
}
until Event() == &lpress
WriteImage("FibFract"||n||".png")
close(&window)
end
procedure draw(p,d,sl)
if d == "north" then p1 := loc(p.x,p.y+sl)
else if d == "south" then p1 := loc(p.x,p.y-sl)
else if d == "east" then p1 := loc(p.x+sl,p.y)
else p1 := loc(p.x-sl,p.y)
DrawLine(p.x,p.y, p1.x,p1.y)
return p1
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
| #GW-BASIC | GW-BASIC | 10 REM All GOTO statements can be replaced with EXIT FOR in newer BASICs.
110 X$ = "/home/user1/tmp/coverage/test"
120 Y$ = "/home/user1/tmp/covert/operator"
130 Z$ = "/home/user1/tmp/coven/members"
150 A = LEN(X$)
160 IF A > LEN(Y$) THEN A = LEN(Y$)
170 IF A > LEN(Z$) THEN A = LEN(Z$)
180 FOR L0 = 1 TO A
190 IF MID$(X$, L0, 1) <> MID$(Y$, L0, 1) THEN GOTO 210
200 NEXT
210 A = L0 - 1
230 FOR L0 = 1 TO A
240 IF MID$(X$, L0, 1) <> MID$(Z$, L0, 1) THEN GOTO 260
250 NEXT
260 A = L0 - 1
280 IF MID$(X$, L0, 1) <> "/" THEN
290 FOR L0 = A TO 1 STEP -1
300 IF "/" = MID$(X$, L0, 1) THEN GOTO 340
310 NEXT
320 END IF
340 REM Task description says no trailing slash, so...
350 A = L0 - 1
360 P$ = LEFT$(X$, A)
370 PRINT "Common path is '"; P$; "'" |
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.
| #BBC_BASIC | BBC BASIC | REM Create the test array:
items% = 1000
DIM array%(items%)
FOR index% = 1 TO items%
array%(index%) = RND
NEXT
REM Count the number of filtered items:
filtered% = 0
FOR index% = 1 TO items%
IF FNfilter(array%(index%)) filtered% += 1
NEXT
REM Create a new array containing the filtered items:
DIM new%(filtered%)
filtered% = 0
FOR index% = 1 TO items%
IF FNfilter(array%(index%)) THEN
filtered% += 1
new%(filtered%) = array%(index%)
ENDIF
NEXT
REM Alternatively modify the original array:
filtered% = 0
FOR index% = 1 TO items%
IF FNfilter(array%(index%)) THEN
filtered% += 1
array%(filtered%) = array%(index%)
ENDIF
NEXT
END
DEF FNfilter(A%) = ((A% AND 1) = 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.
| #LIL | LIL | /* Enable limiting recursive calls to lil_parse - this can be used to avoid call stack
* overflows and is also useful when running through an automated fuzzer like AFL */
/*#define LIL_ENABLE_RECLIMIT 10000*/ |
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.
| #Logo | Logo | make "depth 0
to recurse
make "depth :depth + 1
recurse
end
catch "ERROR [recurse]
; hit control-C after waiting a while
print error ; 16 Stopping... recurse [make "depth :depth + 1]
(print [Depth reached:] :depth) ; some arbitrarily large number |
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.
| #Sidef | Sidef | var format = "%11s %24s %38s\n"
format.printf("decimal", "ternary", "binary")
format.printf(0, 0, 0)
for n in (0 .. 2e5) {
var pal = n.base(3)||''
var b3 = (pal + '1' + pal.flip)
var b2 = Num(b3, 3).base(2)
if (b2 == b2.flip) {
format.printf(Num(b2, 2), b3, b2)
}
} |
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.
| #Swift | Swift | import Foundation
func isPalin2(n: Int) -> Bool {
var x = 0
var n = n
guard n & 1 != 0 else {
return n == 0
}
while x < n {
x = x << 1 | n & 1
n >>= 1
}
return n == x || n == x >> 1
}
func reverse3(n: Int) -> Int {
var x = 0
var n = n
while n > 0 {
x = x * 3 + (n % 3)
n /= 3
}
return x
}
func printN(_ n: Int, base: Int) {
var n = n
print(" ", terminator: "")
repeat {
print("\(n % base)", terminator: "")
n /= base
} while n > 0
print("(\(base))", terminator: "")
}
func show(n: Int) {
print(n, terminator: "")
printN(n, base: 2)
printN(n, base: 3)
print()
}
private var count = 0
private var lo = 0
private var (hi, pow2, pow3) = (1, 1, 1)
show(n: 0)
while true {
var n: Int
for i in lo..<hi {
n = (i * 3 + 1) * pow3 + reverse3(n: i)
guard isPalin2(n: n) else {
continue
}
show(n: n)
count += 1
guard count < 7 else {
exit(0)
}
}
if hi == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
while true {
while pow2 <= pow3 {
pow2 *= 4
}
let lo2 = (pow2 / pow3 - 1) / 3
let hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1
let lo3 = pow3 / 3
let hi3 = pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(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
| #Forth | Forth | : fizz ( n -- ) drop ." Fizz" ;
: buzz ( n -- ) drop ." Buzz" ;
: fb ( n -- ) drop ." FizzBuzz" ;
: vector create does> ( n -- )
over 15 mod cells + @ execute ;
vector .fizzbuzz
' fb , ' . , ' . ,
' fizz , ' . , ' buzz ,
' fizz , ' . , ' . ,
' fizz , ' buzz , ' . ,
' fizz , ' . , ' . , |
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.
| #Euphoria | Euphoria | include file.e
function file_size(sequence file_name)
object x
x = dir(file_name)
if sequence(x) and length(x) = 1 then
return x[1][D_SIZE]
else
return -1 -- the file does not exist
end if
end function
procedure test(sequence file_name)
integer size
size = file_size(file_name)
if size < 0 then
printf(1,"%s file does not exist.\n",{file_name})
else
printf(1,"%s size is %d.\n",{file_name,size})
end if
end procedure
test("input.txt") -- in the current working directory
test("/input.txt") -- in the file system root |
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.
| #F.23 | F# | open NUnit.Framework
open FsUnit
[<Test>]
let ``Validate that the size of the two files is the same`` () =
let local = System.IO.FileInfo(__SOURCE_DIRECTORY__ + "\input.txt")
let root = System.IO.FileInfo(System.IO.Directory.GetDirectoryRoot(__SOURCE_DIRECTORY__) + "input.txt")
local.Length = root.Length |> should be True |
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.
| #Befunge | Befunge | 0110"txt.tupni"#@i10"txt.tuptuo"#@o@ |
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.
| #Bracmat | Bracmat | put$(get$"input.txt","output.txt",NEW) |
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
| #AutoHotkey | AutoHotkey | SetFormat, FloatFast, 0.15
SetBatchLines, -1
OutPut := "N`tLength`t`tEntropy`n"
. "1`t" 1 "`t`t" Entropy(FW1 := "1") "`n"
. "2`t" 1 "`t`t" Entropy(FW2 := "0") "`n"
Loop, 35
{
FW3 := FW2 FW1, FW1 := FW2, FW2 := FW3
Output .= A_Index + 2 "`t" StrLen(FW3) (A_Index > 33 ? "" : "`t") "`t" Entropy(FW3) "`n"
}
MsgBox, % Output
Entropy(n)
{
a := [], len:= StrLen(n), m := n
while StrLen(m)
{
s := SubStr(m, 1, 1)
m := RegExReplace(m, s, "", c)
a[s] := c
}
for key, val in a
{
m := Log(p := val / len)
e -= p * m / Log(2)
}
return, e
} |
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
| #C | C | gcc -o fermat fermat.c -lgmp |
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
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <boost/integer/common_factor.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
typedef boost::multiprecision::cpp_int integer;
integer fermat(unsigned int n) {
unsigned int p = 1;
for (unsigned int i = 0; i < n; ++i)
p *= 2;
return 1 + pow(integer(2), p);
}
inline void g(integer& x, const integer& n) {
x *= x;
x += 1;
x %= n;
}
integer pollard_rho(const integer& n) {
integer x = 2, y = 2, d = 1, z = 1;
int count = 0;
for (;;) {
g(x, n);
g(y, n);
g(y, n);
d = abs(x - y);
z = (z * d) % n;
++count;
if (count == 100) {
d = gcd(z, n);
if (d != 1)
break;
z = 1;
count = 0;
}
}
if (d == n)
return 0;
return d;
}
std::vector<integer> get_prime_factors(integer n) {
std::vector<integer> factors;
for (;;) {
if (miller_rabin_test(n, 25)) {
factors.push_back(n);
break;
}
integer f = pollard_rho(n);
if (f == 0) {
factors.push_back(n);
break;
}
factors.push_back(f);
n /= f;
}
return factors;
}
void print_vector(const std::vector<integer>& factors) {
if (factors.empty())
return;
auto i = factors.begin();
std::cout << *i++;
for (; i != factors.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::cout << "First 10 Fermat numbers:\n";
for (unsigned int i = 0; i < 10; ++i)
std::cout << "F(" << i << ") = " << fermat(i) << '\n';
std::cout << "\nPrime factors:\n";
for (unsigned int i = 0; i < 9; ++i) {
std::cout << "F(" << i << "): ";
print_vector(get_prime_factors(fermat(i)));
}
return 0;
} |
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
| #11l | 11l | T Fiblike
Int addnum
[Int] memo
F (start)
.addnum = start.len
.memo = copy(start)
F ()(n)
X.try
R .memo[n]
X.catch IndexError
V ans = sum((n - .addnum .< n).map(i -> (.)(i)))
.memo.append(ans)
R ans
V fibo = Fiblike([1, 1])
print((0.<10).map(i -> fibo(i)))
V lucas = Fiblike([2, 1])
print((0.<10).map(i -> lucas(i)))
L(n, name) zip(2..10, ‘fibo tribo tetra penta hexa hepta octo nona deca’.split(‘ ’))
V fibber = Fiblike([1] [+] (0 .< n - 1).map(i -> Int(2 ^ i)))
print(‘n=#2, #5nacci -> #. ...’.format(n, name, (0.<15).map(i -> String(@fibber(i))).join(‘ ’))) |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #C.2B.2B | C++ | #include <iostream>
int main() {
const int max_it = 13;
const int max_it_j = 10;
double a1 = 1.0, a2 = 0.0, d1 = 3.2;
std::cout << " i d\n";
for (int i = 2; i <= max_it; ++i) {
double a = a1 + (a1 - a2) / d1;
for (int j = 1; j <= max_it_j; ++j) {
double x = 0.0;
double y = 0.0;
for (int k = 1; 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;
}
return 0;
} |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #D | D | import std.stdio;
void main() {
int max_it = 13;
int max_it_j = 10;
double a1 = 1.0;
double a2 = 0.0;
double d1 = 3.2;
double a;
writeln(" i d");
for (int i=2; i<=max_it; i++) {
a = a1 + (a1 - a2) / d1;
for (int j=1; j<=max_it_j; j++) {
double x = 0.0;
double y = 0.0;
for (int k=1; k <= 1<<i; k++) {
y = 1.0 - 2.0 * y * x;
x = a - x * x;
}
a -= x / y;
}
double d = (a1 - a2) / (a - a1);
writefln("%2d %.8f", 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
| #Java | Java | import java.util.Arrays;
import java.util.Comparator;
public class FileExt{
public static void main(String[] args){
String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"};
String[] exts = {".txt",".gz","",".bat"};
System.out.println("Extensions: " + Arrays.toString(exts) + "\n");
for(String test:tests){
System.out.println(test +": " + extIsIn(test, exts));
}
}
public static boolean extIsIn(String test, String... exts){
int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); //whichever one they decide to use today
String filename = test.substring(lastSlash + 1);//+1 to get rid of the slash or move to index 0 if there's no slash
//end of the name if no dot, last dot index otherwise
int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');
String ext = filename.substring(lastDot);//everything at the last dot and after is the extension
Arrays.sort(exts);//sort for the binary search
return Arrays.binarySearch(exts, ext, new Comparator<String>() { //just use the built-in binary search method
@Override //it will let us specify a Comparator and it's fast enough
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
}) >= 0;//binarySearch returns negative numbers when it's not found
}
}
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Jsish | Jsish | /* File modification times, in Jsi */
var fileTime = File.mtime('fileModificationTime.jsi');
puts("Last mod time was: ", strftime(fileTime * 1000));
exec('touch fileModificationTime.jsi');
fileTime = File.mtime('fileModificationTime.jsi');
puts("Mod time now: ", strftime(fileTime * 1000)); |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Julia | Julia | using Dates
fname, _ = mktemp()
println("The modification time of $fname is ", Dates.unix2datetime(mtime(fname)))
println("\nTouch this file.")
touch(fname)
println("The modification time of $fname is now ", Dates.unix2datetime(mtime(fname))) |
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.)
| #Haskell | Haskell | import Data.List (unfoldr)
import Data.Bool (bool)
import Data.Semigroup (Sum(..), Min(..), Max(..))
import System.IO (writeFile)
fibonacciWord :: a -> a -> [[a]]
fibonacciWord a b = unfoldr (\(a,b) -> Just (a, (b, a <> b))) ([a], [b])
toPath :: [Bool] -> ((Min Int, Max Int, Min Int, Max Int), String)
toPath = foldMap (\p -> (box p, point p)) .
scanl (<>) mempty .
scanl (\dir (turn, s) -> bool dir (turn dir) s) (1, 0) .
zip (cycle [left, right])
where
box (Sum x, Sum y) = (Min x, Max x, Min y, Max y)
point (Sum x, Sum y) = show x ++ "," ++ show y ++ " "
left (x,y) = (-y, x)
right (x,y) = (y, -x)
toSVG :: [Bool] -> String
toSVG w =
let ((Min x1, Max x2, Min y1, Max y2), path) = toPath w
in unwords
[ "<svg xmlns='http://www.w3.org/2000/svg'"
, "width='500' height='500'"
, "stroke='black' fill='none' strokeWidth='2'"
, "viewBox='" ++ unwords (show <$> [x1,y1,x2-x1,y2-y1]) ++ "'>"
, "<polyline points='" ++ path ++ "'/>"
, "</svg>"]
main = writeFile "test.html" $ toSVG $ fibonacciWord True False !! 21 |
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
| #Haskell | Haskell | import Data.List
-- Return the common prefix of two lists.
commonPrefix2 (x:xs) (y:ys) | x == y = x : commonPrefix2 xs ys
commonPrefix2 _ _ = []
-- Return the common prefix of zero or more lists.
commonPrefix (xs:xss) = foldr commonPrefix2 xs xss
commonPrefix _ = []
-- Split a string into path components.
splitPath = groupBy (\_ c -> c /= '/')
-- Return the common prefix of zero or more paths.
-- Note that '/' by itself is not considered a path component,
-- so "/" and "/foo" are treated as having nothing in common.
commonDirPath = concat . commonPrefix . map splitPath
main = putStrLn $ commonDirPath [
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"
] |
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
| #HicEst | HicEst | CHARACTER a='/home/user1/tmp/coverage/test', b='/home/user1/tmp/covert/operator', c='/home/user1/tmp/coven/members'
minLength = MIN( LEN(a), LEN(b), LEN(c) )
lastSlash = 0
DO i = 1, minLength
IF( (a(i) == b(i)) * (b(i) == c(i)) ) THEN
IF(a(i) == "/") lastSlash = i
ELSEIF( lastSlash ) THEN
WRITE(Messagebox) "Common Directory = ", a(1:lastSlash-1)
ELSE
WRITE(Messagebox, Name) "No common directory for", a, b, c
ENDIF
ENDDO |
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.
| #BCPL | BCPL | get "libhdr"
// Copy every value for which p(x) is true from in to out
// This will also work in place by setting out = in
let filter(p, in, ilen, out, olen) be
$( !olen := 0
for i = 0 to ilen-1 do
if p(in!i) do
$( out!!olen := in!i
!olen := !olen + 1
$)
$)
// Write N elements from vector
let writevec(v, n) be
for i = 0 to n-1 do writef("%N ", v!i)
let start() be
$( // Predicates
let even(n) = (n&1) = 0
let mul3(n) = n rem 3 = 0
let nums = table 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
let arr = vec 20
let len = ?
writes("Numbers: ")
writevec(nums, 15)
// Filter 'nums' into 'arr'
filter(even, nums, 15, arr, @len)
writes("*NEven numbers: ")
writevec(arr, len)
// Filter 'arr' in place for multiples of 3
filter(mul3, arr, len, arr, @len)
writes("*NEven multiples of 3: ")
writevec(arr, len)
wrch('*N')
$) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #LSL | LSL | integer iLimit_of_Recursion = 0;
Find_Limit_of_Recursion(integer x) {
llOwnerSay("x="+(string)x);
iLimit_of_Recursion = x;
Find_Limit_of_Recursion(x+1);
}
default {
state_entry() {
Find_Limit_of_Recursion(0);
llOwnerSay("iLimit_of_Recursion="+(string)iLimit_of_Recursion);
}
}
|
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.
| #Lua | Lua |
local c = 0
function Tail(proper)
c = c + 1
if proper then
if c < 9999999 then return Tail(proper) else return c end
else
return 1/c+Tail(proper) -- make the recursive call must keep previous stack
end
end
local ok,check = pcall(Tail,true)
print(c, ok, check)
c=0
ok,check = pcall(Tail,false)
print(c, ok, check)
|
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.
| #Tcl | Tcl | proc format_%t {n} {
while {$n} {
append r [expr {$n % 3}]
set n [expr {$n / 3}]
}
if {![info exists r]} {set r 0}
string reverse $r
} |
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.
| #VBA | VBA | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
'palindromes both in base3 and base2
'using Decimal data type to find number 6 and 7, although slowly
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
'count integer n from 0 upwards
'display representation in base 3
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do 'For n = 1 To 200000 '20000000 takes 1000 seconds and number 7 not found yet
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1 'as j=len3 now and 1=pow3(len3 - j)
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
'do we have a hit?
t = Dec2Bin(full3) 'CStr(DecimalToBinary(full3))
If t = StrReverse(t) Then
'we have a hit
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5 'Next n
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub |
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
| #Fortran | Fortran | program fizzbuzz_if
integer :: i
do i = 1, 100
if (mod(i,15) == 0) then; print *, 'FizzBuzz'
else if (mod(i,3) == 0) then; print *, 'Fizz'
else if (mod(i,5) == 0) then; print *, 'Buzz'
else; print *, i
end if
end do
end program fizzbuzz_if |
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.
| #Factor | Factor | "input.txt" file-info size>> .
1321
"file-does-not-exist.txt" file-info size>>
"Unix system call ``stat'' failed:"... |
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.
| #FBSL | FBSL | #APPTYPE CONSOLE
PRINT FileLen("sync.log")
PRINT FileLen("\sync.log")
PAUSE
|
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.
| #Forth | Forth | : .filesize ( addr len -- ) 2dup type ." is "
r/o open-file throw
dup file-size throw <# #s #> type ." bytes long." cr
close-file throw ;
s" input.txt" .filesize
s" /input.txt" .filesize |
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 | C | #include <stdio.h>
int main(int argc, char **argv) {
FILE *in, *out;
int c;
in = fopen("input.txt", "r");
if (!in) {
fprintf(stderr, "Error opening input.txt for reading.\n");
return 1;
}
out = fopen("output.txt", "w");
if (!out) {
fprintf(stderr, "Error opening output.txt for writing.\n");
fclose(in);
return 1;
}
while ((c = fgetc(in)) != EOF) {
fputc(c, out);
}
fclose(out);
fclose(in);
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 | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void print_headings()
{
printf("%2s", "N");
printf(" %10s", "Length");
printf(" %-20s", "Entropy");
printf(" %-40s", "Word");
printf("\n");
}
double calculate_entropy(int ones, int zeros)
{
double result = 0;
int total = ones + zeros;
result -= (double) ones / total * log2((double) ones / total);
result -= (double) zeros / total * log2((double) zeros / total);
if (result != result) { // NAN
result = 0;
}
return result;
}
void print_entropy(char *word)
{
int ones = 0;
int zeros = 0;
int i;
for (i = 0; word[i]; i++) {
char c = word[i];
switch (c) {
case '0':
zeros++;
break;
case '1':
ones++;
break;
}
}
double entropy = calculate_entropy(ones, zeros);
printf(" %-20.18f", entropy);
}
void print_word(int n, char *word)
{
printf("%2d", n);
printf(" %10ld", strlen(word));
print_entropy(word);
if (n < 10) {
printf(" %-40s", word);
} else {
printf(" %-40s", "...");
}
printf("\n");
}
int main(int argc, char *argv[])
{
print_headings();
char *last_word = malloc(2);
strcpy(last_word, "1");
char *current_word = malloc(2);
strcpy(current_word, "0");
print_word(1, last_word);
int i;
for (i = 2; i <= 37; i++) {
print_word(i, current_word);
char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);
strcpy(next_word, current_word);
strcat(next_word, last_word);
free(last_word);
last_word = current_word;
current_word = next_word;
}
free(last_word);
free(current_word);
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.
| #11l | 11l | V FASTA =
|‘>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED’
F fasta_parse(infile_str)
V key = ‘’
V val = ‘’
[(String, String)] r
L(line) infile_str.split("\n")
I line.starts_with(‘>’)
I key != ‘’
r [+]= (key, val)
key = line[1..].split_py()[0]
val = ‘’
E I key != ‘’
val ‘’= line
I key != ‘’
r [+]= (key, val)
R r
print(fasta_parse(FASTA).map((key, val) -> ‘#.: #.’.format(key, val)).join("\n")) |
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
| #Common_Lisp | Common Lisp | This uses the 'factor' function defined in the page Prime Decomposition
http://rosettacode.org/wiki/Prime_decomposition#Common_Lisp
|
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
| #Crystal | Crystal | This uses the `factor` function from the `coreutils` library
that comes standard with most GNU/Linux, BSD, and Unix systems.
https://www.gnu.org/software/coreutils/
https://en.wikipedia.org/wiki/GNU_Core_Utilities
|
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
| #360_Assembly | 360 Assembly | * Fibonacci n-step number sequences - 14/04/2020
FIBONS CSECT
USING FIBONS,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,2 i=2
DO WHILE=(C,R6,LE,=F'7') do i=2 to 7
ST R6,IR ir=i
IF C,R6,EQ,=F'7' THEN if i=7 then - Lucas
LA R0,2 2
ST R0,IR ir=2
ENDIF , endif
LA R0,1 1
ST R0,T t(1)=1
IF C,R6,EQ,=F'7' THEN if i=7 then - Lucas
LA R0,2 2
ST R0,T t(1)=2
ENDIF , endif
LA R0,1 1
ST R0,T+4 t(2)=1
LA R7,3 j=3
DO WHILE=(C,R7,LE,=A(NMAX)) do j=3 to nmax
SR R0,R0 0
ST R0,SUM sum=0
LR R11,R7 j
S R11,IR j-ir
LR R8,R7 k=j
BCTR R8,0 k=j-1
DO WHILE=(CR,R8,GE,R11) do k=j-1 to j-ir by -1
IF LTR,R8,P,R8 THEN if k>0 then
LR R1,R8 k
SLA R1,2 ~
L R2,T-4(R1) t(k)
L R1,SUM sum
AR R1,R2 +
ST R1,SUM sum=sum+t(k)
ENDIF , endif
BCTR R8,0 k--
ENDDO , enddo k
L R0,SUM sum
LR R1,R7 j
SLA R1,2 ~
ST R0,T-4(R1) t(j)=sum
LA R7,1(R7) j++
ENDDO , enddo j
MVC PG,=CL120' ' clear buffer
LA R9,PG @buffer
LR R1,R6 i
BCTR R1,0 i-1
MH R1,=H'5' ~
LA R4,BONACCI-5(R1) @bonacci(i-1)
MVC 0(5,R9),0(R4) output bonacci(i-1)
LA R9,5(R9) @buffer
IF C,R6,NE,=F'7' THEN if i<>7 then
MVC 0(7,R9),=C'nacci: ' output 'nacci: '
ELSE , else
MVC 0(7,R9),=C' : ' output ' : '
ENDIF , endif
LA R9,7(R9) @buffer
LA R7,1 j=1
DO WHILE=(C,R7,LE,=A(NMAX)) do j=1 to nmax
LR R1,R7 j
SLA R1,2 ~
L R2,T-4(R1) t(j)
XDECO R2,XDEC edit t(j)
MVC 0(6,R9),XDEC+6 output t(j)
LA R9,6(R9) @buffer
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
NMAX EQU 18 sequence length
BONACCI DC CL5' fibo',CL5'tribo',CL5'tetra',CL5'penta',CL5' hexa'
DC CL5'lucas' bonacci(6)
IR DS F ir
SUM DS F sum
T DS (NMAX)F t(nmax)
XDEC DS CL12 temp for xdeco
PG DS CL120 buffer
REGEQU
END FIBONS |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #F.23 | F# | open System
[<EntryPoint>]
let main _ =
let maxIt = 13
let maxItJ = 10
let mutable a1 = 1.0
let mutable a2 = 0.0
let mutable d1 = 3.2
Console.WriteLine(" i d")
for i in 2 .. maxIt do
let mutable a = a1 + (a1 - a2) / d1
for j in 1 .. maxItJ do
let mutable x = 0.0
let mutable y = 0.0
for _ in 1 .. (1 <<< i) do
y <- 1.0 - 2.0 * y * x
x <- a - x * x
a <- a - x / y
let d = (a1 - a2) / (a - a1)
Console.WriteLine("{0,2:d} {1:f8}", i, d)
d1 <- d
a2 <- a1
a1 <- a
0 // return an integer exit code |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Factor | Factor | USING: formatting io locals math math.ranges sequences ;
[let
1 :> a1!
0 :> a2!
3.2 :> d!
" i d" print
2 13 [a,b] [| exp |
a1 a2 - d /f a1 + :> a!
10 [
0 :> x!
0 :> y!
exp 2^ [
1 2 x y * * - y!
a x sq - x!
] times
a x y /f - a!
] times
a1 a2 - a a1 - /f d!
a1 a2! a a1!
exp d "%2d %.8f\n" printf
] each
] |
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
| #jq | jq | # Input: filename
# Output: if the filename ends with one of the extensions (ignoring case), output that extension; else output null.
# Assume that the list of file extensions consists of lower-case strings, including a leading period.
def has_extension(list):
def ascii_downcase: explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;
rindex(".") as $ix
| if $ix then (.[$ix:] | ascii_downcase) as $ext
| if list | index($ext) then $ext else null end
else null
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
| #Julia | Julia | isext(filename, extensions) = any(x -> endswith(lowercase(filename), lowercase(x)), "." .* extensions)
# Test
extensions = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"]
for f in ["MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2"]
@printf("%20s : %5s\n", f, isext(f, extensions))
end |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Kotlin | Kotlin | // version 1.0.6
import java.io.File
fun main(args: Array<String>) {
val filePath = "input.txt" // or whatever
val file = File(filePath)
with (file) {
println("%tc".format(lastModified()))
// update to current time, say
setLastModified(System.currentTimeMillis())
println("%tc".format(lastModified()))
}
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Lasso | Lasso | local(f) = file('input.txt')
handle => { #f->close }
#f->modificationDate->format('%-D %r')
// result: 12/2/2010 11:04:15 PM |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Lua | Lua | require "lfs"
local attributes = lfs.attributes("input.txt")
if attributes then
print(path .. " was last modified " .. os.date("%c", attributes.modification) .. ".")
-- set access and modification time to now ...
lfs.touch("input.txt")
-- ... or set modification time to now, keep original access time
lfs.touch("input.txt", attributes.access, os.time())
else
print(path .. " does not exist.")
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.