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)
... | #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"
11362... |
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"... |
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 ... | #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"
... |
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 ... | #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
... |
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... | #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$[?]
fl... |
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... | #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: "%... |
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 c... |
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
{{20... |
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 no... | #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;... |
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 e... | #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%%... |
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 e... | #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, ... |
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 foll... | #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, l... |
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... |
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.
Re... | #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):
"""
Determi... |
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
E... |
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 ... | #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 p... |
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 ... | #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)
(pr... |
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)
... | #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::e... |
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 ... | #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 ... | #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... |
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... | #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
#includ... |
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... |
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 no... | #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 . ... |
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 e... | #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... |
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 foll... | #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
e... |
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 foll... | #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/membe... |
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.
Re... | #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... |
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.
Re... | #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]... |
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 ... | #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)[... |
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)
... | #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 w... |
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 ... | #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 ... | #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
.... |
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... | #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 st... |
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... |
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 no... | #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).... |
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 no... | #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... |
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 e... | #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';
... |
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 foll... | #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)
... |
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.
Re... | #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)' ... |
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 ... | #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 b... |
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 ... | #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)
... | #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.
... |
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 ... | #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 ... | #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... | #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... | #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",
... |
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... |
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 no... | #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... |
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 no... | #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] =... |
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 e... | #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, ... |
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 e... | #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,... |
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 foll... | #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 )
[ ] sw... |
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 foll... | #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, ... |
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.
Re... | #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,... |
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 ... | #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' ... |
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)
... | #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
... |
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
:... |
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));
... |
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 ... | #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 ... | #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-... | #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
fwor... |
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)
p... |
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... | #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.... |
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, ... |
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 no... | #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 fi... |
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 e... | #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 ( ... |
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 e... | #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
F... |
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 foll... | #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)... |
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, pars... |
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.
Re... | #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
... |
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.
Re... | #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... |
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.