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/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.
#8086_Assembly
8086 Assembly
putch: equ 2 ; Print character puts: equ 9 ; Print $-terminated string setdta: equ 1Ah ; Set DTA stat: equ 4Eh ; Get file info cpu 8086 bits 16 org 100h section .text mov si,curf ; Print file size for 'INPUT.TXT' call pfsize ; (in current directory), mov si,rootf ; Then for '\INPUT.TXT' in root directory ;;; Print file name and size for file in DS:SI pfsize: mov ah,setdta ; Set disc transfer area pointer mov dx,dta int 21h call puts0 ; Print the filename in SI mov ah,puts ; Print colon and space mov dx,colspc int 21h mov ah,stat ; Find file info xor cx,cx ; We want a normal file mov dx,si ; Filename is in SI int 21h jnc .ok ; Carry clear = found mov ah,puts ; Carry set = not found = print 'not found' mov dx,nofile int 21h ret .ok: les bp,[dta+26] ; 32-bit file size in bytes at DTA+26 mov di,es ; DI:BP = 32-bit file size mov bx,numbuf ; ASCII number buffer mov cx,10 ; Divisor (10) .dgt: xor dx,dx ; 32-bit division (to get digits) mov ax,di ; can be done with chained DIVs div cx mov di,ax mov ax,bp div cx mov bp,ax add dl,'0' ; DX is now remainder, i.e. digit dec bx ; Move digit pointer backwards, mov [bx],dl ; Store ASCII digit, or ax,di ; If the new divisor is not zero, jnz .dgt ; then there is another digit. mov ah,puts ; If so, the number is done, mov dx,bx ; and we can print it. int 21h ret ;;; Print 0-terminated string in SI puts0: push si ; Save SI register mov ah,putch ; Print char syscall .loop: lodsb ; Load character from SI test al,al ; If zero, jz .out ; then stop. mov dl,al ; Tell DOS to print character int 21h jmp .loop ; go get another. .out: pop si ; Restore SI register ret section .data rootf: db '\' ; \INPUT.TXT (for root) and curf: db 'INPUT.TXT',0 ; INPUT.TXT (for current directory) nofile: db 'Not found.',13,10,'$' ; "Not found" message db '0000000000' ; Number output buffer numbuf: db ' bytes',13,10,'$' colspc: db ': $' ; Colon and space section .bss dta: resb 512 ; Disc transfer area
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#ALGOL_68
ALGOL 68
PROC get output = (STRING cmd) VOID: IF STRING sh cmd = " " + cmd + " ; 2>&1"; STRING output; execve output ("/bin/sh", ("sh", "-c", sh cmd), "", output) >= 0 THEN print (output) FI; get output ("rm -rf WTC_1"); CO Ensure file doesn't exist CO get output ("touch WTC_1"); CO Create file CO get output ("ls -l --time-style=full-iso WTC_1"); CO Display its last modified time CO get output ("touch -t 200109111246.40 WTC_1"); CO Change its last modified time CO get output ("ls -l --time-style=full-iso WTC_1") CO Verify it changed CO  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#AutoHotkey
AutoHotkey
FileGetTime, OutputVar, output.txt MsgBox % OutputVar FileSetTime, 20080101, output.txt FileGetTime, OutputVar, output.txt MsgBox % OutputVar
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?
#Factor
Factor
USING: accessors assocs formatting io io.directories.search io.files.types io.pathnames kernel math math.functions math.statistics namespaces sequences ;   : classify ( m -- n ) [ 0 ] [ log10 >integer 1 + ] if-zero ;   : file-size-histogram ( path -- assoc ) recursive-directory-entries [ type>> +directory+ = ] reject [ size>> classify ] map histogram ;   current-directory get file-size-histogram dup [ "Count of files < 10^%d bytes: %4d\n" printf ] assoc-each nl values sum "Total files: %d\n" printf
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?
#Go
Go
package main   import ( "fmt" "log" "math" "os" "path/filepath" )   func commatize(n int64) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s }   func fileSizeDistribution(root string) { var sizes [12]int files := 0 directories := 0 totalSize := int64(0) walkFunc := func(path string, info os.FileInfo, err error) error { if err != nil { return err } files++ if info.IsDir() { directories++ } size := info.Size() if size == 0 { sizes[0]++ return nil } totalSize += size logSize := math.Log10(float64(size)) index := int(math.Floor(logSize)) sizes[index+1]++ return nil } err := filepath.Walk(root, walkFunc) if err != nil { log.Fatal(err) } fmt.Printf("File size distribution for '%s' :-\n\n", root) for i := 0; i < len(sizes); i++ { if i == 0 { fmt.Print(" ") } else { fmt.Print("+ ") } fmt.Printf("Files less than 10 ^ %-2d bytes : %5d\n", i, sizes[i]) } fmt.Println(" -----") fmt.Printf("= Total number of files  : %5d\n", files) fmt.Printf(" including directories  : %5d\n", directories) c := commatize(totalSize) fmt.Println("\n Total size of files  :", c, "bytes") }   func main() { fileSizeDistribution("./") }
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
#BBC_BASIC
BBC BASIC
DIM path$(3)   path$(1) = "/home/user1/tmp/coverage/test" path$(2) = "/home/user1/tmp/covert/operator" path$(3) = "/home/user1/tmp/coven/members"   PRINT FNcommonpath(path$(), "/") END   DEF FNcommonpath(p$(), s$) LOCAL I%, J%, O% REPEAT O% = I% I% = INSTR(p$(1), s$, I%+1) FOR J% = 2 TO DIM(p$(), 1) IF LEFT$(p$(1), I%) <> LEFT$(p$(J%), I%) EXIT REPEAT NEXT J% UNTIL I% = 0 = LEFT$(p$(1), O%-1)
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
#C
C
#include <stdio.h>   int common_len(const char *const *names, int n, char sep) { int i, pos; for (pos = 0; ; pos++) { for (i = 0; i < n; i++) { if (names[i][pos] != '\0' && names[i][pos] == names[0][pos]) continue;   /* backtrack */ while (pos > 0 && names[0][--pos] != sep); return pos; } }   return 0; }   int main() { const char *names[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/');   if (!len) printf("No common path\n"); else printf("Common path: %.*s\n", len, names[0]);   return 0; }
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.
#Ada
Ada
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; with Ada.Text_Io; use Ada.Text_Io;   procedure Array_Selection is type Array_Type is array (Positive range <>) of Integer; Null_Array : Array_Type(1..0);   function Evens (Item : Array_Type) return Array_Type is begin if Item'Length > 0 then if Item(Item'First) mod 2 = 0 then return Item(Item'First) & Evens(Item((Item'First + 1)..Item'Last)); else return Evens(Item((Item'First + 1)..Item'Last)); end if; else return Null_Array; end if; end Evens;   procedure Print(Item : Array_Type) is begin for I in Item'range loop Put(Item(I)); New_Line; end loop; end Print;   Foo : Array_Type := (1,2,3,4,5,6,7,8,9,10); begin Print(Evens(Foo)); end Array_Selection;
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]]
#jq
jq
def sum_of_squares(stream): reduce stream as $x (0; . + $x * $x);   def distanceSquared(P1; P2): sum_of_squares(P1[0]-P2[0], P1[1]-P2[1]);   # Emit {x1,y1, ...} for the input triangle def xy: { x1: .[0][0], y1: .[0][1], x2: .[1][0], y2: .[1][1], x3: .[2][0], y3: .[2][1] };   def EPS: 0.001; def EPS_SQUARE: EPS * EPS;
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]]
#Julia
Julia
Point(x, y) = [x, y] Triangle(a, b, c) = [a, b, c] LEzero(x) = x < 0 || isapprox(x, 0, atol=0.00000001) GEzero(x) = x > 0 || isapprox(x, 0, atol=0.00000001)   """ Determine which side of plane cut by line (p2, p3) p1 is on """ side(p1, p2, p3) = (p1[1] - p3[1]) * (p2[2] - p3[2]) - (p2[1] - p3[1]) * (p1[2] - p3[2])   """ Determine if point is within triangle formed by points p1, p2, p3. If so, the point will be on the same side of each of the half planes defined by vectors p1p2, p2p3, and p3p1. Each z is positive if outside, negative if inside such a plane. All should be positive or all negative if point is within the triangle. """ function iswithin(point, p1, p2, p3) z1 = side(point, p1, p2) z2 = side(point, p2, p3) z3 = side(point, p3, p1) notanyneg = GEzero(z1) && GEzero(z2) && GEzero(z3) notanypos = LEzero(z1) && LEzero(z2) && LEzero(z3) return notanyneg || notanypos end   const POINTS = [Point(0 // 1, 0 // 1), Point(0 // 1, 1 // 1), Point(3 // 1, 1 // 1), Point(1 // 10 + (3 // 7) * (100 // 8 - 1 // 10), 1 // 9 + (3 // 7) * (100 // 3 - 1 // 9)), Point(3 // 2, 12 // 5), Point(51 // 100, -31 // 100), Point(-19 // 50, 6 // 5), Point(1 // 10, 1 // 9), Point(25 / 2, 100 // 3), Point(25, 100 // 9), Point(-25 // 2, 50 // 3) ]   const TRI = [ Triangle(POINTS[5], POINTS[6], POINTS[7]), Triangle(POINTS[8], POINTS[9], POINTS[10]), Triangle(POINTS[8], POINTS[9], POINTS[11]) ]   for tri in TRI pstring(pt) = "[$(Float32(pt[1])), $(Float32(pt[2]))]" println("\nUsing triangle [", join([pstring(x) for x in tri], ", "), "]:") a, b, c = tri[1], tri[2], tri[3] for p in POINTS[1:4] isornot = iswithin(p, a, b, c) ? "is" : "is not" println("Point $(pstring(p)) $isornot within the triangle.") end end  
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#TI-89_BASIC
TI-89 BASIC
[[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] flatten
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.
#Elixir
Elixir
(defun my-recurse (n) (my-recurse (1+ n))) (my-recurse 1) => enters debugger at (my-recurse 595), per the default max-lisp-eval-depth 600 in Emacs 24.1
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Emacs_Lisp
Emacs Lisp
(defun my-recurse (n) (my-recurse (1+ n))) (my-recurse 1) => enters debugger at (my-recurse 595), per the default max-lisp-eval-depth 600 in Emacs 24.1
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.
#JavaScript
JavaScript
(() => { 'use strict';   // GENERIC FUNCTIONS   // range :: Int -> Int -> [Int] const range = (m, n) => Array.from({ length: Math.floor(n - m) + 1 }, (_, i) => m + i);   // compose :: (b -> c) -> (a -> b) -> (a -> c) const compose = (f, g) => x => f(g(x));   // listApply :: [(a -> b)] -> [a] -> [b] const listApply = (fs, xs) => [].concat.apply([], fs.map(f => [].concat.apply([], xs.map(x => [f(x)]))));   // pure :: a -> [a] const pure = x => [x];   // curry :: Function -> Function const curry = (f, ...args) => { const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : function () { return go(xs.concat([].slice.apply(arguments))); }; return go([].slice.call(args, 1)); };   // transpose :: [[a]] -> [[a]] const transpose = xs => xs[0].map((_, iCol) => xs.map(row => row[iCol]));   // reverse :: [a] -> [a] const reverse = xs => typeof xs === 'string' ? ( xs.split('') .reverse() .join('') ) : xs.slice(0) .reverse();   // take :: Int -> [a] -> [a] const take = (n, xs) => xs.slice(0, n);   // drop :: Int -> [a] -> [a] const drop = (n, xs) => xs.slice(n);   // maximum :: [a] -> a const maximum = xs => xs.reduce((a, x) => (x > a || a === undefined ? x : a), undefined);   // quotRem :: Integral a => a -> a -> (a, a) const quotRem = (m, n) => [Math.floor(m / n), m % n];   // length :: [a] -> Int const length = xs => xs.length;   // justifyLeft :: Int -> Char -> Text -> Text const justifyLeft = (n, cFiller, strText) => n > strText.length ? ( (strText + cFiller.repeat(n)) .substr(0, n) ) : strText;   // unwords :: [String] -> String const unwords = xs => xs.join(' ');   // unlines :: [String] -> String const unlines = xs => xs.join('\n');     // BASES AND PALINDROMES   // show, showBinary, showTernary :: Int -> String const show = n => n.toString(10); const showBinary = n => n.toString(2); const showTernary = n => n.toString(3);   // readBase3 :: String -> Int const readBase3 = s => parseInt(s, 3);   // base3Palindrome :: Int -> String const base3Palindrome = n => { const s = showTernary(n); return s + '1' + reverse(s); };   // isBinPal :: Int -> Bool const isBinPal = n => { const s = showBinary(n), [q, r] = quotRem(s.length, 2); return (r !== 0) && drop(q + 1, s) === reverse(take(q, s)); };   // solutions :: [Int] const solutions = [0, 1].concat(range(1, 10E5) .map(compose(readBase3, base3Palindrome)) .filter(isBinPal));   // TABULATION   // cols :: [[Int]] const cols = transpose( [ ['Decimal', 'Ternary', 'Binary'] ].concat( solutions.map( compose( xs => listApply([show, showTernary, showBinary], xs), pure ) ) ) );   return unlines( transpose(cols.map(col => col.map( curry(justifyLeft)(maximum(col.map(length)) + 1, ' ') ))) .map(unwords)); })();
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime. Let's work base 3 by hand: 0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3. The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able. Related Tasks: Miller-Rabin primality test
#zkl
zkl
var [const] BN=Import("zklBigNum"); // libGMP fcn largest_lefty_prime(base){ primes,p:=List(),BN(1); while(p.nextPrime()<base){ primes.append(p.copy()) } b,biggest := BN(1),0; while(primes){ b*=base; // base,base^2,base^3... gets big ps:=List(); foreach p,n in (primes,[1..base-1]){ if((z:=(p + b*n)).probablyPrime()){ ps.append(z); if(z>biggest) biggest=z; } } primes=ps; // the number of lists is small } biggest }   foreach n in ([3..17]){ println("%2d %s".fmt(n,largest_lefty_prime(n))) }
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
#Emojicode
Emojicode
🏁🍇 🔂 i 🆕⏩ 1 101 1 ❗ 🍇 ↪️ 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.
#Action.21
Action!
INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit   PROC Dir(CHAR ARRAY filter) BYTE dev=[1] CHAR ARRAY line(255)   Close(dev) Open(dev,filter,6) DO InputSD(dev,line) PrintE(line) IF line(0)=0 THEN EXIT FI OD Close(dev) RETURN   CARD FUNC FileSize(CHAR ARRAY src,dst) DEFINE BUF_LEN="100" BYTE dev=[1] BYTE ARRAY buff(BUF_LEN) CARD len,size   size=0 Close(dev) Open(dev,src,4) DO len=Bget(dev,buff,BUF_LEN) size==+len UNTIL len#BUF_LEN OD Close(dev) RETURN (size)   PROC Main() CHAR ARRAY filter="D:*.*", fname="D:INPUT.TXT" CARD size   Put(125) PutE() ;clear screen   PrintF("Dir ""%S""%E",filter) Dir(filter)   size=FileSize(fname) PrintF("Size of ""%S"" is %U bytes%E",fname,size) RETURN
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.
#Ada
Ada
with Ada.Directories; use Ada.Directories; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_File_Size is begin Put_Line (File_Size'Image (Size ("input.txt")) & " bytes"); Put_Line (File_Size'Image (Size ("/input.txt")) & " bytes"); end Test_File_Size;
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#AWK
AWK
@load "filefuncs" BEGIN {   name = "input.txt"   # display time stat(name, fd) printf("%s\t%s\n", name, strftime("%a %b %e %H:%M:%S %Z %Y", fd["mtime"]) )   # change time cmd = "touch -t 201409082359.59 " name system(cmd) close(cmd)   }
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Batch_File
Batch File
for %%f in (file.txt) do echo.%%~tf
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?
#Haskell
Haskell
{-# LANGUAGE LambdaCase #-}   import Control.Concurrent (forkIO, setNumCapabilities) import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan, writeList2Chan) import Control.Exception (IOException, catch) import Control.Monad (filterM, forever, join, replicateM, replicateM_, (>=>)) import Control.Parallel.Strategies (parTraversable, rseq, using, withStrategy) import Data.Char (isDigit) import Data.List (find, sort) import qualified Data.Map.Strict as Map import GHC.Conc (getNumProcessors) import System.Directory (doesDirectoryExist, doesFileExist, listDirectory, pathIsSymbolicLink) import System.Environment (getArgs) import System.FilePath.Posix ((</>)) import System.IO (FilePath, IOMode (ReadMode), hFileSize, hPutStrLn, stderr, withFile) import Text.Printf (hPrintf, printf)   data Item = File FilePath Integer | Folder FilePath deriving (Show)   type FGKey = (Integer, Integer) type FrequencyGroup = (FGKey, Integer) type FrequencyGroups = Map.Map FGKey Integer   newFrequencyGroups :: FrequencyGroups newFrequencyGroups = Map.empty   fileSizes :: [Item] -> [Integer] fileSizes = foldr f [] where f (File _ n) acc = n:acc f _ acc = acc   folders :: [Item] -> [FilePath] folders = foldr f [] where f (Folder p) acc = p:acc f _ acc = acc   totalBytes :: [Item] -> Integer totalBytes = sum . fileSizes   counts :: [Item] -> (Integer, Integer) counts = foldr (\x (a, b) -> case x of File _ _ -> (succ a, b) Folder _ -> (a, succ b)) (0, 0)   -- |Creates 'FrequencyGroups' from the provided size and data set. frequencyGroups :: Int -- ^ Desired number of frequency groups. -> [Integer] -- ^ List of collected file sizes. Must be sorted. -> FrequencyGroups -- ^ Returns a 'FrequencyGroups' for the file sizes. frequencyGroups _ [] = newFrequencyGroups frequencyGroups totalGroups xs | length xs == 1 = Map.singleton (head xs, head xs) 1 | otherwise = foldr placeGroups newFrequencyGroups xs `using` parTraversable rseq where range = maximum xs - minimum xs groupSize = succ $ ceiling $ realToFrac range / realToFrac totalGroups groups = takeWhile (<=groupSize + maximum xs) $ iterate (+groupSize) 0 groupMinMax = zip groups (pred <$> tail groups) findGroup n = find (\(low, high) -> n >= low && n <= high)   incrementCount (Just n) = Just (succ n) -- Update count for range. incrementCount Nothing = Just 1 -- Insert new range with initial count.   placeGroups n fgMap = case findGroup n groupMinMax of Just k -> Map.alter incrementCount k fgMap Nothing -> fgMap -- Should never happen.   expandGroups :: Int -- ^ Desired number of frequency groups. -> [Integer] -- ^ List of collected file sizes. -> Integer -- ^ Computed frequency group limit. -> FrequencyGroups -- ^ Expanded 'FrequencyGroups' expandGroups gsize fileSizes groupThreshold | groupThreshold > 0 = loop 15 $ frequencyGroups gsize sortedFileSizes | otherwise = frequencyGroups gsize sortedFileSizes where sortedFileSizes = sort fileSizes loop 0 gs = gs -- break out in case we can't go below threshold loop n gs | all (<= groupThreshold) $ Map.elems gs = gs | otherwise = loop (pred n) (expand gs)   expand :: FrequencyGroups -> FrequencyGroups expand = foldr f . withStrategy (parTraversable rseq) <*> Map.mapWithKey groupsFromGroup . Map.filter (> groupThreshold) where f :: Maybe (FGKey, FrequencyGroups) -- ^ expanded frequency group -> FrequencyGroups -- ^ accumulator -> FrequencyGroups -- ^ merged accumulator f (Just (k, fg)) acc = Map.union (Map.delete k acc) fg f Nothing acc = acc   groupsFromGroup :: FGKey -- ^ Group Key -> Integer -- ^ Count -> Maybe (FGKey, FrequencyGroups) -- ^ Returns expanded 'FrequencyGroups' with base key it replaces. groupsFromGroup (min, max) count | length range > 1 = Just ((min, max), frequencyGroups gsize range) | otherwise = Nothing where range = filter (\n -> n >= min && n <= max) sortedFileSizes   displaySize :: Integer -> String displaySize n | n <= 2^10 = printf "%8dB " n | n >= 2^10 && n <= 2^20 = display (2^10) "KB" | n >= 2^20 && n <= 2^30 = display (2^20) "MB" | n >= 2^30 && n <= 2^40 = display (2^30) "GB" | n >= 2^40 && n <= 2^50 = display (2^40) "TB" | otherwise = "Too large!" where display :: Double -> String -> String display b = printf "%7.2f%s " (realToFrac n / b)   displayFrequency :: Integer -> FrequencyGroup -> IO () displayFrequency filesCount ((min, max), count) = do printf "%s <-> %s" (displaySize min) (displaySize max) printf "= %-10d %6.3f%%: %-5s\n" count percentage bars where percentage :: Double percentage = (realToFrac count / realToFrac filesCount) * 100 size = round percentage bars | size == 0 = "▍" | otherwise = replicate size '█'   folderWorker :: Chan FilePath -> Chan [Item] -> IO () folderWorker folderChan resultItemsChan = forever (readChan folderChan >>= collectItems >>= writeChan resultItemsChan)   collectItems :: FilePath -> IO [Item] collectItems folderPath = catch tryCollect $ \e -> do hPrintf stderr "Skipping: %s\n" $ show (e :: IOException) pure [] where tryCollect = (fmap (folderPath </>) <$> listDirectory folderPath) >>= mapM (\p -> doesDirectoryExist p >>= \case True -> pure $ Folder p False -> File p <$> withFile p ReadMode hFileSize)   parallelItemCollector :: FilePath -> IO [Item] parallelItemCollector folder = do wCount <- getNumProcessors setNumCapabilities wCount printf "Using %d worker threads\n" wCount folderChan <- newChan resultItemsChan <- newChan replicateM_ wCount (forkIO $ folderWorker folderChan resultItemsChan) loop folderChan resultItemsChan [Folder folder] where loop :: Chan FilePath -> Chan [Item] -> [Item] -> IO [Item] loop folderChan resultItemsChan xs = do regularFolders <- filterM (pathIsSymbolicLink >=> (pure . not)) $ folders xs if null regularFolders then pure [] else do writeList2Chan folderChan regularFolders childItems <- replicateM (length regularFolders) (readChan resultItemsChan) result <- mapM (loop folderChan resultItemsChan) childItems pure (join childItems <> join result)   parseArgs :: [String] -> Either String (FilePath, Int) parseArgs (x:y:xs) | all isDigit y = Right (x, read y) | otherwise = Left "Invalid frequency group size" parseArgs (x:xs) = Right (x, 4) parseArgs _ = Right (".", 4)   main :: IO () main = parseArgs <$> getArgs >>= \case Left errorMessage -> hPutStrLn stderr errorMessage Right (path, groupSize) -> do items <- parallelItemCollector path let (fileCount, folderCount) = counts items printf "Total files: %d\nTotal folders: %d\n" fileCount folderCount printf "Total size: %s\n" $ displaySize $ totalBytes items printf "\nDistribution:\n\n%9s <-> %9s %7s\n" "From" "To" "Count" putStrLn $ replicate 46 '-' let results = expandGroups groupSize (fileSizes items) (groupThreshold fileCount) mapM_ (displayFrequency fileCount) $ Map.assocs results where groupThreshold = round . (*0.25) . realToFrac
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
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace RosettaCodeTasks {   class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); }   }   class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find Common Directory Path" ); Console.WriteLine ( ); List<string> PathSet1 = new List<string> ( ); PathSet1.Add ( "/home/user1/tmp/coverage/test" ); PathSet1.Add ( "/home/user1/tmp/covert/operator" ); PathSet1.Add ( "/home/user1/tmp/coven/members" ); Console.WriteLine("Path Set 1 (All Absolute Paths):"); foreach ( string path in PathSet1 ) { Console.WriteLine ( path ); } Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) ); } public static string FindCommonPath ( string Separator, List<string> Paths ) { string CommonPath = String.Empty; List<string> SeparatedPath = Paths .First ( str => str.Length == Paths.Max ( st2 => st2.Length ) ) .Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries ) .ToList ( );   foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) ) { if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) ) { CommonPath = PathSegment; } else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) ) { CommonPath += Separator + PathSegment; } else { break; } }   return CommonPath; } } }    
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.
#Aime
Aime
integer even(integer e) { return !(e & 1); }   list filter(list l, integer (*f)(integer)) { integer i; list v;   i = 0; while (i < l_length(l)) { integer e;   e = l_q_integer(l, i); if (f(e)) { lb_p_integer(v, e); }   i += 1; }   return v; }   integer main(void) { integer i; list l;   i = 0; while (i < 10) { lb_p_integer(l, i); i += 1; }   l = filter(l, even);   i = 0; while (i < l_length(l)) { o_space(1); o_integer(l_q_integer(l, i)); i += 1; } o_byte('\n');   return 0; }
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]]
#Kotlin
Kotlin
import kotlin.math.max import kotlin.math.min   private const val EPS = 0.001 private const val EPS_SQUARE = EPS * EPS   private fun test(t: Triangle, p: Point) { println(t) println("Point $p is within triangle ? ${t.within(p)}") }   fun main() { var p1 = Point(1.5, 2.4) var p2 = Point(5.1, -3.1) var p3 = Point(-3.8, 1.2) var tri = Triangle(p1, p2, p3) test(tri, Point(0.0, 0.0)) test(tri, Point(0.0, 1.0)) test(tri, Point(3.0, 1.0)) println() p1 = Point(1.0 / 10, 1.0 / 9) p2 = Point(100.0 / 8, 100.0 / 3) p3 = Point(100.0 / 4, 100.0 / 9) tri = Triangle(p1, p2, p3) val pt = Point(p1.x + 3.0 / 7 * (p2.x - p1.x), p1.y + 3.0 / 7 * (p2.y - p1.y)) test(tri, pt) println() p3 = Point(-100.0 / 8, 100.0 / 6) tri = Triangle(p1, p2, p3) test(tri, pt) }   class Point(val x: Double, val y: Double) { override fun toString(): String { return "($x, $y)" } }   class Triangle(private val p1: Point, private val p2: Point, private val p3: Point) { private fun pointInTriangleBoundingBox(p: Point): Boolean { val xMin = min(p1.x, min(p2.x, p3.x)) - EPS val xMax = max(p1.x, max(p2.x, p3.x)) + EPS val yMin = min(p1.y, min(p2.y, p3.y)) - EPS val yMax = max(p1.y, max(p2.y, p3.y)) + EPS return !(p.x < xMin || xMax < p.x || p.y < yMin || yMax < p.y) }   private fun nativePointInTriangle(p: Point): Boolean { val checkSide1 = side(p1, p2, p) >= 0 val checkSide2 = side(p2, p3, p) >= 0 val checkSide3 = side(p3, p1, p) >= 0 return checkSide1 && checkSide2 && checkSide3 }   private fun distanceSquarePointToSegment(p1: Point, p2: Point, p: Point): Double { val p1P2SquareLength = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y) val dotProduct = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / p1P2SquareLength if (dotProduct < 0) { return (p.x - p1.x) * (p.x - p1.x) + (p.y - p1.y) * (p.y - p1.y) } if (dotProduct <= 1) { val pP1SquareLength = (p1.x - p.x) * (p1.x - p.x) + (p1.y - p.y) * (p1.y - p.y) return pP1SquareLength - dotProduct * dotProduct * p1P2SquareLength } return (p.x - p2.x) * (p.x - p2.x) + (p.y - p2.y) * (p.y - p2.y) }   private fun accuratePointInTriangle(p: Point): Boolean { if (!pointInTriangleBoundingBox(p)) { return false } if (nativePointInTriangle(p)) { return true } if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) { return true } return if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) { true } else distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE }   fun within(p: Point): Boolean { return accuratePointInTriangle(p) }   override fun toString(): String { return "Triangle[$p1, $p2, $p3]" }   companion object { private fun side(p1: Point, p2: Point, p: Point): Double { return (p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - p1.y) } } }
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Trith
Trith
[[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] flatten
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#True_BASIC
True BASIC
LET sstring$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]" FOR sicount = 1 TO LEN(sstring$) IF POS("[] ,",(sstring$)[sicount:sicount+1-1]) = 0 THEN LET sflatter$ = sflatter$ & scomma$ & (sstring$)[sicount:sicount+1-1] LET scomma$ = ", " END IF NEXT sicount PRINT "["; sflatter$; "]" END
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.
#Erlang
Erlang
let rec recurse n = recurse (n+1)   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.
#F.23
F#
let rec recurse n = recurse (n+1)   recurse 0
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.
#Julia
Julia
ispalindrome(n, bas) = (s = string(n, base=bas); s == reverse(s)) prin3online(n) = println(lpad(n, 15), lpad(string(n, base=2), 40), lpad(string(n, base=3), 30)) reversebase3(n) = (x = 0; while n != 0 x = 3x + (n %3); n = div(n, 3); end; x)   function printpalindromes(N) lo, hi, pow2, pow3, count, i = 0, 1, 1, 1, 1, 0 println(lpad("Number", 15), lpad("Base 2", 40), lpad("Base 3", 30)) prin3online(0) while true for j in lo:hi-1 i = j n = (3 * j + 1) * pow3 + reversebase3(j) if ispalindrome(n, 2) prin3online(n) count += 1 if count >= N return end end end if i == pow3 pow3 *= 3 else pow2 *= 4 end   while true while pow2 <= pow3 pow2 *= 4 end lo2 = div(div(pow2, pow3) - 1, 3) hi2 = div(div(pow2 * 2, pow3), 3) + 1 lo3 = div(pow3, 3) hi3 = pow3   if lo2 >= hi3 pow3 *= 3 elseif lo3 >= hi2 pow2 *= 4 else lo = max(lo2, lo3) hi = min(hi2, hi3) break end end end end   printpalindromes(6)  
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
Find palindromic numbers in both binary and ternary bases
Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base 2   base 3   Display   0   (zero) as the first number found, even though some other definitions ignore it.   Optionally, show the decimal number found in its binary and ternary form.   Show all output here. It's permissible to assume the first two numbers and simply list them. See also   Sequence A60792,   numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
#Kotlin
Kotlin
// version 1.0.5-2   /** converts decimal 'n' to its ternary equivalent */ fun Long.toTernaryString(): String = when { this < 0L -> throw IllegalArgumentException("negative numbers not allowed") this == 0L -> "0" else -> { var result = "" var n = this while (n > 0) { result += n % 3 n /= 3 } result.reversed() } }   /** wraps java.lang.Long.toBinaryString in a Kotlin extension function */ fun Long.toBinaryString(): String = java.lang.Long.toBinaryString(this)   /** check if a binary or ternary numeric string 's' is palindromic */ fun isPalindromic(s: String): Boolean = (s == s.reversed())   /** print a number which is both a binary and ternary palindrome in all three bases */ fun printPalindrome(n: Long) { println("Decimal : $n") println("Binary  : ${n.toBinaryString()}") println("Ternary : ${n.toTernaryString()}") println() }   /** create a ternary palindrome whose left part is the ternary equivalent of 'n' and return its decimal equivalent */ fun createPalindrome3(n: Long): Long { val ternary = n.toTernaryString() var power3 = 1L var sum = 0L val length = ternary.length for (i in 0 until length) { // right part of palindrome is mirror image of left part if (ternary[i] > '0') sum += (ternary[i].toInt() - 48) * power3 power3 *= 3L } sum += power3 // middle digit must be 1 power3 *= 3L sum += n * power3 // value of left part is simply 'n' multiplied by appropriate power of 3 return sum }   fun main(args: Array<String>) { var i = 1L var p3: Long var count = 2 var binStr: String println("The first 6 numbers which are palindromic in both binary and ternary are:\n") // we can assume the first two palindromic numbers as per the task description printPalindrome(0L) // 0 is a palindrome in all 3 bases printPalindrome(1L) // 1 is a palindrome in all 3 bases   do { p3 = createPalindrome3(i) if (p3 % 2 > 0L) { // cannot be even as binary equivalent would end in zero binStr = p3.toBinaryString() if (binStr.length % 2 == 1) { // binary palindrome must have an odd number of digits if (isPalindromic(binStr)) { printPalindrome(p3) count++ } } } i++ } while (count < 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
#Erlang
Erlang
-spec fizzbuzz() -> Result :: string(). fizzbuzz() -> F = fun(N) when N rem 15 == 0 -> "FizzBuzz"; (N) when N rem 3 == 0 -> "Fizz"; (N) when N rem 5 == 0 -> "Buzz"; (N) -> integer_to_list(N) end, lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]).
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.
#Aime
Aime
o_(stat("input.txt", ST_SIZE), "\n"); o_("/Cygwin.ico".stat(ST_SIZE), "\n");
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.
#ALGOL_68
ALGOL 68
PROC set = (REF FILE file, INT page, line, character)VOID: ~
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
#11l
11l
F is_ext(file_name, extensions) R any(extensions.map(e -> @file_name.lowercase().ends_with(‘.’e.lowercase())))   F test(file_names, extensions) L(file_name) file_names print(file_name.ljust(max(file_names.map(f_n -> f_n.len)))‘ ’String(is_ext(file_name, extensions)))   test([‘MyData.a##’, ‘MyData.tar.Gz’, ‘MyData.gzip’, ‘MyData.7z.backup’, ‘MyData...’, ‘MyData’], [‘zip’, ‘rar’, ‘7z’, ‘gz’, ‘archive’, ‘A##’, ‘tar.bz2’]) test([‘MyData_v1.0.tar.bz2’, ‘MyData_v1.0.bz2’], [‘tar.bz2’])
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#BBC_BASIC
BBC BASIC
DIM ft{dwLowDateTime%, dwHighDateTime%} DIM st{wYear{l&,h&}, wMonth{l&,h&}, wDayOfWeek{l&,h&}, \ \ wDay{l&,h&}, wHour{l&,h&}, wMinute{l&,h&}, \ \ wSecond{l&,h&}, wMilliseconds{l&,h&} }   REM File is assumed to exist: file$ = @tmp$ + "rosetta.tmp"   REM Get and display the modification time: file% = OPENIN(file$) SYS "GetFileTime", @hfile%(file%), 0, 0, ft{} CLOSE #file% SYS "FileTimeToSystemTime", ft{}, st{} date$ = STRING$(16, CHR$0) time$ = STRING$(16, CHR$0) SYS "GetDateFormat", 0, 0, st{}, 0, date$, LEN(date$) TO N% date$ = LEFT$(date$, N%-1) SYS "GetTimeFormat", 0, 0, st{}, 0, time$, LEN(time$) TO N% time$ = LEFT$(time$, N%-1) PRINT date$ " " time$   REM Set the modification time to the current time: SYS "GetSystemTime", st{} SYS "SystemTimeToFileTime", st{}, ft{} file% = OPENUP(file$) SYS "SetFileTime", @hfile%(file%), 0, 0, ft{} CLOSE #file%  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#C
C
#include <sys/stat.h> #include <stdio.h> #include <time.h> #include <utime.h>   const char *filename = "input.txt";   int main() { struct stat foo; time_t mtime; struct utimbuf new_times;   if (stat(filename, &foo) < 0) { perror(filename); return 1; } mtime = foo.st_mtime; /* seconds since the epoch */   new_times.actime = foo.st_atime; /* keep atime unchanged */ new_times.modtime = time(NULL); /* set mtime to current time */ if (utime(filename, &new_times) < 0) { perror(filename); return 1; }   return 0; }
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?
#J
J
((10x^~.),.#/.~) <.10 ^.1>. /:~;{:|:dirtree '~' 1 2 10 8 100 37 1000 49 10000 20 100000 9 1000000 4 10000000 4
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?
#Julia
Julia
using Humanize   function sizelist(path::AbstractString) rst = Vector{Int}(0) for (root, dirs, files) in walkdir(path) files = joinpath.(root, files) tmp = collect(filesize(f) for f in files if !islink(f)) append!(rst, tmp) end return rst end   byclass(y, classes) = Dict{eltype(classes),Int}(c => count(c[1] .≤ y .< c[2]) for c in classes)   function main(path::AbstractString) s = sizelist(path) cls = append!([(0, 1)], collect((10 ^ (i-1), 10 ^ i) for i in 1:9)) f = byclass(s, cls)   println("filesizes: ") for c in cls @printf(" - between %8s and %8s bytes: %3i\n", datasize(c[1]), datasize(c[2]), f[c]) end println("\n-> total: $(datasize(sum(s))) bytes and $(length(s)) files") end   main(".")
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?
#Kotlin
Kotlin
// version 1.2.10   import java.io.File import kotlin.math.log10 import kotlin.math.floor   fun fileSizeDistribution(path: String) { val sizes = IntArray(12) val p = File(path) val files = p.walk() var accessible = 0 var notAccessible = 0 var totalSize = 0L for (file in files) { try { if (file.isFile()) { val len = file.length() accessible++ if (len == 0L) { sizes[0]++ continue } totalSize += len val logLen = log10(len.toDouble()) val index = floor(logLen).toInt() sizes[index + 1]++ } } catch (se: SecurityException) { notAccessible++ } }   println("File size distribution for '$path' :-\n") for (i in 0 until sizes.size) { print(if (i == 0) " " else "+ ") print("Files less than 10 ^ ${"%-2d".format(i)} bytes : ") println("%5d".format(sizes[i])) } println(" -----") println("= Number of accessible files  : ${"%5d".format(accessible)}") println("\n Total size in bytes  : $totalSize") println("\n Number of inaccessible files  : ${"%5d".format(notAccessible)}") }   fun main(args: Array<String>) { fileSizeDistribution("./") // current directory }
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
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <string> #include <vector>   std::string longestPath( const std::vector<std::string> & , char ) ;   int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; }   std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
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.
#ALGOL_68
ALGOL 68
MODE TYPE = INT;   PROC select = ([]TYPE from, PROC(TYPE)BOOL where)[]TYPE: BEGIN FLEX[0]TYPE result; FOR key FROM LWB from TO UPB from DO IF where(from[key]) THEN [UPB result+1]TYPE new result; new result[:UPB result] := result; new result[UPB new result] := from[key]; result := new result FI OD; result END;   []TYPE from values = (1,2,3,4,5,6,7,8,9,10); PROC where even = (TYPE value)BOOL: NOT ODD value;   print((select(from values, where even), new line));   # Or as a simple one line query # print((select((1,4,9,16,25,36,49,64,81,100), (TYPE x)BOOL: NOT ODD x ), new line))
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]]
#Lua
Lua
EPS = 0.001 EPS_SQUARE = EPS * EPS   function side(x1, y1, x2, y2, x, y) return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1) end   function naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) local checkSide1 = side(x1, y1, x2, y2, x, y) >= 0 local checkSide2 = side(x2, y2, x3, y3, x, y) >= 0 local checkSide3 = side(x3, y3, x1, y1, x, y) >= 0 return checkSide1 and checkSide2 and checkSide3 end   function pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) local xMin = math.min(x1, x2, x3) - EPS local xMax = math.max(x1, x2, x3) + EPS local yMin = math.min(y1, y2, y3) - EPS local yMax = math.max(y1, y2, y3) + EPS return not (x < xMin or xMax < x or y < yMin or yMax < y) end   function distanceSquarePointToSegment(x1, y1, x2, y2, x, y) local p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) local dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength if dotProduct < 0 then return (x - x1) * (x - x1) + (y - y1) * (y - y1) end if dotProduct <= 1 then local p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y) return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength end return (x - x2) * (x - x2) + (y - y2) * (y - y2) end   function accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) if not pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) then return false end if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) then return true end if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE then return true end return false end   function printPoint(x, y) io.write('('..x..", "..y..')') end   function printTriangle(x1, y1, x2, y2, x3, y3) io.write("Triangle is [") printPoint(x1, y1) io.write(", ") printPoint(x2, y2) io.write(", ") printPoint(x3, y3) print("]") end   function test(x1, y1, x2, y2, x3, y3, x, y) printTriangle(x1, y1, x2, y2, x3, y3) io.write("Point ") printPoint(x, y) print(" is within triangle? " .. tostring(accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y))) end   test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0) test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1) test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1) print()   test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348) print()   test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348) print()
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#TXR
TXR
@(bind foo ((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ())) @(bind bar foo) @(flatten bar)
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#VBScript
VBScript
  class flattener dim separator   sub class_initialize separator = "," end sub   private function makeflat( a ) dim i dim res for i = lbound( a ) to ubound( a ) if isarray( a( i ) ) then res = res & makeflat( a( i ) ) else res = res & a( i ) & separator end if next makeflat = res end function   public function flatten( a ) dim res res = makeflat( a ) res = left( res, len( res ) - len(separator)) res = split( res, separator ) flatten = res end function   public property let itemSeparator( c ) separator = c end property end class  
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.
#Factor
Factor
: recurse ( n -- n ) 1 + recurse ;   0 recurse
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.
#Fermat
Fermat
  Func Sisyphus(n)=!!n;Sisyphus(n+1). Sisyphus(0)  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
palindromify3[n_] := Block[{digits}, If[Divisible[n, 3], {}, digits = IntegerDigits[n, 3]; FromDigits[#, 3] & /@ {Join[Reverse[digits], digits], Join[Reverse[Rest[digits]], {First[digits]}, Rest[digits]]} ] ]; base2PalindromeQ[n_] := IntegerDigits[n, 2] === Reverse[IntegerDigits[n, 2]]; Select[Flatten[palindromify3 /@ Range[1000000]], base2PalindromeQ]
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.
#Nim
Nim
import bitops, strformat, times   #---------------------------------------------------------------------------------------------------   func isPal2(k: uint64; digitCount: Natural): bool = ## Return true if the "digitCount" + 1 bits of "k" form a palindromic number.   for i in 0..digitCount: if k.testBit(i) != k.testBit(digitCount - i): return false result = true   #---------------------------------------------------------------------------------------------------   func reverseNumber(k: uint64): uint64 = ## Return the reverse number of "n".   var p = k while p > 0: result += 2 * result + p mod 3 p = p div 3   #---------------------------------------------------------------------------------------------------   func toBase2(n: uint64): string = ## Return the string representation of "n" in base 2.   var n = n while true: result.add(chr(ord('0') + (n and 1))) n = n shr 1 if n == 0: break   #---------------------------------------------------------------------------------------------------   func toBase3(n: uint64): string = ## Return the string representation of "n" in base 3.   var n = n while true: result.add(chr(ord('0') + n mod 3)) n = n div 3 if n == 0: break   #---------------------------------------------------------------------------------------------------   proc print(n: uint64) = ## Print the value in bases 10, 2 and 3.   echo &"{n:>18} {n.toBase2():^59} {n.toBase3():^41}"   #---------------------------------------------------------------------------------------------------   proc findPal23() = ## Find the seven first palindromic numbers in binary and ternary bases.   var p3 = 1u64 var countPal = 1   print(0) for p in 0..31: while (3 * p3 + 1) * p3 < 1u64 shl (2 * p): p3 *= 3 let bound = 1u64 shl (2 * p) div (3 * p3) for k in max(p3 div 3, bound) .. min(2 * bound, p3 - 1): let n = (3 * k + 1) * p3 + reverseNumber(k) if isPal2(n, 2 * p): print(n) inc countPal if countPal == 7: return   #———————————————————————————————————————————————————————————————————————————————————————————————————   let t0 = cpuTime() findPal23() echo fmt"\nTime: {cpuTime() - t0:.2f}s"
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
#ERRE
ERRE
  PROGRAM FIZZ_BUZZ ! ! for rosettacode.org ! BEGIN FOR A=1 TO 100 DO IF A MOD 15=0 THEN PRINT("FizzBuzz") ELSIF A MOD 3=0 THEN PRINT("Fizz") ELSIF A MOD 5=0 THEN PRINT("Buzz") ELSE PRINT(A) END IF END FOR END PROGRAM  
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.
#Arturo
Arturo
print volume "input.txt" print volume "/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.
#AutoHotkey
AutoHotkey
FileGetSize, FileSize, input.txt ; Retrieve the size in bytes. MsgBox, Size of input.txt is %FileSize% bytes FileGetSize, FileSize, \input.txt, K ; Retrieve the size in Kbytes. MsgBox, Size of \input.txt is %FileSize% Kbytes
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
#Action.21
Action!
DEFINE PTR="CARD"   CHAR FUNC ToLower(CHAR c) IF c>='A AND c<='Z THEN c==+'a-'A FI RETURN (c)   BYTE FUNC CheckExt(CHAR ARRAY file,ext) BYTE i,j CHAR c1,c2   i=file(0) j=ext(0) IF i<j THEN RETURN (0) FI   WHILE j>0 DO c1=ToLower(file(i)) c2=ToLower(ext(j)) IF c1#c2 THEN RETURN (0) FI i==-1 j==-1 OD IF file(i)#'. THEN RETURN (0) FI RETURN (1)   BYTE FUNC Check(CHAR ARRAY file PTR ARRAY exts BYTE count) BYTE i   FOR i=0 TO count-1 DO IF CheckExt(file,exts(i)) THEN RETURN (1) FI OD RETURN (0)   PROC Main() PTR ARRAY exts(7),files(8) BYTE i   exts(0)="zip" exts(1)="rar" exts(2)="7z" exts(3)="gz" exts(4)="archive" exts(5)="A##" exts(6)="tar.bz2"   files(0)="MyData.a##" files(1)="MyData.tar.Gz" files(2)="MyData.gzip" files(3)="MyData.7z.backup" files(4)="MyData..." files(5)="MyData" files(6)="MyData_v1.0.tar.bz2" files(7)="MyData_v1.0.bz2"   FOR i=0 to 7 DO Print(files(i)) Print(" -> ") IF Check(files(i),exts,7) THEN PrintE("true") ELSE PrintE("false") FI OD RETURN
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Fixed.Equal_Case_Insensitive; use Ada.Strings.Fixed; with Ada.Strings.Bounded;   procedure Main is   package B_String is new Ada.Strings.Bounded.Generic_Bounded_Length (30); use B_String; function is_equal (left, right : String) return Boolean renames Ada.Strings.Fixed.Equal_Case_Insensitive;   type extension_list is array (Positive range <>) of Bounded_String; Ext_List : extension_list := (To_Bounded_String ("zip"), To_Bounded_String ("rar"), To_Bounded_String ("7z"), To_Bounded_String ("gz"), To_Bounded_String ("archive"), To_Bounded_String ("A##"), To_Bounded_String ("tar.bz2")); type filename_list is array (Positive range <>) of Bounded_String; fnames : filename_list := (To_Bounded_String ("MyData.a##"), To_Bounded_String ("MyData.tar.Gz"), To_Bounded_String ("MyData.gzip"), To_Bounded_String ("MyData..."), To_Bounded_String ("Mydata"), To_Bounded_String ("MyData_V1.0.tar.bz2"), To_Bounded_String ("MyData_v1.0.bz2")); Valid_Extension : Boolean; begin for name of fnames loop Valid_Extension := False; Put (To_String (name)); for ext of Ext_List loop declare S : String := "." & To_String (ext); T : String := Tail (Source => To_String (name), Count => S'Length); begin if is_equal (S, T) then Valid_Extension := True; end if; end; end loop; Set_Col (22); Put_Line (": " & Valid_Extension'Image); end loop; end Main;
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#C.23
C#
using System; using System.IO;   Console.WriteLine(File.GetLastWriteTime("file.txt")); File.SetLastWriteTime("file.txt", DateTime.Now);
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#C.2B.2B
C++
#include <boost/filesystem/operations.hpp> #include <ctime> #include <iostream>   int main( int argc , char *argv[ ] ) { if ( argc != 2 ) { std::cerr << "Error! Syntax: moditime <filename>!\n" ; return 1 ; } boost::filesystem::path p( argv[ 1 ] ) ; if ( boost::filesystem::exists( p ) ) { std::time_t t = boost::filesystem::last_write_time( p ) ; std::cout << "On " << std::ctime( &t ) << " the file " << argv[ 1 ] << " was modified the last time!\n" ; std::cout << "Setting the modification time to now:\n" ; std::time_t n = std::time( 0 ) ; boost::filesystem::last_write_time( p , n ) ; t = boost::filesystem::last_write_time( p ) ; std::cout << "Now the modification time is " << std::ctime( &t ) << std::endl ; return 0 ; } else { std::cout << "Could not find file " << argv[ 1 ] << '\n' ; return 2 ; } }
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?
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
SetDirectory[NotebookDirectory[]]; Histogram[FileByteCount /@ Select[FileNames[__], DirectoryQ /* Not], {"Log", 15}, {"Log", "Count"}]
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?
#Nim
Nim
import math, os, strformat   const MaxPower = 10 Powers = [1, 10, 100]   func powerWithUnit(idx: int): string = ## Return a string representing value 10^idx with a unit. if idx < 0: "0B" elif idx < 3: fmt"{Powers[idx]}B" elif idx < 6: fmt"{Powers[idx - 3]}kB" elif idx < 9: fmt"{Powers[idx - 6]}MB" else: fmt"{Powers[idx - 9]}GB"     # Retrieve the directory path. var dirpath: string if paramCount() == 0: dirpath = getCurrentDir() else: dirpath = paramStr(1) if not dirExists(dirpath): raise newException(ValueError, "wrong directory path: " & dirpath)   # Distribute sizes. var counts: array[-1..MaxPower, Natural] for path in dirpath.walkDirRec(): if not path.fileExists(): continue # Not a regular file. let size = getFileSize(path) let index = if size == 0: -1 else: log10(size.float).toInt inc counts[index]   # Display distribution. let total = sum(counts) echo "File size distribution for directory: ", dirpath echo "" for idx, count in counts: let rangeString = fmt"[{powerWithUnit(idx)}..{powerWithUnit(idx + 1)}[:" echo fmt"Size in {rangeString: 14} {count:>7} {100 * count / total:5.2f}%" echo "" echo "Total number of files: ", sum(counts)
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?
#Perl
Perl
use File::Find; use List::Util qw(max);   my %fsize; $dir = shift || '.'; find(\&fsize, $dir);   $max = max($max,$fsize{$_}) for keys %fsize; $total += $size while (undef,$size) = each %fsize;   print "File size distribution in bytes for directory: $dir\n"; for (0 .. max(keys %fsize)) { printf "# files @ %4sb %8s: %s\n", $_ ? '10e'.($_-1) : 0, $fsize{$_} // 0, histogram( $max, $fsize{$_} // 0, 80); } print "$total total files.\n";   sub histogram { my($max, $value, $width) = @_; my @blocks = qw<| ▏ ▎ ▍ ▌ ▋ ▊ ▉ █>; my $scaled = int $value * $width / $max; my $end = $scaled % 8; my $bar = int $scaled / 8; my $B = $blocks[8] x ($bar * 8) . ($end ? $blocks[$end] : ''); }   sub fsize { $fsize{ log10( (lstat($_))[7] ) }++ } sub log10 { my($s) = @_; $s ? int log($s)/log(10) : 0 }
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
#Clojure
Clojure
(use '[clojure.string :only [join,split]])   (defn common-prefix [sep paths] (let [parts-per-path (map #(split % (re-pattern sep)) paths) parts-per-position (apply map vector parts-per-path)] (join sep (for [parts parts-per-position :while (apply = parts)] (first parts)))))   (println (common-prefix "/" ["/home/user1/tmp/coverage/test" "/home/user1/tmp/covert/operator" "/home/user1/tmp/coven/members"]))
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.
#ALGOL_W
ALGOL W
begin  % sets the elements of out to the elements of in that return true from applying the where procedure to them %  % the bounds of in must be 1 :: inUb - out must be at least as big as in and the number of matching  %  % elements is returned in outUb - in and out can be the same array  % procedure select ( integer array in ( * ); integer value inUb  ; integer array out ( * ); integer result outUb  ; logical procedure where % ( integer value n ) % ) ; begin outUb := 0; for i := 1 until inUb do begin if where( in( i ) ) then begin outUb := outUb + 1; out( outUb ) := in( i ) end f_where_in_i end for_i end select ;  % test the select procedure % logical procedure isEven ( integer value n ) ; not odd( n ); integer array t, out ( 1 :: 10 ); integer outUb; for i := 1 until 10 do t( i ) := i; select( t, 10, out, outUb, isEven ); for i := 1 until outUb do writeon( i_w := 3, s_w := 0, out( i ) ); write() end.  
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]]
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
RegionMember[Polygon[{{1, 2}, {3, 1}, {2, 4}}], {2, 2}]
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]]
#Nim
Nim
import strformat   const Eps = 0.001 Eps2 = Eps * Eps   type Point = tuple[x, y: float] Triangle = object p1, p2, p3: Point     func initTriangle(p1, p2, p3: Point): Triangle = Triangle(p1: p1, p2: p2, p3: p3)   func side(p1, p2, p: Point): float = (p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - p1.y)     func distanceSquarePointToSegment(p1, p2, p: Point): float = let p1P2SquareLength = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y) let dotProduct = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / p1P2SquareLength if dotProduct < 0: return (p.x - p1.x) * (p.x - p1.x) + (p.y - p1.y) * (p.y - p1.y) if dotProduct <= 1: let pP1SquareLength = (p1.x - p.x) * (p1.x - p.x) + (p1.y - p.y) * (p1.y - p.y) return pP1SquareLength - dotProduct * dotProduct * p1P2SquareLength result = (p.x - p2.x) * (p.x - p2.x) + (p.y - p2.y) * (p.y - p2.y)     func pointInTriangleBoundingBox(t: Triangle; p: Point): bool = let xMin = min(t.p1.x, min(t.p2.x, t.p3.x)) - EPS let xMax = max(t.p1.x, max(t.p2.x, t.p3.x)) + EPS let yMin = min(t.p1.y, min(t.p2.y, t.p3.y)) - EPS let yMax = max(t.p1.y, max(t.p2.y, t.p3.y)) + EPS result = p.x in xMin..xMax and p.y in yMin..yMax     func nativePointInTriangle(t: Triangle; p: Point): bool = let checkSide1 = side(t.p1, t.p2, p) >= 0 let checkSide2 = side(t.p2, t.p3, p) >= 0 let checkSide3 = side(t.p3, t.p1, p) >= 0 result = checkSide1 and checkSide2 and checkSide3     func accuratePointInTriangle(t: Triangle; p: Point): bool = if not t.pointInTriangleBoundingBox(p): return false if t.nativePointInTriangle(p): return true if distanceSquarePointToSegment(t.p1, t.p2, p) <= Eps2 or distanceSquarePointToSegment(t.p3, t.p1, p) <= Eps2: return true     func `$`(p: Point): string = &"({p.x}, {p.y})"   func `$`(t: Triangle): string = &"Triangle[{t.p1}, {t.p2}, {t.p3}]"   func contains(t: Triangle; p: Point): bool = t.accuratePointInTriangle(p)     when isMainModule:   proc test(t: Triangle; p: Point) = echo t echo &"Point {p} is within triangle ? {p in t}"   var p1: Point = (1.5, 2.4) var p2: Point = (5.1, -3.1) var p3: Point = (-3.8, 1.2) var tri = initTriangle(p1, p2, p3) test(tri, (0.0, 0.0)) test(tri, (0.0, 1.0)) test(tri, (3.0, 1.0)) echo() p1 = (1 / 10, 1 / 9) p2 = (100 / 8, 100 / 3) p3 = (100 / 4, 100 / 9) tri = initTriangle(p1, p2, p3) let pt = (p1.x + 3.0 / 7 * (p2.x - p1.x), p1.y + 3.0 / 7 * (p2.y - p1.y)) test(tri, pt) echo() p3 = (-100 / 8, 100 / 6) tri = initTriangle(p1, p2, p3) test(tri, pt)
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Wart
Wart
def (flatten seq acc) if no.seq acc ~list?.seq (cons seq acc)  :else (flatten car.seq (flatten cdr.seq acc))
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.
#Forth
Forth
: munge ( n -- n' ) 1+ recurse ;   : test 0 ['] munge catch if ." Recursion limit at depth " . then ;   test \ Default gforth: Recursion limit at depth 3817
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.
#Fortran
Fortran
program recursion_depth   implicit none   call recurse (1)   contains   recursive subroutine recurse (i)   implicit none integer, intent (in) :: i   write (*, '(i0)') i call recurse (i + 1)   end subroutine recurse   end program recursion_depth
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.
#PARI.2FGP
PARI/GP
check(n)={ \\ Check for 2n+1-digit palindromes in base 3 my(N=3^n); forstep(i=N+1,2*N,[1,2], my(base2,base3=digits(i,3),k); base3=concat(Vecrev(base3[2..n+1]), base3); k=subst(Pol(base3),'x,3); base2=binary(k); if(base2==Vecrev(base2), print1(", "k)) ) }; print1("0, 1"); for(i=1,11,check(i))
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
#Euphoria
Euphoria
include std/utils.e   function fb( atom n ) sequence fb if remainder( n, 15 ) = 0 then fb = "FizzBuzz" elsif remainder( n, 5 ) = 0 then fb = "Fizz" elsif remainder( n, 3 ) = 0 then fb = "Buzz" else fb = sprintf( "%d", n ) end if return fb end function   function fb2( atom n ) return iif( remainder(n, 15) = 0, "FizzBuzz", iif( remainder( n, 5 ) = 0, "Fizz", iif( remainder( n, 3) = 0, "Buzz", sprintf( "%d", n ) ) ) ) end function   for i = 1 to 30 do printf( 1, "%s ", { fb( i ) } ) end for   puts( 1, "\n" )   for i = 1 to 30 do printf( 1, "%s ", { fb2( i ) } ) end for   puts( 1, "\n" )
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.
#AWK
AWK
@load "filefuncs" function filesize(name ,fd) { if ( stat(name, fd) == -1) return -1 # doesn't exist else return fd["size"] } BEGIN { print filesize("input.txt") print filesize("/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.
#Axe
Axe
If GetCalc("appvINPUT")→I Disp {I-2}ʳ▶Dec,i Else Disp "NOT FOUND",i 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.
#11l
11l
V file_contents = File(‘input.txt’).read() File(‘output.txt’, ‘w’).write(file_contents)
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
#ALGOL_68
ALGOL 68
# returns the length of str # OP LENGTH = ( STRING str )INT: ( UPB str - LWB str ) + 1; # returns TRUE if str ends with ending FALSE otherwise # PRIO ENDSWITH = 9; OP ENDSWITH = ( STRING str, STRING ending )BOOL: IF INT str length = LENGTH str; INT ending length = LENGTH ending; ending length > str length THEN # the ending is longer than the string # FALSE ELSE # the string is at least as long as the ending # str[ ( str length - ending length ) + 1 : AT 1 ] = ending FI # ENDSWITH # ; # returns str cnverted to upper case # OP TOUPPER = ( STRING str )STRING: BEGIN STRING result := str; FOR s pos FROM LWB result TO UPB result DO result[ s pos ] := to upper( result[ s pos ] ) OD; result END # TOUPPER # ; # tests whether file name has one of the extensions and returns # # the index of the extension in extensions or LWB extensions - 1 # # if it does not end with one of the extensions # # the tests are not case-sensitive # PROC has extension in list = ( STRING file name, []STRING extensions )INT: BEGIN INT extension number := LWB extensions - 1; STRING upper name = TOUPPER file name; FOR pos FROM LWB extensions TO UPB extensions WHILE extension number < LWB extensions DO IF upper name ENDSWITH ( "." + TOUPPER extensions[ pos ] ) THEN # found the extension # extension number := pos FI OD; extension number END # has extension # ; # test the has extension in list procedure # PROC test has extension in list = ( STRING file name, []STRING extensions, BOOL expected result )VOID: IF INT extension number = has extension in list( file name, extensions ); extension number < LWB extensions THEN # the file does not have one of the extensions # print( ( file name , " does not have an extension in the list " , IF expected result THEN "NOT AS EXPECTED" ELSE "" FI , newline ) ) ELSE # the file does have one of the extensions # print( ( file name , " has extension """ , extensions[ extension number ] , """ " , IF NOT expected result THEN "NOT AS EXPECTED" ELSE "" FI , newline ) ) FI # test has extension in list # ; # the extensions for the task # []STRING task extensions = ( "zip", "rar", "7z", "gz", "archive", "A##" ); # test the file names in the standard task # test has extension in list( "MyData.a##", task extensions, TRUE ); test has extension in list( "MyData.tar.Gz", task extensions, TRUE ); test has extension in list( "MyData.gzip", task extensions, FALSE ); test has extension in list( "MyData.7z.backup", task extensions, FALSE ); test has extension in list( "MyData...", task extensions, FALSE ); test has extension in list( "MyData", task extensions, FALSE ); # the extensions for the extra credit # []STRING ec extensions = ( "zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2" ); # test the file names in the extra credit # test has extension in list( "MyData_v1.0.tar.bz2", ec extensions, TRUE ); test has extension in list( "MyData_v1.0.bz2", ec extensions, FALSE )
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Clojure
Clojure
(import '(java.io File) '(java.util Date))   (Date. (.lastModified (File. "output.txt"))) (Date. (.lastModified (File. "docs")))   (.setLastModified (File. "output.txt") (.lastModified (File. "docs")))
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Common_Lisp
Common Lisp
(file-write-date "input.txt")
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?
#Phix
Phix
without js -- file i/o sequence sizes = {1}, res = {0} atom t1 = time()+1 function store_res(string filepath, sequence dir_entry) if not find('d', dir_entry[D_ATTRIBUTES]) then atom size = dir_entry[D_SIZE] integer sdx = 1 while size>sizes[sdx] do if sdx=length(sizes) then sizes &= sizes[$]*iff(mod(length(sizes),3)?10:10.24) res &= 0 end if sdx += 1 end while res[sdx] += 1 if time()>t1 then printf(1,"%,d files found\r",sum(res)) t1 = time()+1 end if end if return 0 -- keep going end function integer exit_code = walk_dir(".", store_res, true) printf(1,"%,d files found\n",sum(res)) integer w = max(res) --include builtins/pfile.e for i=1 to length(res) do integer ri = res[i] string s = file_size_k(sizes[i], 5), p = repeat('*',floor(60*ri/w)) printf(1,"files < %s: %s%,d\n",{s,p,ri}) end for
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
#Common_Lisp
Common Lisp
  (defun common-directory-path (&rest paths) (do* ((pathnames (mapcar #'(lambda (path) (cdr (pathname-directory (pathname path)))) paths)) ; convert strings to lists of subdirectories (rem pathnames (cdr rem)) (pos (length (first rem))) ) ; position of first mismatched element ((null (cdr rem)) (make-pathname :directory (cons :absolute (subseq (first pathnames) 0 pos)))) ; take the common sublists and convert back to a pathname (setq pos (min pos (mismatch (first rem) (second rem) :test #'string-equal))) )) ; compare two paths  
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#AmigaE
AmigaE
PROC main() DEF l : PTR TO LONG, r : PTR TO LONG, x l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] r := List(ListLen(l)) SelectList({x}, l, r, `Mod(x,2)=0) ForAll({x}, r, `WriteF('\d\n', x)) ENDPROC
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]]
#Perl
Perl
# 20201123 added Perl programming solution   use strict; use warnings;   use List::AllUtils qw(min max natatime); use constant EPSILON => 0.001; use constant EPSILON_SQUARE => EPSILON*EPSILON;   sub side { my ($x1, $y1, $x2, $y2, $x, $y) = @_; return ($y2 - $y1)*($x - $x1) + (-$x2 + $x1)*($y - $y1); }   sub naivePointInTriangle { my ($x1, $y1, $x2, $y2, $x3, $y3, $x, $y) = @_; my $checkSide1 = side($x1, $y1, $x2, $y2, $x, $y) >= 0 ; my $checkSide2 = side($x2, $y2, $x3, $y3, $x, $y) >= 0 ; my $checkSide3 = side($x3, $y3, $x1, $y1, $x, $y) >= 0 ; return $checkSide1 && $checkSide2 && $checkSide3 || 0 ; }   sub pointInTriangleBoundingBox { my ($x1, $y1, $x2, $y2, $x3, $y3, $x, $y) = @_; my $xMin = min($x1, min($x2, $x3)) - EPSILON; my $xMax = max($x1, max($x2, $x3)) + EPSILON; my $yMin = min($y1, min($y2, $y3)) - EPSILON; my $yMax = max($y1, max($y2, $y3)) + EPSILON; ( $x < $xMin || $xMax < $x || $y < $yMin || $yMax < $y ) ? 0 : 1 }   sub distanceSquarePointToSegment { my ($x1, $y1, $x2, $y2, $x, $y) = @_; my $p1_p2_squareLength = ($x2 - $x1)**2 + ($y2 - $y1)**2; my $dotProduct = ($x-$x1)*($x2-$x1)+($y-$y1)*($y2-$y1) ; if ( $dotProduct < 0 ) { return ($x - $x1)**2 + ($y - $y1)**2; } elsif ( $dotProduct <= $p1_p2_squareLength ) { my $p_p1_squareLength = ($x1 - $x)**2 + ($y1 - $y)**2; return $p_p1_squareLength - $dotProduct**2 / $p1_p2_squareLength; } else { return ($x - $x2)**2 + ($y - $y2)**2; } }   sub accuratePointInTriangle { my ($x1, $y1, $x2, $y2, $x3, $y3, $x, $y) = @_; return 0 unless pointInTriangleBoundingBox($x1,$y1,$x2,$y2,$x3,$y3,$x,$y); return 1 if ( naivePointInTriangle($x1, $y1, $x2, $y2, $x3, $y3, $x, $y) or distanceSquarePointToSegment($x1, $y1, $x2, $y2, $x, $y) <= EPSILON_SQUARE or distanceSquarePointToSegment($x2, $y2, $x3, $y3, $x, $y) <= EPSILON_SQUARE or distanceSquarePointToSegment($x3, $y3, $x1, $y1, $x, $y) <= EPSILON_SQUARE); return 0 }   my @DATA = (1.5, 2.4, 5.1, -3.1, -3.8, 0.5);   for my $point ( [0,0] , [0,1] ,[3,1] ) { print "Point (", join(',',@$point), ") is within triangle "; my $iter = natatime 2, @DATA; while ( my @vertex = $iter->()) { print '(',join(',',@vertex),') ' } print ': ',naivePointInTriangle (@DATA, @$point) ? 'True' : 'False', "\n" ; }
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#WDTE
WDTE
let a => import 'arrays'; let s => import 'stream';   let flatten array => a.stream array -> s.flatMap (@ f v => v { reflect 'Array' => a.stream v -> s.flatMap f; }) -> s.collect  ;
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.
#GAP
GAP
f := function(n) return f(n+1); end;   # Now loop until an error occurs f(0);   # Error message : # Entering break read-eval-print loop ... # you can 'quit;' to quit to outer loop, or # you may 'return;' to continue   n; # 4998   # quit "brk mode" and return to GAP quit;
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#gnuplot
gnuplot
# Put this in a file foo.gnuplot and run as # gnuplot foo.gnuplot   # probe by 1 up to 1000, then by 1% increases if (! exists("try")) { try=0 } try=(try<1000 ? try+1 : try*1.01)   recurse(n) = (n > 0 ? recurse(n-1) : 'ok') print "try recurse ", try print recurse(try) reread
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.
#Perl
Perl
use ntheory qw/fromdigits todigitstring/;   print "0 0 0\n"; # Hard code the 0 result for (0..2e5) { # Generate middle-1-palindrome in base 3. my $pal = todigitstring($_, 3); my $b3 = $pal . "1" . reverse($pal); # Convert base 3 number to base 2 my $b2 = todigitstring(fromdigits($b3, 3), 2); # Print results (including base 10) if base-2 palindrome print fromdigits($b2,2)," $b3 $b2\n" if $b2 eq reverse($b2); }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#F.23
F#
let fizzbuzz n = match n%3 = 0, n%5 = 0 with | true, false -> "fizz" | false, true -> "buzz" | true, true -> "fizzbuzz" | _ -> string n   let printFizzbuzz() = [1..100] |> List.iter (fizzbuzz >> printfn "%s")
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.
#BaCon
BaCon
' file size ' Return the entire message, FILELEN returns a NUMBER FUNCTION printlen$(STRING name$) IF FILEEXISTS(name$) THEN RETURN name$ & ": " & STR$(FILELEN(name$)) ELSE RETURN "file " & name$ & " not found" END IF END FUNCTION   PRINT printlen$("input.txt") PRINT printlen$("/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.
#Batch_File
Batch File
  @echo off if not exist "%~1" exit /b 1 & rem If file doesn't exist exit with error code of 1. for /f %%i in (%~1) do echo %~zi pause>nul  
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program readwrtFile64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ TAILLEBUF, 1000 /*********************************/ /* Initialized data */ /*********************************/ .data szMessErreur: .asciz "Error open input file.\n" szMessErreur4: .asciz "Error open output file.\n" szMessErreur1: .asciz "Error close file.\n" szMessErreur2: .asciz "Error read file.\n" szMessErreur3: .asciz "Error write output file.\n"   /*************************************************/ szMessCodeErr: .asciz "Error code décimal : @ \n"   szNameFileInput: .asciz "input.txt" szNameFileOutput: .asciz "output.txt"   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss sBuffer: .skip TAILLEBUF sZoneConv: .skip 24 /**********************************************/ /* -- Code section */ /**********************************************/ .text .global main main: // entry of program mov x0,AT_FDCWD ldr x1,qAdrszNameFileInput // file name mov x2,#O_RDWR // flags mov x3,#0 // mode mov x8,#OPEN // call system OPEN svc #0 cmp x0,0 // open error ? ble erreur mov x19,x0 // save File Descriptor ldr x1,qAdrsBuffer // buffer address mov x2,TAILLEBUF // buffer size mov x8,READ // call system READ svc 0 cmp x0,0 // read error ? ble erreur2 mov x20,x0 // length read characters // close imput file mov x0,x19 // Fd mov x8,CLOSE // call system CLOSE svc 0 cmp x0,0 // close error ? blt erreur1   // create output file mov x0,AT_FDCWD ldr x1,qAdrszNameFileOutput // file name mov x2,O_CREAT|O_RDWR // flags ldr x3,qFicMask1 // Mode mov x8,OPEN // call system open file svc 0 cmp x0,#0 // create error ? ble erreur4 mov x19,x0 // file descriptor ldr x1,qAdrsBuffer mov x2,x20 // length to write mov x8, #WRITE // select system call 'write' svc #0 // perform the system call cmp x0,#0 // error write ? blt erreur3   // close output file mov x0,x19 // Fd fichier mov x8, #CLOSE // call system CLOSE svc #0 cmp x0,#0 // error close ? blt erreur1 mov x0,#0 // return code OK b 100f erreur: ldr x1,qAdrszMessErreur bl displayError mov x0,#1 // error return code b 100f erreur1: ldr x1,qAdrszMessErreur1 bl displayError mov x0,#1 // error return code b 100f erreur2: ldr x1,qAdrszMessErreur2 bl displayError mov x0,#1 // error return code b 100f erreur3: ldr x1,qAdrszMessErreur3 bl displayError mov x0,#1 // error return code b 100f erreur4: ldr x1,qAdrszMessErreur4 bl displayError mov x0,#1 // error return code b 100f   100: // end program mov x8,EXIT svc 0 qAdrszNameFileInput: .quad szNameFileInput qAdrszNameFileOutput: .quad szNameFileOutput qAdrszMessErreur: .quad szMessErreur qAdrszMessErreur1: .quad szMessErreur1 qAdrszMessErreur2: .quad szMessErreur2 qAdrszMessErreur3: .quad szMessErreur3 qAdrszMessErreur4: .quad szMessErreur4 qAdrsBuffer: .quad sBuffer qFicMask1: .quad 0644 /******************************************************************/ /* display error message */ /******************************************************************/ /* x0 contains error code */ /* x1 contains address error message */ displayError: stp x2,lr,[sp,-16]! // save registers mov x2,x0 // save error code mov x0,x1 // display message error bl affichageMess mov x0,x2 ldr x1,qAdrsZoneConv // conversion error code bl conversion10S // decimal conversion ldr x0,qAdrszMessCodeErr ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message final ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrsZoneConv: .quad sZoneConv qAdrszMessCodeErr: .quad szMessCodeErr /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
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.
#ACL2
ACL2
:set-state-ok t   (defun read-channel (channel limit state) (mv-let (ch state) (read-char$ channel state) (if (or (null ch) (zp limit)) (let ((state (close-input-channel channel state))) (mv nil state)) (mv-let (so-far state) (read-channel channel (1- limit) state) (mv (cons ch so-far) state)))))   (defun read-from-file (filename limit state) (mv-let (channel state) (open-input-channel filename :character state) (mv-let (contents state) (read-channel channel limit state) (mv (coerce contents 'string) state))))   (defun write-channel (channel cs state) (if (endp cs) (close-output-channel channel state) (let ((state (write-byte$ (char-code (first cs)) channel state))) (let ((state (write-channel channel (rest cs) state))) state))))   (defun write-to-file (filename str state) (mv-let (channel state) (open-output-channel filename :byte state) (write-channel channel (coerce str 'list) state)))   (defun copy-file (in out state) (mv-let (contents state) (read-from-file in (expt 2 40) state) (write-to-file out contents state)))
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
#Arturo
Arturo
fileExtensions: map ["zip" "rar" "7z" "gz" "archive" "A##"] => ["." ++ lower]   hasExtension?: function [file][ in? extract.extension lower file fileExtensions ]   files: ["MyData.a##" "MyData.tar.Gz" "MyData.gzip" "MyData.7z.backup" "MyData..." "MyData"]   loop files 'file -> print [file "=> hasExtension?:" hasExtension? file]
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
#AWK
AWK
  # syntax: GAWK -f FILE_EXTENSION_IS_IN_EXTENSIONS_LIST.AWK BEGIN { n = split("zip,rar,7z,gz,archive,A##,tar.bz2", arr, ",") for (i=1; i<=n; i++) { ext_arr[tolower(arr[i])] = "" } filenames = "MyData.a##,MyData.tar.Gz,MyData.gzip,MyData.7z.backup,MyData...,MyData,MyData_v1.0.tar.bz2,MyData_v1.0.bz2" n = split(filenames, fn_arr, ",")   for (i=1; i<=n; i++) { ext_found = "" for (ext in ext_arr) { if (tolower(fn_arr[i]) ~ (".*\\." ext "$")) { ext_found = ext break } } ans = (ext_found == "") ? "is not in list" : ("is in list: " ext_found) printf("%s extension %s\n", fn_arr[i], ans) } exit(0) }
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#D
D
import std.stdio; import std.file: getTimes, setTimes, SysTime;   void main() { auto fname = "unixdict.txt"; SysTime fileAccessTime, fileModificationTime; getTimes(fname, fileAccessTime, fileModificationTime); writeln(fileAccessTime, "\n", fileModificationTime); setTimes(fname, fileAccessTime, fileModificationTime); }
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Delphi
Delphi
function GetModifiedDate(const aFilename: string): TDateTime; var hFile: Integer; iDosTime: Integer; begin hFile := FileOpen(aFilename, fmOpenRead); iDosTime := FileGetDate(hFile); FileClose(hFile); if (hFile = -1) or (iDosTime = -1) then raise Exception.Create('Cannot read file: ' + sFilename); Result := FileDateToDateTime(iDosTime); end;   procedure ChangeModifiedDate(const aFilename: string; aDateTime: TDateTime); begin FileSetDate(aFileName, DateTimeToFileDate(aDateTime)); end;
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?
#Python
Python
import sys, os from collections import Counter   def dodir(path): global h   for name in os.listdir(path): p = os.path.join(path, name)   if os.path.islink(p): pass elif os.path.isfile(p): h[os.stat(p).st_size] += 1 elif os.path.isdir(p): dodir(p) else: pass   def main(arg): global h h = Counter() for dir in arg: dodir(dir)   s = n = 0 for k, v in sorted(h.items()): print("Size %d -> %d file(s)" % (k, v)) n += v s += k * v print("Total %d bytes for %d files" % (s, n))   main(sys.argv[1:])
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?
#Racket
Racket
#lang racket   (define (file-size-distribution (d (current-directory)) #:size-group-function (sgf values)) (for/fold ((rv (hash)) (Σ 0) (n 0)) ((f (in-directory d)) #:when (file-exists? f)) (define sz (file-size f)) (values (hash-update rv (sgf sz) add1 0) (+ Σ sz) (add1 n))))   (define (log10-or-so x) (if (zero? x) #f (round (/ (log x) (log 10)))))   (define number-maybe-< (match-lambda** [(#f #f) #f] [(#f _) #t] [(_ #f) #f] [(a b) (< a b)]))   (define ...s? (match-lambda** [(one 1) one] [(one n) (string-append one "s")]))   (define ((report-fsd f) fsd Σ n) (for/list ((k (in-list (sort (hash-keys fsd) number-maybe-<)))) (printf "~a(size): ~a -> ~a ~a~%" (object-name f) k (hash-ref fsd k) (...s? "file" (hash-ref fsd k)))) (printf "Total: ~a ~a in ~a ~a~%" Σ (...s? "byte" Σ) n (...s? "file" n)))   (module+ test (call-with-values (λ () (file-size-distribution #:size-group-function log10-or-so)) (report-fsd log10-or-so)))
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.)
#AutoHotkey
AutoHotkey
#NoEnv SetBatchLines, -1 p := 0.3 ; Segment length (pixels) F_Word := 30   SysGet, Mon, MonitorWorkArea W := FibWord(F_Word) d := 1 x1 := 0 y1 := MonBottom Width := A_ScreenWidth Height := A_ScreenHeight   If (!pToken := Gdip_Startup()) { MsgBox, 48, Gdiplus Error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. ExitApp } OnExit, Shutdown   Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs Gui, 1: Show, NA   hwnd1 := WinExist() hbm := CreateDIBSection(Width, Height) hdc := CreateCompatibleDC() obm := SelectObject(hdc, hbm) G := Gdip_GraphicsFromHDC(hdc) Gdip_SetSmoothingMode(G, 4) pPen := Gdip_CreatePen(0xffff0000, 1)   Loop, Parse, W { if (d = 0) x2 := x1 + p, y2 := y1 else if (d = 1 || d = -3) x2 := x1, y2 := y1 - p else if (d = 2 || d = -2) x2 := x1 - p, y2 := y1 else if (d = 3 || d = -1) x2 := x1, y2 := y1 + p Gdip_DrawLine(G, pPen, x1, y1, x2, y2) if (!Mod(A_Index, 1500)) UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height) if (A_LoopField = 0) { if (!Mod(A_Index, 2)) d += 1 else d -= 1 } x1 := x2, y1 := y2, d := Mod(d, 4) }   Gdip_DeletePen(pPen) UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height) SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) return   FibWord(n, FW1=1, FW2=0) { Loop, % n - 2 FW3 := FW2 FW1, FW1 := FW2, FW2 := FW3 return FW3 }   Esc:: Shutdown: Gdip_DeletePen(pPen) SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) Gdip_Shutdown(pToken) ExitApp
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
#D
D
import std.stdio, std.string, std.algorithm, std.path, std.array;   string commonDirPath(in string[] paths, in string sep = "/") pure { if (paths.empty) return null; return paths.map!(p => p.split(sep)).reduce!commonPrefix.join(sep); }   void main() { immutable paths = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"]; writeln(`The common path is: "`, paths.commonDirPath, '"'); }
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.
#AntLang
AntLang
x:range[100] {1- x mod 2}hfilter x
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]]
#Phix
Phix
with javascript_semantics constant p0 = {0,0}, p1 = {0,1}, p2 = {3,1}, triangle = {{3/2, 12/5}, {51/10, -31/10}, {-19/5, 1/2}} function inside(sequence p) return sort(convex_hull({p}&triangle))==sort(deep_copy(triangle)) end function printf(1,"Point %v is with triangle %v?:%t\n",{p0,triangle,inside(p0)}) printf(1,"Point %v is with triangle %v?:%t\n",{p1,triangle,inside(p1)}) printf(1,"Point %v is with triangle %v?:%t\n",{p2,triangle,inside(p2)})
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Wren
Wren
import "/seq" for Lst   var a = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] System.print(Lst.flatten(a))
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.
#Go
Go
package main   import ( "flag" "fmt" "runtime/debug" )   func main() { stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") flag.Parse() if *stack > 0 { debug.SetMaxStack(*stack) } r(1) }   func r(l int) { if l%1000 == 0 { fmt.Println(l) } r(l + 1) }
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Gri
Gri
`Recurse' { show .depth. .depth. = {rpn .depth. 1 +} Recurse } .depth. = 1 Recurse
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.
#Phix
Phix
with javascript_semantics -- widths and limits for 32/64 bit running (see output below): constant {dsize,w3,w2,limit} = iff(machine_bits()=32?{12,23,37,6} :{18,37,59,7}), -- [atoms on 32-bit have only 53 bits of precision, but 7th ^^^^ requires 59] dfmt = sprintf("%%%dd",dsize), -- ie "%12d" or "%18d" esc = #1B function center(string s, integer l) l = max(0,floor((l-length(s))/2)) string space = repeat(' ',l) s = space & s & space return s end function integer count = 1 procedure show(atom n, string p2, p3) if count=1 then printf(1,"  %s %s %s\n",{pad_head("decimal",dsize),center("ternary",w3),center(" binary",w2)}) end if string ns = sprintf(dfmt,n) printf(1,"%2d: %s %s %s\n",{count, ns, center(p3,w3), center(p2,w2)}) count += 1 end procedure procedure progress64(string e, p2, p3) e = pad_head(e,dsize) printf(1,"--: %s %s %s\r",{e, center(p3,w3), center(p2,w2)}) end procedure function to_base(atom i, integer base) string s = "" while i>0 do s = append(s,remainder(i,base)+'0') i = floor(i/base) end while s = reverse(s) if s="" then s = "0" end if return s end function function from_base(string s, integer base) atom res = 0 for i=1 to length(s) do res = res*base+s[i]-'0' end for return res end function function sn(string s, integer f, base) -- helper function, return s mirrored (if f!=0) -- and as a (decimal) number (if base!=0) -- all returns from next_palindrome() get fed through here. if f then s[f+2..$] = reverse(s[1..f]) end if atom n = iff(base?from_base(s,base):0) return {s,n} end function function next_palindrome(integer base, object s) -- -- base is 2 or 3 -- s is not usually a palindrome, but derived from one in <5-base> -- -- all done with very obvious string manipulations, plus a few -- less obvious optimisations (odd length, middle 1 in base 3). -- -- example: next_palindrome(2,"10001000100") -> "10001010001" -- if not string(s) then s = to_base(s,base) end if integer l = length(s), f = floor(l/2), m = f+1, c if mod(l,2) then -- optimisation: palindromes must be odd-length -- 1) is a plain mirror greater? (as in the example just given) {string r} = sn(s,f,0) -- optimisation: base 3 palindromes have '1' in the middle if base=3 and r[m]!='1' then r[m] = '1' end if if r>s then return sn(r,0,base) end if -- 2) can we (just) increment the middle digit? c = s[m]-'0'+1 if base=2 or c=1 then if c<base then s[m] = c+'0' return sn(s,f,base) end if s[m] = '0' elsif base=3 then s[m] = '1' end if -- 3) can we increment left half (or is it all <base-1>s?) for i=f to 1 by -1 do if s[i]<base-1+'0' then s[i] += 1 return sn(s,f,base) else s[i] = '0' end if end for l += 2 -- (stay odd) else l += 1 -- (even->odd) end if -- 4) well then, next palindrome is longer, 1000..0001-style s = sprintf("1%s1",{repeat('0',l-2)}) -- optimisation: base 3 palindromes have '1' in the middle if base=3 then m = (l+1)/2 s[m] = '1' end if return sn(s,0,base) end function string p2 = "0", p3 = "0" -- palindromes as strings in base 2 and 3 atom n2 = 0, n3 = 0, -- decimal equivalents of the above. t0 = time(), t1 = time()+1 while count<=limit do if n2=n3 then show(n2,p2,p3) {p2,n2} = next_palindrome(2,p2) {p3,n3} = next_palindrome(3,p3) elsif n2<n3 then {p2,n2} = next_palindrome(2,n3-1) elsif n2>n3 then {p3,n3} = next_palindrome(3,n2-1) end if if time()>t1 and platform()!=JS then progress64(elapsed_short(time()-t0),p2,p3) t1 = time()+1 if find(get_key(),{'q','Q',esc}) then exit end if end if end while ?elapsed(time()-t0)