task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #8086_Assembly | 8086 Assembly | putch: equ 2 ; Print character
puts: equ 9 ; Print $-terminated string
setdta: equ 1Ah ; Set DTA
stat: equ 4Eh ; Get file info
cpu 8086
bits 16
org 100h
section .text
mov si,curf ; Print file size for 'INPUT.TXT'
call pfsize ; (in current directory),
mov si,rootf ; Then for '\INPUT.TXT' in root directory
;;; ... |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #ALGOL_68 | ALGOL 68 | PROC get output = (STRING cmd) VOID:
IF STRING sh cmd = " " + cmd + " ; 2>&1";
STRING output;
execve output ("/bin/sh", ("sh", "-c", sh cmd), "", output) >= 0
THEN print (output) FI;
get output ("rm -rf WTC_1"); CO Ensure file doesn't exist CO
get output ("touch WTC_1"); CO Create file CO
get output ("ls -l... |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #AutoHotkey | AutoHotkey | FileGetTime, OutputVar, output.txt
MsgBox % OutputVar
FileSetTime, 20080101, output.txt
FileGetTime, OutputVar, output.txt
MsgBox % OutputVar |
http://rosettacode.org/wiki/File_size_distribution | File size distribution | Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no... | #Factor | Factor | USING: accessors assocs formatting io io.directories.search
io.files.types io.pathnames kernel math math.functions
math.statistics namespaces sequences ;
: classify ( m -- n ) [ 0 ] [ log10 >integer 1 + ] if-zero ;
: file-size-histogram ( path -- assoc )
recursive-directory-entries
[ type>> +directory+ = ] ... |
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... | #Go | Go | package main
import (
"fmt"
"log"
"math"
"os"
"path/filepath"
)
func commatize(n int64) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
... |
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... | #BBC_BASIC | BBC BASIC | DIM path$(3)
path$(1) = "/home/user1/tmp/coverage/test"
path$(2) = "/home/user1/tmp/covert/operator"
path$(3) = "/home/user1/tmp/coven/members"
PRINT FNcommonpath(path$(), "/")
END
DEF FNcommonpath(p$(), s$)
LOCAL I%, J%, O%
REPEAT
O% = I%
I% =... |
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... | #C | C | #include <stdio.h>
int common_len(const char *const *names, int n, char sep)
{
int i, pos;
for (pos = 0; ; pos++) {
for (i = 0; i < n; i++) {
if (names[i][pos] != '\0' &&
names[i][pos] == names[0][pos])
continue;
/* backtrack */
while (pos > 0 && names[0][--pos] != sep);
return pos;
}
}
... |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Ada | Ada | with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Text_Io; use Ada.Text_Io;
procedure Array_Selection is
type Array_Type is array (Positive range <>) of Integer;
Null_Array : Array_Type(1..0);
function Evens (Item : Array_Type) return Array_Type is
begin
if Item'Length > 0 then
... |
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... | #jq | jq | def sum_of_squares(stream): reduce stream as $x (0; . + $x * $x);
def distanceSquared(P1; P2): sum_of_squares(P1[0]-P2[0], P1[1]-P2[1]);
# Emit {x1,y1, ...} for the input triangle
def xy:
{ x1: .[0][0],
y1: .[0][1],
x2: .[1][0],
y2: .[1][1],
x3: .[2][0],
y3: .[2][1] };
def EPS: 0.001;
def EP... |
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... | #Julia | Julia | Point(x, y) = [x, y]
Triangle(a, b, c) = [a, b, c]
LEzero(x) = x < 0 || isapprox(x, 0, atol=0.00000001)
GEzero(x) = x > 0 || isapprox(x, 0, atol=0.00000001)
""" Determine which side of plane cut by line (p2, p3) p1 is on """
side(p1, p2, p3) = (p1[1] - p3[1]) * (p2[2] - p3[2]) - (p2[1] - p3[1]) * (p1[2] - p3[2])
... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #TI-89_BASIC | TI-89 BASIC | [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] flatten |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Elixir | Elixir | (defun my-recurse (n)
(my-recurse (1+ n)))
(my-recurse 1)
=>
enters debugger at (my-recurse 595),
per the default max-lisp-eval-depth 600 in Emacs 24.1 |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Emacs_Lisp | Emacs Lisp | (defun my-recurse (n)
(my-recurse (1+ n)))
(my-recurse 1)
=>
enters debugger at (my-recurse 595),
per the default max-lisp-eval-depth 600 in Emacs 24.1 |
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 ... | #JavaScript | JavaScript | (() => {
'use strict';
// GENERIC FUNCTIONS
// range :: Int -> Int -> [Int]
const range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// compose :: (b -> c) -> (a -> b) -> (a -> c)
const compose = (f, g) => x => f(g(x));
// li... |
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base | Find largest left truncatable prime in a given base | A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in... | #zkl | zkl | var [const] BN=Import("zklBigNum"); // libGMP
fcn largest_lefty_prime(base){
primes,p:=List(),BN(1); while(p.nextPrime()<base){ primes.append(p.copy()) }
b,biggest := BN(1),0;
while(primes){
b*=base; // base,base^2,base^3... gets big
ps:=List();
foreach p,n in (primes,[1..base-1]){
... |
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)
... | #Emojicode | Emojicode | 🏁🍇
🔂 i 🆕⏩ 1 101 1 ❗ 🍇
↪️ i 🚮 15 🙌 0 🍇
😀 🔤FizzBuzz🔤 ❗
🍉
🙅↪️ i 🚮 3 🙌 0 🍇
😀 🔤Fizz🔤 ❗
🍉
🙅↪️ i 🚮 5 🙌 0 🍇
😀 🔤Buzz🔤 ❗
🍉🙅🍇
😀 🔤🧲i🧲🔤 ❗
🍉
🍉
🍉 |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Action.21 | Action! | INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit
PROC Dir(CHAR ARRAY filter)
BYTE dev=[1]
CHAR ARRAY line(255)
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
PrintE(line)
IF line(0)=0 THEN
EXIT
FI
OD
Close(dev)
RETURN
CARD FUNC FileSize(CHAR ARRAY src,dst)
DEFINE BUF_LEN="1... |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Ada | Ada | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_File_Size is
begin
Put_Line (File_Size'Image (Size ("input.txt")) & " bytes");
Put_Line (File_Size'Image (Size ("/input.txt")) & " bytes");
end Test_File_Size; |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #AWK | AWK | @load "filefuncs"
BEGIN {
name = "input.txt"
# display time
stat(name, fd)
printf("%s\t%s\n", name, strftime("%a %b %e %H:%M:%S %Z %Y", fd["mtime"]) )
# change time
cmd = "touch -t 201409082359.59 " name
system(cmd)
close(cmd)
} |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Batch_File | Batch File | for %%f in (file.txt) do echo.%%~tf |
http://rosettacode.org/wiki/File_size_distribution | File size distribution | Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no... | #Haskell | Haskell | {-# LANGUAGE LambdaCase #-}
import Control.Concurrent (forkIO, setNumCapabilities)
import Control.Concurrent.Chan (Chan, newChan, readChan,
writeChan, writeList2Chan)
import Control.Exception (IOException, catch)
import... |
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... | #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCodeTasks
{
class Program
{
static void Main ( string[ ] args )
{
FindCommonDirectoryPath.Test ( );
}
}
class FindCommonDirectoryPath
{
public static void Test ( )
{
Console.WriteLine ( ... |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Aime | Aime | integer
even(integer e)
{
return !(e & 1);
}
list
filter(list l, integer (*f)(integer))
{
integer i;
list v;
i = 0;
while (i < l_length(l)) {
integer e;
e = l_q_integer(l, i);
if (f(e)) {
lb_p_integer(v, e);
}
i += 1;
}
return v;
... |
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... | #Kotlin | Kotlin | import kotlin.math.max
import kotlin.math.min
private const val EPS = 0.001
private const val EPS_SQUARE = EPS * EPS
private fun test(t: Triangle, p: Point) {
println(t)
println("Point $p is within triangle ? ${t.within(p)}")
}
fun main() {
var p1 = Point(1.5, 2.4)
var p2 = Point(5.1, -3.1)
va... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Trith | Trith | [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] flatten |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #True_BASIC | True BASIC | LET sstring$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
FOR sicount = 1 TO LEN(sstring$)
IF POS("[] ,",(sstring$)[sicount:sicount+1-1]) = 0 THEN
LET sflatter$ = sflatter$ & scomma$ & (sstring$)[sicount:sicount+1-1]
LET scomma$ = ", "
END IF
NEXT sicount
PRINT "["; sflatter$; "]"
END |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Erlang | Erlang | let rec recurse n =
recurse (n+1)
recurse 0 |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #F.23 | F# | let rec recurse n =
recurse (n+1)
recurse 0 |
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 ... | #Julia | Julia | ispalindrome(n, bas) = (s = string(n, base=bas); s == reverse(s))
prin3online(n) = println(lpad(n, 15), lpad(string(n, base=2), 40), lpad(string(n, base=3), 30))
reversebase3(n) = (x = 0; while n != 0 x = 3x + (n %3); n = div(n, 3); end; x)
function printpalindromes(N)
lo, hi, pow2, pow3, count, i = 0, 1, 1, 1, 1... |
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 ... | #Kotlin | Kotlin | // version 1.0.5-2
/** converts decimal 'n' to its ternary equivalent */
fun Long.toTernaryString(): String = when {
this < 0L -> throw IllegalArgumentException("negative numbers not allowed")
this == 0L -> "0"
else -> {
var result = ""
var n = this
while (n > 0) {
r... |
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)
... | #Erlang | Erlang | -spec fizzbuzz() -> Result :: string().
fizzbuzz() ->
F = fun(N) when N rem 15 == 0 -> "FizzBuzz";
(N) when N rem 3 == 0 -> "Fizz";
(N) when N rem 5 == 0 -> "Buzz";
(N) -> integer_to_list(N)
end,
lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]). |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Aime | Aime | o_(stat("input.txt", ST_SIZE), "\n");
o_("/Cygwin.ico".stat(ST_SIZE), "\n"); |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #ALGOL_68 | ALGOL 68 | PROC set = (REF FILE file, INT page, line, character)VOID: ~ |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename... | #11l | 11l | F is_ext(file_name, extensions)
R any(extensions.map(e -> @file_name.lowercase().ends_with(‘.’e.lowercase())))
F test(file_names, extensions)
L(file_name) file_names
print(file_name.ljust(max(file_names.map(f_n -> f_n.len)))‘ ’String(is_ext(file_name, extensions)))
test([‘MyData.a##’, ‘MyData.tar.Gz’, ‘... |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #BBC_BASIC | BBC BASIC | DIM ft{dwLowDateTime%, dwHighDateTime%}
DIM st{wYear{l&,h&}, wMonth{l&,h&}, wDayOfWeek{l&,h&}, \
\ wDay{l&,h&}, wHour{l&,h&}, wMinute{l&,h&}, \
\ wSecond{l&,h&}, wMilliseconds{l&,h&} }
REM File is assumed to exist:
file$ = @tmp$ + "rosetta.tmp"
REM Get and display... |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #C | C | #include <sys/stat.h>
#include <stdio.h>
#include <time.h>
#include <utime.h>
const char *filename = "input.txt";
int main() {
struct stat foo;
time_t mtime;
struct utimbuf new_times;
if (stat(filename, &foo) < 0) {
perror(filename);
return 1;
}
mtime = foo.st_mtime; /* seconds since the epoch... |
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... | #J | J | ((10x^~.),.#/.~) <.10 ^.1>. /:~;{:|:dirtree '~'
1 2
10 8
100 37
1000 49
10000 20
100000 9
1000000 4
10000000 4 |
http://rosettacode.org/wiki/File_size_distribution | File size distribution | Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no... | #Julia | Julia | using Humanize
function sizelist(path::AbstractString)
rst = Vector{Int}(0)
for (root, dirs, files) in walkdir(path)
files = joinpath.(root, files)
tmp = collect(filesize(f) for f in files if !islink(f))
append!(rst, tmp)
end
return rst
end
byclass(y, classes) = Dict{eltype(c... |
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... | #Kotlin | Kotlin | // version 1.2.10
import java.io.File
import kotlin.math.log10
import kotlin.math.floor
fun fileSizeDistribution(path: String) {
val sizes = IntArray(12)
val p = File(path)
val files = p.walk()
var accessible = 0
var notAccessible = 0
var totalSize = 0L
for (file in files) {
try ... |
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... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
std::string longestPath( const std::vector<std::string> & , char ) ;
int main( ) {
std::string dirs[ ] = {
"/home/user1/tmp/coverage/test" ,
"/home/user1/tmp/covert/operator" ,
"/home/user1/tmp/coven/members" } ;
st... |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #ALGOL_68 | ALGOL 68 | MODE TYPE = INT;
PROC select = ([]TYPE from, PROC(TYPE)BOOL where)[]TYPE:
BEGIN
FLEX[0]TYPE result;
FOR key FROM LWB from TO UPB from DO
IF where(from[key]) THEN
[UPB result+1]TYPE new result;
new result[:UPB result] := result;
new result[UPB new result] := from[key];
result := new res... |
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... | #Lua | Lua | EPS = 0.001
EPS_SQUARE = EPS * EPS
function side(x1, y1, x2, y2, x, y)
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1)
end
function naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
local checkSide1 = side(x1, y1, x2, y2, x, y) >= 0
local checkSide2 = side(x2, y2, x3, y3, x, y) >= 0
local check... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #TXR | TXR | @(bind foo ((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()))
@(bind bar foo)
@(flatten bar) |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #VBScript | VBScript |
class flattener
dim separator
sub class_initialize
separator = ","
end sub
private function makeflat( a )
dim i
dim res
for i = lbound( a ) to ubound( a )
if isarray( a( i ) ) then
res = res & makeflat( a( i ) )
else
res = res & a( i ) & separator
end if
next
makeflat = res
end... |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Factor | Factor | : recurse ( n -- n ) 1 + recurse ;
0 recurse |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Fermat | Fermat |
Func Sisyphus(n)=!!n;Sisyphus(n+1).
Sisyphus(0)
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | palindromify3[n_] :=
Block[{digits},
If[Divisible[n, 3], {},
digits = IntegerDigits[n, 3];
FromDigits[#, 3] & /@
{Join[Reverse[digits], digits], Join[Reverse[Rest[digits]], {First[digits]}, Rest[digits]]}
]
];
base2PalindromeQ[n_] := IntegerDigits[n, 2] === Reverse[Inte... |
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 ... | #Nim | Nim | import bitops, strformat, times
#---------------------------------------------------------------------------------------------------
func isPal2(k: uint64; digitCount: Natural): bool =
## Return true if the "digitCount" + 1 bits of "k" form a palindromic number.
for i in 0..digitCount:
if k.testBit(i) != ... |
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)
... | #ERRE | ERRE |
PROGRAM FIZZ_BUZZ
!
! for rosettacode.org
!
BEGIN
FOR A=1 TO 100 DO
IF A MOD 15=0 THEN
PRINT("FizzBuzz")
ELSIF A MOD 3=0 THEN
PRINT("Fizz")
ELSIF A MOD 5=0 THEN
PRINT("Buzz")
ELSE
PRINT(A)
END IF
END FOR
END PROGRAM
|
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Arturo | Arturo | print volume "input.txt"
print volume "/input.txt" |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #AutoHotkey | AutoHotkey | FileGetSize, FileSize, input.txt ; Retrieve the size in bytes.
MsgBox, Size of input.txt is %FileSize% bytes
FileGetSize, FileSize, \input.txt, K ; Retrieve the size in Kbytes.
MsgBox, Size of \input.txt is %FileSize% Kbytes |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename... | #Action.21 | Action! | DEFINE PTR="CARD"
CHAR FUNC ToLower(CHAR c)
IF c>='A AND c<='Z THEN
c==+'a-'A
FI
RETURN (c)
BYTE FUNC CheckExt(CHAR ARRAY file,ext)
BYTE i,j
CHAR c1,c2
i=file(0) j=ext(0)
IF i<j THEN RETURN (0) FI
WHILE j>0
DO
c1=ToLower(file(i))
c2=ToLower(ext(j))
IF c1#c2 THEN RETURN (0) FI
... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed.Equal_Case_Insensitive; use Ada.Strings.Fixed;
with Ada.Strings.Bounded;
procedure Main is
package B_String is new Ada.Strings.Bounded.Generic_Bounded_Length (30);
use B_String;
function is_equal (left, right : String) r... |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #C.23 | C# | using System;
using System.IO;
Console.WriteLine(File.GetLastWriteTime("file.txt"));
File.SetLastWriteTime("file.txt", DateTime.Now); |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #C.2B.2B | C++ | #include <boost/filesystem/operations.hpp>
#include <ctime>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 2 ) {
std::cerr << "Error! Syntax: moditime <filename>!\n" ;
return 1 ;
}
boost::filesystem::path p( argv[ 1 ] ) ;
if ( boost::filesystem::exists( p ) ) {
s... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | SetDirectory[NotebookDirectory[]];
Histogram[FileByteCount /@ Select[FileNames[__], DirectoryQ /* Not], {"Log", 15}, {"Log", "Count"}] |
http://rosettacode.org/wiki/File_size_distribution | File size distribution | Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no... | #Nim | Nim | import math, os, strformat
const
MaxPower = 10
Powers = [1, 10, 100]
func powerWithUnit(idx: int): string =
## Return a string representing value 10^idx with a unit.
if idx < 0:
"0B"
elif idx < 3:
fmt"{Powers[idx]}B"
elif idx < 6:
fmt"{Powers[idx - 3]}kB"
elif idx < 9:
fmt"{Powers[idx ... |
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... | #Perl | Perl | use File::Find;
use List::Util qw(max);
my %fsize;
$dir = shift || '.';
find(\&fsize, $dir);
$max = max($max,$fsize{$_}) for keys %fsize;
$total += $size while (undef,$size) = each %fsize;
print "File size distribution in bytes for directory: $dir\n";
for (0 .. max(keys %fsize)) {
printf "# files @ %4sb %8s: ... |
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... | #Clojure | Clojure | (use '[clojure.string :only [join,split]])
(defn common-prefix [sep paths]
(let [parts-per-path (map #(split % (re-pattern sep)) paths)
parts-per-position (apply map vector parts-per-path)]
(join sep
(for [parts parts-per-position :while (apply = parts)]
(first parts)))))
(println
(co... |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #ALGOL_W | ALGOL W | begin
% sets the elements of out to the elements of in that return true from applying the where procedure to them %
% the bounds of in must be 1 :: inUb - out must be at least as big as in and the number of matching %
% elements is returned in outUb - in and out can be the same array ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | RegionMember[Polygon[{{1, 2}, {3, 1}, {2, 4}}], {2, 2}] |
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle | Find if a point is within a triangle | Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Re... | #Nim | Nim | import strformat
const
Eps = 0.001
Eps2 = Eps * Eps
type
Point = tuple[x, y: float]
Triangle = object
p1, p2, p3: Point
func initTriangle(p1, p2, p3: Point): Triangle =
Triangle(p1: p1, p2: p2, p3: p3)
func side(p1, p2, p: Point): float =
(p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - ... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Wart | Wart | def (flatten seq acc)
if no.seq
acc
~list?.seq
(cons seq acc)
:else
(flatten car.seq (flatten cdr.seq acc)) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Forth | Forth | : munge ( n -- n' ) 1+ recurse ;
: test 0 ['] munge catch if ." Recursion limit at depth " . then ;
test \ Default gforth: Recursion limit at depth 3817 |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Fortran | Fortran | program recursion_depth
implicit none
call recurse (1)
contains
recursive subroutine recurse (i)
implicit none
integer, intent (in) :: i
write (*, '(i0)') i
call recurse (i + 1)
end subroutine recurse
end program recursion_depth |
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 ... | #PARI.2FGP | PARI/GP | check(n)={ \\ Check for 2n+1-digit palindromes in base 3
my(N=3^n);
forstep(i=N+1,2*N,[1,2],
my(base2,base3=digits(i,3),k);
base3=concat(Vecrev(base3[2..n+1]), base3);
k=subst(Pol(base3),'x,3);
base2=binary(k);
if(base2==Vecrev(base2), print1(", "k))
)
};
print1("0, 1"); for(i=1,11,check(i)) |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #Euphoria | Euphoria | include std/utils.e
function fb( atom n )
sequence fb
if remainder( n, 15 ) = 0 then
fb = "FizzBuzz"
elsif remainder( n, 5 ) = 0 then
fb = "Fizz"
elsif remainder( n, 3 ) = 0 then
fb = "Buzz"
else
fb = sprintf( "%d", n )
end if
return fb
end function
function fb2( atom n )
return iif( remainder(n, 15... |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #AWK | AWK | @load "filefuncs"
function filesize(name ,fd) {
if ( stat(name, fd) == -1)
return -1 # doesn't exist
else
return fd["size"]
}
BEGIN {
print filesize("input.txt")
print filesize("/input.txt")
} |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Axe | Axe | If GetCalc("appvINPUT")→I
Disp {I-2}ʳ▶Dec,i
Else
Disp "NOT FOUND",i
End |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write ... | #11l | 11l | V file_contents = File(‘input.txt’).read()
File(‘output.txt’, ‘w’).write(file_contents) |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename... | #ALGOL_68 | ALGOL 68 | # returns the length of str #
OP LENGTH = ( STRING str )INT: ( UPB str - LWB str ) + 1;
# returns TRUE if str ends with ending FALSE otherwise #
PRIO ENDSWITH = 9;
OP ENDSWITH = ( STRING str, STRING ending )BOOL:
IF INT str length = LENGTH str;
... |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Clojure | Clojure | (import '(java.io File)
'(java.util Date))
(Date. (.lastModified (File. "output.txt")))
(Date. (.lastModified (File. "docs")))
(.setLastModified (File. "output.txt")
(.lastModified (File. "docs"))) |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Common_Lisp | Common Lisp | (file-write-date "input.txt") |
http://rosettacode.org/wiki/File_size_distribution | File size distribution | Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no... | #Phix | Phix | without js -- file i/o
sequence sizes = {1},
res = {0}
atom t1 = time()+1
function store_res(string filepath, sequence dir_entry)
if not find('d', dir_entry[D_ATTRIBUTES]) then
atom size = dir_entry[D_SIZE]
integer sdx = 1
while size>sizes[sdx] do
if sdx=length(sizes) ... |
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... | #Common_Lisp | Common Lisp |
(defun common-directory-path (&rest paths)
(do* ((pathnames (mapcar #'(lambda (path) (cdr (pathname-directory (pathname path)))) paths)) ; convert strings to lists of subdirectories
(rem pathnames (cdr rem))
(pos (length (first rem))) ) ; position of first mismatched element
((null (cdr rem)) (make-pa... |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #AmigaE | AmigaE | PROC main()
DEF l : PTR TO LONG, r : PTR TO LONG, x
l := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
r := List(ListLen(l))
SelectList({x}, l, r, `Mod(x,2)=0)
ForAll({x}, r, `WriteF('\d\n', x))
ENDPROC |
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle | Find if a point is within a triangle | Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Re... | #Perl | Perl | # 20201123 added Perl programming solution
use strict;
use warnings;
use List::AllUtils qw(min max natatime);
use constant EPSILON => 0.001;
use constant EPSILON_SQUARE => EPSILON*EPSILON;
sub side {
my ($x1, $y1, $x2, $y2, $x, $y) = @_;
return ($y2 - $y1)*($x - $x1) + (-$x2 + $x1)*($y - $y... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #WDTE | WDTE | let a => import 'arrays';
let s => import 'stream';
let flatten array =>
a.stream array
-> s.flatMap (@ f v => v {
reflect 'Array' => a.stream v -> s.flatMap f;
})
-> s.collect
; |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #GAP | GAP | f := function(n)
return f(n+1);
end;
# Now loop until an error occurs
f(0);
# Error message :
# Entering break read-eval-print loop ...
# you can 'quit;' to quit to outer loop, or
# you may 'return;' to continue
n;
# 4998
# quit "brk mode" and return to GAP
quit; |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #gnuplot | gnuplot | # Put this in a file foo.gnuplot and run as
# gnuplot foo.gnuplot
# probe by 1 up to 1000, then by 1% increases
if (! exists("try")) { try=0 }
try=(try<1000 ? try+1 : try*1.01)
recurse(n) = (n > 0 ? recurse(n-1) : 'ok')
print "try recurse ", try
print recurse(try)
reread |
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 ... | #Perl | Perl | use ntheory qw/fromdigits todigitstring/;
print "0 0 0\n"; # Hard code the 0 result
for (0..2e5) {
# Generate middle-1-palindrome in base 3.
my $pal = todigitstring($_, 3);
my $b3 = $pal . "1" . reverse($pal);
# Convert base 3 number to base 2
my $b2 = todigitstring(fromdigits($b3, 3), 2);
# Print resu... |
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)
... | #F.23 | F# | let fizzbuzz n =
match n%3 = 0, n%5 = 0 with
| true, false -> "fizz"
| false, true -> "buzz"
| true, true -> "fizzbuzz"
| _ -> string n
let printFizzbuzz() =
[1..100] |> List.iter (fizzbuzz >> printfn "%s") |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #BaCon | BaCon | ' file size
' Return the entire message, FILELEN returns a NUMBER
FUNCTION printlen$(STRING name$)
IF FILEEXISTS(name$) THEN
RETURN name$ & ": " & STR$(FILELEN(name$))
ELSE
RETURN "file " & name$ & " not found"
END IF
END FUNCTION
PRINT printlen$("input.txt")
PRINT printlen$("/input.txt") |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Batch_File | Batch File |
@echo off
if not exist "%~1" exit /b 1 & rem If file doesn't exist exit with error code of 1.
for /f %%i in (%~1) do echo %~zi
pause>nul
|
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write ... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program readwrtFile64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantes... |
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 ... | #ACL2 | ACL2 | :set-state-ok t
(defun read-channel (channel limit state)
(mv-let (ch state)
(read-char$ channel state)
(if (or (null ch)
(zp limit))
(let ((state (close-input-channel channel state)))
(mv nil state))
(mv-let (so-far state)
(read-cha... |
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... | #Arturo | Arturo | fileExtensions: map ["zip" "rar" "7z" "gz" "archive" "A##"] => ["." ++ lower]
hasExtension?: function [file][
in? extract.extension lower file
fileExtensions
]
files: ["MyData.a##" "MyData.tar.Gz" "MyData.gzip" "MyData.7z.backup" "MyData..." "MyData"]
loop files 'file ->
print [file "=> hasExtensi... |
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... | #AWK | AWK |
# syntax: GAWK -f FILE_EXTENSION_IS_IN_EXTENSIONS_LIST.AWK
BEGIN {
n = split("zip,rar,7z,gz,archive,A##,tar.bz2", arr, ",")
for (i=1; i<=n; i++) {
ext_arr[tolower(arr[i])] = ""
}
filenames = "MyData.a##,MyData.tar.Gz,MyData.gzip,MyData.7z.backup,MyData...,MyData,MyData_v1.0.tar.bz2,MyData_v1.0.b... |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #D | D | import std.stdio;
import std.file: getTimes, setTimes, SysTime;
void main() {
auto fname = "unixdict.txt";
SysTime fileAccessTime, fileModificationTime;
getTimes(fname, fileAccessTime, fileModificationTime);
writeln(fileAccessTime, "\n", fileModificationTime);
setTimes(fname, fileAccessTime, fileM... |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Delphi | Delphi | function GetModifiedDate(const aFilename: string): TDateTime;
var
hFile: Integer;
iDosTime: Integer;
begin
hFile := FileOpen(aFilename, fmOpenRead);
iDosTime := FileGetDate(hFile);
FileClose(hFile);
if (hFile = -1) or (iDosTime = -1) then raise Exception.Create('Cannot read file: ' + sFilename);
Result :=... |
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... | #Python | Python | import sys, os
from collections import Counter
def dodir(path):
global h
for name in os.listdir(path):
p = os.path.join(path, name)
if os.path.islink(p):
pass
elif os.path.isfile(p):
h[os.stat(p).st_size] += 1
elif os.path.isdir(p):
dodir... |
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... | #Racket | Racket | #lang racket
(define (file-size-distribution (d (current-directory)) #:size-group-function (sgf values))
(for/fold ((rv (hash)) (Σ 0) (n 0)) ((f (in-directory d)) #:when (file-exists? f))
(define sz (file-size f))
(values (hash-update rv (sgf sz) add1 0) (+ Σ sz) (add1 n))))
(define (log10-or-so x) (if (z... |
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... | #AutoHotkey | AutoHotkey | #NoEnv
SetBatchLines, -1
p := 0.3 ; Segment length (pixels)
F_Word := 30
SysGet, Mon, MonitorWorkArea
W := FibWord(F_Word)
d := 1
x1 := 0
y1 := MonBottom
Width := A_ScreenWidth
Height := A_ScreenHeight
If (!pToken := Gdip_Startup()) {
MsgBox, 48, Gdiplus Error!, Gdiplus failed to start. Please ensure you have Gdip... |
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... | #D | D | import std.stdio, std.string, std.algorithm, std.path, std.array;
string commonDirPath(in string[] paths, in string sep = "/") pure {
if (paths.empty)
return null;
return paths.map!(p => p.split(sep)).reduce!commonPrefix.join(sep);
}
void main() {
immutable paths = ["/home/user1/tmp/coverage/tes... |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #AntLang | AntLang | x:range[100]
{1- x mod 2}hfilter x |
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle | Find if a point is within a triangle | Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Re... | #Phix | Phix | with javascript_semantics
constant p0 = {0,0},
p1 = {0,1},
p2 = {3,1},
triangle = {{3/2, 12/5}, {51/10, -31/10}, {-19/5, 1/2}}
function inside(sequence p)
return sort(convex_hull({p}&triangle))==sort(deep_copy(triangle))
end function
printf(1,"Point %v is with triangle %v?:%t\n",{... |
http://rosettacode.org/wiki/Flatten_a_list | Flatten a list | Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
| #Wren | Wren | import "/seq" for Lst
var a = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
System.print(Lst.flatten(a)) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Go | Go | package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
} |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Gri | Gri | `Recurse'
{
show .depth.
.depth. = {rpn .depth. 1 +}
Recurse
}
.depth. = 1
Recurse |
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases | Find palindromic numbers in both binary and ternary bases | Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 ... | #Phix | Phix | with javascript_semantics
-- widths and limits for 32/64 bit running (see output below):
constant {dsize,w3,w2,limit} = iff(machine_bits()=32?{12,23,37,6}
:{18,37,59,7}),
-- [atoms on 32-bit have only 53 bits of precision, but 7th ^^^^ requires 59]
dfmt = spr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.