task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Common_Lisp
|
Common Lisp
|
(defun fizzbuzz ()
(loop for x from 1 to 100 do
(princ (cond ((zerop (mod x 15)) "FizzBuzz")
((zerop (mod x 3)) "Fizz")
((zerop (mod x 5)) "Buzz")
(t x)))
(terpri)))
|
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
|
#Prolog
|
Prolog
|
flatten(List, FlatList) :-
flatten(List, [], FlatList).
flatten(Var, T, [Var|T]) :-
var(Var), !.
flatten([], T, T) :- !.
flatten([H|T], TailList, List) :- !,
flatten(H, FlatTail, List),
flatten(T, TailList, FlatTail).
flatten(NonList, T, [NonList|T]).
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Coq
|
Coq
|
Require Import Coq.Lists.List.
(* https://coq.inria.fr/library/Coq.Lists.List.html *)
Require Import Coq.Strings.String.
(* https://coq.inria.fr/library/Coq.Strings.String.html *)
Require Import Coq.Strings.Ascii.
(* https://coq.inria.fr/library/Coq.Strings.Ascii.html *)
Require Import Coq.Init.Nat.
(* https://coq.inria.fr/library/Coq.Init.Nat.html *)
(** Definition of [string_of_nat] to convert natural numbers to strings. *)
Definition ascii_of_digit (n: nat): ascii :=
ascii_of_nat (n + 48).
Definition is_digit (n: nat): bool :=
andb (0 <=? n) (n <=? 9).
Fixpoint rec_string_of_nat (counter: nat) (n: nat) (acc: string): string :=
match counter with
| 0 => EmptyString
| S c =>
if (is_digit n)
then String (ascii_of_digit n) acc
else rec_string_of_nat c (n / 10) (String (ascii_of_digit (n mod 10)) acc)
end.
(** The counter is only used to ensure termination. *)
Definition string_of_nat (n: nat): string :=
rec_string_of_nat n n EmptyString.
(** The FizzBuzz problem. *)
Definition fizz: string :=
"Fizz" .
Definition buzz: string :=
"Buzz" .
Definition new_line: string :=
String (ascii_of_nat 10) EmptyString.
Definition is_divisible_by (n: nat) (k: nat): bool :=
(n mod k) =? 0.
Definition get_fizz_buzz_term (n: nat): string :=
if (is_divisible_by n 15) then fizz ++ buzz
else if (is_divisible_by n 3) then fizz
else if (is_divisible_by n 5) then buzz
else (string_of_nat n).
Definition get_first_positive_numbers (n: nat): list nat :=
seq 1 n.
Definition fizz_buzz_terms (n: nat): list string :=
map get_fizz_buzz_term (get_first_positive_numbers n).
Definition fizz_buzz: string :=
concat new_line (fizz_buzz_terms 100).
(** This shows the string. *)
Eval compute in fizz_buzz.
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#C.2B.2B
|
C++
|
#include<iostream>
#include<string>
#include<boost/filesystem.hpp>
#include<boost/format.hpp>
#include<boost/iostreams/device/mapped_file.hpp>
#include<optional>
#include<algorithm>
#include<iterator>
#include<execution>
#include"dependencies/xxhash.hpp" // https://github.com/RedSpah/xxhash_cpp
/**
* Find ranges (neighbouring elements) of the same value within [begin, end[ and
* call callback for each such range
* @param begin start of container
* @param end end of container (1 beyond last element)
* @param function returns value for each iterator V(*T&)
* @param callback void(start, end, value)
* @return number of range
*/
template<typename T, typename V, typename F>
size_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {
size_t partitions = 0;
while (begin != end) {
auto const& value = getvalue(*begin);
auto current = begin;
while (++current != end && getvalue(*current) == value);
callback(begin, current, value);
++partitions;
begin = current;
}
return partitions;
}
namespace bi = boost::iostreams;
namespace fs = boost::filesystem;
struct file_entry {
public:
explicit file_entry(fs::directory_entry const & entry)
: path_{entry.path()}, size_{fs::file_size(entry)}
{}
auto size() const { return size_; }
auto const& path() const { return path_; }
auto get_hash() {
if (!hash_)
hash_ = compute_hash();
return *hash_;
}
private:
xxh::hash64_t compute_hash() {
bi::mapped_file_source source;
source.open<fs::wpath>(this->path());
if (!source.is_open()) {
std::cerr << "Cannot open " << path() << std::endl;
throw std::runtime_error("Cannot open file");
}
xxh::hash_state64_t hash_stream;
hash_stream.update(source.data(), size_);
return hash_stream.digest();
}
private:
fs::wpath path_;
uintmax_t size_;
std::optional<xxh::hash64_t> hash_;
};
using vector_type = std::vector<file_entry>;
using iterator_type = vector_type::iterator;
auto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {
size_t found = 0, ignored = 0;
if (!fs::is_directory(path)) {
std::cerr << path << " is not a directory!" << std::endl;
}
else {
std::cerr << "Searching " << path << std::endl;
for (auto& e : fs::recursive_directory_iterator(path)) {
++found;
if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)
file_vector.emplace_back(e);
else ++ignored;
}
}
return std::make_tuple(found, ignored);
}
int main(int argn, char* argv[])
{
vector_type files;
for (auto i = 1; i < argn; ++i) {
fs::wpath path(argv[i]);
auto [found, ignored] = find_files_in_dir(path, files);
std::cerr << boost::format{
" %1$6d files found\n"
" %2$6d files ignored\n"
" %3$6d files added\n" } % found % ignored % (found - ignored)
<< std::endl;
}
std::cerr << "Found " << files.size() << " regular files" << std::endl;
// sort files in descending order by file size
std::sort(std::execution::par_unseq, files.begin(), files.end()
, [](auto const& a, auto const& b) { return a.size() > b.size(); }
);
for_each_adjacent_range(
std::begin(files)
, std::end(files)
, [](vector_type::value_type const& f) { return f.size(); }
, [](auto start, auto end, auto file_size) {
// Files with same size
size_t nr_of_files = std::distance(start, end);
if (nr_of_files > 1) {
// sort range start-end by hash
std::sort(start, end, [](auto& a, auto& b) {
auto const& ha = a.get_hash();
auto const& hb = b.get_hash();
auto const& pa = a.path();
auto const& pb = b.path();
return std::tie(ha, pa) < std::tie(hb, pb);
});
for_each_adjacent_range(
start
, end
, [](vector_type::value_type& f) { return f.get_hash(); }
, [file_size](auto hstart, auto hend, auto hash) {
// Files with same size and same hash are assumed to be identical
// could resort to compare files byte-by-byte now
size_t hnr_of_files = std::distance(hstart, hend);
if (hnr_of_files > 1) {
std::cout << boost::format{ "%1$3d files with hash %3$016x and size %2$d\n" }
% hnr_of_files % file_size % hash;
std::for_each(hstart, hend, [hash, file_size](auto& e) {
std::cout << '\t' << e.path() << '\n';
}
);
}
}
);
}
}
);
return 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
|
#PureBasic
|
PureBasic
|
Structure RCList
Value.i
List A.RCList()
EndStructure
Procedure Flatten(List A.RCList())
ResetList(A())
While NextElement(A())
With A()
If \Value
Continue
Else
ResetList(\A())
While NextElement(\A())
If \A()\Value: A()\Value=\A()\Value: EndIf
Wend
EndIf
While ListSize(\A()): DeleteElement(\A()): Wend
If Not \Value: DeleteElement(A()): EndIf
EndWith
Wend
EndProcedure
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Cowgol
|
Cowgol
|
include "cowgol.coh";
var i: uint8 := 1;
while i <= 100 loop
if i % 15 == 0 then
print("FizzBuzz");
elseif i % 5 == 0 then
print("Buzz");
elseif i % 3 == 0 then
print("Fizz");
else
print_i8(i);
end if;
print_nl();
i := i + 1;
end loop;
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Elixir
|
Elixir
|
defmodule Files do
def find_duplicate_files(dir) do
IO.puts "\nDirectory : #{dir}"
File.cd!(dir, fn ->
Enum.filter(File.ls!, fn fname -> File.regular?(fname) end)
|> Enum.group_by(fn file -> File.stat!(file).size end)
|> Enum.filter(fn {_, files} -> length(files)>1 end)
|> Enum.each(fn {size, files} ->
Enum.group_by(files, fn file -> :erlang.md5(File.read!(file)) end)
|> Enum.filter(fn {_, files} -> length(files)>1 end)
|> Enum.each(fn {_md5, fs} ->
IO.puts " --------------------------------------------"
Enum.each(fs, fn file ->
IO.puts " #{inspect File.stat!(file).mtime}\t#{size} #{file}"
end)
end)
end)
end)
end
end
hd(System.argv) |> Files.find_duplicate_files
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Go
|
Go
|
package main
import (
"fmt"
"crypto/md5"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"time"
)
type fileData struct {
filePath string
info os.FileInfo
}
type hash [16]byte
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func checksum(filePath string) hash {
bytes, err := ioutil.ReadFile(filePath)
check(err)
return hash(md5.Sum(bytes))
}
func findDuplicates(dirPath string, minSize int64) [][2]fileData {
var dups [][2]fileData
m := make(map[hash]fileData)
werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && info.Size() >= minSize {
h := checksum(path)
fd, ok := m[h]
fd2 := fileData{path, info}
if !ok {
m[h] = fd2
} else {
dups = append(dups, [2]fileData{fd, fd2})
}
}
return nil
})
check(werr)
return dups
}
func main() {
dups := findDuplicates(".", 1)
fmt.Println("The following pairs of files have the same size and the same hash:\n")
fmt.Println("File name Size Date last modified")
fmt.Println("==========================================================")
sort.Slice(dups, func(i, j int) bool {
return dups[i][0].info.Size() > dups[j][0].info.Size() // in order of decreasing size
})
for _, dup := range dups {
for i := 0; i < 2; i++ {
d := dup[i]
fmt.Printf("%-20s %8d %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))
}
fmt.Println()
}
}
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#BASIC
|
BASIC
|
100 REM DERIVE SP-ID FROM CHESS960 POS
110 PRINT "ENTER START ARRAY AS SEEN BY WHITE."
120 PRINT: PRINT "STARTING ARRAY:";
130 OPEN 1,0: INPUT#1, AR$: CLOSE 1: PRINT
140 IF LEN(AR$)=0 THEN END
150 IF LEN(AR$)=8 THEN 170
160 PRINT "ARRAY MUST BE 8 PIECES.": GOTO 120
170 FOR I=1 TO 8
180 : P$=MID$(AR$,I,1)
190 : IF P$="Q" THEN Q(Q)=I: Q=Q+1: GOTO 250
200 : IF P$="K" THEN K(K)=I: K=K+1: GOTO 250
210 : IF P$="B" THEN B(B)=I: B=B+1: GOTO 250
220 : IF P$="N" THEN N(N)=I: N=N+1: GOTO 250
230 : IF P$="R" THEN R(R)=I: R=R+1: GOTO 250
240 : PRINT "ILLEGAL PIECE '"P$"'.": GOTO 120
250 NEXT I
260 IF K<>1 THEN PRINT "THERE MUST BE EXACTLY ONE KING.": GOTO 120
270 IF Q<>1 THEN PRINT "THERE MUST BE EXACTLY ONE QUEEN.": GOTO 120
280 IF B<>2 THEN PRINT "THERE MUST BE EXACTLY TWO BISHOPS.": GOTO 120
290 IF N<>2 THEN PRINT "THERE MUST BE EXACTLY TWO KNIGHTS.": GOTO 120
300 IF R<>2 THEN PRINT "THERE MUST BE EXACTLY TWO ROOKS.": GOTO 120
310 IF (K(0) > R(0)) AND (K(0) < R(1)) THEN 330
320 PRINT "KING MUST BE BETWEEN THE ROOKS.": GOTO 120
330 IF (B(0) AND 1) <> (B(1) AND 1) THEN 350
340 PRINT "BISHOPS MUST BE ON OPPOSITE COLORS.": GOTO 120
350 FOR I=0 TO 1
360 : N=N(I)
370 : IF N(I)>Q(I) THEN N=N-1
380 : FOR J=0 TO 1
390 : IF N(I)>B(J) THEN N=N-1
400 : NEXT J
410 : N(I)=N
420 NEXT I
430 N0=1: N1=2
440 FOR N=0 TO 9
450 : IF N0=N(0) AND N1=N(1) THEN 490
460 : N1=N1+1
470 : IF N1>5 THEN N0=N0+1: N1=N0+1
480 NEXT N
490 Q=Q(0)-1
500 FOR I=0 TO 1
510 : IF Q(0)>N(I) THEN Q=Q-1
520 NEXT I
530 FOR I=0 TO 1
540 : B=B(I)-1
550 : IF B AND 1 THEN L=INT(B/2)
560 : IF (B AND 1)=0 THEN D=B/2
570 NEXT I
580 PRINT "SPID ="; 96*N+16*Q+4*D+L
|
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
|
#Python
|
Python
|
>>> def flatten(lst):
return sum( ([x] if not isinstance(x, list) else flatten(x)
for x in lst), [] )
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flatten(lst)
[1, 2, 3, 4, 5, 6, 7, 8]
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Crystal
|
Crystal
|
1.upto(100) do |v|
p fizz_buzz(v)
end
def fizz_buzz(value)
word = ""
word += "fizz" if value % 3 == 0
word += "buzz" if value % 5 == 0
word += value.to_s if word.empty?
word
end
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Haskell
|
Haskell
|
- checks for wrong command line input (not existing directory / negative size)
- works on Windows as well as Unix Systems (tested with Mint 17 / Windows 7)
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Java
|
Java
|
import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.security.*;
import java.util.*;
public class DuplicateFiles {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Directory name and minimum file size are required.");
System.exit(1);
}
try {
findDuplicateFiles(args[0], Long.parseLong(args[1]));
} catch (Exception e) {
e.printStackTrace();
}
}
private static void findDuplicateFiles(String directory, long minimumSize)
throws IOException, NoSuchAlgorithmException {
System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes.");
Path path = FileSystems.getDefault().getPath(directory);
FileVisitor visitor = new FileVisitor(path, minimumSize);
Files.walkFileTree(path, visitor);
System.out.println("The following sets of files have the same size and checksum:");
for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {
Map<Object, List<String>> map = e.getValue();
if (!containsDuplicates(map))
continue;
List<List<String>> fileSets = new ArrayList<>(map.values());
for (List<String> files : fileSets)
Collections.sort(files);
Collections.sort(fileSets, new StringListComparator());
FileKey key = e.getKey();
System.out.println();
System.out.println("Size: " + key.size_ + " bytes");
for (List<String> files : fileSets) {
for (int i = 0, n = files.size(); i < n; ++i) {
if (i > 0)
System.out.print(" = ");
System.out.print(files.get(i));
}
System.out.println();
}
}
}
private static class StringListComparator implements Comparator<List<String>> {
public int compare(List<String> a, List<String> b) {
int len1 = a.size(), len2 = b.size();
for (int i = 0; i < len1 && i < len2; ++i) {
int c = a.get(i).compareTo(b.get(i));
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
private static boolean containsDuplicates(Map<Object, List<String>> map) {
if (map.size() > 1)
return true;
for (List<String> files : map.values()) {
if (files.size() > 1)
return true;
}
return false;
}
private static class FileVisitor extends SimpleFileVisitor<Path> {
private MessageDigest digest_;
private Path directory_;
private long minimumSize_;
private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();
private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {
directory_ = directory;
minimumSize_ = minimumSize;
digest_ = MessageDigest.getInstance("MD5");
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (attrs.size() >= minimumSize_) {
FileKey key = new FileKey(file, attrs, getMD5Sum(file));
Map<Object, List<String>> map = fileMap_.get(key);
if (map == null)
fileMap_.put(key, map = new HashMap<>());
List<String> files = map.get(attrs.fileKey());
if (files == null)
map.put(attrs.fileKey(), files = new ArrayList<>());
Path relative = directory_.relativize(file);
files.add(relative.toString());
}
return FileVisitResult.CONTINUE;
}
private byte[] getMD5Sum(Path file) throws IOException {
digest_.reset();
try (InputStream in = new FileInputStream(file.toString())) {
byte[] buffer = new byte[8192];
int bytes;
while ((bytes = in.read(buffer)) != -1) {
digest_.update(buffer, 0, bytes);
}
}
return digest_.digest();
}
}
private static class FileKey implements Comparable<FileKey> {
private byte[] hash_;
private long size_;
private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {
size_ = attrs.size();
hash_ = hash;
}
public int compareTo(FileKey other) {
int c = Long.compare(other.size_, size_);
if (c == 0)
c = hashCompare(hash_, other.hash_);
return c;
}
}
private static int hashCompare(byte[] a, byte[] b) {
int len1 = a.length, len2 = b.length;
for (int i = 0; i < len1 && i < len2; ++i) {
int c = Byte.compare(a[i], b[i]);
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Factor
|
Factor
|
USING: assocs assocs.extras combinators formatting kernel
literals math math.combinatorics sequences sequences.extras sets
strings ;
! ====== optional error-checking ======
: check-length ( str -- )
length 8 = [ "Must have 8 pieces." throw ] unless ;
: check-one ( str -- )
"KQ" counts [ nip 1 = not ] assoc-find nip
[ 1string "Must have one %s." sprintf throw ] [ drop ] if ;
: check-two ( str -- )
"BNR" counts [ nip 2 = not ] assoc-find nip
[ 1string "Must have two %s." sprintf throw ] [ drop ] if ;
: check-king ( str -- )
"QBN" without "RKR" =
[ "King must be between rooks." throw ] unless ;
: check-bishops ( str -- )
CHAR: B swap indices sum odd?
[ "Bishops must be on opposite colors." throw ] unless ;
: check-sp ( str -- )
{
[ check-length ]
[ check-one ]
[ check-two ]
[ check-king ]
[ check-bishops ]
} cleave ;
! ====== end optional error-checking ======
CONSTANT: convert $[ "RNBQK" "♖♘♗♕♔" zip ]
CONSTANT: table $[ "NN---" all-unique-permutations ]
: knightify ( str -- newstr )
[ dup CHAR: N = [ drop CHAR: - ] unless ] map ;
: n ( str -- n ) "QB" without knightify table index ;
: q ( str -- q ) "N" without CHAR: Q swap index ;
: d ( str -- d ) CHAR: B swap <evens> index ;
: l ( str -- l ) CHAR: B swap <odds> index ;
: sp-id ( str -- n )
dup check-sp
{ [ n 96 * ] [ q 16 * + ] [ d 4 * + ] [ l + ] } cleave ;
: sp-id. ( str -- )
dup [ convert substitute ] [ sp-id ] bi
"%s / %s: %d\n" printf ;
"QNRBBNKR" sp-id.
"RNBQKBNR" sp-id.
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Go
|
Go
|
package main
import (
"fmt"
"log"
"strings"
)
var glyphs = []rune("♜♞♝♛♚♖♘♗♕♔")
var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"}
var g2lMap = map[rune]string{
'♜': "R", '♞': "N", '♝': "B", '♛': "Q", '♚': "K",
'♖': "R", '♘': "N", '♗': "B", '♕': "Q", '♔': "K",
}
var ntable = map[string]int{"01": 0, "02": 1, "03": 2, "04": 3, "12": 4, "13": 5, "14": 6, "23": 7, "24": 8, "34": 9}
func g2l(pieces string) string {
lets := ""
for _, p := range pieces {
lets += g2lMap[p]
}
return lets
}
func spid(pieces string) int {
pieces = g2l(pieces) // convert glyphs to letters
/* check for errors */
if len(pieces) != 8 {
log.Fatal("There must be exactly 8 pieces.")
}
for _, one := range "KQ" {
count := 0
for _, p := range pieces {
if p == one {
count++
}
}
if count != 1 {
log.Fatalf("There must be one %s.", names[one])
}
}
for _, two := range "RNB" {
count := 0
for _, p := range pieces {
if p == two {
count++
}
}
if count != 2 {
log.Fatalf("There must be two %s.", names[two])
}
}
r1 := strings.Index(pieces, "R")
r2 := strings.Index(pieces[r1+1:], "R") + r1 + 1
k := strings.Index(pieces, "K")
if k < r1 || k > r2 {
log.Fatal("The king must be between the rooks.")
}
b1 := strings.Index(pieces, "B")
b2 := strings.Index(pieces[b1+1:], "B") + b1 + 1
if (b2-b1)%2 == 0 {
log.Fatal("The bishops must be on opposite color squares.")
}
/* compute SP_ID */
piecesN := strings.ReplaceAll(pieces, "Q", "")
piecesN = strings.ReplaceAll(piecesN, "B", "")
n1 := strings.Index(piecesN, "N")
n2 := strings.Index(piecesN[n1+1:], "N") + n1 + 1
np := fmt.Sprintf("%d%d", n1, n2)
N := ntable[np]
piecesQ := strings.ReplaceAll(pieces, "N", "")
Q := strings.Index(piecesQ, "Q")
D := strings.Index("0246", fmt.Sprintf("%d", b1))
L := strings.Index("1357", fmt.Sprintf("%d", b2))
if D == -1 {
D = strings.Index("0246", fmt.Sprintf("%d", b2))
L = strings.Index("1357", fmt.Sprintf("%d", b1))
}
return 96*N + 16*Q + 4*D + L
}
func main() {
for _, pieces := range []string{"♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖"} {
fmt.Printf("%s or %s has SP-ID of %d\n", pieces, g2l(pieces), spid(pieces))
}
}
|
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
|
#Q
|
Q
|
(raze/) ((1); 2; ((3;4); 5); ((())); (((6))); 7; 8; ())
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#CSS
|
CSS
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<style>
li {
list-style-position: inside;
}
li:nth-child(3n), li:nth-child(5n) {
list-style-type: none;
}
li:nth-child(3n)::before {
content:'Fizz';
}
li:nth-child(5n)::after {
content:'Buzz';
}
</style>
</head>
<body>
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
</body>
</html>
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Julia
|
Julia
|
using Printf, Nettle
function find_duplicates(path::String, minsize::Int = 0)
filesdict = Dict{String,Array{NamedTuple}}()
for (root, dirs, files) in walkdir(path), fn in files
filepath = joinpath(root, fn)
filestats = stat(filepath)
filestats.size > minsize || continue
hash = open(f -> hexdigest("md5", read(f)), filepath)
if haskey(filesdict, hash)
push!(filesdict[hash], (path = filepath, stats = filestats))
else
filesdict[hash] = [(path = filepath, stats = filestats)]
end
end
# Get duplicates
dups = [tups for tups in values(filesdict) if length(tups) > 1]
return dups
end
function main()
path = "."
println("Finding duplicates in \"$path\"")
dups = find_duplicates(".", 1)
println("The following group of files have the same size and the same hash:\n")
println("File name Size last modified")
println("="^76)
for files in sort(dups, by = tups -> tups[1].stats.size, rev = true)
for (path, stats) in sort(files, by = tup -> tup.path, rev = true)
@printf("%-44s%8d %s\n", path, stats.size, Libc.strftime(stats.mtime))
end
println()
end
end
main()
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
hash="SHA256";
minSize=Quantity[1,"Megabytes"];
allfiles=Once@Select[FileNames["*","",∞],!Once@DirectoryQ[#]&&Once@FileSize[#]>minSize&];
data={#,Once[FileHash[#,hash,All,"HexString"]]}&/@allfiles[[;;5]];
Grid[Select[GatherBy[data,Last],Length[#]>1&][[All,All,1]]]
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Julia
|
Julia
|
const whitepieces = "♖♘♗♕♔♗♘♖♙"
const whitechars = "rnbqkp"
const blackpieces = "♜♞♝♛♚♝♞♜♟"
const blackchars = "RNBQKP"
const piece2ascii = Dict(zip("♖♘♗♕♔♗♘♖♙♜♞♝♛♚♝♞♜♟", "rnbqkbnrpRNBQKBNRP"))
""" Derive a chess960 position's SP-ID from its string representation. """
function chess960spid(position::String = "♖♘♗♕♔♗♘♖", errorchecking = true)
if errorchecking
@assert length(position) == 8 "Need exactly 8 pieces"
@assert all(p -> p in whitepieces || p in blackpieces, position) "Invalid piece character"
@assert all(p -> p in whitepieces, position) || all(p -> p in blackpieces, position) "Side of pieces is mixed"
@assert all(p -> !(p in "♙♟"), position) "No pawns allowed"
end
a = uppercase(String([piece2ascii[c] for c in position]))
if errorchecking
@assert all(p -> count(x -> x == p, a) == 1, "KQ") "Need exactly one of each K and Q"
@assert all(p -> count(x -> x == p, a) == 2, "RNB") "Need exactly 2 of each R, N, B"
@assert findfirst(p -> p == 'R', a) < findfirst(p -> p == 'K', a) < findlast(p -> p == 'R', a) "King must be between rooks"
@assert isodd(findfirst(p -> p == 'B', a) + findlast(p -> p == 'B', a)) "Bishops must be on different colors"
end
knighttable = [12, 13, 14, 15, 23, 24, 25, 34, 35, 45]
noQB = replace(a, r"[QB]" => "")
knightpos1, knightpos2 = findfirst(c -> c =='N', noQB), findlast(c -> c =='N', noQB)
N = findfirst(s -> s == 10 * knightpos1 + knightpos2, knighttable) - 1
Q = findfirst(c -> c == 'Q', replace(a, "N" => "")) - 1
bishoppositions = [findfirst(c -> c =='B', a), findlast(c -> c =='B', a)]
if isodd(bishoppositions[2])
bishoppositions = reverse(bishoppositions) # dark color bishop first
end
D, L = bishoppositions[1] ÷ 2, bishoppositions[2] ÷ 2 - 1
return 96N + 16Q + 4D + L
end
for position in ["♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖"]
println(collect(position), " => ", chess960spid(position))
end
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Nim
|
Nim
|
import sequtils, strformat, strutils, sugar, tables, unicode
type Piece {.pure.} = enum Rook = "R", Knight = "N", Bishop = "B", Queen = "Q", King = "K"
const
GlypthToPieces = {"♜": Rook, "♞": Knight, "♝": Bishop, "♛": Queen, "♚": King,
"♖": Rook, "♘": Knight, "♗": Bishop, "♕": Queen, "♔": King}.toTable
Names = [Rook: "rook", Knight: "knight", Bishop: "bishop", Queen: "queen", King: "king"]
NTable = {[0, 1]: 0, [0, 2]: 1, [0, 3]: 2, [0, 4]: 3, [1, 2]: 4,
[1, 3]: 5, [1, 4]: 6, [2, 3]: 7, [2, 4]: 8, [3, 4]: 9}.toTable
func toPieces(glyphs: string): seq[Piece] =
collect(newSeq, for glyph in glyphs.runes: GlypthToPieces[glyph.toUTF8])
func isEven(n: int): bool = (n and 1) == 0
func positions(pieces: seq[Piece]; piece: Piece): array[2, int] =
var idx = 0
for i, p in pieces:
if p == piece:
result[idx] = i
inc idx
func spid(glyphs: string): int =
let pieces = glyphs.toPieces()
# Check for errors.
if pieces.len != 8:
raise newException(ValueError, "there must be exactly 8 pieces.")
for piece in [King, Queen]:
if pieces.count(piece) != 1:
raise newException(ValueError, &"there must be one {Names[piece]}.")
for piece in [Rook, Knight, Bishop]:
if pieces.count(piece) != 2:
raise newException(ValueError, &"there must be two {Names[piece]}s.")
let r = pieces.positions(Rook)
let k = pieces.find(King)
if k < r[0] or k > r[1]:
raise newException(ValueError, "the king must be between the rooks.")
var b = pieces.positions(Bishop)
if isEven(b[1] - b[0]):
raise newException(ValueError, "the bishops must be on opposite color squares.")
# Compute SP_ID.
let piecesN = pieces.filterIt(it notin [Queen, Bishop])
let n = NTable[piecesN.positions(Knight)]
let piecesQ = pieces.filterIt(it != Knight)
let q = piecesQ.find(Queen)
if b[1].isEven: swap b[0], b[1]
let d = [0, 2, 4, 6].find(b[0])
let l = [1, 3, 5, 7].find(b[1])
result = 96 * n + 16 * q + 4 * d + l
for glyphs in ["♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖"]:
echo &"{glyphs} or {glyphs.toPieces().join()} has SP-ID of {glyphs.spid()}"
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
use List::AllUtils 'indexes';
sub sp_id {
my $setup = shift // 'RNBQKBNR';
8 == length $setup or die 'Illegal position: should have exactly eight pieces';
1 == @{[ $setup =~ /$_/g ]} or die "Illegal position: should have exactly one $_" for <K Q>;
2 == @{[ $setup =~ /$_/g ]} or die "Illegal position: should have exactly two $_\'s" for <B N R>;
$setup =~ m/R .* K .* R/x or die 'Illegal position: King not between rooks.';
index($setup,'B')%2 != rindex($setup,'B')%2 or die 'Illegal position: Bishops not on opposite colors.';
my @knights = indexes { 'N' eq $_ } split '', $setup =~ s/[QB]//gr;
my $knight = indexes { join('', @knights) eq $_ } <01 02 03 04 12 13 14 23 24 34>; # combinations(5,2)
my @bishops = indexes { 'B' eq $_ } split '', $setup;
my $dark = int ((grep { $_ % 2 == 0 } @bishops)[0]) / 2;
my $light = int ((grep { $_ % 2 == 1 } @bishops)[0]) / 2;
my $queen = index(($setup =~ s/B//gr), 'Q');
int 4*(4*(6*$knight + $queen)+$dark)+$light;
}
say "$_ " . sp_id($_) for <QNRBBNKR RNBQKBNR>;
|
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
|
#QBasic
|
QBasic
|
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_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#BBC_BASIC
|
BBC BASIC
|
HIMEM = PAGE + 3000000
INSTALL @lib$+"HIMELIB"
PROC_himeinit("HIMEkey")
DIM old$(20000), new$(20000)
h1% = 1 : h2% = 2 : h3% = 3 : h4% = 4
FOR base% = 3 TO 17
PRINT "Base "; base% " : " FN_largest_left_truncated_prime(base%)
NEXT
END
DEF FN_largest_left_truncated_prime(base%)
LOCAL digit%, i%, new%, old%, prime%, fast%, slow%
fast% = 1 : slow% = 50
old$() = ""
PROC_hiputdec(1, STR$(base%))
PROC_hiputdec(2, "1")
REPEAT
new% = 0 : new$() = ""
PROC_hiputdec(3, "0")
FOR digit% = 1 TO base%-1
SYS `hi_Add`, ^h2%, ^h3%, ^h3%
FOR i% = 0 TO old%-1
PROC_hiputdec(4, old$(i%))
SYS `hi_Add`, ^h3%, ^h4%, ^h4%
IF old% OR digit% > 1 THEN
IF old% > 100 THEN
SYS `hi_IsPrime_RB`, ^fast%, ^h4% TO prime%
ELSE
SYS `hi_IsPrime_RB`, ^slow%, ^h4% TO prime%
ENDIF
IF prime% THEN new$(new%) = FN_higetdec(4) : new% += 1
ENDIF
NEXT
NEXT
SYS `hi_Mul`, ^h1%, ^h2%, ^h2%
SWAP old$(), new$()
SWAP old%, new%
UNTIL old% = 0
= new$(new%-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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Cubescript
|
Cubescript
|
alias fizzbuzz [
loop i 100 [
push i (+ $i 1) [
cond (! (mod $i 15)) [
echo FizzBuzz
] (! (mod $i 3)) [
echo Fizz
] (! (mod $i 5)) [
echo Buzz
] [
echo $i
]
]
]
]
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Nim
|
Nim
|
import algorithm
import os
import strformat
import strutils
import tables
import std/sha1
import times
type
# Mapping "size" -> "list of paths".
PathsFromSizes = Table[BiggestInt, seq[string]]
# Mapping "hash" -> "list fo paths".
PathsFromHashes = Table[string, seq[string]]
# Information data.
Info = tuple[size: BiggestInt; paths: seq[string]]
#---------------------------------------------------------------------------------------------------
proc processCmdLine(): tuple[dirpath: string; minsize: Natural] =
## Process the command line. Extra parameters are ignored.
if paramCount() == 0:
quit fmt"Usage: {getAppFileName().splitPath()[1]} folder minsize"
result.dirpath = paramStr(1)
if not result.dirpath.dirExists():
quit fmt"Wrong directory path: {result.dirpath}"
if paramCount() >= 2:
try:
result.minsize = parseInt(paramStr(2))
except ValueError:
quit fmt"Wrong minimum size: {paramStr(2)}"
#---------------------------------------------------------------------------------------------------
proc initPathsFromSize(dirpath: string; minsize: Natural): PathsFromSizes =
## Retrieve the files in directory "dirpath" with minimal size "minsize"
## and build the mapping from size to paths.
for path in dirpath.walkDirRec():
if not path.fileExists():
continue # Not a regular file.
let size = path.getFileSize()
if size >= minSize:
# Store path in "size to paths" table.
result.mgetOrPut(size, @[]).add(path)
#---------------------------------------------------------------------------------------------------
proc initPathsFromHashes(pathsFromSizes: PathsFromSizes): PathsFromHashes =
## Compute hashes for files whose size is not unique and build the mapping
## from hash to paths.
for size, paths in pathsFromSizes.pairs:
if paths.len > 1:
for path in paths:
# Store path in "digest to paths" table.
result.mgetOrPut($path.secureHashFile(), @[]).add(path)
#---------------------------------------------------------------------------------------------------
proc cmp(x, y: Info): int =
## Compare two information tuples. Used to sort the list of duplicates files.
result = cmp(x.size, y.size)
if result == 0:
# Same size. Compare the first paths (we are sure that they are different).
result = cmp(x.paths[0], y.paths[0])
#---------------------------------------------------------------------------------------------------
proc displayDuplicates(dirpath: string; pathsFromHashes: PathsFromHashes) =
## Display duplicates files in directory "dirpath".
echo "Files with same size and same SHA1 hash value in directory: ", dirpath
echo ""
# Build list of duplicates.
var duplicates: seq[Info]
for paths in pathsFromHashes.values:
if paths.len > 1:
duplicates.add((paths[0].getFileSize(), sorted(paths)))
if duplicates.len == 0:
echo "No files"
return
duplicates.sort(cmp, Descending)
# Display duplicates.
echo fmt"""{"Size":>10} {"Last date modified":^19} {"Inode":>8} HL File name"""
echo repeat('=', 80)
for (size, paths) in duplicates:
echo ""
for path in paths:
let mtime = path.getLastModificationTime().format("YYYY-MM-dd HH:mm:ss")
let info = path.getFileInfo()
let inode = info.id.file
let hardlink = if info.linkCount == 1: " " else: "*"
echo fmt"{size:>10} {mtime:>23} {inode:>12} {hardlink:<5} {path.relativePath(dirpath)}"
#———————————————————————————————————————————————————————————————————————————————————————————————————
let (dirpath, minsize) = processCmdLine()
let pathsFromSizes = initPathsFromSize(dirpath, minsize)
let pathsFromHashes = initPathsFromHashes(pathsFromSizes)
dirpath.displayDuplicates(pathsFromHashes)
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Objeck
|
Objeck
|
use System.IO.File;
use System.Time;
use Collection;
class Duplicate {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 2) {
file_sets := SortDups(GetDups(args[0], args[1]->ToInt()));
each(i : file_sets) {
file_set := file_sets->Get(i)->As(Vector);
if(file_set->Size() > 1) {
"Duplicates:"->PrintLine();
"----"->PrintLine();
each(j : file_set) {
file_set->Get(j)->As(FileMeta)->ToString()->PrintLine();
};
};
'\n'->Print();
};
};
}
function : SortDups(unsorted : Vector) ~ Vector {
sorted := IntMap->New();
each(i : unsorted) {
value := unsorted->Get(i)->As(Vector);
key := value->Get(0)->As(FileMeta)->GetSize();
sorted->Insert(key, value);
};
return sorted->GetValues();
}
function : GetDups(dir : String, size : Int) ~ Vector {
duplicates := StringMap->New();
files := Directory->List(dir);
each(i : files) {
file_name := String->New(dir);
file_name += '/';
file_name += files[i];
file_size := File->Size(file_name);
if(file_size >= size) {
file_date := File->ModifiedTime(file_name);
file_hash := file_size->ToString();
file_hash += ':';
file_hash += Encryption.Hash->MD5(FileReader->ReadBinaryFile(file_name))->ToString();
file_meta := FileMeta->New(file_name, file_size, file_date, file_hash);
file_set := duplicates->Find(file_hash)->As(Vector);
if(file_set = Nil) {
file_set := Vector->New();
duplicates->Insert(file_hash, file_set);
};
file_set->AddBack(file_meta);
};
};
return duplicates->GetValues();
}
}
class FileMeta {
@name : String;
@size : Int;
@date : Date;
@hash : String;
New(name : String, size : Int, date : Date, hash : String) {
@name := name;
@size := size;
@date := date;
@hash := hash;
}
method : public : GetSize() ~ Int {
return @size;
}
method : public : ToString() ~ String {
date_str := @date->ToShortString();
return "{$@name}, {$@size}, {$date_str}";
}
}
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Phix
|
Phix
|
with javascript_semantics
function spid(string s)
if sort(s)!="BBKNNQRR" then return -1 end if
if filter(s,"in","RK")!="RKR" then return -1 end if
sequence b = find_all('B',s)
if even(sum(b)) then return -1 end if
integer {n1,n2} = find_all('N',filter(s,"out","QB")),
N = {-2,1,3,4}[n1]+n2,
Q = find('Q',filter(s,"!=",'N'))-1,
D = filter(b,odd)[1]-1, -- (nb not /2)
L = filter(b,even)[1]/2-1
return 96*N + 16*Q + 2*D + L
end function
procedure test(string s)
printf(1,"%s : %d\n",{s,spid(s)})
end procedure
test("QNRBBNKR")
test("RNBQKBNR")
|
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
|
#Quackery
|
Quackery
|
forward is flatten
[ [] swap
witheach
[ dup nest?
if flatten
join ] ] resolves flatten ( [ --> [ )
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#C
|
C
|
#include <stdio.h>
#include <gmp.h>
typedef unsigned long ulong;
ulong small_primes[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,
43,47,53,59,61,67,71,73,79,83,89,97};
#define MAX_STACK 128
mpz_t tens[MAX_STACK], value[MAX_STACK], answer;
ulong base, seen_depth;
void add_digit(ulong i)
{
ulong d;
for (d = 1; d < base; d++) {
mpz_set(value[i], value[i-1]);
mpz_addmul_ui(value[i], tens[i], d);
if (!mpz_probab_prime_p(value[i], 1)) continue;
if (i > seen_depth ||
(i == seen_depth && mpz_cmp(value[i], answer) == 1))
{
if (!mpz_probab_prime_p(value[i], 50)) continue;
mpz_set(answer, value[i]);
seen_depth = i;
gmp_fprintf(stderr, "\tb=%lu d=%2lu | %Zd\n", base, i, answer);
}
add_digit(i+1);
}
}
void do_base()
{
ulong i;
mpz_set_ui(answer, 0);
mpz_set_ui(tens[0], 1);
for (i = 1; i < MAX_STACK; i++)
mpz_mul_ui(tens[i], tens[i-1], base);
for (seen_depth = i = 0; small_primes[i] < base; i++) {
fprintf(stderr, "\tb=%lu digit %lu\n", base, small_primes[i]);
mpz_set_ui(value[0], small_primes[i]);
add_digit(1);
}
gmp_printf("%d: %Zd\n", base, answer);
}
int main(void)
{
ulong i;
for (i = 0; i < MAX_STACK; i++) {
mpz_init_set_ui(tens[i], 0);
mpz_init_set_ui(value[i], 0);
}
mpz_init_set_ui(answer, 0);
for (base = 22; base < 30; base++) do_base();
return 0;
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#D
|
D
|
import std.stdio, std.algorithm, std.conv;
/// With if-else.
void fizzBuzz(in uint n) {
foreach (immutable i; 1 .. n + 1)
if (!(i % 15))
"FizzBuzz".writeln;
else if (!(i % 3))
"Fizz".writeln;
else if (!(i % 5))
"Buzz".writeln;
else
i.writeln;
}
/// With switch case.
void fizzBuzzSwitch(in uint n) {
foreach (immutable i; 1 .. n + 1)
switch (i % 15) {
case 0:
"FizzBuzz".writeln;
break;
case 3, 6, 9, 12:
"Fizz".writeln;
break;
case 5, 10:
"Buzz".writeln;
break;
default:
i.writeln;
}
}
void fizzBuzzSwitch2(in uint n) {
foreach (immutable i; 1 .. n + 1)
(i % 15).predSwitch(
0, "FizzBuzz",
3, "Fizz",
5, "Buzz",
6, "Fizz",
9, "Fizz",
10, "Buzz",
12, "Fizz",
/*else*/ i.text).writeln;
}
void main() {
100.fizzBuzz;
writeln;
100.fizzBuzzSwitch;
writeln;
100.fizzBuzzSwitch2;
}
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Perl
|
Perl
|
use File::Find qw(find);
use File::Compare qw(compare);
use Sort::Naturally;
use Getopt::Std qw(getopts);
my %opts;
$opts{s} = 1;
getopts("s:", \%opts);
sub find_dups {
my($dir) = @_;
my @results;
my %files;
find {
no_chdir => 1,
wanted => sub { lstat; -f _ && (-s >= $opt{s} ) && push @{$files{-s _}}, $_ }
} => $dir;
foreach my $files (values %files) {
next unless @$files;
my %dups;
foreach my $a (0 .. @$files - 1) {
for (my $b = $a + 1 ; $b < @$files ; $b++) {
next if compare(@$files[$a], @$files[$b]);
push @{$dups{ @$files[$a] }}, splice @$files, $b--, 1;
}
}
while (my ($original, $clones) = each %dups) {
push @results, sprintf "%8d %s\n", (stat($original))[7], join ', ', sort $original, @$clones;
}
}
reverse nsort @results;
}
print for find_dups(@ARGV);
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Python
|
Python
|
# optional, but task function depends on it as written
def validate_position(candidate: str):
assert (
len(candidate) == 8
), f"candidate position has invalide len = {len(candidate)}"
valid_pieces = {"R": 2, "N": 2, "B": 2, "Q": 1, "K": 1}
assert {
piece for piece in candidate
} == valid_pieces.keys(), f"candidate position contains invalid pieces"
for piece_type in valid_pieces.keys():
assert (
candidate.count(piece_type) == valid_pieces[piece_type]
), f"piece type '{piece_type}' has invalid count"
bishops_pos = [index for index, value in enumerate(candidate) if value == "B"]
assert (
bishops_pos[0] % 2 != bishops_pos[1] % 2
), f"candidate position has both bishops in the same color"
assert [piece for piece in candidate if piece in "RK"] == [
"R",
"K",
"R",
], "candidate position has K outside of RR"
def calc_position(start_pos: str):
try:
validate_position(start_pos)
except AssertionError:
raise AssertionError
# step 1
subset_step1 = [piece for piece in start_pos if piece not in "QB"]
nights_positions = [
index for index, value in enumerate(subset_step1) if value == "N"
]
nights_table = {
(0, 1): 0,
(0, 2): 1,
(0, 3): 2,
(0, 4): 3,
(1, 2): 4,
(1, 3): 5,
(1, 4): 6,
(2, 3): 7,
(2, 4): 8,
(3, 4): 9,
}
N = nights_table.get(tuple(nights_positions))
# step 2
subset_step2 = [piece for piece in start_pos if piece != "N"]
Q = subset_step2.index("Q")
# step 3
dark_squares = [
piece for index, piece in enumerate(start_pos) if index in range(0, 9, 2)
]
light_squares = [
piece for index, piece in enumerate(start_pos) if index in range(1, 9, 2)
]
D = dark_squares.index("B")
L = light_squares.index("B")
return 4 * (4 * (6*N + Q) + D) + L
|
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
|
#R
|
R
|
x <- list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list())
unlist(x)
|
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
|
#Racket
|
Racket
|
#lang racket
(flatten '(1 (2 (3 4 5) (6 7)) 8 9))
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#C.23
|
C#
|
using Mpir.NET; // 0.4.0
using System; // [email protected]
using System.Collections.Generic;
class MaxLftTrP_B
{
static void Main()
{
mpz_t p; var sw = System.Diagnostics.Stopwatch.StartNew(); L(3);
for (uint b = 3; b < 13; b++)
{
sw.Restart(); p = L(b);
Console.WriteLine("{0} {1,2} {2}", sw.Elapsed, b, p);
}
Console.Read();
}
static mpz_t L(uint b)
{
var p = new List<mpz_t>(); mpz_t np = 0;
while ((np = nxtP(np)) < b) p.Add(np);
int i0 = 0, i = 0, i1 = p.Count - 1; mpz_t n0 = b, n, n1 = b * (b - 1);
for (; i < p.Count; n0 *= b, n1 *= b, i0 = i1 + 1, i1 = p.Count - 1)
for (n = n0; n <= n1; n += n0)
for (i = i0; i <= i1; i++)
if (mpir.mpz_probab_prime_p(np = n + p[i], 15) > 0) p.Add(np);
return p[p.Count - 1];
}
static mpz_t nxtP(mpz_t n) { mpz_t p = 0; mpir.mpz_nextprime(p, n); return p; }
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Dart
|
Dart
|
main() {
for (int i = 1; i <= 100; i++) {
List<String> out = [];
if (i % 3 == 0)
out.add("Fizz");
if (i % 5 == 0)
out.add("Buzz");
print(out.length > 0 ? out.join("") : i);
}
}
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Phix
|
Phix
|
without js -- file i/o
integer min_size=1
sequence res = {}
atom t1 = time()+1
function store_res(string filepath, sequence dir_entry)
if not match("backup",filepath) -- (example filter)
and not find('d', dir_entry[D_ATTRIBUTES]) then
atom size = dir_entry[D_SIZE]
if size>=min_size then
res = append(res,{size,filepath,dir_entry})
if time()>t1 then
printf(1,"%d files found\r",length(res))
t1 = time()+1
end if
end if
end if
return 0 -- keep going
end function
integer exit_code = walk_dir("demo\\clocks\\love", store_res, true)
res = sort(res,DESCENDING)
printf(1,"%d files found\n",length(res))
integer duplicates = 0
for i=1 to length(res)-1 do
for j=i+1 to length(res) do
if res[i][1]!=res[j][1] then exit end if
string si = join_path({res[i][2],res[i][3][D_NAME]}),
sj = join_path({res[j][2],res[j][3][D_NAME]})
integer fni = open(si,"rb"),
fnj = open(sj,"rb"),
size = res[i][1]
bool same = true
if fni=-1 or fnj=-1 then ?9/0 end if
for k=1 to size+1 do -- (check eof as well)
if getc(fni)!=getc(fnj) then
same = false
exit
end if
end for
close(fni)
close(fnj)
if same then
-- prettifying the output left as an exercise...
?res[i]
?res[j]
duplicates += 1
end if
end for
if time()>t1 then
printf(1,"processing %d/%d...\r",{i,length(res)})
t1 = time()+1
end if
end for
printf(1,"%d duplicates found\n",duplicates)
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Raku
|
Raku
|
#!/usr/bin/env raku
# derive a chess960 position's SP-ID
unit sub MAIN($array = "♖♘♗♕♔♗♘♖");
# standardize on letters for easier processing
my $ascii = $array.trans("♜♞♝♛♚♖♘♗♕♔" => "RNBQKRNBQK");
# (optional error-checking)
if $ascii.chars != 8 {
die "Illegal position: should have exactly eight pieces\n";
}
for «K Q» -> $one {
if +$ascii.indices($one) != 1 {
die "Illegal position: should have exactly one $one\n";
}
}
for «B N R» -> $two {
if +$ascii.indices($two) != 2 {
die "Illegal position: should have exactly two $two\'s\n";
}
}
if $ascii !~~ /'R' .* 'K' .* 'R'/ {
die "Illegal position: King not between rooks.";
}
if [+]($ascii.indices('B').map(* % 2)) != 1 {
die "Illegal position: Bishops not on opposite colors.";
}
# (end optional error-checking)
# Work backwards through the placement rules.
# King and rooks are forced during placement, so ignore them.
# 1. Figure out which knight combination was used:
my @knights = $ascii
.subst(/<[QB]>/,'',:g)
.indices('N');
my $knight = combinations(5,2).kv.grep(
-> $i,@c { @c eq @knights }
)[0][0];
# 2. Then which queen position:
my $queen = $ascii
.subst(/<[B]>/,'',:g)
.index('Q');
# 3. Finally the two bishops:
my @bishops = $ascii.indices('B');
my $dark = @bishops.grep({ $_ %% 2 })[0] div 2;
my $light = @bishops.grep({ not $_ %% 2 })[0] div 2;
my $sp-id = 4*(4*(6*$knight + $queen)+$dark)+$light;
# standardize output
my $display = $ascii.trans("RNBQK" => "♖♘♗♕♔");
say "$display: $sp-id";
|
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
|
#Raku
|
Raku
|
my @l = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []];
say .perl given gather @l.deepmap(*.take); # lazy recursive version
# Another way to do it is with a recursive function (here actually a Block calling itself with the &?BLOCK dynamic variable):
say { |(@$_ > 1 ?? map(&?BLOCK, @$_) !! $_) }(@l)
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#C.2B.2B
|
C++
|
#include <gmpxx.h>
#include <algorithm>
#include <cassert>
#include <functional>
#include <iostream>
#include <vector>
using big_int = mpz_class;
const unsigned int small_primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97};
bool is_probably_prime(const big_int& n, int reps) {
return mpz_probab_prime_p(n.get_mpz_t(), reps) != 0;
}
big_int largest_left_truncatable_prime(unsigned int base) {
std::vector<big_int> powers = {1};
std::vector<big_int> value = {0};
big_int result = 0;
std::function<void(unsigned int)> add_digit = [&](unsigned int i) {
if (i == value.size()) {
value.resize(i + 1);
powers.push_back(base * powers.back());
}
for (unsigned int d = 1; d < base; ++d) {
value[i] = value[i - 1] + powers[i] * d;
if (!is_probably_prime(value[i], 1))
continue;
if (value[i] > result) {
if (!is_probably_prime(value[i], 50))
continue;
result = value[i];
}
add_digit(i + 1);
}
};
for (unsigned int i = 0; small_primes[i] < base; ++i) {
value[0] = small_primes[i];
add_digit(1);
}
return result;
}
int main() {
for (unsigned int base = 3; base < 18; ++base) {
std::cout << base << ": " << largest_left_truncatable_prime(base)
<< '\n';
}
for (unsigned int base = 19; base < 32; base += 2) {
std::cout << base << ": " << largest_left_truncatable_prime(base)
<< '\n';
}
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#dc
|
dc
|
[[Fizz]P 1 sw]sF
[[Buzz]P 1 sw]sB
[li p sz]sN
[[
]P]sW
[
0 sw [w = 0]sz
li 3 % 0 =F [Fizz if 0 == i % 3]sz
li 5 % 0 =B [Buzz if 0 == i % 5]sz
lw 0 =N [print Number if 0 == w]sz
lw 1 =W [print neWline if 1 == w]sz
li 1 + si [i += 1]sz
li 100 !<L [continue Loop if 100 >= i]sz
]sL
1 si [i = 1]sz
0 0 =L [enter Loop]sz
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#PicoLisp
|
PicoLisp
|
`(== 64 64)
(de mmap (L F)
(native "@" "mmap" 'N 0 L 1 2 F 0) )
(de munmap (A L)
(native "@" "munmap" 'N A L) )
(de xxh64 (M S)
(let
(R (native "libxxhash.so" "XXH64" 'N M S 0)
P `(** 2 64) )
(if (lt0 R)
(& (+ R P) (dec P))
R ) ) )
(de walk (Dir)
(recur (Dir)
(for F (dir Dir)
(let (Path (pack Dir "/" F) Info (info Path T))
(when (car Info)
(if (=T (car Info))
(recurse Path)
(if (lup D (car Info))
(push (cdr @) Path)
(idx 'D (list (car Info) (cons Path)) T) ) ) ) ) ) ) )
(off D)
(walk "/bin")
(for Lst (filter cdadr (idx 'D))
(let L
(by
'((F)
(let (M (mmap (car Lst) (open F T))
S (car Lst) )
(prog1 (xxh64 M S) (munmap M S)) ) )
group
(cadr Lst) )
(and (filter cdr L) (println (car Lst) @)) ) )
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Python
|
Python
|
from __future__ import print_function
import os
import hashlib
import datetime
def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"):
knownFiles = {}
#Analyse files
for root, dirs, files in os.walk(pth):
for fina in files:
fullFina = os.path.join(root, fina)
isSymLink = os.path.islink(fullFina)
if isSymLink:
continue # Skip symlinks
si = os.path.getsize(fullFina)
if si < minSize:
continue
if si not in knownFiles:
knownFiles[si] = {}
h = hashlib.new(hashName)
h.update(open(fullFina, "rb").read())
hashed = h.digest()
if hashed in knownFiles[si]:
fileRec = knownFiles[si][hashed]
fileRec.append(fullFina)
else:
knownFiles[si][hashed] = [fullFina]
#Print result
sizeList = list(knownFiles.keys())
sizeList.sort(reverse=True)
for si in sizeList:
filesAtThisSize = knownFiles[si]
for hashVal in filesAtThisSize:
if len(filesAtThisSize[hashVal]) < 2:
continue
fullFinaLi = filesAtThisSize[hashVal]
print ("=======Duplicate=======")
for fullFina in fullFinaLi:
st = os.stat(fullFina)
isHardLink = st.st_nlink > 1
infoStr = []
if isHardLink:
infoStr.append("(Hard linked)")
fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')
print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr))
if __name__=="__main__":
FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Ruby
|
Ruby
|
def chess960_to_spid(pos)
start_str = pos.tr("♖♘♗♕♔", "RNBQK")
#1 knights score
s = start_str.delete("QB")
n = [0,1,2,3,4].combination(2).to_a.index( [s.index("N"), s.rindex("N")] )
#2 queen score
q = start_str.delete("N").index("Q")
#3 bishops
bs = start_str.index("B"), start_str.rindex("B")
d = bs.detect(&:even?).div(2)
l = bs.detect(&:odd? ).div(2)
96*n + 16*q + 4*d + l
end
positions = ["QNRBBNKR", "♖♘♗♕♔♗♘♖"]
positions.each{|pos| puts "#{pos}: #{chess960_to_spid(pos)}" }
|
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
|
Find Chess960 starting position identifier
|
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
Task
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
Algorithm
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example):
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
2. Now ignoring the Knights (but including the Queen and Bishops), find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
4. Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.
|
#Wren
|
Wren
|
import "/trait" for Indexed
var glyphs = "♜♞♝♛♚♖♘♗♕♔".toList
var letters = "RNBQKRNBQK"
var names = { "R": "rook", "N": "knight", "B": "bishop", "Q": "queen", "K": "king" }
var g2lMap = {}
for (se in Indexed.new(glyphs)) g2lMap[glyphs[se.index]] = letters[se.index]
var g2l = Fn.new { |pieces| pieces.reduce("") { |acc, p| acc + g2lMap[p] } }
var ntable = { "01":0, "02":1, "03":2, "04":3, "12":4, "13":5, "14":6, "23":7, "24":8, "34":9 }
var spid = Fn.new { |pieces|
pieces = g2l.call(pieces) // convert glyphs to letters
/* check for errors */
if (pieces.count != 8) Fiber.abort("There must be exactly 8 pieces.")
for (one in "KQ") {
if (pieces.count { |p| p == one } != 1 ) Fiber.abort("There must be one %(names[one]).")
}
for (two in "RNB") {
if (pieces.count { |p| p == two } != 2 ) Fiber.abort("There must be two %(names[two])s.")
}
var r1 = pieces.indexOf("R")
var r2 = pieces.indexOf("R", r1 + 1)
var k = pieces.indexOf("K")
if (k < r1 || k > r2) Fiber.abort("The king must be between the rooks.")
var b1 = pieces.indexOf("B")
var b2 = pieces.indexOf("B", b1 + 1)
if ((b2 - b1) % 2 == 0) Fiber.abort("The bishops must be on opposite color squares.")
/* compute SP_ID */
var piecesN = pieces.replace("Q", "").replace("B", "")
var n1 = piecesN.indexOf("N")
var n2 = piecesN.indexOf("N", n1 + 1)
var np = "%(n1)%(n2)"
var N = ntable[np]
var piecesQ = pieces.replace("N", "")
var Q = piecesQ.indexOf("Q")
var D = "0246".indexOf(b1.toString)
var L = "1357".indexOf(b2.toString)
if (D == -1) {
D = "0246".indexOf(b2.toString)
L = "1357".indexOf(b1.toString)
}
return 96*N + 16*Q + 4*D + L
}
for (pieces in ["♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖"]) {
System.print("%(pieces) or %(g2l.call(pieces)) has SP-ID of %(spid.call(pieces))")
}
|
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
|
#REBOL
|
REBOL
|
flatten: func [
"Flatten the block in place."
block [any-block!]
][
parse block [
any [block: any-block! (change/part block first block 1) :block | skip]
]
head block
]
|
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.
|
#6502_Assembly
|
6502 Assembly
|
;beginning of your program
lda #$BE
sta $0100
lda #$EF
sta $0101
ldx #$ff
txs ;stack pointer is set to $FF
;later...
lda $0100 ;if this no longer equals $BE the stack has overflowed
cmp #$BE
bne StackHasOverflowed
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Eiffel
|
Eiffel
|
class
LARGEST_LEFT_TRUNCABLE_PRIME
create
make
feature
make
-- Tests find_prime for different bases.
local
i: INTEGER
decimal: INTEGER_64
do
from
i := 3
until
i = 10
loop
largest := 0
find_prime ("", i)
decimal := convert_to_decimal (largest, i)
io.put_string (i.out + ":%T" + decimal.out)
io.new_line
i := i + 1
end
end
find_prime (right_part: STRING; base: INTEGER)
-- Largest left truncable prime for a given 'base'.
local
i, larger, larger_dec: INTEGER_64
right: STRING
prime: BOOLEAN
do
from
i := 1
until
i = base
loop
create right.make_empty
right.deep_copy (right_part)
right.prepend (i.out)
larger := right.to_integer_64
if base /= 10 then
larger_dec := convert_to_decimal (larger, base)
if larger_dec < 0 then
io.put_string ("overflow")
prime := False
else
prime := is_prime (larger_dec)
end
else
prime := is_prime (larger)
end
if prime = TRUE then
find_prime (larger.out, base)
else
if right_part.count > 0 and right_part.to_integer_64 > largest then
largest := right_part.to_integer_64
end
end
i := i + 1
end
end
largest: INTEGER_64
convert_to_decimal (given, base: INTEGER_64): INTEGER_64
-- 'given' converted to base ten.
require
local
n, i: INTEGER
st_digits: STRING
dec: REAL_64
do
n := given.out.count
dec := 0
st_digits := given.out
from
i := 1
until
n < 0 or i > given.out.count
loop
n := n - 1
dec := dec + st_digits.at (i).out.to_integer * base ^ n
i := i + 1
end
Result := dec.truncated_to_integer_64
end
is_prime (n: INTEGER_64): BOOLEAN
--Is 'n' a prime number?
require
positiv_input: n > 0
local
i: INTEGER
max: REAL_64
math: DOUBLE_MATH
do
create math
if n = 2 then
Result := True
elseif n <= 1 or n \\ 2 = 0 then
Result := False
else
Result := True
max := math.sqrt (n)
from
i := 3
until
i > max
loop
if n \\ i = 0 then
Result := False
end
i := i + 2
end
end
end
end
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Delphi
|
Delphi
|
program FizzBuzz;
{$APPTYPE CONSOLE}
uses SysUtils;
var
i: Integer;
begin
for i := 1 to 100 do
begin
if i mod 15 = 0 then
Writeln('FizzBuzz')
else if i mod 3 = 0 then
Writeln('Fizz')
else if i mod 5 = 0 then
Writeln('Buzz')
else
Writeln(i);
end;
end.
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Racket
|
Racket
|
#lang racket
(struct F (name id size [links #:mutable]))
(require openssl/sha1)
(define (find-duplicate-files path size)
(define Fs
(sort
(fold-files
(λ(path type acc)
(define s (and (eq? 'file type) (file-size path)))
(define i (and s (<= size s) (file-or-directory-identity path)))
(define ln (and i (findf (λ(x) (equal? i (F-id x))) acc)))
(when ln (set-F-links! ln (cons (path->string path) (F-links ln))))
(if (and i (not ln)) (cons (F path i s '()) acc) acc))
'() path #f)
> #:key F-size))
(define (find-duplicates Fs)
(define t (make-hash))
(for ([F Fs])
(define cksum (call-with-input-file (F-name F) sha1))
(hash-set! t cksum (cons F (hash-ref t cksum '()))))
(for/list ([(n Fs) (in-hash t)] #:unless (null? (cdr Fs))) Fs))
(let loop ([Fs Fs])
(if (null? Fs) '()
(let-values ([(Fs Rs)
(splitf-at Fs (λ(F) (= (F-size F) (F-size (car Fs)))))])
(append (find-duplicates Fs)
(loop Rs))))))
(define (show-duplicates path size)
(for ([Fs (find-duplicate-files path size)])
(define (links F)
(if (null? (F-links F)) ""
(format " also linked at ~a" (string-join (F-links F) ", "))))
(printf "~a (~a)~a\n" (F-name (car Fs)) (F-size (car Fs)) (links (car Fs)))
(for ([F (cdr Fs)]) (printf " ~a~a\n" (F-name F) (links F)))))
(show-duplicates (find-system-path 'home-dir) 1024)
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Raku
|
Raku
|
use Digest::SHA256::Native;
sub MAIN( $dir = '.', :$minsize = 5, :$recurse = True ) {
my %files;
my @dirs = $dir.IO.absolute.IO;
while @dirs {
my @files = @dirs.pop;
while @files {
for @files.pop.dir -> $path {
%files{ $path.s }.push: $path if $path.f and $path.s >= $minsize;
@dirs.push: $path if $path.d and $path.r and $recurse
}
}
}
for %files.sort( +*.key ).grep( *.value.elems > 1)».kv -> ($size, @list) {
my %dups;
@list.map: { %dups{ sha256( $_.slurp :bin ) }.push: $_.Str };
for %dups.grep( *.value.elems > 1)».value -> @dups {
say sprintf("%9s : ", scale $size ), @dups.join(', ');
}
}
}
sub scale ($bytes) {
given $bytes {
when $_ < 2**10 { $bytes ~ ' B' }
when $_ < 2**20 { ($bytes / 2**10).round(.1) ~ ' KB' }
when $_ < 2**30 { ($bytes / 2**20).round(.1) ~ ' MB' }
default { ($bytes / 2**30).round(.1) ~ ' GB' }
}
}
|
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
|
#Red
|
Red
|
flatten: function [
"Flatten the block"
block [any-block!]
][
load form block
]
red>> flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]
== [1 2 3 4 5 6 7 8]
;flatten a list to a string
>> blk: [1 2 ["test"] "a" [["bb"]] 3 4 [[[99]]]]
>> form blk
== "1 2 test a bb 3 4 99"
|
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
|
#REXX
|
REXX
|
/*REXX program (translated from PL/I) flattens a list (the data need not be numeric).*/
list= '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]' /*the list to be flattened. */
say list /*display the original list. */
c= ',' /*define a literal (1 comma). */
cc= ',,' /* " " " (2 commas).*/
list= translate(list, , "[]") /*translate brackets to blanks.*/
list= space(list, 0) /*Converts spaces to nulls. */
do while index(list, cc) > 0 /*any double commas ? */
list= changestr(cc, list, c) /*convert ,, to single comma.*/
end /*while*/
list= strip(list, 'T', c) /*strip the last trailing comma*/
list = '['list"]" /*repackage the list. */
say list /*display the flattened list. */
|
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.
|
#8080_Assembly
|
8080 Assembly
|
org 100h
lxi b,0 ; BC holds the amount of calls
call recur ; Call the recursive routine
;;; BC now holds the maximum amount of recursive calls one
;;; can make, and the stack is back to the beginning.
;;; Print the value in BC to the console. The stack is freed by ret
;;; so push and pop can be used.
;;; Make number into ASCII string
lxi h,num
push h
mov h,b
mov l,c
lxi b,-10
dgt: lxi d,-1
clcdgt: inx d
dad b
jc clcdgt
mov a,l
adi 10+'0'
xthl
dcx h
mov m,a
xthl
xchg
mov a,h
ora l
jnz dgt
;;; Use CP/M routine to print the string
pop d
mvi c,9
call 5
rst 0
;;; Recursive routine
recur: inx b ; Count the call
lxi d,-GUARD ; See if the guard is intact (stack not full)
lhld guard ; (subtract the original value from the
dad d ; current one)
mov a,h ; If so, the answer should be zero
ora l
cz recur ; If it is, do another recursive call
ret ; Return
;;; Placeholder for numeric output
db '00000'
num: db '$'
;;; The program doesn't need any memory after this location,
;;; so all memory beyond here is free for use by the stack.
;;; If the guard is overwritten, the stack has overflowed.
GUARD: equ $+2 ; Make sure it is not a valid return address
guard: dw GUARD
|
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.
|
#ACL2
|
ACL2
|
(defun recursion-limit (x)
(if (zp x)
0
(prog2$ (cw "~x0~%" x)
(1+ (recursion-limit (1+ x))))))
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#F.23
|
F#
|
(* Find some probable candidates for The Largest Left Trucatable Prime in a given base
Nigel Galloway: April 25th., 2017 *)
let snF Fbase pZ =
let rec fn i g (e:bigint) l =
match e with
| _ when e.IsZero -> i=1I
| _ when e.IsEven -> fn i ((g*g)%l) (e/2I) l
| _ -> fn ((i*g)%l) ((g*g)%l) (e/2I) l
let rec fi n i =
let g = n|>Array.Parallel.collect(fun n->[|for g in 1I..(Fbase-1I) do yield g*i+n|])|>Array.filter(fun n->fn 1I 2I (n-1I) n)
if (Array.isEmpty g) then n else (fi g (i*Fbase))
pZ |> Array.Parallel.map (fun n -> fi [|n|] Fbase)|>Seq.concat|>Seq.max
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#DeviousYarn
|
DeviousYarn
|
each { x range(1 100)
? { divisible(x 3)
p:'Fizz' }
? { divisible(x 5)
p:'Buzz' }
-? { !:divisible(x 3)
p:x }
o
}
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#REXX
|
REXX
|
/*REXX program to reads a (DOS) directory and finds and displays files that identical.*/
sep=center(' files are identical in size and content: ',79,"═") /*define the header. */
tFID= 'c:\TEMP\FINDDUP.TMP' /*use this as a temporary FileID. */
arg maxSize aDir /*obtain optional arguments from the CL*/
if maxSize='' | maxSize="," then maxSize=1000000 /*filesize limit (in bytes) [1 million]*/
aDir=strip(aDir) /*remove any leading or trailing blanks*/
if right(aDir,1)\=='\' then aDir=aDir"\" /*possibly add a trailing backslash [\]*/
"DIR" aDir '/a-d-s-h /oS /s | FIND "/" >' tFID /*the (DOS) DIR output ───► temp file. */
pFN= /*the previous filename and filesize. */
pSZ=; do j=0 while lines(tFID)\==0 /*process each of the files in the list*/
aLine=linein(tFID) /*obtain (DOS) DIR's output about a FID*/
parse var aLine . . sz fn /*obtain the filesize and its fileID. */
sz=space(translate(sz,,','),0) /*elide any commas from the size number*/
if sz>maxSize then leave /*Is the file > maximum? Ignore file. */
/* [↓] files identical? (1st million)*/
if sz==pSZ then if charin(aDir||pFN,1,sz)==charin(aDir||FN,1,sz) then do
say sep
say pLine
say aLine
say
end
pSZ=sz; pFN=FN; pLine=aLine /*remember the previous stuff for later*/
end /*j*/
if lines(tFID)\==0 then 'ERASE' tFID /*do housecleaning (delete temp file).*/
/*stick a fork in it, we're all done. */
|
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
|
#Ring
|
Ring
|
aString = "[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]"
bString = ""
cString = ""
for n=1 to len(aString)
if ascii(aString[n]) >= 48 and ascii(aString[n]) <= 57
bString = bString + ", " + aString[n]
ok
next
cString = substr(bString,3,Len(bString)-2)
cString = '"' + cString + '"'
see cString + nl
|
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.
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Recursion_Depth is
function Recursion (Depth : Positive) return Positive is
begin
return Recursion (Depth + 1);
exception
when Storage_Error =>
return Depth;
end Recursion;
begin
Put_Line ("Recursion depth on this system is" & Integer'Image (Recursion (1)));
end Test_Recursion_Depth;
|
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.
|
#ALGOL_68
|
ALGOL 68
|
PROC recurse = VOID : recurse; recurse
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Fortran
|
Fortran
|
USE PRIMEBAG !Gain access to NEXTPRIME and ISPRIME.
Calculates the largest "left-truncatable" digit sequence that is a prime number, in various bases.
INTEGER LBASE,MANY,ENUFF !Some sizes.
PARAMETER (LBASE = 13, MANY = 66666, ENUFF = 66)
INTEGER NS,START(LBASE) !A list of single-digit prime numbers for starters.
INTEGER NH,LH !Counters for the horde.
INTEGER N,HORDEN(MANY) !Numerical value of a digit sequence.
INTEGER*1 HORDED(ENUFF,MANY) !Single-digit values only.
INTEGER B,D,DB !The base, a digit, some power of the base.
INTEGER L !The length of the digit sequence: DB = B**L.
INTEGER P !Possibly a prime number.
INTEGER I !A stepper.
MSG = 6 !I/O unit number for "standard output".
IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!" !Attempt in hope.
NS = 0 !No starters.
P = 1 !Start looking for some primes.
1 P = NEXTPRIME(P) !Thus skipping non-primes.
IF (P.LE.LBASE) THEN !Beyond the limit?
NS = NS + 1 !No. Count another starter.
START(NS) = P !Save its value.
GO TO 1 !And seek further.
END IF !One could insted prepare some values, the primes being well-known.
WRITE (MSG,2) LBASE,NS,START(1:NS) !But, parameterisation is easy enough.
2 FORMAT ("Working in bases 3 to ",I0," there are ",I0, !Announce the known.
* " single-digit primes: ",666(I0:", ")) !The : sez stop if the list is exhausted.
WRITE (MSG,3) !Produce a heading for the tabular output.
3 FORMAT (/"Base Digits Count Max. Value = (in base)")
10 DO B = 3,LBASE !Work through the bases.
NH = 0 !The horde is empty.
DO I = 1,NS !Prepare the starters for base B.
IF (START(I).GE.B) EXIT !Like, they're single-digits in base B.
NH = NH + 1 !So, count another in.
HORDEN(NH) = START(I) !Its numerical value.
HORDED(1,NH) = START(I) !Its digits. Just one.
END DO !On to the next single-digit prime number.
L = 0 !Syncopation. The length of the digit sequences.
DB = 1 !The power for the incoming digit.
20 L = L + 1 !We're about to add another digit.
IF (L.GE.ENUFF) STOP "Too many digits!" !Hopefully, there's room.
DB = DB*B !The new power of B.
IF (DB.LE.0) GO TO 29 !Integer overflow?
LH = NH !The live ones, awaiting extension.
DO I = 1,LH !Step through each starter.
N = HORDEN(I) !Grab its numerical value.
DO D = 1,B - 1 !Consider all possible lead digits.
P = D*DB + N !Place it at the start of the number.
IF (P.LE.0) GO TO 29 !Oh for IF OVERFLOW ...
IF (ISPRIME(P)) THEN !And if it is a prime,
IF (NH.GE.MANY) STOP "Too many sequences!" !Add a sequence.
NH = NH + 1 !Count in a survivor.
HORDEN(NH) = P !The numerical value.
HORDED(1:L,NH) = HORDED(1:L,I) !The digits.
HORDED(L + 1,NH) = D !Plus the added high-order digit.
END IF !So much for persistent primality.
END DO !On to the next lead digit.
END DO !On to the next starter.
N = NH - LH !The number of entries added to the horde.
IF (N.GT.0) THEN !Were there any?
DO I = 1,MIN(LH,N) !Yes. Overwrite the starters.
HORDEN(I) = HORDEN(NH) !From the tail end of the horde.
HORDED(1:L + 1,I) = HORDED(1:L + 1,NH) !Digit sequences as well.
NH = NH - 1 !One snipped off.
END DO !Thus fill the gap at the start.
NH = N !The new horde count.
LH = NH !All are starters for the next level.
GO TO 20 !See how it goes.
END IF !So much for further progress.
GO TO 30 !But if none, done.
29 WRITE (MSG,28) B,L,NH,DB,P !Curses. Offer some details.
28 FORMAT (I4,I7,I6,28X,"Integer overflow!",2I12)
CYCLE !Or, GO TO the end of the loop.
30 I = MAXLOC(HORDEN(1:NH),DIM = 1) !Finger the mostest number.
WRITE (MSG,31) B,L,NH,HORDEN(I),HORDED(L:1:-1,I) !Results!
31 FORMAT (I4,I7,I6,I11," = "666(I0:".")) !See Format 3.
END DO !On to the next base.
END !Simple enough.
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Draco
|
Draco
|
proc nonrec main() void:
byte i;
for i from 1 upto 100 do
if i % 15 = 0 then writeln("FizzBuzz")
elif i % 5 = 0 then writeln("Buzz")
elif i % 3 = 0 then writeln("Fizz")
else writeln(i)
fi
od
corp
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Ring
|
Ring
|
# Project : Find duplicate files
d = "/Windows/System32"
chdir(d)
dir = dir(d)
dirlist = []
for n = 1 to len(dir)
if dir[n][2] = 0
str = read(dir[n][1])
lenstr = len(str)
add(dirlist,[lenstr,dir[n][1]])
ok
next
see "Directory : " + d + nl
see "--------------------------------------------" + nl
dirlist = sortfirst(dirlist)
line = 0
for n = 1 to len(dirlist)-1
if dirlist[n][1] = dirlist[n+1][1]
see "" + dirlist[n][1] + " " + dirlist[n][2] + nl
see "" + dirlist[n+1][1] + " " + dirlist[n+1][2] + nl
if n < len(dirlist)-2 and dirlist[n+1][1] != dirlist[n+2][1]
line = 1
ok
else
line = 0
ok
if line = 1
see "--------------------------------------------" + nl
ok
next
func sortfirst(alist)
for n = 1 to len(alist) - 1
for m = n + 1 to len(alist)
if alist[m][1] < alist[n][1]
swap(alist,m,n)
ok
if alist[m][1] = alist[n][1] and strcmp(alist[m][2],alist[n][2]) < 0
swap(alist,m,n)
ok
next
next
return alist
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Ruby
|
Ruby
|
require 'digest/md5'
def find_duplicate_files(dir)
puts "\nDirectory : #{dir}"
Dir.chdir(dir) do
file_size = Dir.foreach('.').select{|f| FileTest.file?(f)}.group_by{|f| File.size(f)}
file_size.each do |size, files|
next if files.size==1
files.group_by{|f| Digest::MD5.file(f).to_s}.each do |md5,fs|
next if fs.size==1
puts " --------------------------------------------"
fs.each{|file| puts " #{File.mtime(file)} #{size} #{file}"}
end
end
end
end
find_duplicate_files("/Windows/System32")
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#11l
|
11l
|
V EPS = 0.001
V EPS_SQUARE = EPS * EPS
F side(p1, p2, p)
R (p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - p1.y)
F distanceSquarePointToSegment(p1, p2, p)
V p1P2SquareLength = sqlen(p2 - p1)
V dotProduct = dot(p - p1, p2 - p1) / p1P2SquareLength
I dotProduct < 0
R sqlen(p - p1)
I dotProduct <= 1
V pP1SquareLength = sqlen(p1 - p)
R pP1SquareLength - dotProduct * dotProduct * p1P2SquareLength
R sqlen(p - p2)
T Triangle
(Float, Float) p1, p2, p3
F (p1, p2, p3)
.p1 = p1
.p2 = p2
.p3 = p3
F String()
R ‘Triangle[’(.p1)‘, ’(.p2)‘, ’(.p3)‘]’
F.const pointInTriangleBoundingBox(p)
V xMin = min(.p1.x, min(.p2.x, .p3.x)) - :EPS
V xMax = max(.p1.x, max(.p2.x, .p3.x)) + :EPS
V yMin = min(.p1.y, min(.p2.y, .p3.y)) - :EPS
V yMax = max(.p1.y, max(.p2.y, .p3.y)) + :EPS
R !(p.x < xMin | xMax < p.x | p.y < yMin | yMax < p.y)
F.const nativePointInTriangle(p)
V checkSide1 = side(.p1, .p2, p) >= 0
V checkSide2 = side(.p2, .p3, p) >= 0
V checkSide3 = side(.p3, .p1, p) >= 0
R checkSide1 & checkSide2 & checkSide3
F.const accuratePointInTriangle(p)
I !.pointInTriangleBoundingBox(p)
R 0B
I .nativePointInTriangle(p)
R 1B
I distanceSquarePointToSegment(.p1, .p2, p) <= :EPS_SQUARE
R 1B
I distanceSquarePointToSegment(.p2, .p3, p) <= :EPS_SQUARE
R 1B
R distanceSquarePointToSegment(.p3, .p1, p) <= :EPS_SQUARE
F test(t, p)
print(t)
print(‘Point ’p‘ is within triangle ? ’(I t.accuratePointInTriangle(p) {‘true’} E ‘false’))
V p1 = (1.5, 2.4)
V p2 = (5.1, -3.1)
V p3 = (-3.8, 1.2)
V tri = Triangle(p1, p2, p3)
test(tri, (0.0, 0.0))
test(tri, (0.0, 1.0))
test(tri, (3.0, 1.0))
print()
p1 = (1.0 / 10, 1.0 / 9)
p2 = (100.0 / 8, 100.0 / 3)
p3 = (100.0 / 4, 100.0 / 9)
tri = Triangle(p1, p2, p3)
V pt = (p1.x + 3.0 / 7 * (p2.x - p1.x), p1.y + 3.0 / 7 * (p2.y - p1.y))
test(tri, pt)
print()
p3 = (-100.0 / 8, 100.0 / 6)
tri = Triangle(p1, p2, p3)
test(tri, pt)
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Ruby
|
Ruby
|
flat = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten
p flat # => [1, 2, 3, 4, 5, 6, 7, 8]
|
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.
|
#AppleScript
|
AppleScript
|
-- recursionDepth :: () -> IO String
on recursionDepth()
script go
on |λ|(i)
try
|λ|(1 + i)
on error
"Recursion limit encountered at " & i
end try
end |λ|
end script
go's |λ|(0)
end recursionDepth
on run
recursionDepth()
end run
|
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.
|
#Arturo
|
Arturo
|
recurse: function [x][
print x
recurse x+1
]
recurse 0
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Go
|
Go
|
package main
import (
"fmt"
"math/big"
)
var smallPrimes = [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}
const maxStack = 128
var (
tens, values [maxStack]big.Int
bigTemp, answer = new(big.Int), new(big.Int)
base, seenDepth int
)
func addDigit(i int) {
for d := 1; d < base; d++ {
values[i].Set(&values[i-1])
bigTemp.SetUint64(uint64(d))
bigTemp.Mul(bigTemp, &tens[i])
values[i].Add(&values[i], bigTemp)
if !values[i].ProbablyPrime(0) {
continue
}
if i > seenDepth || (i == seenDepth && values[i].Cmp(answer) == 1) {
if !values[i].ProbablyPrime(0) {
continue
}
answer.Set(&values[i])
seenDepth = i
}
addDigit(i + 1)
}
}
func doBase() {
answer.SetUint64(0)
tens[0].SetUint64(1)
bigTemp.SetUint64(uint64(base))
seenDepth = 0
for i := 1; i < maxStack; i++ {
tens[i].Mul(&tens[i-1], bigTemp)
}
for i := 0; smallPrimes[i] < base; i++ {
values[0].SetUint64(uint64(smallPrimes[i]))
addDigit(1)
}
fmt.Printf("%2d: %s\n", base, answer.String())
}
func main() {
for base = 3; base <= 17; base++ {
doBase()
}
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#DUP
|
DUP
|
[$$3/%$[]['F,'i,'z,'z,]?\5/%$[]['B,'u,'z,'z,]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print proper output}
0[$100<][1+c;!]# {loop from 1 to 100}
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Rust
|
Rust
|
use std::{
collections::BTreeMap,
fs::{read_dir, File},
hash::Hasher,
io::Read,
path::{Path, PathBuf},
};
type Duplicates = BTreeMap<(u64, u64), Vec<PathBuf>>;
struct DuplicateFinder {
found: Duplicates,
min_size: u64,
}
impl DuplicateFinder {
fn search(path: impl AsRef<Path>, min_size: u64) -> std::io::Result<Duplicates> {
let mut result = Self {
found: BTreeMap::new(),
min_size,
};
result.walk(path)?;
Ok(result.found)
}
fn walk(&mut self, path: impl AsRef<Path>) -> std::io::Result<()> {
let listing = read_dir(path.as_ref())?;
for entry in listing {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
self.walk(path)?;
} else {
self.compute_digest(&path)?;
}
}
Ok(())
}
fn compute_digest(&mut self, file: &Path) -> std::io::Result<()> {
let size = file.metadata()?.len();
if size < self.min_size {
return Ok(());
}
// This hasher is weak, we could otherwise use an external crate
let mut hasher = std::collections::hash_map::DefaultHasher::default();
let mut bytes = [0u8; 8182];
let mut f = File::open(file)?;
loop {
let n = f.read(&mut bytes[..])?;
hasher.write(&bytes[..n]);
if n == 0 {
break;
}
}
let hash = hasher.finish();
self.found
.entry((size, hash))
.or_insert_with(Vec::new)
.push(file.to_owned());
Ok(())
}
}
fn main() -> std::io::Result<()> {
let mut args = std::env::args();
args.next(); // Skip the executable name
let dir = args.next().unwrap_or_else(|| ".".to_owned());
let min_size = args
.next()
.and_then(|arg| arg.parse::<u64>().ok())
.unwrap_or(0u64);
DuplicateFinder::search(dir, min_size)?
.iter()
.rev()
.filter(|(_, files)| files.len() > 1)
.for_each(|((size, _), files)| {
println!("Size: {}", size);
files
.iter()
.for_each(|file| println!("{}", file.to_string_lossy()));
println!();
});
Ok(())
}
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Sidef
|
Sidef
|
# usage: sidef fdf.sf [size] [dir1] [...]
require('File::Find')
func find_duplicate_files(Block code, size_min=0, *dirs) {
var files = Hash()
%S<File::Find>.find(
Hash(
no_chdir => true,
wanted => func(arg) {
var file = File(arg)
file.is_file || return()
file.is_link && return()
var size = file.size
size >= size_min || return()
files{size} := [] << file
},
) => dirs...
)
files.values.each { |set|
set.len > 1 || next
var dups = Hash()
for i in (^set.end) {
for (var j = set.end; j > i; --j) {
if (set[i].compare(set[j]) == 0) {
dups{set[i]} := [] << set.pop_at(j++)
}
}
}
dups.each{ |k,v| code(k.to_file, v...) }
}
return()
}
var duplicates = Hash()
func collect(*files) {
duplicates{files[0].size} := [] << files
}
find_duplicate_files(collect, Num(ARGV.shift), ARGV...)
for k,v in (duplicates.sort_by { |k| -k.to_i }) {
say "=> Size: #{k}\n#{'~'*80}"
for files in v {
say "#{files.sort.join(%Q[\n])}\n#{'-'*80}"
}
}
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#Ada
|
Ada
|
-- triangle.ads
generic
type Dimension is private;
Zero, Two: Dimension;
with function "*"(Left, Right: in Dimension) return Dimension is <>;
with function "/"(Left, Right: in Dimension) return Dimension is <>;
with function "+"(Left, Right: in Dimension) return Dimension is <>;
with function "-"(Left, Right: in Dimension) return Dimension is <>;
with function ">"(Left, Right: in Dimension) return Boolean is <>;
with function "="(Left, Right: in Dimension) return Boolean is <>;
with function Image(D: in Dimension) return String is <>;
package Triangle is
type Point is record
X: Dimension;
Y: Dimension;
end record;
type Triangle_T is record
A,B,C: Point;
end record;
function Area(T: in Triangle_T) return Dimension;
function IsPointInTriangle(P: Point; T: Triangle_T) return Boolean;
function Image(P: Point) return String is
("(X="&Image(P.X)&", Y="&Image(P.Y)&")")
with Inline;
function Image(T: Triangle_T) return String is
("(A="&Image(T.A)&", B="&Image(T.B)&", C="&Image(T.C)&")")
with Inline;
end;
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Run_BASIC
|
Run BASIC
|
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$;"]"
|
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.
|
#AutoHotkey
|
AutoHotkey
|
Recurse(0)
Recurse(x)
{
TrayTip, Number, %x%
Recurse(x+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.
|
#AutoIt
|
AutoIt
|
;AutoIt Version: 3.2.10.0
$depth=0
recurse($depth)
Func recurse($depth)
ConsoleWrite($depth&@CRLF)
Return recurse($depth+1)
EndFunc
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#11l
|
11l
|
V digits = ‘0123456789abcdefghijklmnopqrstuvwxyz’
F baseN(=num, b)
I num == 0
R ‘0’
V result = ‘’
L num != 0
(num, V d) = divmod(num, b)
result ‘’= :digits[Int(d)]
R reversed(result)
F pal2(num)
I num == 0 | num == 1
R 1B
V based = bin(num)
R based == reversed(based)
F pal_23(limit)
V r = [Int64(0), 1]
V n = 1
L
n++
V b = baseN(n, 3)
V revb = reversed(b)
L(trial) (b‘’revb, b‘0’revb, b‘1’revb, b‘2’revb)
V t = Int64(trial, radix' 3)
I pal2(t)
r.append(t)
I r.len == limit
R r
L(pal23) pal_23(6)
print(pal23‘ ’baseN(pal23, 3)‘ ’baseN(pal23, 2))
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Haskell
|
Haskell
|
primesTo100 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
-- (eq. to) find2km (2^k * n) = (k,n)
find2km :: Integral a => a -> (Int,a)
find2km n = f 0 n
where f k m
| r == 1 = (k,m)
| otherwise = f (k+1) q
where (q,r) = quotRem m 2
-- n is the number to test; a is the (presumably randomly chosen) witness
millerRabinPrimality :: Integer -> Integer -> Bool
millerRabinPrimality n a
| a >= n_ = True
| b0 == 1 || b0 == n_ = True
| otherwise = iter (tail b)
where
n_ = n-1
(k,m) = find2km n_
b0 = powMod n a m
b = take k $ iterate (squareMod n) b0
iter [] = False
iter (x:xs)
| x == 1 = False
| x == n_ = True
| otherwise = iter xs
-- (eq. to) pow_ (*) (^2) n k = n^k
pow_ :: (Num a, Integral b) => (a->a->a) -> (a->a) -> a -> b -> a
pow_ _ _ _ 0 = 1
pow_ mul sq x_ n_ = f x_ n_ 1
where
f x n y
| n == 1 = x `mul` y
| r == 0 = f x2 q y
| otherwise = f x2 q (x `mul` y)
where
(q,r) = quotRem n 2
x2 = sq x
mulMod :: Integral a => a -> a -> a -> a
mulMod a b c = (b * c) `mod` a
squareMod :: Integral a => a -> a -> a
squareMod a b = (b * b) `rem` a
-- (eq. to) powMod m n k = n^k `mod` m
powMod :: Integral a => a -> a -> a -> a
powMod m = pow_ (mulMod m) (squareMod m)
-- Caller supplies a witness list w, which may be used for MR test.
-- Use faster trial division against a small primes list first, to
-- weed out more obvious composites.
is_prime w n
| n < 100 = n `elem` primesTo100
| any ((==0).(n`mod`)) primesTo100 = False
| otherwise = all (millerRabinPrimality n) w
-- final result gets a more thorough Miller-Rabin
left_trunc base = head $ filter (is_prime primesTo100) (reverse hopeful) where
hopeful = extend base $ takeWhile (<base) primesTo100 where
extend b x = if null d then x else extend (b*base) d where
d = concatMap addDigit [1..base-1]
-- we do *one* prime test, which seems good enough in practice
addDigit a = filter (is_prime [3]) $ map (a*b+) x
main = mapM_ print $ map (\x->(x, left_trunc x)) [3..21]
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#DWScript
|
DWScript
|
var i : Integer;
for i := 1 to 100 do begin
if i mod 15 = 0 then
PrintLn('FizzBuzz')
else if i mod 3 = 0 then
PrintLn('Fizz')
else if i mod 5 = 0 then
PrintLn('Buzz')
else PrintLn(i);
end;
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Tcl
|
Tcl
|
package require fileutil
package require md5
proc finddupfiles {dir {minsize 1}} {
foreach fn [fileutil::find $dir] {
file lstat $fn stat
if {$stat(size) < $minsize} continue
dict lappend byino $stat(dev),$stat(ino) $fn
if {$stat(type) ne "file"} continue
set f [open $fn "rb"]
set content [read $f]
close $f
set md5 [md5::md5 -hex $content]
dict lappend byhash $md5 $fn
}
set groups {}
foreach group [dict values $byino] {
if {[llength $group] <= 1} continue
set gs [lsort $group]
dict set groups [lindex $gs 0] $gs
}
foreach group [dict values $byhash] {
if {[llength $group] <= 1} continue
foreach f $group {
if {[dict exists $groups $f]} {
dict set groups $f [lsort -unique \
[concat [dict get $groups $f] $group]]
unset group
break
}
}
if {[info exist group]} {
set gs [lsort $group]
dict set groups [lindex $gs 0] $gs
}
}
set masters {}
dict for {n g} $groups {
lappend masters [list $n [llength $g],$n]
}
set result {}
foreach p [lsort -decreasing -index 1 -dictionary $masters] {
set n [lindex $p 0]
lappend result $n [dict get $groups $n]
}
return $result
}
foreach {leader dupes} [finddupfiles {*}$argv] {
puts "$leader has duplicates"
set n 0
foreach d $dupes {
if {$d ne $leader} {
puts " dupe #[incr n]: $d"
}
}
}
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#ALGOL_68
|
ALGOL 68
|
BEGIN # determine whether a point is within a triangle or not #
# tolerance for the accurate test #
REAL eps = 0.001;
REAL eps squared = eps * eps;
# mode to hold a point #
MODE POINT = STRUCT( REAL x, y );
# returns a readable representation of p #
OP TOSTRING = ( POINT p )STRING: "[" + fixed( x OF p, -8, 4 ) + "," + fixed( y OF p, -8, 4 ) + "]";
# returns 1 if p is to the right of the line ( a, b ), -1 if it is to the left and 0 if it is on it #
PROC side of line = ( POINT p, a, b )INT:
SIGN ( ( ( x OF b - x OF a ) * ( y OF p - y OF a ) )
- ( ( y OF b - y OF a ) * ( x OF p - x OF a ) )
);
# returns the minimum of a and b #
PROC min = ( REAL a, b )REAL: IF a < b THEN a ELSE b FI;
# returns the maximum of a and b #
PROC max = ( REAL a, b )REAL: IF a > b THEN a ELSE b FI;
# returns TRUE if p is within the bounding box of the triangle a, b, c, FALSE otherwise #
PROC point inside bounding box of triangle = ( POINT p, a, b, c )BOOL:
BEGIN
REAL x min = min( x OF a, min( x OF b, x OF c ) );
REAL y min = min( y OF a, min( y OF b, y OF c ) );
REAL x max = max( x OF a, max( x OF b, x OF c ) );
REAL y max = max( y OF a, max( y OF b, y OF c ) );
x min <= x OF p AND x OF p <= x max AND y min <= y OF p AND y OF p <= y max
END # point inside bounding box of triangle # ;
# returns the squared distance between p and the line a, b #
PROC distance square point to segment = ( POINT p, a, b )REAL:
IF REAL a b square length = ( ( x OF b - x OF a ) ^ 2 ) + ( ( y OF b - y OF a ) ^ 2 );
REAL dot product = ( ( ( x OF p - x OF a ) ^ 2 ) + ( ( y OF p - y OF a ) ^ 2 ) ) / a b square length;
dot product < 0
THEN ( ( x OF p - x OF a ) ^ 2 ) + ( ( y OF p - y OF a ) ^ 2 )
ELIF dot product <= 1
THEN ( ( x OF a - x OF p ) ^ 2 ) + ( ( y OF a - y OF p ) ^ 2 )
- ( dot product * dot product * a b square length )
ELSE ( ( x OF p - x OF b ) ^ 2 ) + ( ( y OF p - y OF b ) ^ 2 )
FI # distance square point to segment # ;
# returns TRUE if p is within the triangle defined by a, b and c, FALSE otherwise #
PROC point inside triangle = ( POINT p, a, b, c )BOOL:
IF NOT point inside bounding box of triangle( p, a, b, c )
THEN FALSE
ELIF INT side of ab = side of line( p, a, b );
INT side of bc = side of line( p, b, c );
side of ab /= side of bc
THEN FALSE
ELIF side of ab = side of line( p, c, a )
THEN TRUE
ELIF distance square point to segment( p, a, b ) <= eps squared
THEN TRUE
ELIF distance square point to segment( p, b, c ) <= eps squared
THEN TRUE
ELSE distance square point to segment( p, c, a ) <= eps squared
FI # point inside triangle # ;
# test the point inside triangle procedure #
PROC test point = ( POINT p, a, b, c )VOID:
print( ( TOSTRING p, " in ( ", TOSTRING a, ", ", TOSTRING b, ", ", TOSTRING c, ") -> "
, IF point inside triangle( p, a, b, c ) THEN "true" ELSE "false" FI
, newline
)
);
# test cases as in Commpn Lisp #
test point( ( 0, 0 ), ( 1.5, 2.4 ), ( 5.1, -3.1 ), ( -3.8, 1.2 ) );
test point( ( 0, 1 ), ( 1.5, 2.4 ), ( 5.1, -3.1 ), ( -3.8, 1.2 ) );
test point( ( 3, 1 ), ( 1.5, 2.4 ), ( 5.1, -3.1 ), ( -3.8, 1.2 ) );
test point( ( 5.414286, 14.349206 ), ( 0.1, 0.111111 ), ( 12.5, 33.333333 ), ( 25.0, 11.111111 ) );
test point( ( 5.414286, 14.349206 ), ( 0.1, 0.111111 ), ( 12.5, 33.333333 ), ( -12.5, 16.666667 ) );
# additional Wren test cases #
test point( ( 5.4142857142857, 14.349206349206 )
, ( 0.1, 0.11111111111111 ), ( 12.5, 33.333333333333 ), ( 25, 11.111111111111 )
);
test point( ( 5.4142857142857, 14.349206349206 )
, ( 0.1, 0.11111111111111 ), ( 12.5, 33.333333333333 ), ( -12.5, 16.666666666667 )
)
END
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Rust
|
Rust
|
use std::{vec, mem, iter};
enum List<T> {
Node(Vec<List<T>>),
Leaf(T),
}
impl<T> IntoIterator for List<T> {
type Item = List<T>;
type IntoIter = ListIter<T>;
fn into_iter(self) -> Self::IntoIter {
match self {
List::Node(vec) => ListIter::NodeIter(vec.into_iter()),
leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)),
}
}
}
enum ListIter<T> {
NodeIter(vec::IntoIter<List<T>>),
LeafIter(iter::Once<List<T>>),
}
impl<T> ListIter<T> {
fn flatten(self) -> Flatten<T> {
Flatten {
stack: Vec::new(),
curr: self,
}
}
}
impl<T> Iterator for ListIter<T> {
type Item = List<T>;
fn next(&mut self) -> Option<Self::Item> {
match *self {
ListIter::NodeIter(ref mut v_iter) => v_iter.next(),
ListIter::LeafIter(ref mut o_iter) => o_iter.next(),
}
}
}
struct Flatten<T> {
stack: Vec<ListIter<T>>,
curr: ListIter<T>,
}
// Flatten code is a little messy since we are shoehorning recursion into an Iterator
impl<T> Iterator for Flatten<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.curr.next() {
Some(list) => {
match list {
node @ List::Node(_) => {
self.stack.push(node.into_iter());
let len = self.stack.len();
mem::swap(&mut self.stack[len - 1], &mut self.curr);
}
List::Leaf(item) => return Some(item),
}
}
None => {
if let Some(next) = self.stack.pop() {
self.curr = next;
} else {
return None;
}
}
}
}
}
}
use List::*;
fn main() {
let list = Node(vec![Node(vec![Leaf(1)]),
Leaf(2),
Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]),
Node(vec![Node(vec![Node(vec![])])]),
Node(vec![Node(vec![Node(vec![Leaf(6)])])]),
Leaf(7),
Leaf(8),
Node(vec![])]);
for elem in list.into_iter().flatten() {
print!("{} ", elem);
}
println!();
}
|
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.
|
#AWK
|
AWK
|
# syntax: GAWK -f FIND_LIMIT_OF_RECURSION.AWK
#
# version depth messages
# ------------------ ----- --------
# GAWK 3.1.4 2892 none
# XML GAWK 3.1.4 3026 none
# GAWK 4.0 >999999
# MAWK 1.3.3 4976 A stack overflow was encountered at
# address 0x7c91224e.
# TAWK-DOS AWK 5.0c 357 stack overflow
# TAWK-WIN AWKW 5.0c 2477 awk stack overflow
# NAWK 20100523 4351 Segmentation fault (core dumped)
#
BEGIN {
x()
print("done")
}
function x() {
print(++n)
if (n > 999999) { return }
x()
}
|
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.
|
#Axe
|
Axe
|
RECURSE(1)
Lbl RECURSE
.Optionally, limit the number of times the argument is printed
Disp r₁▶Dec,i
RECURSE(r₁+1)
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#Ada
|
Ada
|
with Ada.Text_IO, Base_Conversion;
procedure Brute is
type Long is range 0 .. 2**63-1;
package BC is new Base_Conversion(Long);
function Palindrome (S : String) return Boolean is
(if S'Length < 2 then True
elsif S(S'First) /= S(S'Last) then False
else Palindrome(S(S'First+1 .. S'Last-1)));
function Palindrome(N: Long; Base: Natural) return Boolean is
(Palindrome(BC.Image(N, Base =>Base)));
package IIO is new Ada.Text_IO.Integer_IO(Long);
begin
for I in Long(1) .. 10**8 loop
if Palindrome(I, 3) and then Palindrome(I, 2) then
IIO.Put(I, Width => 12); -- prints I (Base 10)
Ada.Text_IO.Put_Line(": " & BC.Image(I, Base => 2) & "(2)" &
", " & BC.Image(I, Base => 3) & "(3)");
-- prints I (Base 2 and Base 3)
end if;
end loop;
end Brute;
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#J
|
J
|
ltp=:3 :0
probe=. i.1 0
while. #probe do.
probe=. (#~ 1 p: y #.]),/(}.i.y),"0 _1/have=. probe
end.
>./y#.have
)
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Java
|
Java
|
import java.math.BigInteger;
import java.util.*;
class LeftTruncatablePrime
{
private static List<BigInteger> getNextLeftTruncatablePrimes(BigInteger n, int radix, int millerRabinCertainty)
{
List<BigInteger> probablePrimes = new ArrayList<BigInteger>();
String baseString = n.equals(BigInteger.ZERO) ? "" : n.toString(radix);
for (int i = 1; i < radix; i++)
{
BigInteger p = new BigInteger(Integer.toString(i, radix) + baseString, radix);
if (p.isProbablePrime(millerRabinCertainty))
probablePrimes.add(p);
}
return probablePrimes;
}
public static BigInteger getLargestLeftTruncatablePrime(int radix, int millerRabinCertainty)
{
List<BigInteger> lastList = null;
List<BigInteger> list = getNextLeftTruncatablePrimes(BigInteger.ZERO, radix, millerRabinCertainty);
while (!list.isEmpty())
{
lastList = list;
list = new ArrayList<BigInteger>();
for (BigInteger n : lastList)
list.addAll(getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty));
}
if (lastList == null)
return null;
Collections.sort(lastList);
return lastList.get(lastList.size() - 1);
}
public static void main(String[] args)
{
if (args.length != 2) {
System.err.println("There must be exactly two command line arguments.");
return;
}
int maxRadix;
try {
maxRadix = Integer.parseInt(args[0]);
if (maxRadix < 3) throw new NumberFormatException();
} catch (NumberFormatException e) {
System.err.println("Radix must be an integer greater than 2.");
return;
}
int millerRabinCertainty;
try {
millerRabinCertainty = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.println("Miiller-Rabin Certainty must be an integer.");
return;
}
for (int radix = 3; radix <= maxRadix; radix++)
{
BigInteger largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty);
System.out.print("n=" + radix + ": ");
if (largest == null)
System.out.println("No left-truncatable prime");
else
System.out.println(largest + " (in base " + radix + "): " + largest.toString(radix));
}
}
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Dyalect
|
Dyalect
|
var n = 1
while n < 20 {
if n % 15 == 0 {
print("fizzbuzz")
} else if n % 3 == 0 {
print("fizz")
} else if n % 5 == 0 {
print("buzz")
} else {
print(n)
}
n = n + 1
}
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#Wren
|
Wren
|
import "io" for Directory, File, Stat
import "/crypto" for Sha1
import "/sort" for Sort
var findDuplicates = Fn.new { |dir, minSize|
if (!Directory.exists(dir)) Fiber.abort("Directory does not exist.")
var files = Directory.list(dir).where { |f| Stat.path("%(dir)/%(f)").size >= minSize }
var hashMap = {}
for (file in files) {
var path = "%(dir)/%(file)"
if (Stat.path(path).isDirectory) continue
var contents = File.read(path)
var hash = Sha1.digest(contents)
var exists = hashMap.containsKey(hash)
if (exists) {
hashMap[hash].add(file)
} else {
hashMap[hash] = [file]
}
}
var duplicates = []
for (key in hashMap.keys) {
if (hashMap[key].count > 1) {
var files = hashMap[key]
var path = "%(dir)/%(files[0])"
var size = Stat.path(path).size
duplicates.add([size, files])
}
}
var cmp = Fn.new { |i, j| (j[0] - i[0]).sign } // by decreasing size
Sort.insertion(duplicates, cmp)
System.print("The sets of duplicate files are:\n")
for (dup in duplicates) {
System.print("Size %(dup[0]) bytes:")
System.print(dup[1].join("\n"))
System.print()
}
}
findDuplicates.call("./", 1000)
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#AutoHotkey
|
AutoHotkey
|
T := [[1.5, 2.4], [5.1, -3.1], [-3.8, 1.2]]
for i, p in [[0, 0], [0, 1], [3, 1], [5.4142857, 14.349206]]
result .= "[" p.1 ", " p.2 "] is within triangle?`t" (TriHasP(T, p) ? "ture" : "false") "`n"
MsgBox % result
return
TriHasP(T, P){
Ax := TriArea(T.1.1, T.1.2, T.2.1, T.2.2, T.3.1, T.3.2)
A1 := TriArea(P.1 , P.2 , T.2.1, T.2.2, T.3.1, T.3.2)
A2 := TriArea(T.1.1, T.1.2, P.1 , P.2 , T.3.1, T.3.2)
A3 := TriArea(T.1.1, T.1.2, T.2.1, T.2.2, P.1 , P.2)
return (Ax = A1 + A2 + A3)
}
TriArea(x1, y1, x2, y2, x3, y3){
return Abs((x1 * (y2-y3) + x2 * (y3-y1) + x3 * (y1-y2)) / 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
|
#S-lang
|
S-lang
|
define flatten ();
define flatten (list) {
variable item,
retval,
val;
if (typeof(list) != List_Type) {
retval = list;
} else {
retval = {};
foreach item (list) {
foreach val (flatten(item)) {
list_append(retval, val);
}
}
}
return retval;
}
|
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.
|
#BASIC
|
BASIC
|
100 PRINT "RECURSION DEPTH"
110 PRINT D" ";
120 LET D = D + 1
130 GOSUB 110"RECURSION
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#Batch_File
|
Batch File
|
@echo off
set /a c=c+1
echo [Depth %c%] Mung until no good
cmd /c mung.cmd
echo [Depth %c%] No good
set /a c=c-1
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#AppleScript
|
AppleScript
|
on intToText(int, base) -- Simple version for brevity.
script o
property digits : {int mod base as integer}
end script
set int to int div base
repeat until (int = 0)
set beginning of o's digits to int mod base as integer
set int to int div base
end repeat
return join(o's digits, "")
end intToText
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
on task()
set output to {"0 0 0", "1 1 1"} -- Results for 0 and 1 taken as read.
set b3Hi to 0 -- Integer value of a palindromic ternary number, minus its low end.
set msdCol to 1 -- Column number (0-based) of its leftmost ternary digit.
set lsdCol to 1 -- Column number of the high end's rightmost ternary digit.
set lsdUnit to 3 ^ lsdCol as integer -- Value of 1 in this column.
set lrdCol to 1 -- Column number of the rightmost hi end digit to mirror in the low end.
set lrdUnit to 3 ^ lrdCol as integer -- Value of 1 in this column.
set columnTrigger to 3 ^ (msdCol + 1) as integer -- Next value that will need an additional column.
repeat until ((count output) = 6)
-- Notionally increment the high end's rightmost column.
set b3Hi to b3Hi + lsdUnit
-- If this carries through to start an additional column, adjust the presets.
if (b3Hi = columnTrigger) then
set lrdCol to lrdCol + msdCol mod 2
set lrdUnit to 3 ^ lrdCol as integer
set msdCol to msdCol + 1
set lsdCol to (msdCol + 1) div 2
set lsdUnit to 3 ^ lsdCol as integer
set columnTrigger to columnTrigger * 3
end if
-- Work out a mirroring low end value and add it in.
set b3Lo to b3Hi div lrdUnit mod 3
repeat with p from (lrdCol + 1) to msdCol
set b3Lo to b3Lo * 3 + b3Hi div (3 ^ p) mod 3
end repeat
set n to b3Hi + b3Lo
-- See if the result's palindromic in base 2 too. It must be an odd number and the value of the
-- reverse of its low end (including any overlap) must match that of its truncated high end.
set oL2b to n mod 2
if (oL2b = 1) then
set b2Hi to n
repeat while (b2Hi > oL2b)
set b2Hi to b2Hi div 2
if (b2Hi > oL2b) then set oL2b to oL2b * 2 + b2Hi mod 2
end repeat
-- If it is, append its decimal, binary, and ternary representations to the output.
if (b2Hi = oL2b) then ¬
set end of output to join({intToText(n, 10), intToText(n, 2), intToText(n, 3)}, " ")
end if
end repeat
set beginning of output to "decimal binary ternary:"
return join(output, linefeed)
end task
task()
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Julia
|
Julia
|
using Primes, Printf
function addmsdigit(p::Integer, b::Integer, s::Integer)
a = Vector{typeof(p)}()
q = p
for i in 1:(b-1)
q += s
isprime(q) || continue
push!(a, q)
end
return a
end
function lefttruncprime(pbase::Integer)
a = Vector{BigInt}()
append!(a, primes(pbase - 1))
mlt = zero(BigInt)
s = one(BigInt)
while !isempty(a)
mlt = maximum(a)
s *= pbase
for i in 1:length(a)
p = popfirst!(a)
append!(a, addmsdigit(p, pbase, s))
end
end
return mlt
end
lo, hi = 3, 17
println("The largest left truncatable primes for bases", @sprintf(" %d to %d.", lo, hi))
for i in lo:hi
mlt = lefttruncprime(i)
@printf("%10d %-30d (%s)\n", i, mlt, string(mlt, base=i))
end
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Kotlin
|
Kotlin
|
// version 1.1.2
import java.math.BigInteger
fun nextLeftTruncatablePrimes(n: BigInteger, radix: Int, certainty: Int): List<BigInteger> {
val probablePrimes = mutableListOf<BigInteger>()
val baseString = if (n == BigInteger.ZERO) "" else n.toString(radix)
for (i in 1 until radix) {
val p = BigInteger(i.toString(radix) + baseString, radix)
if (p.isProbablePrime(certainty)) probablePrimes.add(p)
}
return probablePrimes
}
fun largestLeftTruncatablePrime(radix: Int, certainty: Int): BigInteger? {
var lastList: List<BigInteger>? = null
var list = nextLeftTruncatablePrimes(BigInteger.ZERO, radix, certainty)
while (!list.isEmpty()) {
lastList = list
list = mutableListOf()
for (n in lastList) list.addAll(nextLeftTruncatablePrimes(n, radix, certainty))
}
if (lastList == null) return null
return lastList.sorted().last()
}
fun main(args: Array<String>) {
print("Enter maximum radix : ")
val maxRadix = readLine()!!.toInt()
print("Enter certainty : ")
val certainty = readLine()!!.toInt()
println()
for (radix in 3..maxRadix) {
val largest = largestLeftTruncatablePrime(radix, certainty)
print("Base = ${"%-2d".format(radix)} : ")
if (largest == null)
println("No left truncatable prime")
else
println("${largest.toString().padEnd(35)} -> ${largest.toString(radix)}")
}
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
for i range 1 100:
if = 0 % i 15:
"FizzBuzz"
elseif = 0 % i 3:
"Fizz"
elseif = 0 % i 5:
"Buzz"
else:
i
!print
|
http://rosettacode.org/wiki/Find_duplicate_files
|
Find duplicate files
|
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
Task
Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
|
#zkl
|
zkl
|
include(zkl.h.zkl);
const FLAGS=FILE.GLOB.IGNORE_CASE + FILE.GLOB.NO_DIRS;
var [const] MsgHash=Import("zklMsgHash");
var recurse=False, fileSpec, minSz=0, maxSz=(0).MAX;
argh:=Utils.Argh(
T("+R","R","Recurse into subdirectories, starting at <arg>",
fcn(arg){ recurse=arg }),
T("+minSz","","Only consider files larger than <arg>",
fcn(arg){ minSz=arg.toInt() }),
T("+maxSz","","Only consider files less than <arg>",
fcn(arg){ maxSz=arg.toInt() }),
);
argh.parse(vm.arglist);
try { fileSpec=argh.loners[0]; }
catch{
argh.usage("Find duplicate files");
System.exit(1);
}
fnames:=Data(0,String);
if (recurse) File.globular(recurse,fileSpec,True,FLAGS,fnames);
else File.glob(fileSpec,FLAGS).pump(fnames);
files:=Dictionary(); // (len:(name,name...), ...)
foreach fname in (fnames){
sz:=File.len(fname);
if(minSz<=sz<=maxSz) files.appendV(File.len(fname),fname);
}
//////////////////////// group files by size
files=files.pump(List,Void.Xplode,fcn(k,v){ v.len()>1 and v or Void.Skip });
println("Found %d groups of same sized files, %d files total.".fmt(files.len(),
files.apply("len").sum(0)));
if(not files) System.exit(); // no files found
buffer:=Data(0d100_000); // we'll resuse this buffer for hashing
hashes:=files.pump(List,'wrap(fnames){ // get the MD5 hash for each file
fnames.pump(List,'wrap(fname){
file,hash := File(fname,"rb"), MsgHash.toSink("MD5");
file.pump(buffer,hash); file.close();
return(hash.close(),fname); // -->( (hash,name), (hash,name) ... )
})
},T(Void.Write,Void.Write)); // flatten list of lists of lists to above
// Hash the file hashes, then scoop out the files with the same hash
buffer:=Dictionary();
files:=hashes.pump(Void,Void.Xplode,buffer.appendV)
.pump(List,Void.Xplode,fcn(k,v){ v.len()>1 and v or Void.Skip });
println("Found %d duplicate files:".fmt(files.apply("len").sum(0)));
foreach group in (files){ println(" ",group.concat(", ")) }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.