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/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
| #Factor | Factor | USING: math kernel io math.functions math.parser math.ranges ;
IN: fizzbuzz
: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ;
: buzz ( n -- str ) 5 divisor? "Buzz" "" ? ;
: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ;
: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ;
MAIN: main |
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.
| #BBC_BASIC | BBC BASIC | file% = OPENIN(@dir$+"input.txt")
IF file% THEN
PRINT "File size = " ; EXT#file%
CLOSE #file%
ENDIF
file% = OPENIN("\input.txt")
IF file% THEN
PRINT "File size = " ; EXT#file%
CLOSE #file%
ENDIF |
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.
| #Bracmat | Bracmat | (getFileSize=
size
. fil$(!arg,rb) {read in binary mode}
& fil$(,END) {seek to end of file}
& fil$(,TEL):?size {tell where we are}
& fil$(,SET,-1) {seeking to an impossible position closes the file, and fails}
| !size {return the size}
);
getFileSize$"valid.bra"
113622
getFileSize$"c:\\boot.ini"
211
|
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.
| #C | C | #include <stdlib.h>
#include <stdio.h>
long getFileSize(const char *filename)
{
long result;
FILE *fh = fopen(filename, "rb");
fseek(fh, 0, SEEK_END);
result = ftell(fh);
fclose(fh);
return result;
}
int main(void)
{
printf("%ld\n", getFileSize("input.txt"));
printf("%ld\n", getFileSize("/input.txt"));
return 0;
} |
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.
| #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
PROC CopyFile(CHAR ARRAY src,dst)
DEFINE BUF_LEN="1000"
BYTE in=[1], out=[2]
BYTE ARRAY buff(BUF_LEN)
CARD len
Close(in)
Close(out)
Open(in,src,4)
Open(out,dst,8)
DO
len=Bget(in,buff,BUF_LEN)
IF len>0 THEN
Bput(out,buff,len)
FI
UNTIL len#BUF_LEN
OD
Close(in)
Close(out)
RETURN
PROC Main()
CHAR ARRAY filter="D:*.*",
src="D:INPUT.TXT", dst="D:OUTPUT.TXT"
Put(125) PutE() ;clear screen
PrintF("Dir ""%S""%E",filter)
Dir(filter)
PrintF("Copy ""%S"" to ""%S""%E%E",src,dst)
CopyFile(src,dst)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
RETURN |
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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Read_And_Write_File_Line_By_Line is
Input, Output : File_Type;
begin
Open (File => Input,
Mode => In_File,
Name => "input.txt");
Create (File => Output,
Mode => Out_File,
Name => "output.txt");
loop
declare
Line : String := Get_Line (Input);
begin
-- You can process the contents of Line here.
Put_Line (Output, Line);
end;
end loop;
Close (Input);
Close (Output);
exception
when End_Error =>
if Is_Open(Input) then
Close (Input);
end if;
if Is_Open(Output) then
Close (Output);
end if;
end Read_And_Write_File_Line_By_Line; |
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
| #BASIC | BASIC | arraybase 1
dim extensions$ = {".zip", ".rar", ".7z", ".gz", ".archive", ".a##", ".tar.bz2"}
dim filenames$ = {"MyData.a##", "MyData.tar.gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2"}
#dim as integer n, m
#dim as boolean flag
for n = 1 to filenames$[?]
flag = False
for m = 1 to extensions$[?]
if right(filenames$[n], length(extensions$[m])) = extensions$[m] then
flag = True
print filenames$[n]; " -> "; extensions$[m]; " -> "; " true"
exit for
end if
next m
if flag = False then print filenames$[n]; " -> "; "false"
next n
end |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
set "extensions=.zip .rar .7z .gz .archive .A##"
:loop
if "%~1"=="" exit /b
set onlist=0
for %%i in (%extensions%) do if /i "%~x1"=="%%i" set onlist=1
if %onlist%==1 (
echo Filename: "%~1" ^| Extension: "%~x1" ^| TRUE
) else (
echo Filename: "%~1" ^| Extension: "%~x1" ^| FALSE
)
shift
goto loop
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #E | E | def strdate(date) {
return E.toString(<unsafe:java.util.makeDate>(date))
}
def test(type, file) {
def t := file.lastModified()
println(`The following $type called ${file.getPath()} ${
if (t == 0) { "does not exist." } else { `was modified at ${strdate(t)}` }}`)
println(`The following $type called ${file.getPath()} ${
escape ne { file.setLastModified(timer.now(), ne); "was modified to current time." } catch _ { "does not exist." }}`)
println(`The following $type called ${file.getPath()} ${
escape ne { file.setLastModified(t, ne); "was modified to previous time." } catch _ { "does not exist." }}`)
}
test("file", <file:output.txt>)
test("directory", <file:docs>) |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Elixir | Elixir | iex(1)> info = File.stat!("input.txt")
%File.Stat{access: :read_write, atime: {{2015, 10, 29}, {20, 44, 28}},
ctime: {{2015, 9, 20}, {9, 5, 58}}, gid: 0, inode: 0, links: 1,
major_device: 3, minor_device: 0, mode: 33206,
mtime: {{2015, 10, 29}, {20, 44, 28}}, size: 45, type: :regular, uid: 0}
iex(2)> info.mtime
{{2015, 10, 29}, {20, 44, 28}}
iex(3)> File.touch!("input.txt")
:ok
iex(4)> File.stat!("input.txt")
%File.Stat{access: :read_write, atime: {{2016, 3, 7}, {23, 12, 35}},
ctime: {{2016, 3, 7}, {23, 12, 35}}, gid: 0, inode: 0, links: 1,
major_device: 3, minor_device: 0, mode: 33206,
mtime: {{2016, 3, 7}, {23, 12, 35}}, size: 45, type: :regular, uid: 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?
| #Raku | Raku | sub MAIN($dir = '.') {
sub log10 (Int $s) { $s ?? $s.log(10).Int !! 0 }
my %fsize;
my @dirs = $dir.IO;
while @dirs {
for @dirs.pop.dir -> $path {
%fsize{$path.s.&log10}++ if $path.f;
@dirs.push: $path if $path.d and $path.r
}
}
my $max = %fsize.values.max;
my $bar-size = 80;
say "File size distribution in bytes for directory: $dir\n";
for 0 .. %fsize.keys.max {
say sprintf( "# Files @ %5sb %8s: ", $_ ?? "10e{$_-1}" !! 0, %fsize{$_} // 0 ),
histogram( $max, %fsize{$_} // 0, $bar-size )
}
say %fsize.values.sum, ' total files.';
}
sub histogram ($max, $value, $width = 60) {
my @blocks = <| ▏ ▎ ▍ ▌ ▋ ▊ ▉ █>;
my $scaled = ($value * $width / $max).Int;
my ($end, $bar) = $scaled.polymod(8);
(@blocks[8] x $bar * 8) ~ (@blocks[$end] if $end) ~ "\n"
} |
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.)
| #C | C | #include <stdio.h>
int main(void)
{
puts( "%!PS-Adobe-3.0 EPSF\n"
"%%BoundingBox: -10 -10 400 565\n"
"/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n"
"/b{a 90 rotate}def");
char i;
for (i = 'c'; i <= 'z'; i++)
printf("/%c{%c %c}def\n", i, i-1, i-2);
puts("0 setlinewidth z showpage\n%%EOF");
return 0;
} |
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.)
| #C.2B.2B | C++ |
#include <windows.h>
#include <string>
using namespace std;
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
clear();
return true;
}
void clear()
{
ZeroMemory( pBits, width * height * sizeof( DWORD ) );
}
void setPenColor( DWORD clr )
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, 1, clr );
SelectObject( hdc, pen );
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD* dwpBits;
DWORD wb;
HANDLE file;
GetObject( bmp, sizeof( bitmap ), &bitmap );
dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() { return hdc; }
int getWidth() { return width; }
int getHeight() { return height; }
private:
HBITMAP bmp;
HDC hdc;
HPEN pen;
void *pBits;
int width, height;
};
class fiboFractal
{
public:
fiboFractal( int l )
{
bmp.create( 600, 440 );
bmp.setPenColor( 0x00ff00 );
createWord( l ); createFractal();
bmp.saveBitmap( "path_to_save_bitmap" );
}
private:
void createWord( int l )
{
string a = "1", b = "0", c;
l -= 2;
while( l-- )
{ c = b + a; a = b; b = c; }
fWord = c;
}
void createFractal()
{
int n = 1, px = 10, dir,
py = 420, len = 1,
x = 0, y = -len, goingTo = 0;
HDC dc = bmp.getDC();
MoveToEx( dc, px, py, NULL );
for( string::iterator si = fWord.begin(); si != fWord.end(); si++ )
{
px += x; py += y;
LineTo( dc, px, py );
if( !( *si - 48 ) )
{ // odd
if( n & 1 ) dir = 1; // right
else dir = 0; // left
switch( goingTo )
{
case 0: // up
y = 0;
if( dir ){ x = len; goingTo = 1; }
else { x = -len; goingTo = 3; }
break;
case 1: // right
x = 0;
if( dir ) { y = len; goingTo = 2; }
else { y = -len; goingTo = 0; }
break;
case 2: // down
y = 0;
if( dir ) { x = -len; goingTo = 3; }
else { x = len; goingTo = 1; }
break;
case 3: // left
x = 0;
if( dir ) { y = -len; goingTo = 0; }
else { y = len; goingTo = 2; }
}
}
n++;
}
}
string fWord;
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
fiboFractal ff( 23 );
return system( "pause" );
}
|
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
| #Delphi | Delphi |
program Find_common_directory_path;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function FindCommonPath(Separator: Char; Paths: TArray<string>): string;
var
SeparatedPath: array of TArray<string>;
minLength, index: Integer;
isSame: Boolean;
j, i: Integer;
cmp: string;
begin
SetLength(SeparatedPath, length(Paths));
minLength := MaxInt;
for i := 0 to High(SeparatedPath) do
begin
SeparatedPath[i] := Paths[i].Split([Separator]);
if minLength > length(SeparatedPath[i]) then
minLength := length(SeparatedPath[i]);
end;
index := -1;
for i := 0 to minLength - 1 do
begin
isSame := True;
cmp := SeparatedPath[0][i];
for j := 1 to High(SeparatedPath) do
if SeparatedPath[j][i] <> cmp then
begin
isSame := False;
Break;
end;
if not isSame then
begin
index := i - 1;
Break;
end;
end;
Result := '';
if index >= 0 then
for i := 0 to index do
begin
Result := Result + SeparatedPath[0][i];
if i < index then
Result := Result + Separator;
end;
end;
begin
Writeln(FindCommonPath('/', [
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members']));
Readln;
end. |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Apex | Apex | List<Integer> integers = new List<Integer>{1,2,3,4,5};
Set<Integer> evenIntegers = new Set<Integer>();
for(Integer i : integers)
{
if(math.mod(i,2) == 0)
{
evenIntegers.add(i);
}
}
system.assert(evenIntegers.size() == 2, 'We should only have two even numbers in the set');
system.assert(!evenIntegers.contains(1), '1 should not be a number in the set');
system.assert(evenIntegers.contains(2), '2 should be a number in the set');
system.assert(!evenIntegers.contains(3), '3 should not be a number in the set');
system.assert(evenIntegers.contains(4), '4 should be a number in the set');
system.assert(!evenIntegers.contains(5), '5 should not be a number in the set'); |
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]]
| #Python | Python |
""" find if point is in a triangle """
from sympy.geometry import Point, Triangle
def sign(pt1, pt2, pt3):
""" which side of plane cut by line (pt2, pt3) is pt1 on? """
return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)
def iswithin(point, pt1, pt2, pt3):
"""
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. zval is positive if outside,
negative if inside such a plane. All should be positive or all negative
if point is within the triangle.
"""
zval1 = sign(point, pt1, pt2)
zval2 = sign(point, pt2, pt3)
zval3 = sign(point, pt3, pt1)
notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
return notanyneg or notanypos
if __name__ == "__main__":
POINTS = [Point(0, 0)]
TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
for pnt in POINTS:
a, b, c = TRI.vertices
isornot = "is" if iswithin(pnt, a, b, c) else "is not"
print("Point", pnt, isornot, "within the triangle", TRI)
|
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
| #XBasic | XBasic | PROGRAM "Flatten a list"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
n$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
FOR i = 1 TO LEN(n$)
IF INSTR("[] ,",MID$(n$,i,1)) = 0 THEN
flatten$ = flatten$ + c$ + MID$(n$,i,1)
c$ = ", "
END IF
NEXT i
PRINT "[";flatten$;"]"
END FUNCTION
END PROGRAM |
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.
| #Groovy | Groovy | def recurse;
recurse = {
try {
recurse (it + 1)
} catch (StackOverflowError e) {
return it
}
}
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.
| #Haskell | Haskell | import Debug.Trace (trace)
recurse :: Int -> Int
recurse n = trace (show n) recurse (succ n)
main :: IO ()
main = print $ recurse 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.
| #Picat | Picat |
import sat.
to_num(List, Base, Num) =>
Len = length(List),
Num #= sum([List[I] * Base**(Len-I) : I in 1..Len]).
palindrom(S) =>
N = len(S),
Start :: 1..N, % start at the first non-zero position:
foreach(I in 1..N)
I1 #= max(1, min(N, N-(I-Start))), % I1 is the symmetry index partner of I (if relevant)
element(I1, S, S1), % S1 is the respective digit
I #< Start #=> S[I] #= 0, % skip leading 0´s
I #= Start #=> S[I] #> 0, % Start points to the first non-zero digit
I #>= Start #=> S[I] #= S1 % palindromic symmetry
end.
constrain(Max, B, X) =>
Len = floor(log(Max) / log(B)) + 1, % length of Max in Base B representation
Digits = new_list(Len), Digits :: 0..B-1,
to_num(Digits, B, X), % Digits show the Base B representation of X
palindrom(Digits).
main =>
N = 11, % maximum number of decimal digits for search, can be set freely
Max = 10**N - 1, % maximum number
X :: 2..Max,
constrain(Max, 2, X),
constrain(Max, 3, X),
Pnumbers = solve_all([X]),
foreach([Y] in [[0], [1]] ++ Pnumbers.sort()) % start with 0 and 1, then show solutions > 1
printf("%w %s %s%n", Y, to_radix_string(Y,2), to_radix_string(Y,3))
end.
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
| #PicoLisp | PicoLisp | (de ternary (N)
(if (=0 N)
(cons N)
(make
(while (gt0 N)
(yoke (% (swap 'N (/ N 3)) 3)) ) ) ) )
(de p? (L1 L2)
(and
(= L1 (reverse L1))
(= L2 (reverse L2)) ) )
(zero N)
(for (I 0 (> 6 I))
(let (B2 (chop (bin N)) B3 (ternary N))
(when (p? B2 B3)
(println N (pack B2) (pack B3))
(inc 'I) )
(inc '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
| #Falcon | Falcon | for i in [1:101]
switch i % 15
case 0 : > "FizzBuzz"
case 5,10 : > "Buzz"
case 3,6,9,12 : > "Fizz"
default : > i
end
end |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #C.23 | C# | using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new FileInfo("/input.txt").Length);
Console.WriteLine(new FileInfo("input.txt").Length);
}
}
|
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #C.2B.2B | C++ | #include <iostream>
#include <fstream>
std::ios::off_type getFileSize(const char *filename) {
std::ifstream f(filename);
std::ios::pos_type begin = f.tellg();
f.seekg(0, std::ios::end);
std::ios::pos_type end = f.tellg();
return end - begin;
}
int main() {
std::cout << getFileSize("input.txt") << std::endl;
std::cout << getFileSize("/input.txt") << std::endl;
return 0;
} |
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.
| #Aime | Aime | file i, o;
text s;
i.open("input.txt", OPEN_READONLY, 0);
o.open("output.txt", OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY,
0644);
while (i.line(s) ^ -1) {
o.text(s);
o.byte('\n');
} |
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.
| #ALGOL_68 | ALGOL 68 | PROC copy file v1 = (STRING in name, out name)VOID: (
# note: algol68toc-1.18 - can compile, but not run v1 #
INT errno;
FILE in file, out file;
errno := open(in file, in name, stand in channel);
errno := open(out file, out name, stand out channel);
BOOL in ended := FALSE;
PROC call back ended = (REF FILE f) BOOL: in ended := TRUE;
on logical file end(in file, call back ended);
STRING line;
WHILE
get(in file, (line, new line));
# WHILE # NOT in ended DO # break to avoid excess new line #
put(out file, (line, new line))
OD;
ended:
close(in file);
close(out file)
);
PROC copy file v2 = (STRING in name, out name)VOID: (
INT errno;
FILE in file, out file;
errno := open(in file, in name, stand in channel);
errno := open(out file, out name, stand out channel);
PROC call back ended = (REF FILE f) BOOL: GO TO done;
on logical file end(in file, call back ended);
STRING line;
DO
get(in file, line);
put(out file, line);
get(in file, new line);
put(out file, new line)
OD;
done:
close(in file);
close(out file)
);
test:(
copy file v2("input.txt","output.txt")
) |
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
| #C | C | /*
* File extension is in extensions list (dots allowed).
*
* This problem is trivial because the so-called extension is simply the end
* part of the name.
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <locale.h>
#include <string.h>
#ifdef _Bool
#include <stdbool.h>
#else
#define bool int
#define true 1
#define false 0
#endif
/*
* The implemented algorithm is not the most efficient one: for N extensions
* of length M it has the cost O(N * M).
*/
int checkFileExtension(char* fileName, char* fileExtensions)
{
char* fileExtension = fileExtensions;
if ( *fileName )
{
while ( *fileExtension )
{
int fileNameLength = strlen(fileName);
int extensionLength = strlen(fileExtension);
if ( fileNameLength >= extensionLength )
{
char* a = fileName + fileNameLength - extensionLength;
char* b = fileExtension;
while ( *a && toupper(*a++) == toupper(*b++) )
;
if ( !*a )
return true;
}
fileExtension += extensionLength + 1;
}
}
return false;
}
void printExtensions(char* extensions)
{
while( *extensions )
{
printf("%s\n", extensions);
extensions += strlen(extensions) + 1;
}
}
bool test(char* fileName, char* extension, bool expectedResult)
{
bool result = checkFileExtension(fileName,extension);
bool returnValue = result == expectedResult;
printf("%20s result: %-5s expected: %-5s test %s\n",
fileName,
result ? "true" : "false",
expectedResult ? "true" : "false",
returnValue ? "passed" : "failed" );
return returnValue;
}
int main(void)
{
static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0";
setlocale(LC_ALL,"");
printExtensions(extensions);
printf("\n");
if ( test("MyData.a##", extensions,true )
&& test("MyData.tar.Gz", extensions,true )
&& test("MyData.gzip", extensions,false)
&& test("MyData.7z.backup", extensions,false)
&& test("MyData...", extensions,false)
&& test("MyData", extensions,false)
&& test("MyData_v1.0.tar.bz2",extensions,true )
&& test("MyData_v1.0.bz2", extensions,false)
&& test("filename", extensions,false)
)
printf("\n%s\n", "All tests passed.");
else
printf("\n%s\n", "Last test failed.");
printf("\n%s\n", "press enter");
getchar();
return 0;
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Emacs_Lisp | Emacs Lisp | (nth 5 (file-attributes "input.txt")) ;; mod date+time
(set-file-times "input.txt") ;; to current-time
(set-file-times "input.txt"
(encode-time 0 0 0 1 1 2014)) ;; to given date+time |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Erlang | Erlang |
-module( file_modification_time ).
-include_lib("kernel/include/file.hrl").
-export( [task/0] ).
task() ->
File = "input.txt",
{ok, File_info} = file:read_file_info( File ),
io:fwrite( "Modification time ~p~n", [File_info#file_info.mtime] ),
ok = file:write_file_info( File, File_info#file_info{mtime=calendar:local_time()} ).
|
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?
| #REXX | REXX | /*REXX program displays a histogram of filesize distribution of a directory structure(s)*/
numeric digits 30 /*ensure enough decimal digits for a #.*/
parse arg ds . /*obtain optional argument from the CL.*/
parse source . . path . /* " the path of this REXX program.*/
fID= substr(path, 1 + lastpos('\', path) ) /* " the filename and the filetype.*/
parse var fID fn '.' /* " just the pure filename of pgm.*/
sw=max(79, linesize() - 1) /* " terminal width (linesize) - 1.*/
work= fn".OUT" /*filename for workfile output of DIR.*/
'DIR' ds '/s /-c /a-d >' work /*do (DOS) DIR cmd for a data structure*/
call linein 0, 1 /*open output file, point to 1st record*/
maxL= 0; @.= 00; g= 0 /*max len size; log array; # good recs.*/
$=0 /*$: total bytes used by files found. */
do while lines(work)\==0; _= linein(work) /*process the data in the DIR work file*/
if left(_, 1)==' ' then iterate /*Is the record not legitimate? Skip. */
parse upper var _ . . sz . /*uppercase the suffix (if any). */
sz= space( translate(sz, , ','), 0) /*remove any commas if present in the #*/
if \datatype(sz,'W') then do; #= left(sz, length(sz) - 1) /*SZ has a suffix?*/
if \datatype(#,'N') then iterate /*Meat ¬ numeric? */
sz= # * 1024 ** pos( right(sz, 1), 'KMGTPEZYXWVU') / 1
end /* [↑] use suffix*/
$= $ + sz /*keep a running total for the filesize*/
if sz==0 then L= 0 /*handle special case for an empty file*/
else L= length(sz) /*obtain the length of filesize number.*/
g= g + 1 /*bump the counter of # of good records*/
maxL= max(L, maxL) /*get max length filesize for alignment*/
@.L= @.L + 1 /*bump counter of record size category.*/
end /*j*/ /* [↑] categories: split by log ten.*/
if g==0 then do; say 'file not found: ' ds; exit 13; end /*no good records*/
say ' record size range count '
hdr= '══════════════════ ══════════ '; say hdr; Lhdr=length(hdr)
mC=0 /*mC: the maximum count for any range.*/
do t=1 to 2 /*T==1 is used to find the max count.*/
do k=0 to maxL; mC= max(mC, @.k); if t==1 then iterate /*1st pass? */
if k==0 then y= center('zero', length( word(hdr, 1) ) )
else y= '10^'left(k-1,2) "──► 10^"left(k,2) '-1'
say y || right( commas(@.k), 11) copies('─', max(1, (@.k / mC * sw % 1) - LHdr) )
end /*k*/
end /*y*/
say
trace off; 'ERASE' work /*perform clean─up (erase a work file).*/
say commas(g) ' files detected, ' commas($) " total bytes."
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do j#=length(_)-3 to 1 by -3; _=insert(',', _, j#); end; return _ |
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.)
| #D | D | import std.range, grayscale_image, turtle;
void drawFibonacci(Color)(Image!Color img, ref Turtle t,
in string word, in real step) {
foreach (immutable i, immutable c; word) {
t.forward(img, step);
if (c == '0') {
if ((i + 1) % 2 == 0)
t.left(90);
else
t.right(90);
}
}
}
void main() {
auto img = new Image!Gray(1050, 1050);
auto t = Turtle(30, 1010, -90);
const w = recurrence!q{a[n-1] ~ a[n-2]}("1", "0").drop(24).front;
img.drawFibonacci(t, w, 1);
img.savePGM("fibonacci_word_fractal.pgm");
} |
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
| #Elixir | Elixir | defmodule RC do
def common_directory_path(dirs, separator \\ "/") do
dir1 = Enum.min(dirs) |> String.split(separator)
dir2 = Enum.max(dirs) |> String.split(separator)
Enum.zip(dir1,dir2) |> Enum.take_while(fn {a,b} -> a==b end)
|> Enum.map_join(separator, fn {a,a} -> a end)
end
end
dirs = ~w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members )
IO.inspect RC.common_directory_path(dirs) |
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
| #Erlang | Erlang |
-module( find_common_directory ).
-export( [path/2, task/0] ).
path( [Path | T], _Separator ) -> filename:join( lists:foldl(fun keep_common/2, filename:split(Path), [filename:split(X) || X <- T]) ).
task() -> path( ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"], "/" ).
keep_common( Components, Acc ) -> [X || X <- Components, Y <- Acc, X =:= Y].
|
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.
| #APL | APL | (0=2|x)/x←⍳20
2 4 6 8 10 12 14 16 18 20 |
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]]
| #Racket | Racket | #lang racket/base
(define-syntax-rule (all-between-0..1? x ...)
(and (<= 0 x 1) ...))
(define (point-in-triangle?/barycentric x1 y1 x2 y2 x3 y3)
(let* ((y2-y3 (- y2 y3))
(x1-x3 (- x1 x3))
(x3-x2 (- x3 x2))
(y1-y3 (- y1 y3))
(d (+ (* y2-y3 x1-x3) (* x3-x2 y1-y3))))
(λ (x y)
(define a (/ (+ (* x3-x2 (- y y3)) (* y2-y3 (- x x3))) d))
(define b (/ (- (* x1-x3 (- y y3)) (* y1-y3 (- x x3))) d))
(define c (- 1 a b))
(all-between-0..1? a b c))))
(define (point-in-triangle?/parametric x1 y1 x2 y2 x3 y3)
(let ((dp (+ (* x1 (- y2 y3)) (* y1 (- x3 x2)) (* x2 y3) (- (* y2 x3)))))
(λ (x y)
(define t1 (/ (+ (* x (- y3 y1)) (* y (- x1 x3)) (- (* x1 y3)) (* y1 x3)) dp))
(define t2 (/ (+ (* x (- y2 y1)) (* y (- x1 x2)) (- (* x1 y2)) (* y1 x2)) (- dp)))
(all-between-0..1? t1 t2 (+ t1 t2)))))
(define (point-in-triangle?/dot-product X1 Y1 X2 Y2 X3 Y3)
(λ (x y)
(define (check-side x1 y1 x2 y2)
(>= (+ (* (- y2 y1) (- x x1)) (* (- x1 x2) (- y y1))) 0))
(and
(check-side X1 Y1 X2 Y2)
(check-side X2 Y2 X3 Y3)
(check-side X3 Y3 X1 Y1))))
(module+ main
(require rackunit)
(define (run-tests point-in-triangle?)
(define pit?-1 (point-in-triangle? #e1.5 #e2.4 #e5.1 #e-3.1 #e-3.8 #e1.2))
(check-true (pit?-1 0 0))
(check-true (pit?-1 0 1))
(check-false (pit?-1 3 1))
(check-true ((point-in-triangle? 1/10 1/9 25/2 100/3 25 10/9) #e5.414285714285714 #e14.349206349206348))
; exactly speaking, point is _not_ in the triangle
(check-false ((point-in-triangle? 1/10 1/9 25/2 100/3 -25/2 50/3) #e5.414285714285714 #e14.349206349206348)))
(run-tests point-in-triangle?/barycentric)
(run-tests point-in-triangle?/parametric)
(run-tests point-in-triangle?/dot-product)) |
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]]
| #Raku | Raku | class Point {
has Real $.x is rw;
has Real $.y is rw;
method gist { [~] '(', self.x,', ', self.y, ')' };
}
sub sign (Point $a, Point $b, Point $c) {
($b.x - $a.x)*($c.y - $a.y) - ($b.y - $a.y)*($c.x - $a.x);
}
sub triangle (*@points where *.elems == 6) {
@points.batch(2).map: { Point.new(:x(.[0]),:y(.[1])) };
}
sub is-within ($point, @triangle is copy) {
my @signs = sign($point, |(@triangle.=rotate)[0,1]) xx 3;
so (all(@signs) >= 0) or so(all(@signs) <= 0);
}
my @triangle = triangle((1.5, 2.4), (5.1, -3.1), (-3.8, 0.5));
for Point.new(:x(0),:y(0)),
Point.new(:x(0),:y(1)),
Point.new(:x(3),:y(1))
-> $point {
say "Point {$point.gist} is within triangle {join ', ', @triangle».gist}: ",
$point.&is-within: @triangle
} |
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
| #Yabasic | Yabasic | sString$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
For siCount = 1 To Len(sString$)
If Instr("[] ,", Mid$(sString$, siCount, 1)) = 0 Then
sFlatter$ = sFlatter$ + sComma$ + Mid$(sString$, siCount, 1)
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.
| #hexiscript | hexiscript | fun rec n
println n
rec (n + 1)
endfun
rec 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.
| #HolyC | HolyC | U0 Recurse(U64 i) {
Print("%d\n", i);
Recurse(i + 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.
| #Python | Python | from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1] # reverse
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
#if len(b) > 12: break
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2)) |
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
| #FALSE | FALSE | class FizzBuzz
{
public static Void main ()
{
for (Int i:=1; i <= 100; ++i)
{
if (i % 15 == 0)
echo ("FizzBuzz")
else if (i % 3 == 0)
echo ("Fizz")
else if (i % 5 == 0)
echo ("Buzz")
else
echo (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.
| #Clean | Clean | import StdEnv
fileSize fileName world
# (ok, file, world) = fopen fileName FReadData world
| not ok = abort "Cannot open file"
# (ok, file) = fseek file 0 FSeekEnd
| not ok = abort "Cannot seek file"
# (size, file) = fposition file
(_, world) = fclose file world
= (size, world)
Start world = fileSize "input.txt" world |
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.
| #Clojure | Clojure | (require '[clojure.java.io :as io])
(defn show-size [filename]
(println filename "size:" (.length (io/file filename))))
(show-size "input.txt")
(show-size "/input.txt") |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #AppleScript | AppleScript | on copyFile from src into dst
set filedata to read file src
set outfile to open for access dst with write permission
write filedata to outfile
close access outfile
end copyFile
copyFile from ":input.txt" into ":output.txt" |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program readwrtfile.s */
/*********************************************/
/*constantes */
/********************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3
.equ WRITE, 4
.equ OPEN, 5
.equ CLOSE, 6
.equ CREATE, 8
/* file */
.equ O_RDWR, 0x0002 @ open for reading and writing
.equ TAILLEBUF, 1000
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessErreur: .asciz "Erreur ouverture fichier input.\n"
szMessErreur4: .asciz "Erreur création fichier output.\n"
szMessErreur1: .asciz "Erreur fermeture fichier.\n"
szMessErreur2: .asciz "Erreur lecture fichier.\n"
szMessErreur3: .asciz "Erreur d'écriture dans fichier de sortie.\n"
szRetourligne: .asciz "\n"
szMessErr: .ascii "Error code : "
sDeci: .space 15,' '
.asciz "\n"
szNameFileInput: .asciz "input.txt"
szNameFileOutput: .asciz "output.txt"
/*******************************************/
/* DONNEES NON INITIALISEES */
/*******************************************/
.bss
sBuffer: .skip TAILLEBUF
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main
main:
push {fp,lr} /* save registers */
ldr r0,iAdrszNameFileInput @ file name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7,#OPEN @ call system OPEN
swi #0
cmp r0,#0 @ open error ?
ble erreur
mov r8,r0 @ save File Descriptor
ldr r1,iAdrsBuffer @ buffer address
mov r2,#TAILLEBUF @ buffer size
mov r7, #READ @ call system READ
swi 0
cmp r0,#0 @ read error ?
ble erreur2
mov r2,r0 @ length read characters
/* close imput file */
mov r0,r8 @ Fd
mov r7, #CLOSE @ call system CLOSE
swi 0
cmp r0,#0 @ close error ?
blt erreur1
@ create output file
ldr r0,iAdrszNameFileOutput @ file name
ldr r1,iFicMask1 @ flags
mov r7, #CREATE @ call system create file
swi 0
cmp r0,#0 @ create error ?
ble erreur4
mov r0,r8 @ file descriptor
ldr r1,iAdrsBuffer
@ et r2 contains the length to write
mov r7, #WRITE @ select system call 'write'
swi #0 @ perform the system call
cmp r0,#0 @ error write ?
blt erreur3
@ close output file
mov r0,r8 @ Fd fichier
mov r7, #CLOSE @ call system CLOSE
swi #0
cmp r0,#0 @ error close ?
blt erreur1
mov r0,#0 @ return code OK
b 100f
erreur:
ldr r1,iAdrszMessErreur
bl afficheerreur
mov r0,#1 @ error return code
b 100f
erreur1:
ldr r1,iAdrszMessErreur1
bl afficheerreur
mov r0,#1 @ error return code
b 100f
erreur2:
ldr r1,iAdrszMessErreur2
bl afficheerreur
mov r0,#1 @ error return code
b 100f
erreur3:
ldr r1,iAdrszMessErreur3
bl afficheerreur
mov r0,#1 @ error return code
b 100f
erreur4:
ldr r1,iAdrszMessErreur4
bl afficheerreur
mov r0,#1 @ error return code
b 100f
100: @ end program
pop {fp,lr} /* restaur des 2 registres */
mov r7, #EXIT /* appel fonction systeme pour terminer */
swi 0
iAdrszNameFileInput: .int szNameFileInput
iAdrszNameFileOutput: .int szNameFileOutput
iAdrszMessErreur: .int szMessErreur
iAdrszMessErreur1: .int szMessErreur1
iAdrszMessErreur2: .int szMessErreur2
iAdrszMessErreur3: .int szMessErreur3
iAdrszMessErreur4: .int szMessErreur4
iAdrsBuffer: .int sBuffer
iFicMask1: .octa 0644
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} /* save registres */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7,lr} /* restaur des 2 registres */
bx lr /* return */
/***************************************************/
/* display error message */
/***************************************************/
/* r0 contains error code r1 address error message */
afficheerreur:
push {r1-r2,lr} @ save registers
mov r2,r0 @ save error code
mov r0,r1 @ address error message
bl affichageMess @ display error message
mov r0,r2 @ error code
ldr r1,iAdrsDeci @ result address
bl conversion10S
ldr r0,iAdrszMessErr @ display error code
bl affichageMess
pop {r1-r2,lr} @ restaur registers
bx lr @ return function
iAdrszMessErr: .int szMessErr
iAdrsDeci: .int sDeci
/***************************************************/
/* Converting a register to a signed decimal */
/***************************************************/
/* r0 contains value and r1 area address */
conversion10S:
push {r0-r4,lr} @ save registers
mov r2,r1 /* debut zone stockage */
mov r3,#'+' /* par defaut le signe est + */
cmp r0,#0 @ negative number ?
movlt r3,#'-' @ yes
mvnlt r0,r0 @ number inversion
addlt r0,#1
mov r4,#10 @ length area
1: @ start loop
bl divisionPar10R
add r1,#48 @ digit
strb r1,[r2,r4] @ store digit on area
sub r4,r4,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b
strb r3,[r2,r4] @ store signe
subs r4,r4,#1 @ previous position
blt 100f @ if r4 < 0 -> end
mov r1,#' ' @ space
2:
strb r1,[r2,r4] @store byte space
subs r4,r4,#1 @ previous position
bge 2b @ loop if r4 > 0
100:
pop {r0-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* division for 10 fast unsigned */
/***************************************************/
@ r0 contient le dividende
@ r0 retourne le quotient
@ r1 retourne le reste
divisionPar10R:
push {r2,lr} @ save registers
sub r1, r0, #10 @ calcul de r0 - 10
sub r0, r0, r0, lsr #2 @ calcul de r0 - (r0 /4)
add r0, r0, r0, lsr #4 @ calcul de (r0-(r0/4))+ ((r0-(r0/4))/16
add r0, r0, r0, lsr #8 @ etc ...
add r0, r0, r0, lsr #16
mov r0, r0, lsr #3
add r2, r0, r0, asl #2
subs r1, r1, r2, asl #1 @ calcul (N-10) - (N/10)*10
addpl r0, r0, #1 @ regul quotient
addmi r1, r1, #10 @ regul reste
pop {r2,lr}
bx lr
|
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
| #C.2B.2B | C++ | #include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
const size_t n1 = str.length();
const size_t n2 = suffix.length();
if (n1 < n2)
return false;
return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),
[](char c1, char c2) {
return std::tolower(static_cast<unsigned char>(c1))
== std::tolower(static_cast<unsigned char>(c2));
});
}
bool filenameHasExtension(const std::string& filename,
const std::vector<std::string>& extensions) {
return std::any_of(extensions.begin(), extensions.end(),
[&filename](const std::string& extension) {
return endsWithIgnoreCase(filename, "." + extension);
});
}
void test(const std::string& filename,
const std::vector<std::string>& extensions) {
std::cout << std::setw(20) << std::left << filename
<< ": " << std::boolalpha
<< filenameHasExtension(filename, extensions) << '\n';
}
int main() {
const std::vector<std::string> extensions{"zip", "rar", "7z",
"gz", "archive", "A##", "tar.bz2"};
test("MyData.a##", extensions);
test("MyData.tar.Gz", extensions);
test("MyData.gzip", extensions);
test("MyData.7z.backup", extensions);
test("MyData...", extensions);
test("MyData", extensions);
test("MyData_v1.0.tar.bz2", extensions);
test("MyData_v1.0.bz2", extensions);
return 0;
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #F.23 | F# | open System
open System.IO
[<EntryPoint>]
let main args =
Console.WriteLine(File.GetLastWriteTime(args.[0]))
File.SetLastWriteTime(args.[0], DateTime.Now)
0 |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Factor | Factor | "foo.txt" file-info modified>> . |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Fortran | Fortran | ' FB 1.05.0 Win64
' This example is taken directly from the FB documentation (see [http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgFiledatetime])
#include "vbcompat.bi" '' to use Format function
Dim filename As String, d As Double
Print "Enter a filename: "
Line Input filename
If FileExists(filename) Then
Print "File last modified: ";
d = FileDateTime( filename )
Print Format( d, "yyyy-mm-dd hh:mm AM/PM" )
Else
Print "File not found"
End If
Sleep |
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?
| #Rust | Rust |
use std::error::Error;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::{env, fmt, io, time};
use walkdir::{DirEntry, WalkDir};
fn main() -> Result<(), Box<dyn Error>> {
let start = time::Instant::now();
let args: Vec<String> = env::args().collect();
let root = parse_path(&args).expect("not a valid path");
let dir = WalkDir::new(&root);
let (files, dirs): (Vec<PathBuf>, Vec<PathBuf>) = {
let pool = pool(dir).expect("unable to retrieve entries from WalkDir");
partition_from(pool).expect("unable to partition files from directories")
};
let (fs_count, dr_count) = (files.len(), dirs.len());
let (file_counter, total_size) = file_count(files);
{
println!("++ File size distribution for : {} ++\n", &root.display());
println!("Files @ 0B : {:4}", file_counter[0]);
println!("Files > 1B - 1,023B : {:4}", file_counter[1]);
println!("Files > 1KB - 1,023KB : {:4}", file_counter[2]);
println!("Files > 1MB - 1,023MB : {:4}", file_counter[3]);
println!("Files > 1GB - 1,023GB : {:4}", file_counter[4]);
println!("Files > 1TB+ : {:4}\n", file_counter[5]);
println!("Files encountered: {}", fs_count);
println!("Directories traversed: {}", dr_count);
println!(
"Total size of all files: {}\n",
Filesize::<Kilobytes>::from(total_size)
);
}
let end = time::Instant::now();
println!("Run time: {:?}\n", end.duration_since(start));
Ok(())
}
fn parse_path(args: &[String]) -> Result<&Path, io::Error> {
// If there's no `args` entered, the executable will search it's own path.
match args.len() {
1 => Ok(Path::new(&args[0])),
_ => Ok(Path::new(&args[1])),
}
}
fn pool(dir: WalkDir) -> Result<Vec<DirEntry>, Box<dyn Error>> {
// Check each item for errors and drop possible invalid `DirEntry`s
Ok(dir.into_iter().filter_map(|e| e.ok()).collect())
}
fn partition_from(pool: Vec<DirEntry>) -> Result<(Vec<PathBuf>, Vec<PathBuf>), Box<dyn Error>> {
// Read `Path` from `DirEntry`, checking if `Path` is a file or directory.
Ok(pool
.into_iter()
.map(|e| e.into_path())
.partition(|path| path.is_file()))
}
fn file_count(files: Vec<PathBuf>) -> ([u64; 6], u64) {
let mut counter: [u64; 6] = [0; 6];
for file in &files {
match Filesize::<Bytes>::from(file).bytes {
0 => counter[0] += 1, // Empty file
1..=1_023 => counter[1] += 1, // 1 byte to 0.99KB
1_024..=1_048_575 => counter[2] += 1, // 1 kilo to 0.99MB
1_048_576..=1_073_741_823 => counter[3] += 1, // 1 mega to 0.99GB
1_073_741_824..=1_099_511_627_775 => counter[4] += 1, // 1 giga to 0.99TB
1_099_511_627_776..=std::u64::MAX => counter[5] += 1, // 1 terabyte or larger
}
}
let total_file_size = files
.iter()
.fold(0, |acc, file| acc + Filesize::<Bytes>::from(file).bytes);
(counter, total_file_size)
}
trait SizeUnit: Copy {
fn singular_name() -> String;
fn num_byte_in_unit() -> u64;
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Bytes;
impl SizeUnit for Bytes {
fn singular_name() -> String {
"B".to_string()
}
fn num_byte_in_unit() -> u64 {
1
}
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Kilobytes;
impl SizeUnit for Kilobytes {
fn singular_name() -> String {
"KB".to_string()
}
fn num_byte_in_unit() -> u64 {
1_024
}
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Filesize<T: SizeUnit> {
bytes: u64,
unit: PhantomData<T>,
}
impl<T> From<u64> for Filesize<T>
where
T: SizeUnit,
{
fn from(n: u64) -> Self {
Filesize {
bytes: n * T::num_byte_in_unit(),
unit: PhantomData,
}
}
}
impl<T> From<Filesize<T>> for u64
where
T: SizeUnit,
{
fn from(fsz: Filesize<T>) -> u64 {
((fsz.bytes as f64) / (T::num_byte_in_unit() as f64)) as u64
}
}
impl<T> fmt::Display for Filesize<T>
where
T: SizeUnit,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// convert value in associated units to float
let size_val = ((self.bytes as f64) / (T::num_byte_in_unit() as f64)) as u64;
// plural?
let name_plural = match size_val {
1 => "",
_ => "s",
};
write!(
f,
"{} {}{}",
(self.bytes as f64) / (T::num_byte_in_unit() as f64),
T::singular_name(),
name_plural
)
}
}
// Can be expanded for From<File>, or any type that has an alias for Metadata
impl<T> From<&PathBuf> for Filesize<T>
where
T: SizeUnit,
{
fn from(f: &PathBuf) -> Self {
Filesize {
bytes: f
.metadata()
.expect("error with metadata from pathbuf into filesize")
.len(),
unit: PhantomData,
}
}
}
|
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?
| #Sidef | Sidef | func traverse(Block callback, Dir dir) {
dir.open(\var dir_h) || return nil
for entry in (dir_h.entries) {
if (entry.kind_of(Dir)) {
traverse(callback, entry)
} else {
callback(entry)
}
}
}
var dir = (ARGV ? Dir(ARGV[0]) : Dir.cwd)
var group = Hash()
var files_num = 0
var total_size = 0
traverse({ |file|
group{file.size+1 -> log10.round} := 0 += 1
total_size += file.size
files_num += 1
}, dir)
for k,v in (group.sort_by { |k,_| Num(k) }) {
say "log10(size) ~~ #{k} -> #{v} files"
}
say "Total: #{total_size} bytes in #{files_num} files" |
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.)
| #Delphi | Delphi |
program Fibonacci_word;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Vcl.Graphics;
function GetWordFractal(n: Integer): string;
var
f1, f2, tmp: string;
i: Integer;
begin
case n of
0:
Result := '';
1:
Result := '1';
else
begin
f1 := '1';
f2 := '0';
for i := n - 2 downto 1 do
begin
tmp := f2;
f2 := f2 + f1;
f1 := tmp;
end;
Result := f2;
end;
end;
end;
procedure DrawWordFractal(n: Integer; g: TCanvas; x, y, dx, dy: integer);
var
i, tx: Integer;
wordFractal: string;
begin
wordFractal := GetWordFractal(n);
with g do
begin
Brush.Color := clWhite;
FillRect(ClipRect);
Pen.Color := clBlack;
pen.Width := 1;
MoveTo(x, y);
end;
for i := 1 to wordFractal.Length do
begin
g.LineTo(x + dx, y + dy);
inc(x, dx);
inc(y, dy);
if wordFractal[i] = '0' then
begin
tx := dx;
if Odd(i) then
begin
dx := dy;
dy := -tx;
end
else
begin
dx := -dy;
dy := tx;
end;
end;
end;
end;
function WordFractal2Bitmap(n, x, y, width, height: Integer): TBitmap;
begin
Result := TBitmap.Create;
Result.SetSize(width, height);
DrawWordFractal(n, Result.Canvas, x, height - y, 1, 0);
end;
begin
with WordFractal2Bitmap(23, 20, 20, 450, 620) do
begin
SaveToFile('WordFractal.bmp');
Free;
end;
end.
|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.23 | F# | open System
let (|SeqNode|SeqEmpty|) s =
if Seq.isEmpty s then SeqEmpty
else SeqNode ((Seq.head s), Seq.skip 1 s)
[<EntryPoint>]
let main args =
let splitBySeparator (str : string) = Seq.ofArray (str.Split('/'))
let rec common2 acc = function
| SeqEmpty -> Seq.ofList (List.rev acc)
| SeqNode((p1, p2), rest) ->
if p1 = p2 then common2 (p1::acc) rest
else Seq.ofList (List.rev acc)
let commonPrefix paths =
match Array.length(paths) with
| 0 -> [||]
| 1 -> Seq.toArray (splitBySeparator paths.[0])
| _ ->
let argseq = Seq.ofArray paths
Seq.fold (
fun (acc : seq<string>) items ->
common2 [] (List.ofSeq (Seq.zip acc (splitBySeparator items)))
) (splitBySeparator (Seq.head argseq)) (Seq.skip 1 argseq)
|> Seq.toArray
printfn "The common preffix is: %A" (String.Join("/", (commonPrefix args)))
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.
| #AppleScript | AppleScript | set array to {1, 2, 3, 4, 5, 6}
set evens to {}
repeat with i in array
if (i mod 2 = 0) then set end of evens to i's contents
end repeat
return evens |
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]]
| #REXX | REXX | /*REXX program determines if a specified point is within a specified triangle. */
parse arg p a b c . /*obtain optional arguments from the CL*/
if p=='' | p=="," then p= '(0,0)' /*Not specified? Then use the default.*/
if a=='' | a=="," then a= '(1.5,2.4)' /* " " " " " " */
if b=='' | b=="," then b= '(5.1,-3.1)' /* " " " " " " */
if c=='' | c=="," then c= '(-3.8,0.5)' /* " " " " " " */
if ?(p, a, b, c) then @= ' is ' /*Is the point inside the triangle ? */
else @= " isn't " /* " " " outside " " */
say 'point' p @ " within the triangle " a ',' b "," c
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cert: parse arg z,W; if datatype(z,'N') then return z; call serr z /*return coördinate.*/
serr: say W 'data point ' z " isn't numeric or missing."; exit 13 /*tell error message*/
x: procedure; parse arg "(" x ',' ; return cert(x,"X") /*return the X coördinate.*/
y: procedure; parse arg ',' y ")"; return cert(y,"Y") /* " " Y " */
$: parse arg aa,bb,cc; return (x(aa)-x(cc)) *(y(bb)-y(cc)) - (x(bb)-x(cc)) *(y(aa)-y(cc))
?: #1=$(p,a,b); #2=$(p,b,c); #3=$(p,c,a); return (#1>=0>=0>=0) | (#1<=0<=0<=0) |
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
| #zkl | zkl | fcn flatten(list){ list.pump(List,
fcn(i){ if(List.isType(i)) return(Void.Recurse,i,self.fcn); i}) }
flatten(L(L(1), L(2), L(L(3,4), 5), L(L(L())), L(L(L(6))), 7, 8, L()))
//-->L(1,2,3,4,5,6,7,8) |
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
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET f$="["
20 LET n$="[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
30 FOR i=2 TO (LEN n$)-1
40 IF n$(i)>"/" AND n$(i)<":" THEN LET f$=f$+n$(i): GO TO 60
50 IF n$(i)="," AND f$(LEN f$)<>"," THEN LET f$=f$+","
60 NEXT i
70 LET f$=f$+"]": PRINT f$ |
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.
| #i | i | function test(counter) {
print(counter)
test(counter+1)
}
software {
test(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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
envar := "MSTKSIZE"
write(&errout,"Program to test recursion depth - dependant on the environment variable ",envar," = ",\getenv(envar)|&null)
deepdive()
end
procedure deepdive()
static d
initial d := 0
write( d +:= 1)
deepdive()
end |
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
| #Racket | Racket | #lang racket
(require racket/generator)
(define (digital-reverse/base base N)
(define (inr n r)
(if (zero? n) r (inr (quotient n base) (+ (* r base) (modulo n base)))))
(inr N 0))
(define (palindrome?/base base N)
(define (inr? n m)
(if (= n 0)
(= m N)
(inr? (quotient n base) (+ (* m base) (modulo n base)))))
(inr? N 0))
(define (palindrome?/3 n)
(palindrome?/base 3 n))
(define (b-palindromes-generator b)
(generator
()
;; it's a bit involved getting the initial palindroms, so we do them manually
(for ((p (in-range b))) (yield p))
(let loop ((rhs 1) (mx-rhs b) (mid #f) (mx-rhs*b (* b b)))
(cond
[(= rhs mx-rhs)
(cond
[(not mid) (loop (quotient mx-rhs b) mx-rhs 0 mx-rhs*b)]
[(zero? mid) (loop mx-rhs mx-rhs*b #f (* mx-rhs*b b))])]
[else
(define shr (digital-reverse/base b rhs))
(cond
[(not mid)
(yield (+ (* rhs mx-rhs) shr))
(loop (add1 rhs) mx-rhs #f mx-rhs*b)]
[(= mid (- b 1))
(yield (+ (* rhs mx-rhs*b) (* mid mx-rhs) shr))
(loop (+ 1 rhs) mx-rhs 0 mx-rhs*b)]
[else
(yield (+ (* rhs mx-rhs*b) (* mid mx-rhs) shr))
(loop rhs mx-rhs (add1 mid) mx-rhs*b)])]))))
(define (number->string/base n b)
(define (inr acc n)
(if (zero? n) acc
(let-values (((q r) (quotient/remainder n b)))
(inr (cons (number->string r) acc) q))))
(if (zero? n) "0" (apply string-append (inr null n))))
(module+ main
(for ((n (sequence-filter palindrome?/3 (in-producer (b-palindromes-generator 2))))
(i (in-naturals))
#:final (= i 5))
(printf "~a: ~a_10 ~a_3 ~a_2~%"
(~a #:align 'right #:min-width 3 (add1 i))
(~a #:align 'right #:min-width 11 n)
(~a #:align 'right #:min-width 23 (number->string/base n 3))
(~a #:align 'right #:min-width 37 (number->string/base n 2)))))
(module+ test
(require rackunit)
(check-true (palindrome?/base 2 #b0))
(check-true (palindrome?/base 2 #b10101))
(check-false (palindrome?/base 2 #b1010))
(define from-oeis:A060792
(list 0 1 6643 1422773 5415589 90396755477 381920985378904469
1922624336133018996235 2004595370006815987563563
8022581057533823761829436662099))
(check-match from-oeis:A060792
(list (? (curry palindrome?/base 2)
(? (curry palindrome?/base 3))) ...))
(check-eq? (digital-reverse/base 2 #b0) #b0)
(check-eq? (digital-reverse/base 2 #b1) #b1)
(check-eq? (digital-reverse/base 2 #b10) #b01)
(check-eq? (digital-reverse/base 2 #b1010) #b0101)
(check-eq? (digital-reverse/base 10 #d0) #d0)
(check-eq? (digital-reverse/base 10 #d1) #d1)
(check-eq? (digital-reverse/base 10 #d10) #d01)
(check-eq? (digital-reverse/base 10 #d1010) #d0101)
(define pg ((b-palindromes-generator 2)))
(check-match
(map (curryr number->string 2) (for/list ((i 16) (p (in-producer (b-palindromes-generator 2)))) p))
(list "0" "1" "11" "101" "111" "1001" "1111" "10001" "10101" "11011"
"11111" "100001" "101101" "110011" "111111" "1000001"))) |
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.
| #Raku | Raku | constant palindromes = 0, 1, |gather for 1 .. * -> $p {
my $pal = $p.base(3);
my $n = :3($pal ~ '1' ~ $pal.flip);
next if $n %% 2;
my $b2 = $n.base(2);
next if $b2.chars %% 2;
next unless $b2 eq $b2.flip;
take $n;
}
printf "%d, %s, %s\n", $_, .base(2), .base(3) for palindromes[^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
| #Fantom | Fantom | class FizzBuzz
{
public static Void main ()
{
for (Int i:=1; i <= 100; ++i)
{
if (i % 15 == 0)
echo ("FizzBuzz")
else if (i % 3 == 0)
echo ("Fizz")
else if (i % 5 == 0)
echo ("Buzz")
else
echo (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.
| #COBOL | COBOL |
identification division.
program-id. FileInfo.
data division.
working-storage section.
01 file-name pic x(256).
01 file-size-edited pic zzz,zzz,zzz.
01 file-details.
05 file-size pic x(8) comp-x.
05 file-date.
10 file-day pic x comp-x.
10 file-month pic x comp-x.
10 file-year pic xx comp-x.
05 file-time.
10 file-hour pic x comp-x.
10 file-minute pic x comp-x.
10 file-second pic x comp-x.
10 file-hundredths pic x comp-x.
procedure division.
main.
move "input.txt" to file-name
perform file-info
move "\input.txt" to file-name
perform file-info
stop run
.
file-info.
call "CBL_CHECK_FILE_EXIST"
using file-name, file-details
returning return-code
if return-code = 0
move file-size to file-size-edited
display function trim(file-name) " "
function trim(file-size-edited) " Bytes"
else
display function trim(file-name) " not found!"
end-if
.
|
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #ColdFusion | ColdFusion | <cfscript>
localFile = getFileInfo(expandpath("input.txt"));
rootFile = getFileInfo("/input.txt");
</cfscript>
<cfoutput>
Size of input.txt is #localFile.size# bytes.
Size of /input.txt is #rootFile.size# bytes.
</cfoutput> |
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.
| #Arturo | Arturo | source: read "input.txt"
write "output.txt" source
print source |
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.
| #AutoHotkey | AutoHotkey | Loop, Read, input.txt, output.txt
FileAppend, %A_LoopReadLine%`n |
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
| #Clojure | Clojure | (defn matches-extension [ext s]
(re-find (re-pattern (str "\\." ext "$"))
(clojure.string/lower-case s)))
(defn matches-extension-list [ext-list s]
(some #(matches-extension % s) ext-list)) |
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
| #D | D |
import std.stdio;
import std.string;
import std.range;
import std.algorithm;
void main()
{
auto exts = ["zip", "rar", "7z", "gz", "archive", "A##"];
auto filenames = ["MyData.a##",
"MyData.tar.Gz",
"MyData.gzip",
"MyData.7z.backup",
"MyData...",
"MyData"];
writeln("extensions: ", exts);
writeln;
foreach(filename; filenames)
{
string extension = filename.drop(filename.lastIndexOf(".") + 1).toLower;
bool found;
foreach(ext; exts)
{
if (extension == ext.toLower)
{
found = true;
break;
}
}
writeln(filename, " : ", found);
}
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' This example is taken directly from the FB documentation (see [http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgFiledatetime])
#include "vbcompat.bi" '' to use Format function
Dim filename As String, d As Double
Print "Enter a filename: "
Line Input filename
If FileExists(filename) Then
Print "File last modified: ";
d = FileDateTime( filename )
Print Format( d, "yyyy-mm-dd hh:mm AM/PM" )
Else
Print "File not found"
End If
Sleep |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Frink | Frink | f = newJava["java.io.File", "FileModificationTime.frink"]
f.setLastModified[(#2022-01-01 5:00 AM# - #1970 UTC#) / ms]
println[f.lastModified[] ms + #1970 UTC#] |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Gambas | Gambas | ' There is no built in command in Gambas to 'set' the modification time of a file
' A shell call to 'touch' would do it
Public Sub Main()
Dim stInfo As Stat = Stat(User.home &/ "Rosetta.txt")
Print "Rosetta.txt was last modified " & Format(stInfo.LastModified, "dd/mm/yyy hh:nn:ss")
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?
| #Tcl | Tcl | package require fileutil::traverse
namespace path {::tcl::mathfunc ::tcl::mathop}
# Ternary helper
proc ? {test a b} {tailcall if $test [list subst $a] [list subst $b]}
set dir [? {$argc} {[lindex $argv 0]} .]
fileutil::traverse Tobj $dir \
-prefilter {apply {path {ne [file type $path] link}}} \
-filter {apply {path {eq [file type $path] file}}}
Tobj foreach path {
set size [file size $path]
dict incr hist [? {$size} {[int [log10 $size]]} -1]
}
Tobj destroy
foreach key [lsort -int [dict keys $hist]] {
puts "[? {$key == -1} 0 {1e$key}]\t[dict get $hist $key]"
} |
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?
| #UNIX_Shell | UNIX Shell | #!/bin/sh
set -eu
tabs -8
if [ ${GNU:-} ]
then
find -- "${1:-.}" -type f -exec du -b -- {} +
else
# Use a subshell to remove the last "total" line per each ARG_MAX
find -- "${1:-.}" -type f -exec sh -c 'wc -c -- "$@" | sed \$d' argv0 {} +
fi | awk -vOFS='\t' '
BEGIN {split("KB MB GB TB PB", u); u[0] = "B"}
{
++hist[$1 ? length($1) - 1 : -1]
total += $1
}
END {
max = -2
for (i in hist)
max = (i > max ? i : max)
print "From", "To", "Count\n"
for (i = -1; i <= max; ++i)
{
if (i in hist)
{
if (i == -1)
print "0B", "0B", hist[i]
else
print 10 ** (i % 3) u[int(i / 3)],
10 ** ((i + 1) % 3) u[int((i + 1) / 3)],
hist[i]
}
}
l = length(total) - 1
printf "\nTotal: %.1f %s in %d files\n",
total / (10 ** l), u[int(l / 3)], NR
}' |
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.)
| #Elixir | Elixir | defmodule Fibonacci do
def fibonacci_word, do: Stream.unfold({"1","0"}, fn{a,b} -> {a, {b, b<>a}} end)
def word_fractal(n) do
word = fibonacci_word |> Enum.at(n)
walk(to_char_list(word), 1, 0, 0, 0, -1, %{{0,0}=>"S"})
|> print
end
defp walk([], _, _, _, _, _, map), do: map
defp walk([h|t], n, x, y, dx, dy, map) do
map2 = Map.put(map, {x+dx, y+dy}, (if dx==0, do: "|", else: "-"))
|> Map.put({x2=x+2*dx, y2=y+2*dy}, "+")
if h == ?0 do
if rem(n,2)==0, do: walk(t, n+1, x2, y2, dy, -dx, map2),
else: walk(t, n+1, x2, y2, -dy, dx, map2)
else
walk(t, n+1, x2, y2, dx, dy, map2)
end
end
defp print(map) do
xkeys = Map.keys(map) |> Enum.map(fn {x,_} -> x end)
{xmin, xmax} = Enum.min_max(xkeys)
ykeys = Map.keys(map) |> Enum.map(fn {_,y} -> y end)
{ymin, ymax} = Enum.min_max(ykeys)
Enum.each(ymin..ymax, fn y ->
IO.puts Enum.map(xmin..xmax, fn x -> Map.get(map, {x,y}, " ") end)
end)
end
end
Fibonacci.word_fractal(16) |
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #F.23 | F# | let sigma s = seq {
for c in s do if c = '1' then yield '0' else yield '0'; yield '1'
}
let rec fibwordIterator s = seq { yield s; yield! fibwordIterator (sigma s) }
let goto (x, y) (dx, dy) c n =
let (dx', dy') =
if c = '0' then
match (dx, dy), n with
| (1,0),0 -> (0,1) | (1,0),1 -> (0,-1)
| (0,1),0 -> (-1,0) | (0,1),1 -> (1,0)
| (-1,0),0 -> (0,-1)| (-1,0),1 -> (0,1)
| (0,-1),0 -> (1,0) | (0,-1),1 -> (-1,0)
| _ -> failwith "not possible (c=0)"
else
(dx, dy)
(x+dx, y+dy), (dx', dy')
// How much longer a line is, compared to its thickness:
let factor = 2
let rec draw (x, y) (dx, dy) n = function
| [] -> ()
| z::zs ->
printf "%d,%d " (factor*(x+dx)) (factor*(y+dy))
let (xyd, d') = goto (x, y) (dx, dy) z n
draw xyd d' (n^^^1) zs
// Seq of (width,height). n-th (n>=0) pair is for fibword fractal f(3*n+2)
let wh = Seq.unfold (fun ((w1,h1,n),(w2,h2)) ->
Some((if n=0 then (w1,h1) else (h1,w1)), ((w2,h2,n^^^1),(2*w2+w1,w2+h2)))) ((1,0,1),(3,1))
[<EntryPoint>]
let main argv =
let n = (if argv.Length > 0 then int (System.UInt16.Parse(argv.[0])) else 23)
let (width,height) = Seq.head <| Seq.skip (n/3) wh
let fibWord = Seq.toList (Seq.item (n-1) <| fibwordIterator ['1'])
let (viewboxWidth, viewboxHeight) = ((factor*(width+1)), (factor*(height+1)))
printf """<!DOCTYPE html>
<html><body><svg height="100%%" width="100%%" viewbox="0 0 %d %d">
<polyline points="0,0 """ viewboxWidth viewboxHeight
draw (0,0) (0,1) 1 <| Seq.toList fibWord
printf """" style="fill:white;stroke:red;stroke-width:1" transform="matrix(1,0,0,-1,1,%d)"/>
Sorry, your browser does not support inline SVG.
</svg></body></html>""" (viewboxHeight-1)
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
| #Factor | Factor | : take-shorter ( seq1 seq2 -- shorter )
[ shorter? ] 2keep ? ;
: common-head ( seq1 seq2 -- head )
2dup mismatch [ nip head ] [ take-shorter ] if* ;
: common-prefix-1 ( file1 file2 separator -- prefix )
[ common-head ] dip '[ _ = not ] trim-tail ;
: common-prefix ( seq separator -- prefix )
[ ] swap '[ _ common-prefix-1 ] map-reduce ; |
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
| #FreeBASIC | FreeBASIC |
' compile: fbc.exe -s console cdp.bas
Function CommonDirectoryPath Cdecl(count As Integer, ...) As String
Dim As String Path(), s
Dim As Integer i, j, k = 1
Dim arg As Any Ptr
Const PATH_SEPARATOR As String = "/"
arg = va_first()
ReDim Preserve Path(1 To count)
For i = 1 To count
Path(i) = *Va_Arg(arg, ZString Ptr)
Print Path(i)
arg = va_next(arg, ZString Ptr)
Next i
Do
For i = 1 To count
If i > 1 Then
If InStr(k, Path(i), PATH_SEPARATOR) <> j Then
Exit Do
ElseIf Left(Path(i), j) <> Left(Path(1), j) Then
Exit Do
End If
Else
j = InStr(k, Path(i), PATH_SEPARATOR)
If j = 0 Then
Exit Do
End If
End If
Next i
s = Left(Path(1), j + CLng(k <> 1))
k = j + 1
Loop
Return s
End Function
' testing the above function
Print CommonDirectoryPath( 3, _
"/home/user1/tmp/coverage/test", _
"/home/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members") & " <- common"
Print
Print CommonDirectoryPath( 4, _
"/home/user1/tmp/coverage/test", _
"/home/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members", _
"/home/user1/abc/coven/members") & " <- common"
Print
Print CommonDirectoryPath( 3, _
"/home/user1/tmp/coverage/test", _
"/hope/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members") & " <- common"
Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Arturo | Arturo | arr: [1 2 3 4 5 6 7 8 9 10]
print select arr [x][even? 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]]
| #Ruby | Ruby | EPS = 0.001
EPS_SQUARE = EPS * EPS
def side(x1, y1, x2, y2, x, y)
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1)
end
def naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
checkSide1 = side(x1, y1, x2, y2, x, y) >= 0
checkSide2 = side(x2, y2, x3, y3, x, y) >= 0
checkSide3 = side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
end
def pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)
xMin = [x1, x2, x3].min - EPS
xMax = [x1, x2, x3].max + EPS
yMin = [y1, y2, y3].min - EPS
yMax = [y1, y2, y3].max + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
end
def distanceSquarePointToSegment(x1, y1, x2, y2, x, y)
p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)
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
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
def accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
if !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
def main
pts = [[0, 0], [0, 1], [3, 1]]
tri = [[1.5, 2.4], [5.1, -3.1], [-3.8, 1.2]]
print "Triangle is ", tri, "\n"
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
for pt in pts
x, y = pt[0], pt[1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
print "Point ", pt, " is within triangle? ", within, "\n"
end
print "\n"
tri = [[0.1, 1.0 / 9.0], [12.5, 100.0 / 3.0], [25.0, 100.0 / 9.0]]
print "Triangle is ", tri, "\n"
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x = x1 + (3.0 / 7.0) * (x2 - x1)
y = y1 + (3.0 / 7.0) * (y2 - y1)
pt = [x, y]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
print "Point ", pt, " is within triangle? ", within, "\n"
print "\n"
tri = [[0.1, 1.0 / 9.0], [12.5, 100.0 / 3.0], [-12.5, 100.0 / 6.0]]
print "Triangle is ", tri, "\n"
x3, y3 = tri[2][0], tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
print "Point ", pt, " is within triangle? ", within, "\n"
end
main() |
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.
| #Inform_7 | Inform 7 | Home is a room.
When play begins: recurse 0.
To recurse (N - number):
say "[N].";
recurse N + 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.
| #J | J | (recur=: verb def 'recur smoutput N=:N+1')N=: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.
| #REXX | REXX | /*REXX program finds numbers that are palindromic in both binary and ternary. */
digs=50; numeric digits digs /*biggest known B2B3 palindrome: 44 dig*/
parse arg maxHits .; if maxHits=='' then maxHits=6 /*use six as a limit.*/
hits=0; #= 'fiat' /*the number of palindromes (so far). */
call show 0,0,0; call show 1,1,1 /*show the first two palindromes (fiat)*/
!.= /* [↓] build list of powers of three. */
do i=1 until !.i>10**digs; !.i=3**i; end /*compute powers of three for radix3.*/
p=1 /* [↓] primary search: bin palindromes*/
do #=digs /*use all numbers, however, DEC is odd.*/
binH=x2b( d2x(#) ) + 0 /*convert some decimal number to binary*/
binL=reverse(binH) /*reverse the binary digits (or bits).*/
dec=x2d( b2x( binH'0'binL) ); if dec//3\==0 then call radix3
dec=x2d( b2x( binH'1'binL) ); if dec//3\==0 then call radix3
end /*#*/ /* [↑] crunch 'til found 'nuff numbers*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
radix3: parse var dec x 1 $,q /* [↓] convert decimal # ──► ternary.*/
do j=p while !.j<=x; end /*find upper limit of power of three. */
p=j-1 /*use this power of three for next time*/
do k=p by -1 for p; _=!.k; d=x%_; q=q || d; x=x//_; end /*k*/
t=q || x /*handle residual of ternary conversion*/
if t\==reverse(t) then return /*is T ternary number not palindromic? */
call show $, t, strip(x2b(d2x($)), , 0) /*show number: decimal, ternary, binary*/
return /* [↑] RADIX3 subroutine is sluggish.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: hits=hits+1; say /*bump the number of palindromes found.*/
say right('['hits"]", 5) right( arg(1), digs) '(decimal), ternary=' arg(2)
say right('', 5+1+ digs) ' binary =' arg(3)
if hits>2 then if hits//2 then #=#'0'
if hits<maxHits then return /*Not enough palindromes? Keep looking*/
exit /*stick a fork in it, we're all done. */ |
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
| #FBSL | FBSL | #APPTYPE CONSOLE
DIM numbers AS STRING
DIM imod5 AS INTEGER
DIM imod3 AS INTEGER
FOR DIM i = 1 TO 100
numbers = ""
imod3 = i MOD 3
imod5 = i MOD 5
IF NOT imod3 THEN numbers = "Fizz"
IF NOT imod5 THEN numbers = numbers & "Buzz"
IF imod3 AND imod5 THEN numbers = i
PRINT numbers, " ";
NEXT
PAUSE |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Common_Lisp | Common Lisp | (with-open-file (stream (make-pathname :name "input.txt")
:direction :input
:if-does-not-exist nil)
(print (if stream (file-length stream) 0)))
(with-open-file (stream (make-pathname :directory '(:absolute "") :name "input.txt")
:direction :input
:if-does-not-exist nil)
(print (if stream (file-length stream) 0))) |
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.
| #D | D | import std.file, std.stdio, std.path, std.file, std.stream,
std.mmfile;
void main() {
immutable fileName = "file_size.exe";
try {
writefln("File '%s' has size:", fileName);
writefln("%10d bytes by std.file.getSize (function)",
std.file.getSize(fileName));
writefln("%10d bytes by std.stream (class)",
new std.stream.File(fileName).size);
// mmfile can treat the file as an array in memory.
writefln("%10d bytes by std.mmfile (class)",
new std.mmfile.MmFile(fileName).length);
} catch (Exception e) {
e.msg.writefln;
}
} |
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.
| #AWK | AWK | BEGIN {
while ( (getline <"input.txt") > 0 ) {
print >"output.txt"
}
} |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Babel | Babel | (main
{ "input.txt" >>> -- File is now on stack
foo set -- File is now in 'foo'
foo "output.txt" <<< }) |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #11l | 11l | F entropy(s)
I s.len <= 1
R 0.0
V lns = Float(s.len)
V count0 = s.count(‘0’)
R -sum((count0, s.len - count0).map(count -> count / @lns * log(count / @lns, 2)))
V fwords = [String(‘1’), ‘0’]
print(‘#<3 #10 #<10 #.’.format(‘N’, ‘Length’, ‘Entropy’, ‘Fibword’))
L(n) 1..37
L fwords.len < n
fwords [+]= reversed(fwords[(len)-2..]).join(‘’)
V v = fwords[n - 1]
print(‘#3.0 #10.0 #2.7 #.’.format(n, v.len, entropy(v), I v.len < 56 {v} E ‘<too long>’)) |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #11l | 11l | V max_it = 13
V max_it_j = 10
V a1 = 1.0
V a2 = 0.0
V d1 = 3.2
V a = 0.0
print(‘ i d’)
L(i) 2..max_it
a = a1 + (a1 - a2) / d1
L(j) 1..max_it_j
V x = 0.0
V y = 0.0
L(k) 1..(1 << i)
y = 1.0 - 2.0 * y * x
x = a - x * x
a = a - x / y
V d = (a1 - a2) / (a - a1)
print(‘#2 #.8’.format(i, d))
d1 = d
a2 = a1
a1 = a |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Delphi | Delphi |
program File_extension_is_in_extensions_list;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
const
exts: TArray<string> = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];
filenames: TArray<string> = ['MyData.a##', 'MyData.tar.Gz', 'MyData.gzip',
'MyData.7z.backup', 'MyData...', 'MyData', 'MyData_v1.0.tar.bz2', 'MyData_v1.0.bz2'];
begin
write('extensions: [');
for var ext in exts do
begin
write(ext, ' ');
end;
writeln(']'#10);
for var filename in filenames do
begin
var found := false;
for var ext in exts do
if (filename.toLower.endsWith('.' + ext.toLower)) then
begin
found := True;
Break;
end;
writeln(filename: 20, ' : ', found);
end;
readln;
end. |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Go | Go | package main
import (
"fmt"
"os"
"syscall"
"time"
)
var filename = "input.txt"
func main() {
foo, err := os.Stat(filename)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("mod time was:", foo.ModTime())
mtime := time.Now()
atime := mtime // a default, because os.Chtimes has an atime parameter.
// but see if there's a real atime that we can preserve.
if ss, ok := foo.Sys().(*syscall.Stat_t); ok {
atime = time.Unix(ss.Atim.Sec, ss.Atim.Nsec)
}
os.Chtimes(filename, atime, mtime)
fmt.Println("mod time now:", mtime)
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #GUISS | GUISS | Start,My Documents,Rightclick:Icon:Foobar.txt,Properties |
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?
| #Wren | Wren | import "io" for Directory, File, Stat
import "os" for Process
import "/math" for Math
import "/fmt" for Fmt
var sizes = List.filled(12, 0)
var totalSize = 0
var numFiles = 0
var numDirs = 0
var fileSizeDist // recursive function
fileSizeDist = Fn.new { |path|
var files = Directory.list(path)
for (file in files) {
var path2 = "%(path)/%(file)"
var stat = Stat.path(path2)
if (stat.isFile) {
numFiles = numFiles + 1
var size = stat.size
if (size == 0) {
sizes[0] = sizes[0] + 1
} else {
totalSize = totalSize + size
var logSize = Math.log10(size)
var index = logSize.floor + 1
sizes[index] = sizes[index] + 1
}
} else if (stat.isDirectory) {
numDirs = numDirs + 1
fileSizeDist.call(path2)
}
}
}
var args = Process.arguments
var path = (args.count == 0) ? "./" : args[0]
if (!Directory.exists(path)) Fiber.abort("Path does not exist or is not a directory.")
fileSizeDist.call(path)
System.print("File size distribution for '%(path)' :-\n")
for (i in 0...sizes.count) {
System.write((i == 0) ? " " : "+ ")
Fmt.print("Files less than 10 ^ $-2d bytes : $,5d", i, sizes[i])
}
System.print(" -----")
Fmt.print("= Number of files : $,5d", numFiles)
Fmt.print(" Total size in bytes : $,d", totalSize)
Fmt.print(" Number of sub-directories : $,5d", numDirs) |
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.)
| #Factor | Factor | USING: accessors arrays combinators fry images images.loader
kernel literals make match math math.vectors pair-rocket
sequences ;
FROM: fry => '[ _ ;
IN: rosetta-code.fibonacci-word-fractal
! === Turtle code ==============================================
TUPLE: turtle heading loc ;
C: <turtle> turtle
: forward ( turtle -- turtle' )
dup heading>> [ v+ ] curry change-loc ;
MATCH-VARS: ?a ;
CONSTANT: left { { 0 ?a } => [ ?a 0 ] { ?a 0 } => [ 0 ?a neg ] }
CONSTANT: right { { 0 ?a } => [ ?a neg 0 ] { ?a 0 } => [ 0 ?a ] }
: turn ( turtle left/right -- turtle' )
[ dup heading>> ] dip match-cond 2array >>heading ; inline
! === Fib word =================================================
: fib-word ( n -- str )
{
1 => [ "1" ]
2 => [ "0" ]
[ [ 1 - fib-word ] [ 2 - fib-word ] bi append ]
} case ;
! === Fractal ==================================================
: fib-word-fractal ( n -- seq )
[
[ { 0 -1 } { 10 417 } dup , <turtle> ] dip fib-word
[
1 + -rot forward dup loc>> ,
-rot CHAR: 0 = [
even? [ left turn ] [ right turn ] if
] [ drop ] if drop
] with each-index
] { } make ;
! === Image ====================================================
CONSTANT: w 598
CONSTANT: h 428
: init-img-data ( -- seq )
w h * 4 * [ 255 ] B{ } replicate-as ;
: <fib-word-fractal-img> ( -- img )
<image>
${ w h } >>dim
BGRA >>component-order
ubyte-components >>component-type
init-img-data >>bitmap ;
: fract>img ( seq -- img' )
[ <fib-word-fractal-img> dup ] dip [
'[ B{ 33 33 33 255 } _ first2 ] dip set-pixel-at
] with each ;
: main ( -- )
23 fib-word-fractal fract>img "fib-word-fractal.png"
save-graphic-image ;
MAIN: main |
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.)
| #FreeBASIC | FreeBASIC | ' version 23-06-2015
' compile with: fbc -s console "filename".bas
Dim As String fw1, fw2, fw3
Dim As Integer a, b, d , i, n , x, y, w, h
Dim As Any Ptr img_ptr, scr_ptr
' data for screen/buffer size
Data 1, 2, 3, 2, 2, 2, 2, 2, 7, 10, 8, 14
Dim As Integer s(38,2)
For i = 3 To 9
Read s(i,1) : Read s(i,2)
Next
For i = 9 To 38 Step 6
s(i, 1) = s(i -1, 1) +2 : s(i, 2) = s(i -1, 1) + s(i -1, 2)
s(i +1, 1) = s(i, 2) +2 : s(i +1, 2) = s(i, 2)
s(i +2, 1) = s(i, 1) + s(i, 2) : s(i +2, 2) = s(i, 2)
s(i +3, 1) = s(i +1, 1 ) + s(i +2, 1) : s(i +3, 2) = s(i ,2)
s(i +4, 1) = s(i +3, 1) : s(i +4, 2) = s(i +3, 1) + 2
s(i +5, 1) = s(i +3, 1) : s(i +5, 2) = s(i +3, 2) + s(i +4, 2) +2
Next
' we need to set screen in order to create image buffer in memory
Screen 21
scr_ptr = ScreenPtr()
If (scr_ptr = 0) Then
Print "Error: graphics screen not initialized."
Sleep
End -1
End If
Do
Cls
Do
Print
Print "For wich n do you want the Fibonacci Word fractal (3 to 35)."
While Inkey <> "" : fw1 = Inkey : Wend ' empty keyboard buffer
Input "Enter or a value smaller then 3 to stop: "; n
If n < 3 Then
Print : Print "Stopping."
Sleep 3000,1
End
EndIf
If n > 35 then
Print : Print "Fractal is to big, unable to create it."
Sleep 3000,1
Continue Do
End If
Loop Until n < 36
fw1 = "1" : fw2 = "0" ' construct the string
For i = 3 To n
fw3 = fw2 + fw1
Swap fw1, fw2 ' swap pointers of fw1 and fw2
Swap fw2, fw3 ' swap pointers of fw2 and fw3
Next
fw1 = "" : fw3 = "" ' free up memory
w = s(n, 1) +1 : h = s(n, 2) +1
' allocate memory for a buffer to hold the image
' use 8 bits to hold the color
img_ptr = ImageCreate(w,h,0,8)
If img_ptr = 0 Then ' check if we have created a image buffer
Print "Failed to create image."
Sleep
End -1
End If
x = 0: y = h -1 : d = 1 ' set starting point and direction flag
PSet img_ptr, (x, y) ' set start point
For a = 1 To Len(fw2)
Select Case As Const d
Case 0
x = x + 2
Case 1
y = y - 2
Case 2
x = x - 2
Case 3
y = y + 2
End Select
Line img_ptr, -(x, y)
b = fw2[a-1] - Asc("0")
If b = 0 Then
If (a And 1) Then
d = d + 3 ' a = odd
Else
d = d + 1 ' a = even
End If
d = d And 3
End If
Next
If n < 24 Then ' size is smaller then screen dispay fractal
Cls
Put (5, 5),img_ptr, PSet
Else
Print
Print "Fractal is to big for display."
End If
' saves fractal as bmp file (8 bit palette)
If n > 23 Then h = 80
Draw String (0, h +16), "saving fractal as fibword" + Str(n) + ".bmp."
BSave "F_Word" + Str(n) + ".bmp", img_ptr
Draw String (0, h +32), "Hit any key to continue."
Sleep
ImageDestroy(img_ptr) ' free memory holding the image
Loop |
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
| #Gambas | Gambas | Public Sub Main()
Dim sFolder As String[] = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"]
Dim sSame As String
Dim siCount As Short = 1
Do
If Mid(sFolder[0], siCount, 1) = Mid(sFolder[1], siCount, 1) And Mid(sFolder[0], siCount, 1) = Mid(sFolder[2], siCount, 1) Then
sSame &= Mid(sFolder[0], siCount, 1)
Else
Break
End If
Inc siCount
Loop
Print Mid(sSame, 1, RInStr(sSame, "/") - 1)
End |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #AutoHotkey | AutoHotkey | array = 1,2,3,4,5,6,7
loop, parse, array, `,
{
if IsEven(A_LoopField)
evens = %evens%,%A_LoopField%
}
stringtrimleft, evens, evens, 1
msgbox % evens
return
IsEven(number)
{
return !mod(number, 2)
}
; ----- Another version: always with csv string ------
array = 1,2,3,4,5,6,7
even(s) {
loop, parse, s, `,
if !mod(A_LoopField, 2)
r .= "," A_LoopField
return SubStr(r, 2)
}
MsgBox % "Array => " array "`n" "Result => " even(array)
; ----- Yet another version: with array (requires AutoHotKey_L) ------
array2 := [1,2,3,4,5,6,7]
even2(a) {
r := []
For k, v in a
if !mod(v, 2)
r.Insert(v)
return r
}
; Add "join" method to string object (just like python)
s_join(o, a) {
Loop, % a.MaxIndex()
r .= o a[A_Index]
return SubStr(r, StrLen(o) + 1)
}
"".base.join := Func("s_join")
MsgBox % "Array => " ",".join(array2) "`n" "Result => " ",".join(even2(array2))
|
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]]
| #Vlang | Vlang | import math
const eps = 0.001
const eps_square = eps * eps
fn side(x1 f64, y1 f64, x2 f64, y2 f64, x f64, y f64) f64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
fn native_point_in_triangle(x1 f64, y1 f64, x2 f64, y2 f64, x3 f64, y3 f64, x f64, y f64) bool {
check_side1 := side(x1, y1, x2, y2, x, y) >= 0
check_side2 := side(x2, y2, x3, y3, x, y) >= 0
check_side3 := side(x3, y3, x1, y1, x, y) >= 0
return check_side1 && check_side2 && check_side3
}
fn point_in_triangle_bounding_box(x1 f64, y1 f64, x2 f64, y2 f64, x3 f64, y3 f64, x f64, y f64) bool {
x_min := math.min(x1, math.min(x2, x3)) - eps
x_max := math.max(x1, math.max(x2, x3)) + eps
y_min := math.min(y1, math.min(y2, y3)) - eps
y_max := math.max(y1, math.max(y2, y3)) + eps
return !(x < x_min || x_max < x || y < y_min || y_max < y)
}
fn distance_square_point_to_segment(x1 f64, y1 f64, x2 f64, y2 f64, x f64, y f64) f64 {
pq_p2_square_length := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dot_product := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / pq_p2_square_length
if dot_product < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dot_product <= 1 {
p_p1_square_length := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_square_length - dot_product*dot_product*pq_p2_square_length
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
fn accurate_point_in_triangle(x1 f64, y1 f64, x2 f64, y2 f64, x3 f64, y3 f64, x f64, y f64) bool {
if !point_in_triangle_bounding_box(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if native_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distance_square_point_to_segment(x1, y1, x2, y2, x, y) <= eps_square {
return true
}
if distance_square_point_to_segment(x2, y2, x3, y3, x, y) <= eps_square {
return true
}
if distance_square_point_to_segment(x3, y3, x1, y1, x, y) <= eps_square {
return true
}
return false
}
fn main() {
pts := [[f64(0), 0], [f64(0), 1], [f64(3), 1]]
mut tri := [[3.0 / 2, 12.0 / 5], [51.0 / 10, -31.0 / 10], [-19.0 / 5, 1.2]]
println("Triangle is $tri")
mut x1, mut y1 := tri[0][0], tri[0][1]
mut x2, mut y2 := tri[1][0], tri[1][1]
mut x3, mut y3 := tri[2][0], tri[2][1]
for pt in pts {
x, y := pt[0], pt[1]
within := accurate_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y)
println("Point $pt is within triangle? $within")
}
println('')
tri = [[1.0 / 10, 1.0 / 9], [100.0 / 8, 100.0 / 3], [100.0 / 4, 100.0 / 9]]
println("Triangle is $tri")
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [x, y]
mut within := accurate_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y)
println("Point $pt is within triangle ? $within")
println('')
tri = [[1.0 / 10, 1.0 / 9], [100.0 / 8, 100.0 / 3], [-100.0 / 8, 100.0 / 6]]
println("Triangle is $tri")
x3 = tri[2][0]
y3 = tri[2][1]
within = accurate_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y)
println("Point $pt is within triangle ? $within")
} |
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]]
| #Wren | Wren | var EPS = 0.001
var EPS_SQUARE = EPS * EPS
var side = Fn.new { |x1, y1, x2, y2, x, y|
return (y2 - y1)*(x - x1) + (-x2 + x1)*(y - y1)
}
var naivePointInTriangle = Fn.new { |x1, y1, x2, y2, x3, y3, x, y|
var checkSide1 = side.call(x1, y1, x2, y2, x, y) >= 0
var checkSide2 = side.call(x2, y2, x3, y3, x, y) >= 0
var checkSide3 = side.call(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
var pointInTriangleBoundingBox = Fn.new { |x1, y1, x2, y2, x3, y3, x, y|
var xMin = x1.min(x2.min(x3)) - EPS
var xMax = x1.max(x2.max(x3)) + EPS
var yMin = y1.min(y2.min(y3)) - EPS
var yMax = y1.max(y2.max(y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
var distanceSquarePointToSegment = Fn.new { |x1, y1, x2, y2, x, y|
var p1_p2_squareLength = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)
var dotProduct = ((x - x1)*(x2 - x1) + (y - y1)*(y2 - y1)) / p1_p2_squareLength
if (dotProduct < 0) {
return (x - x1)*(x - x1) + (y - y1)*(y - y1)
} else if (dotProduct <= 1) {
var p_p1_squareLength = (x1 - x)*(x1 - x) + (y1 - y)*(y1 - y)
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength
} else {
return (x - x2)*(x - x2) + (y - y2)*(y - y2)
}
}
var accuratePointInTriangle = Fn.new { |x1, y1, x2, y2, x3, y3, x, y|
if (!pointInTriangleBoundingBox.call(x1, y1, x2, y2, x3, y3, x, y)) return false
if (naivePointInTriangle.call(x1, y1, x2, y2, x3, y3, x, y)) return true
if (distanceSquarePointToSegment.call(x1, y1, x2, y2, x, y) <= EPS_SQUARE) return true
if (distanceSquarePointToSegment.call(x2, y2, x3, y3, x, y) <= EPS_SQUARE) return true
if (distanceSquarePointToSegment.call(x3, y3, x1, y1, x, y) <= EPS_SQUARE) return true
return false
}
var pts = [ [0, 0], [0, 1], [3, 1]]
var tri = [ [3/2, 12/5], [51/10, -31/10], [-19/5, 1.2] ]
System.print("Triangle is %(tri)")
var x1 = tri[0][0]
var y1 = tri[0][1]
var x2 = tri[1][0]
var y2 = tri[1][1]
var x3 = tri[2][0]
var y3 = tri[2][1]
for (pt in pts) {
var x = pt[0]
var y = pt[1]
var within = accuratePointInTriangle.call(x1, y1, x2, y2, x3, y3, x, y)
System.print("Point %(pt) is within triangle ? %(within)")
}
System.print()
tri = [ [1/10, 1/9], [100/8, 100/3], [100/4, 100/9] ]
System.print("Triangle is %(tri)")
x1 = tri[0][0]
y1 = tri[0][1]
x2 = tri[1][0]
y2 = tri[1][1]
x3 = tri[2][0]
y3 = tri[2][1]
var x = x1 + (3/7)*(x2 - x1)
var y = y1 + (3/7)*(y2 - y1)
var pt = [x, y]
var within = accuratePointInTriangle.call(x1, y1, x2, y2, x3, y3, x, y)
System.print("Point %(pt) is within triangle ? %(within)")
System.print()
tri = [ [1/10, 1/9], [100/8, 100/3], [-100/8, 100/6] ]
System.print("Triangle is %(tri)")
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle.call(x1, y1, x2, y2, x3, y3, x, y)
System.print("Point %(pt) is within triangle ? %(within)") |
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.
| #Java | Java |
public class RecursionTest {
private static void recurse(int i) {
try {
recurse(i+1);
} catch (StackOverflowError e) {
System.out.print("Recursion depth on this system is " + i + ".");
}
}
public static void main(String[] args) {
recurse(0);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.