txt
stringlengths
202
72.4k
### ---------------------------------------------------- ### -- Algorithm::LCS ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/raku-community-modules/Algorithm-LCS/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-LCS/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-LCS/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-LCS/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-LCS/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-LCS/actions) NAME ==== Algorithm::LCS - Implementation of the longest common subsequence algorithm SYNOPSIS ======== ```raku use Algorithm::LCS; # regular usage say lcs(<A B C D E F G>, <A C F H J>); # prints T<A C F> # custom comparator via :compare say lcs(<A B C>, <D C F>, :compare(&infix:<eq>)); # extra special custom comparison via :compare-i my @a = slurp('one.txt'); my @b = slurp('two.txt'); my @a-hashed = @a.map({ hash-algorithm($_) }); my @b-hashed = @b.map({ hash-algorithm($_) }); say lcs(@a, @b, :compare-i({ @a-hashed[$^i] eqv @b-hashed[$^j] })); ``` DESCRIPTION =========== This module contains a single subroutine, `lcs`, that calculates the longest common subsequence between two sequences of data. `lcs` takes two lists as required parameters; you may also specify the comparison function (which defaults to `eqv`) via the `&compare` named parameter). Sometimes you may want to maintain a parallel array of information to consult during calculation (for example, if you're comparing long lines of a file, and you'd like a speedup by comparing their hashes rather than their contents); for that, you may use the `&compare-i` named argumeny SUBROUTINES =========== ### sub lcs ```raku sub lcs( @a, @b, :&compare = Code.new, :&compare-i is copy ) returns Mu ``` Returns the longest common subsequence of two sequences of data. class Mu $ ---------- The first sequence class Mu $ ---------- The second sequence class Mu $ ---------- The comparison function (defaults to C<eqv>) class Mu $ ---------- The compare-by-index function (defaults to using &compare) SEE ALSO ======== [Wikipedia article](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem) AUTHORS ======= * Rob Hoelz * Raku Community COPYRIGHT AND LICENSE ===================== Copyright (c) 2014 - 2017 Rob Hoelz Copyright (c) 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the MIT license.
### ---------------------------------------------------- ### -- Algorithm::LCS ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm::LCS [ReadmeFromPod] filename = lib/Algorithm/LCS.rakumod [UploadToZef] [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- Algorithm::LCS ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use Algorithm::LCS; plan 17; is-deeply([lcs(<A B C>, <D E F>)], [], 'the lcs of two sequences with nothing in common should be empty'); is-deeply([lcs(<A B C>, <A B C>)], [<A B C>], 'the lcs of two identical sequences should be the that sequence'); is-deeply([lcs(<A B C D E F>, <A B C>)], [<A B C>], 'the lcs of two sequences where one is the prefix of the other should be the prefix'); is-deeply([lcs(<A B C>, <A B C D E F>)], [<A B C>], 'the lcs of two sequences where one is the prefix of the other should be the prefix'); is-deeply([lcs(<A B C D E F>, <D E F>)], [<D E F>], 'the lcs of two sequences where one is the suffix of the other should be the suffix'); is-deeply([lcs(<D E F>, <A B C D E F>)], [<D E F>], 'the lcs of two sequences where one is the suffix of the other should be the suffix'); is-deeply([lcs(<A B C D E F>, <A B C G H I>)], [<A B C>]); is-deeply([lcs(<A B C G H I>, <A B C D E F>)], [<A B C>]); is-deeply([lcs(<A B C D E F>, <A B C G E I>)], [<A B C E>]); is-deeply([lcs(<A B C G E I>, <A B C D E F>)], [<A B C E>]); is-deeply([lcs(<A B C D E F>, <G H I D E F>)], [<D E F>]); is-deeply([lcs(<G H I D E F>, <A B C D E F>)], [<D E F>]); is-deeply([lcs(<A B C D E F>, <G B I D E F>)], [<B D E F>]); is-deeply([lcs(<G B I D E F>, <A B C D E F>)], [<B D E F>]); is-deeply([lcs(<A B C L M N X Y Z>, <A B C P Q R X Y Z>)], [<A B C X Y Z>]); is-deeply([lcs(<A B C D E F G>, <B C D G K>)], [<B C D G>]); is-deeply([lcs(<A B C D E F G>, <A C E G>)], [<A C E G>]); # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::LCS ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: lib/Algorithm/LCS.rakumod ### ---------------------------------------------------- =begin pod =head1 NAME Algorithm::LCS - Implementation of the longest common subsequence algorithm =head1 SYNOPSIS =begin code :lang<raku> use Algorithm::LCS; # regular usage say lcs(<A B C D E F G>, <A C F H J>); # prints T<A C F> # custom comparator via :compare say lcs(<A B C>, <D C F>, :compare(&infix:<eq>)); # extra special custom comparison via :compare-i my @a = slurp('one.txt'); my @b = slurp('two.txt'); my @a-hashed = @a.map({ hash-algorithm($_) }); my @b-hashed = @b.map({ hash-algorithm($_) }); say lcs(@a, @b, :compare-i({ @a-hashed[$^i] eqv @b-hashed[$^j] })); =end code =head1 DESCRIPTION This module contains a single subroutine, C<lcs>, that calculates the longest common subsequence between two sequences of data. C<lcs> takes two lists as required parameters; you may also specify the comparison function (which defaults to C<eqv>) via the C<&compare> named parameter). Sometimes you may want to maintain a parallel array of information to consult during calculation (for example, if you're comparing long lines of a file, and you'd like a speedup by comparing their hashes rather than their contents); for that, you may use the C<&compare-i> named argumeny =head1 SUBROUTINES =end pod my sub strip-prefix(@a, @b, &compare-i) { my $i = 0; my @prefix; while $i < (@a & @b) && &compare-i($i, $i) { @prefix.push: @a[$i++]; } @prefix } my sub strip-suffix(@a, @b, &compare-i) { # XXX could be optimized, but this is easy for now strip-prefix(@a.reverse, @b.reverse, -> $i, $j { &compare-i(@a.end - $i, @b.end - $j) }).reverse } my sub build-lcs-matrix(@a, @b, &compare-i) { my @matrix = 0 xx ((@a + 1) * (@b + 1)); my $row-len = @a + 1; for 1 .. @b X 1 .. @a -> ($row, $offset) { my $index = $row * $row-len + $offset; if &compare-i($offset - 1, $row - 1) { @matrix[$index] = @matrix[$index - $row-len - 1] + 1; } else { @matrix[$index] = [max] @matrix[ $index - $row-len, $index - 1 ]; } } @matrix } #| Returns the longest common subsequence of two sequences of data. my sub lcs( @a, #= The first sequence @b, #= The second sequence :&compare=&infix:<eqv>, #= The comparison function (defaults to C<eqv>) :&compare-i is copy #= The compare-by-index function (defaults to using &compare) ) is export { unless &compare-i.defined { &compare-i = -> $i, $j { &compare(@a[$i], @b[$j]) }; } my @prefix = strip-prefix(@a, @b, &compare-i); my @suffix = strip-suffix(@a[+@prefix .. *], @b[+@prefix .. *], -> $i, $j { &compare-i($i + @prefix, $j + @prefix) }); my @a-middle = @a[+@prefix .. @a.end - @suffix]; my @b-middle = @b[+@prefix .. @b.end - @suffix]; if @a-middle && @b-middle { my @matrix = build-lcs-matrix(@a-middle, @b-middle, -> $i, $j { &compare-i($i + @prefix, $j + @prefix) }); my $matrix-row-len = @a-middle + 1; my $i = @matrix.end; my @result := gather while $i > 0 && @matrix[$i] > 0 { my $current-length = @matrix[$i]; my $next-row-length = @matrix[$i - $matrix-row-len]; my $next-col-length = @matrix[$i - 1]; if $current-length > $next-row-length && $next-row-length == $next-col-length { take @b-middle[$i div $matrix-row-len - 1]; $i -= $matrix-row-len + 1; } elsif $next-row-length < $next-col-length { $i--; } elsif $next-col-length <= $next-row-length { $i -= $matrix-row-len; } else { die "this should never be reached!"; } }.list; ( @prefix, @result.reverse, @suffix ).flat } else { ( @prefix, @suffix ).flat } } =begin pod =head1 SEE ALSO L<Wikipedia article|http://en.wikipedia.org/wiki/Longest_common_subsequence_problem> =head1 AUTHORS =item Rob Hoelz =item Raku Community =head1 COPYRIGHT AND LICENSE Copyright (c) 2014 - 2017 Rob Hoelz Copyright (c) 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the MIT license. =end pod # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::LDA ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: META6.json ### ---------------------------------------------------- { "auth": "cpan:TITSUKI", "authors": [ "titsuki" ], "build-depends": [ "LibraryMake", "Distribution::Builder::MakeFromJSON", "Algorithm::LDA::CustomBuilder" ], "builder": "Algorithm::LDA::CustomBuilder", "depends": [ ], "description": "A Raku Latent Dirichlet Allocation implementation.", "license": "Artistic-2.0", "name": "Algorithm::LDA", "perl": "6.c", "provides": { "Algorithm::LDA": "lib/Algorithm/LDA.pm6", "Algorithm::LDA::CustomBuilder": "lib/Algorithm/LDA/CustomBuilder.pm6", "Algorithm::LDA::Document": "lib/Algorithm/LDA/Document.pm6", "Algorithm::LDA::Formatter": "lib/Algorithm/LDA/Formatter.pm6", "Algorithm::LDA::LDAModel": "lib/Algorithm/LDA/LDAModel.pm6", "Algorithm::LDA::Phi": "lib/Algorithm/LDA/Phi.pm6", "Algorithm::LDA::Theta": "lib/Algorithm/LDA/Theta.pm6" }, "resources": [ "libraries/lda" ], "source-url": "https://github.com/titsuki/raku-Algorithm-LDA.git", "tags": [ ], "test-depends": [ ], "version": "0.0.10" }
### ---------------------------------------------------- ### -- Algorithm::LDA ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::LDA ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: README.md ### ---------------------------------------------------- [![Build Status](https://travis-ci.org/titsuki/raku-Algorithm-LDA.svg?branch=master)](https://travis-ci.org/titsuki/raku-Algorithm-LDA) NAME ==== Algorithm::LDA - A Raku Latent Dirichlet Allocation implementation. SYNOPSIS ======== EXAMPLE 1 --------- use Algorithm::LDA; use Algorithm::LDA::Formatter; use Algorithm::LDA::LDAModel; my @documents = ( "a b c", "d e f", ); my ($documents, $vocabs) = Algorithm::LDA::Formatter.from-plain(@documents); my Algorithm::LDA $lda .= new(:$documents, :$vocabs); my Algorithm::LDA::LDAModel $model = $lda.fit(:num-topics(3), :num-iterations(500)); $model.topic-word-matrix.say; # show topic-word matrix $model.document-topic-matrix; # show document-topic matrix $model.log-likelihood.say; # show likelihood $model.nbest-words-per-topic.say # show nbest words per topic EXAMPLE 2 --------- use Algorithm::LDA; use Algorithm::LDA::Formatter; use Algorithm::LDA::LDAModel; # Note: You can get AP corpus as follows: # $ wget "https://github.com/Blei-Lab/lda-c/blob/master/example/ap.tgz?raw=true" -O ap.tgz # $ tar xvzf ap.tgz my @vocabs = "./ap/vocab.txt".IO.lines; my @documents = "./ap/ap.dat".IO.lines; my $documents = Algorithm::LDA::Formatter.from-libsvm(@documents); my Algorithm::LDA $lda .= new(:$documents, :@vocabs); my Algorithm::LDA::LDAModel $model = $lda.fit(:num-topics(20), :num-iterations(500)); $model.topic-word-matrix.say; # show topic-word matrix $model.document-topic-matrix; # show document-topic matrix $model.log-likelihood.say; # show likelihood $model.nbest-words-per-topic.say # show nbest words per topic DESCRIPTION =========== Algorithm::LDA is a Raku Latent Dirichlet Allocation implementation. CONSTRUCTOR ----------- ### new Defined as: submethod BUILD(:$!documents!, :$!vocabs! is raw) { } Constructs a new Algorithm::LDA instance. METHODS ------- ### fit Defined as: method fit(Int :$num-iterations = 500, Int :$num-topics!, Num :$alpha = 0.1e0, Num :$beta = 0.1e0, Int :$seed --> Algorithm::LDA::LDAModel) Returns an Algorithm::LDA::LDAModel instance. * `:$num-ierations` is the number of iterations for gibbs sampler * `:$num-topics!` is the number of topics * `alpha` is the prior for theta distribution (i.e., document-topic distribution) * `beta` is the prior for phi distribution (i.e., topic-word distribution) * `seed` is the seed for srand AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2018 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. The algorithm is from: * Blei, David M., Andrew Y. Ng, and Michael I. Jordan. "Latent dirichlet allocation." Journal of machine Learning research 3.Jan (2003): 993-1022. * Li, Wei, and Andrew McCallum. "Pachinko allocation: DAG-structured mixture models of topic correlations." Proceedings of the 23rd international conference on Machine learning. ACM, 2006. * Wallach, Hanna M., et al. "Evaluation methods for topic models." Proceedings of the 26th annual international conference on machine learning. ACM, 2009. * Minka, Thomas. "Estimating a Dirichlet distribution." (2000): 4.
### ---------------------------------------------------- ### -- Algorithm::LDA ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: .travis.yml ### ---------------------------------------------------- os: - linux - osx language: perl6 perl6: - latest install: - rakudobrew build zef - zef install --deps-only --/test . script: - PERL6LIB=$PWD/lib zef build . - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::LDA ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm-LDA [ReadmeFromPod] ; enable = false filename = lib/Algorithm/LDA.pm6 [PruneFiles] ; match = ^ 'xt/'
### ---------------------------------------------------- ### -- Algorithm::LDA ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6.c; use NativeCall; use Test; use Algorithm::LDA; use Algorithm::LDA::LDAModel; use Algorithm::LDA::Document; use Algorithm::LDA::Formatter; subtest { my @documents = ( "a b c", "d e f", ); my ($documents, $vocabs) = Algorithm::LDA::Formatter.from-plain(@documents); is-deeply $vocabs, ["a", "b", "c", "d", "e", "f"]; my Algorithm::LDA $lda .= new(:$documents, :$vocabs); my Algorithm::LDA::LDAModel $model = $lda.fit(:num-topics(3), :num-iterations(1000)); lives-ok { $model.topic-word-matrix } lives-ok { $model.document-topic-matrix } lives-ok { $model.log-likelihood } lives-ok { $model.nbest-words-per-topic } }, "Check if it could process a very short document. (just a smoke test)"; subtest { my @documents = ( "a b c d", "e f g h", ); my ($documents, $vocabs) = Algorithm::LDA::Formatter.from-plain(@documents); my Algorithm::LDA $lda .= new(:$documents, :$vocabs); my Algorithm::LDA::LDAModel $model = $lda.fit(:num-topics(3), :num-iterations(1000)); is $model.topic-word-matrix.shape, (3,8); is $model.document-topic-matrix.shape, (2,3); is $model.nbest-words-per-topic(9).shape, (3, 8), "n is greater than vocab size"; is $model.nbest-words-per-topic(8).shape, (3, 8), "n is equal to the vocab size"; is $model.nbest-words-per-topic(7).shape, (3, 7), "n is less than vocab size"; }, "Check resulting matrix shape"; subtest { my @documents = ( "a b c d", "e f g h", ); my ($documents, $vocabs) = Algorithm::LDA::Formatter.from-plain(@documents); my Algorithm::LDA $lda .= new(:$documents, :$vocabs); my Algorithm::LDA::LDAModel $model = $lda.fit(:num-topics(3), :num-iterations(1000)); is $model.vocabulary.elems, 8; }, "Check vocabulary size"; subtest { my @documents = ( ("a" .. "z").pick(100).join(" "), ("a" .. "z").pick(100).join(" "), ("a" .. "z").pick(100).join(" ") ); my ($documents, $vocabs) = Algorithm::LDA::Formatter.from-plain(@documents); my Algorithm::LDA $lda .= new(:$documents, :$vocabs); my @prev; for 1..5 { my Algorithm::LDA::LDAModel $model = $lda.fit(:num-topics(3), :num-iterations(1000), :seed(2)); if @prev { is @prev, $model.document-topic-matrix; } @prev = $model.document-topic-matrix; } }, "Check reproducibility"; done-testing;
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:titsuki", "authors": [ "titsuki" ], "build-depends": [ "LibraryMake", "Distribution::Builder::MakeFromJSON", "Algorithm::LibSVM::CustomBuilder" ], "builder": "Algorithm::LibSVM::CustomBuilder", "depends": [ ], "description": "A Raku bindings for libsvm", "license": "MIT", "name": "Algorithm::LibSVM", "perl": "6.c", "provides": { "Algorithm::LibSVM": "lib/Algorithm/LibSVM.pm6", "Algorithm::LibSVM::Actions": "lib/Algorithm/LibSVM/Actions.pm6", "Algorithm::LibSVM::CustomBuilder": "lib/Algorithm/LibSVM/CustomBuilder.pm6", "Algorithm::LibSVM::Grammar": "lib/Algorithm/LibSVM/Grammar.pm6", "Algorithm::LibSVM::Model": "lib/Algorithm/LibSVM/Model.pm6", "Algorithm::LibSVM::Node": "lib/Algorithm/LibSVM/Node.pm6", "Algorithm::LibSVM::Parameter": "lib/Algorithm/LibSVM/Parameter.pm6", "Algorithm::LibSVM::Problem": "lib/Algorithm/LibSVM/Problem.pm6" }, "resources": [ "libraries/svm" ], "source-url": "git://github.com/titsuki/raku-Algorithm-LibSVM.git", "tags": [ ], "test-depends": [ ], "version": "0.0.18" }
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: LICENSE ### ---------------------------------------------------- The MIT License Copyright (c) 2017 titsuki <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/titsuki/raku-Algorithm-LibSVM/workflows/test/badge.svg)](https://github.com/titsuki/raku-Algorithm-LibSVM/actions) NAME ==== Algorithm::LibSVM - A Raku bindings for libsvm SYNOPSIS ======== EXAMPLE 1 --------- use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Problem; use Algorithm::LibSVM::Model; my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => RBF); # heart_scale is here: https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/heart_scale my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-file('heart_scale'); my @r = $libsvm.cross-validation($problem, $parameter, 10); $libsvm.evaluate($problem.y, @r).say; # {acc => 81.1111111111111, mse => 0.755555555555556, scc => 1.01157627463546} EXAMPLE 2 --------- use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Problem; use Algorithm::LibSVM::Model; sub gen-train { my $max-x = 1; my $min-x = -1; my $max-y = 1; my $min-y = -1; my @x; my @y; do for ^300 { my $x = $min-x + rand * ($max-x - $min-x); my $y = $min-y + rand * ($max-y - $min-y); my $label = do given $x, $y { when ($x - 0.5) ** 2 + ($y - 0.5) ** 2 <= 0.2 { 1 } when ($x - -0.5) ** 2 + ($y - -0.5) ** 2 <= 0.2 { -1 } default { Nil } } if $label.defined { @y.push: $label; @x.push: [$x, $y]; } } (@x, @y) } my (@train-x, @train-y) := gen-train; my @test-x = 1 => 0.5e0, 2 => 0.5e0; my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => LINEAR); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); my $model = $libsvm.train($problem, $parameter); say $model.predict(features => @test-x)<label> # 1 DESCRIPTION =========== Algorithm::LibSVM is a Raku bindings for libsvm. METHODS ------- ### cross-validation Defined as: method cross-validation(Algorithm::LibSVM::Problem $problem, Algorithm::LibSVM::Parameter $param, Int $nr-fold --> List) Conducts `$nr-fold`-fold cross validation and returns predicted values. ### train Defined as: method train(Algorithm::LibSVM::Problem $problem, Algorithm::LibSVM::Parameter $param --> Algorithm::LibSVM::Model) Trains a SVM model. * `$problem` The instance of Algorithm::LibSVM::Problem. * `$param` The instance of Algorithm::LibSVM::Parameter. ### **DEPRECATED** load-problem Defined as: multi method load-problem(\lines --> Algorithm::LibSVM::Problem) multi method load-problem(Str $filename --> Algorithm::LibSVM::Problem) Loads libsvm-format data. ### load-model Defined as: method load-model(Str $filename --> Algorithm::LibSVM::Model) Loads libsvm model. ### evaluate Defined as: method evaluate(@true-values, @predicted-values --> Hash) Evaluates the performance of the three metrics (i.e. accuracy, mean squared error and squared correlation coefficient) * `@true-values` The array that contains ground-truth values. * `@predicted-values` The array that contains predicted values. ### nr-feature Defined as: method nr-feature(--> Int:D) Returns the maximum index of all the features. ROUTINES -------- ### parse-libsvmformat Defined as: sub parse-libsvmformat(Str $text --> List) is export Is a helper routine for handling libsvm-format text. CAUTION ======= DON'T USE `PRECOMPUTED` KERNEL ------------------------------ As a workaround for [RT130187](https://rt.perl.org/Public/Bug/Display.html?id=130187), I applied the patch programs (e.g. [src/3.22/svm.cpp.patch](src/3.22/svm.cpp.patch)) for the sake of disabling random access of the problematic array. Sadly to say, those patches drastically increase the complexity of using `PRECOMPUTED` kernel. SEE ALSO ======== * libsvm [https://github.com/cjlin1/libsvm](https://github.com/cjlin1/libsvm) * RT130187 [https://rt.perl.org/Public/Bug/Display.html?id=130187](https://rt.perl.org/Public/Bug/Display.html?id=130187) AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the terms of the MIT License. libsvm ( https://github.com/cjlin1/libsvm ) by Chih-Chung Chang and Chih-Jen Lin is licensed under the BSD 3-Clause License.
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: .travis.yml ### ---------------------------------------------------- os: - linux language: perl6 perl6: - latest install: - rakudobrew build-zef - zef --debug --depsonly --/test install . script: - PERL6LIB=$PWD/lib zef build . - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: dist.ini ### ---------------------------------------------------- name = raku-Algorithm-LibSVM [ReadmeFromPod] ; disable = true filename = lib/Algorithm/LibSVM.pm6 [UploadToZef] [PruneFiles] ; match = ^ 'xt/' [Badges] provider = github-actions/test
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: t/06-nusvr.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Problem; use Algorithm::LibSVM::Model; { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => NU_SVR, kernel-type => LINEAR, :probability); my @train-x[100;1] = (1..100).map: { [$_] }; my @train-y = (1..100).map: { 2.0 * $_ }; my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); my $model = $libsvm.train($problem, $parameter); my @test-x = 1 => @train-x[0;0]; my $actual = $model.predict(features => @test-x)<label>; my $expected = 2.0 * @test-x[0].value; my $mae = $model.svr-probability; my $std = sqrt(2.0 * $mae * $mae); ok $expected - 5.0 * $std <= $actual <= $expected + 5.0 * $std, { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM::Model.predict<label> should predict f(x)" }("NU_SVR/LINEAR"); } done-testing;
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: t/02-csvc.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Problem; use Algorithm::LibSVM::Model; sub gen-train { my $max-x = 1; my $min-x = -1; my $max-y = 1; my $min-y = -1; my @tmp-x; my @tmp-y; do for ^300 { my $x = $min-x + rand * ($max-x - $min-x); my $y = $min-y + rand * ($max-y - $min-y); my $label = do given $x, $y { when ($x - 0.5) ** 2 + ($y - 0.5) ** 2 <= 0.2 { 1 } when ($x - -0.5) ** 2 + ($y - -0.5) ** 2 <= 0.2 { -1 } default { Nil } } if $label.defined { @tmp-y.push: $label; @tmp-x.push: [$x, $y]; } } my @x[+@tmp-x;2] = @tmp-x.clone; my @y = @tmp-y.clone; (@x, @y) } my (@train-x, @train-y) := gen-train; my @test-x = 1 => 0.5e0, 2 => 0.5e0; my @text-y = [1]; { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => LINEAR); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/LINEAR"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/LINEAR"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => LINEAR, :probability); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/LINEAR/:probability"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x, :probability)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/LINEAR/:probability"); ok $model.predict(features => @test-x, :probability)<prob-estimates>[0] > 0.25e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<prob-estimates> predicts a probability that given instance (where the instance is at the center of the cluster labeled as 1 in the training set) is labeled as 1, it should return a value larger than 0.25e0" }("C_SVC/LINEAR/:probability"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => POLY); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/POLY"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/POLY"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => POLY, :probability); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/POLY/:probability"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x, :probability)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/POLY/:probability"); ok $model.predict(features => @test-x, :probability)<prob-estimates>[0] > 0.25e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<prob-estimates> predicts a probability that given instance (where the instance is at the center of the cluster labeled as 1 in the training set) is labeled as 1, it should return a value larger than 0.25e0" }("C_SVC/POLY/:probability"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => RBF); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/RBF"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/RBF"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => RBF, :probability); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/RBF/:probability"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x, :probability)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/RBF/:probability"); ok $model.predict(features => @test-x, :probability)<prob-estimates>[0] > 0.25e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<prob-estimates> predicts a probability that given instance (where the instance is at the center of the cluster labeled as 1 in the training set) is labeled as 1, it should return a value larger than 0.25e0" }("C_SVC/RBF/:probability"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => SIGMOID); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/SIGMOID"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/SIGMOID"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => SIGMOID, :probability); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/SIGMOID/:probability"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x, :probability)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/SIGMOID/:probability"); ok $model.predict(features => @test-x, :probability)<prob-estimates>[0] > 0.25e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<prob-estimates> predicts a probability that given instance (where the instance is at the center of the cluster labeled as 1 in the training set) is labeled as 1, it should return a value larger than 0.25e0" }("C_SVC/SIGMOID/:probability"); } { my ($nrow, $ncol) = @train-x.shape; my @precomp-train-x[$nrow;$nrow]; for ^$nrow X ^$nrow -> ($i, $j) { @precomp-train-x[$i;$j] = @train-x[$i;0] * @train-x[$j;0] + @train-x[$i;1] * @train-x[$j;1]; } my $target-row = @train-y.pairs.grep(*.value == 1).head.key; my @precomp-test-x = gather for ^$nrow -> $i { if $i == 0 { take $i => $target-row + 1; } take $i + 1 => @precomp-train-x[$target-row;$i]; } my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => PRECOMPUTED); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-kernel-matrix(@precomp-train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/PRECOMPUTED"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @precomp-test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("C_SVC/PRECOMPUTED"); } sub gen-train-multiclass { my $max-x = 1; my $min-x = -1; my $max-y = 1; my $min-y = -1; my @tmp-x; my @tmp-y; do for ^300 { my $x = $min-x + rand * ($max-x - $min-x); my $y = $min-y + rand * ($max-y - $min-y); my $label = do given $x, $y { when ($x - 0.5) ** 2 + ($y - 0.5) ** 2 <= 0.2 { 1 } when ($x - 0.5) ** 2 + ($y - -0.5) ** 2 <= 0.2 { 2 } when ($x - -0.5) ** 2 + ($y - -0.5) ** 2 <= 0.2 { 3 } when ($x - -0.5) ** 2 + ($y - 0.5) ** 2 <= 0.2 { 4 } default { Nil } } if $label.defined { @tmp-y.push: $label; @tmp-x.push: [$x, $y]; } } my @x[+@tmp-x;2] = @tmp-x.clone; my @y = @tmp-y.clone; (@x, @y) } my (@train-multi-x, @train-multi-y) := gen-train-multiclass; my @test-multi-x = 1 => -0.5e0, 2 => 0.5e0; my @text-multi-y = [4]; { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => LINEAR); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-multi-x, @train-multi-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("C_SVC/LINEAR"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-multi-x)<label>, 4.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 4 in the training set), it should return 4.0e0" }("C_SVC/LINEAR (Multi Class)"); } done-testing;
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Model; { lives-ok { my $libsvm = Algorithm::LibSVM.new }, "Algorithm::LibSVM.new should create a instance"; } { lives-ok { my $libsvm = Algorithm::LibSVM.new.load-problem(("1 1:0 # comment",)) }, "Algorithm::LibSVM.load-problem should read lines include comments"; } { lives-ok { my $p = Algorithm::LibSVM::Problem.from-file("{$*PROGRAM.parent}/australian"); }, "Algorithm::LibSVM::Problem.from-file should create an instance from the libsvm format file "; } { lives-ok { my @y = [1 xx 100, 0 xx 100]>>.List.flat; # y: 0 0 1 # x: [1 0 1] [1 0 1] [1 1 1] my @x[200;3] = gather for ^@y { if $_ == 1 { take [1, 1, 1] } else { take [1, 0, 1] } }; my $libsvm = Algorithm::LibSVM.new; my $problem = Algorithm::LibSVM::Problem.from-matrix(@x, @y); my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => RBF); my @r = $libsvm.cross-validation($problem, $parameter, 10); $libsvm.evaluate($problem.y, @r); }, "Algorithm::LibSVM::Problem.from-matrix should create an instance from a shaped 2d @x and an 1d @y."; } { lives-ok { my @y = [1 xx 100, 0 xx 100]>>.List.flat; # y: 0 0 1 # x: [1 0 1] [1 0 1] [1 1 1] my @x = gather for ^@y { if $_ == 1 { take [1, 1, 1] } else { take [1, 0, 1] } }; my $libsvm = Algorithm::LibSVM.new; my $problem = Algorithm::LibSVM::Problem.from-matrix(@x, @y); my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => RBF); my @r = $libsvm.cross-validation($problem, $parameter, 10); $libsvm.evaluate($problem.y, @r); }, "Algorithm::LibSVM::Problem.from-matrix should create an instance from an unshaped @x and an 1d @y."; } { lives-ok { my @lines = (("1 1:0" xx 100), ("0 1:1" xx 100)).flat; my $libsvm = Algorithm::LibSVM.new; my $problem = $libsvm.load-problem(@lines); my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => C_SVC, kernel-type => RBF); my @r = $libsvm.cross-validation($problem, $parameter, 10); $libsvm.evaluate($problem.y, @r); }, "Make sure problem.y is feasible even if its instance was used by cross-validation (#55)"; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: t/07-parse.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Problem; use Algorithm::LibSVM::Model; subtest { my \myhash = parse-libsvmformat(q:to/END/); 1 1:0.5 2:0.6 2 1:0.2 2:0.3 END is myhash[0]<label>, 1; is myhash[1]<label>, 2; ok myhash[0]<pairs> ~~ (1 => 0.5, 2 => 0.6); ok myhash[1]<pairs> ~~ (1 => 0.2, 2 => 0.3); }, "parse-libsvmformat should parse lines which contain label and features"; subtest { my \myhash = parse-libsvmformat(q:to/END/); 1 1:0.5 2:0.6#comment 2 1:0.2 2:0.3 # comment END is myhash[0]<label>, 1; is myhash[1]<label>, 2; ok myhash[0]<pairs> ~~ (1 => 0.5, 2 => 0.6); ok myhash[1]<pairs> ~~ (1 => 0.2, 2 => 0.3); }, "parse-libsvmformat should parse lines which contain label, features and comment"; lives-ok { my Pair @test1 = parse-libsvmformat(q:to/END/).head<pairs>.flat; 1 1:0.5 2:9.954492307950868e-05 END my Pair @test2 = parse-libsvmformat(q:to/END/).head<pairs>.flat; 1 1:0.5 2:9.954492307950868e05 END }, "Any Num numbers with e or e- expression are parsable"; dies-ok { my Pair @test = parse-libsvmformat(q:to/END/).head<pairs>.flat; 1 1;0.5 2:0.5 # comment: END }, "Cannot use : in a comment"; dies-ok { my Pair @test = parse-libsvmformat(q:to/END/).head<pairs>.flat; 1 1;0.5 2:0.5 END }, "Cannot use ; as a delimiter"; dies-ok { my Pair @test = parse-libsvmformat(q:to/END/).head<pairs>.flat; 1 1:0.52:0.5 END }, "Cannot use integer:number:number form"; done-testing;
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: t/05-epssvr.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Problem; use Algorithm::LibSVM::Model; { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => EPSILON_SVR, kernel-type => LINEAR, :probability); my @train-x[100;1] = (1..100).map: { [$_] }; my @train-y = (1..100).map: { 2.0 * $_ }; my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); my $model = $libsvm.train($problem, $parameter); my @test-x = 1 => @train-x[0;0]; my $actual = $model.predict(features => @test-x)<label>; my $expected = 2.0 * @test-x[0].value; my $mae = $model.svr-probability; my $std = sqrt(2.0 * $mae * $mae); ok $expected - 5.0 * $std <= $actual <= $expected + 5.0 * $std, { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM::Model.predict<label> should predict f(x)" }("EPSILON_SVR/LINEAR"); } done-testing;
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: t/03-nusvc.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Problem; use Algorithm::LibSVM::Model; sub gen-train { my $max-x = 1; my $min-x = -1; my $max-y = 1; my $min-y = -1; my @tmp-x; my @tmp-y; do for ^300 { my $x = $min-x + rand * ($max-x - $min-x); my $y = $min-y + rand * ($max-y - $min-y); my $label = do given $x, $y { when ($x - 0.5) ** 2 + ($y - 0.5) ** 2 <= 0.2 { 1 } when ($x - -0.5) ** 2 + ($y - -0.5) ** 2 <= 0.2 { -1 } default { Nil } } if $label.defined { @tmp-y.push: $label; @tmp-x.push: [$x, $y]; } } my @x[+@tmp-x;2] = @tmp-x.clone; my @y = @tmp-y.clone; (@x, @y) } my (@train-x, @train-y) := gen-train; my @test-x = 1 => 0.5e0, 2 => 0.5e0; my @text-y = [1]; { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => NU_SVC, kernel-type => LINEAR); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("NU_SVC/LINEAR"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("NU_SVC/LINEAR"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => NU_SVC, kernel-type => POLY); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("NU_SVC/POLY"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("NU_SVC/POLY"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => NU_SVC, kernel-type => RBF); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("NU_SVC/RBF"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("NU_SVC/RBF"); } { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => NU_SVC, kernel-type => SIGMOID); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("NU_SVC/SIGMOID"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("NU_SVC/SIGMOID"); } { my ($nrow, $ncol) = @train-x.shape; my @precomp-train-x[$nrow;$nrow]; for ^$nrow X ^$nrow -> ($i, $j) { @precomp-train-x[$i;$j] = @train-x[$i;0] * @train-x[$j;0] + @train-x[$i;1] * @train-x[$j;1]; } my $target-row = @train-y.pairs.grep(*.value == 1).head.key; my @precomp-test-x = gather for ^$nrow -> $i { if $i == 0 { take $i => $target-row + 1; } take $i + 1 => @precomp-train-x[$target-row;$i]; } my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => NU_SVC, kernel-type => PRECOMPUTED); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-kernel-matrix(@precomp-train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("NU_SVC/PRECOMPUTED"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @precomp-test-x)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center of the cluster labeled as 1 in the training set), it should return 1.0e0" }("NU_SVC/PRECOMPUTED"); } done-testing;
### ---------------------------------------------------- ### -- Algorithm::LibSVM ### -- Licenses: MIT ### -- Authors: titsuki ### -- File: t/04-oneclass.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::LibSVM; use Algorithm::LibSVM::Parameter; use Algorithm::LibSVM::Problem; use Algorithm::LibSVM::Model; sub gen-train { my $max-x = 1; my $min-x = -1; my $max-y = 1; my $min-y = -1; my @tmp-x; my @tmp-y; do for ^300 { my $x = $min-x + rand * ($max-x - $min-x); my $y = $min-y + rand * ($max-y - $min-y); my $label = do given $x, $y { when $x ** 2 + $y ** 2 <= 0.3 ** 2 { 1 } default { Nil } } if $label.defined { @tmp-y.push: $label; @tmp-x.push: [$x, $y]; } } my @x[+@tmp-x;2] = @tmp-x.clone; my @y = @tmp-y.clone; (@x, @y) } my (@train-x, @train-y) := gen-train; my Pair @test-in = [1 => sqrt(0), 2 => sqrt(0)]; my Pair @test-out = [1 => sqrt(10), 2 => sqrt(10)]; { my $libsvm = Algorithm::LibSVM.new; my Algorithm::LibSVM::Parameter $parameter .= new(svm-type => ONE_CLASS, kernel-type => RBF, nu => 1e-2); my Algorithm::LibSVM::Problem $problem = Algorithm::LibSVM::Problem.from-matrix(@train-x, @train-y); ok $libsvm.check-parameter($problem, $parameter), { "Given a setting of " ~ $_ ~ ", Algorithm::LibSVM.check-parameter should return True" }("ONE_CLASS/RBF"); my $model = $libsvm.train($problem, $parameter); is $model.predict(features => @test-in)<label>, 1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance is at the center in the training set), it should return 1.0e0" }("ONE_CLASS/RBF"); is $model.predict(features => @test-out)<label>, -1.0e0, { "Given a setting of " ~ $_ ~ ", When Algorithm::LibSVM::Model.predict<label> predicts a label of a instance (where the instance keeps at a distance from the center in the training set), it should return -1.0e0" }("ONE_CLASS/RBF"); } done-testing;
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: META6.json ### ---------------------------------------------------- { "author" : "cpan:TITSUKI", "authors" : [ "Itsuki Toyota" ], "build-depends" : [ ], "depends" : [ ], "description" : "A perl6 implementation of the extended Manacher's Algorithm for solving longest palindromic substring(i.e. palindrome) problem", "license" : "Artistic-2.0", "name" : "Algorithm::Manacher", "perl" : "6.c", "provides" : { "Algorithm::Manacher" : "lib/Algorithm/Manacher.pm6" }, "resources" : [ ], "source-url" : "git://github.com/titsuki/p6-Algorithm-Manacher.git", "tags" : [ ], "test-depends" : [ ], "version" : "0.0.1" }
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2016, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: README.md ### ---------------------------------------------------- [![Build Status](https://travis-ci.org/titsuki/p6-Algorithm-Manacher.svg?branch=master)](https://travis-ci.org/titsuki/p6-Algorithm-Manacher) NAME ==== Algorithm::Manacher - A perl6 implementation of the extended Manacher's Algorithm for solving longest palindromic substring(i.e. palindrome) problem SYNOPSIS ======== use Algorithm::Manacher; # "たけやぶやけた" is one of the most famous palindromes in Japan. # It means "The bamboo grove was destroyed by a fire." in English. my $manacher = Algorithm::Manacher.new(text => "たけやぶやけた"); $manacher.is-palindrome(); # True $manacher.find-longest-palindrome(); # {"たけやぶやけた" => [0]}; $manacher.find-all-palindrome(); # {"た" => [0, 6], "け" => [1, 5], "や" => [2, 4], "たけやぶやけた" => [0]} DESCRIPTION =========== Algorithm::Manacher is a perl6 implementation of the extended Manacher's Algorithm for solving longest palindromic substring problem. A palindrome is a sequence which can be read same from left to right and right to left. In the original Manacher's paper [0], his algorithm has some limitations(e.g. couldn't handle a text of even length). Therefore this module employs the extended Manacher's Algorithm in [1], it enables to handle a text of both even and odd length, and compute all palindromes in a given text. CONSTRUCTOR ----------- my $manacher = Algorithm::Manacher.new(text => $text); METHODS ------- ### find-all-palindrome Algorithm::Manacher.new(text => "たけやぶやけた").find-all-palindrome(); # {"た" => [0, 6], "け" => [1, 5], "や" => [2, 4], "たけやぶやけた" => [0]} Finds all palindromes in a text and returns a hash containing key/value pairs, where key is a palindromic substring and value is an array of its starting positions. If there are multiple palindromes that share the same point of symmetry, it remains the longest one. ### is-palindrome Algorithm::Manacher.new(text => "たけやぶやけた").is-palindrome(); # True Algorithm::Manacher.new(text => "たけやぶやけたわ").is-palindrome(); # False Algorithm::Manacher.new(text => "Perl6").is-palindrome(); # False Returns whether a given text is a palindrome or not. ### find-longest-palindrome Algorithm::Manacher.new(text => "たけやぶやけた").find-longest-palindrome(); # {"たけやぶやけた" => [0]}; Algorithm::Manacher.new(text => "たけやぶやけた。、だんしがしんだ").find-longest-palindrome(), {"たけやぶやけた" => [0], "だんしがしんだ" => [9]}; Returns the longest palindrome. If there are many candidates, it returns all of them. AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. This algorithm is from * [0] Manacher, Glenn. "A New Linear-Time``On-Line''Algorithm for Finding the Smallest Initial Palindrome of a String." Journal of the ACM (JACM) 22.3 (1975): 346-351. * [1] Tomohiro, I., et al. "Counting and verifying maximal palindromes." String Processing and Information Retrieval. Springer Berlin Heidelberg, 2010.
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 perl6: - latest install: - rakudobrew build-zef - zef --debug --depsonly --/test install . script: - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm-Manacher [ReadmeFromPod] ; disable = true filename = lib/Algorithm/Manacher.pm6 [PruneFiles] ; match = ^ 'xt/'
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/04-find-all-palindrome.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::Manacher; { is Algorithm::Manacher.new(text => "").find-all-palindrome(), {}; is Algorithm::Manacher.new(text => "あ").find-all-palindrome(), {"あ" => [0]}; is Algorithm::Manacher.new(text => "ああ").find-all-palindrome(), {"あ" => [0, 1], "ああ" => [0]}; is Algorithm::Manacher.new(text => "あいあ").find-all-palindrome(), {"あいあ" => [0], "あ" => [0, 2]}; # "い" is the center of both "い" and "あいあ". then it returns "あいあ" as a final result. is Algorithm::Manacher.new(text => "たけやぶやけた").find-all-palindrome(), {"た" => [0, 6], "け" => [1, 5], "や" => [2, 4], "たけやぶやけた" => [0]}; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/03-is-palindrome.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::Manacher; { is Algorithm::Manacher.new(text => "").is-palindrome(), False; is Algorithm::Manacher.new(text => "あ").is-palindrome(), True; is Algorithm::Manacher.new(text => "ああ").is-palindrome(), True; is Algorithm::Manacher.new(text => "あいあ").is-palindrome(), True; is Algorithm::Manacher.new(text => "たけやぶやけた").is-palindrome(), True; is Algorithm::Manacher.new(text => "たけやぶやけた?").is-palindrome(), False; is Algorithm::Manacher.new(text => "...たけやぶやけた").is-palindrome(), False; is Algorithm::Manacher.new(text => "たけやぶはやけた").is-palindrome(), False; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::Manacher; lives-ok { my $manacher = Algorithm::Manacher.new(text => "") }; lives-ok { my $manacher = Algorithm::Manacher.new(text => "aaa") }; dies-ok { my $manacher = Algorithm::Manacher.new(text => 1234) }; done-testing;
### ---------------------------------------------------- ### -- Algorithm::Manacher ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/02-find-longest-palindrome.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::Manacher; { is Algorithm::Manacher.new(text => "").find-longest-palindrome(), {}; is Algorithm::Manacher.new(text => "あ").find-longest-palindrome(), {"あ" => [0]}; is Algorithm::Manacher.new(text => "ああ").find-longest-palindrome(), {"ああ" => [0]}; is Algorithm::Manacher.new(text => "あいあ").find-longest-palindrome(), {"あいあ" => [0]}; is Algorithm::Manacher.new(text => "たけやぶやけた").find-longest-palindrome(), {"たけやぶやけた" => 0}; is Algorithm::Manacher.new(text => "たけやぶやけた。わたしまけましたわ").find-longest-palindrome(), {"わたしまけましたわ" => [8]}; is Algorithm::Manacher.new(text => "たけやぶやけた。、たけやぶやけた").find-longest-palindrome(), {"たけやぶやけた" => [0, 9]}; is Algorithm::Manacher.new(text => "たけやぶやけた。、だんしがしんだ").find-longest-palindrome(), {"たけやぶやけた" => [0], "だんしがしんだ" => [9]}; is Algorithm::Manacher.new(text => "ああたけやぶやけた。、たけやぶやけた").find-longest-palindrome(), {"たけやぶやけた" => [2, 11]}; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: META6.json ### ---------------------------------------------------- { "author" : "cpan:TITSUKI", "authors" : [ "Itsuki Toyota" ], "build-depends" : [ ], "depends" : [ ], "description" : "A Raku implementation of double ended priority queue", "license" : "Artistic-2.0", "name" : "Algorithm::MinMaxHeap", "perl" : "6.c", "provides" : { "Algorithm::MinMaxHeap" : "lib/Algorithm/MinMaxHeap.pm6", "Algorithm::MinMaxHeap::CmpOperator" : "lib/Algorithm/MinMaxHeap/CmpOperator.pm6", "Algorithm::MinMaxHeap::Comparable" : "lib/Algorithm/MinMaxHeap/Comparable.pm6" }, "resources" : [ ], "source-url" : "git://github.com/titsuki/raku-Algorithm-MinMaxHeap.git", "tags" : [ ], "test-depends" : [ ], "version" : "0.13.5" }
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2016, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: README.md ### ---------------------------------------------------- [![Build Status](https://travis-ci.org/titsuki/raku-Algorithm-MinMaxHeap.svg?branch=master)](https://travis-ci.org/titsuki/raku-Algorithm-MinMaxHeap) NAME ==== Algorithm::MinMaxHeap - A Raku implementation of double ended priority queue SYNOPSIS ======== EXAMPLE1 -------- use Algorithm::MinMaxHeap; my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(2); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); $heap.find-max.say # 8; $heap.find-min.say # 0; my @array; @array.push($heap.pop-max) until $heap.is-empty; @array.say # [8, 7, 6, 5, 4, 3, 2, 1, 0] EXAMPLE2 -------- use Algorithm::MinMaxHeap; use Algorithm::MinMaxHeap::Comparable; # sets compare-to method using Algorithm::MinMaxHeap::Comparable role my class State { also does Algorithm::MinMaxHeap::Comparable[State]; has Int $.value; has $.payload; submethod BUILD(:$!value) { } method compare-to(State $s) { if $!value == $s.value { return Order::Same; } if $!value > $s.value { return Order::More; } if $!value < $s.value { return Order::Less; } } } # specify Algorithm::MinMaxHeap::Comparable role as an item type my $class-heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; $class-heap.insert(State.new(value => 0)); $class-heap.insert(State.new(value => 1)); $class-heap.insert(State.new(value => 2)); $class-heap.insert(State.new(value => 3)); $class-heap.insert(State.new(value => 4)); $class-heap.insert(State.new(value => 5)); $class-heap.insert(State.new(value => 6)); $class-heap.insert(State.new(value => 7)); $class-heap.insert(State.new(value => 8)); $class-heap.find-max.value.say # 8; $class-heap.find-min.value.say # 0; my @array; until $class-heap.is-empty { my $state = $class-heap.pop-max; @array.push($state.value); } @array.say # [8, 7, 6, 5, 4, 3, 2, 1, 0] DESCRIPTION =========== Algorithm::MinMaxHeap is a simple implementation of double ended priority queue. CONSTRUCTOR ----------- Defined as: role Algorithm::MinMaxHeap[::Type] {} Usage: my $heap = Algorithm::MinMaxHeap[Int].new; my $heap = Algorithm::MinMaxHeap[Rat].new; my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; Sets `::Type` parameter, where `::Type` is a type of nodes in the queue. Use `subset` for creating complex type constraints: my subset MyCool of Cool where Int|Num|Rat; my $heap = Algorithm::MinMaxHeap[MyCool].new; METHODS ------- ### insert($item) $heap.insert($item); Inserts an item to the queue. ### pop-max() my $max-value-item = $heap.pop-max(); Returns a maximum value item in the queue and deletes this item in the queue. ### pop-min() my $min-value-item = $heap.pop-min(); Returns a minimum value item in the queue and deletes this item in the queue. ### find-max() my $max-value-item = $heap.find-max(); Returns a maximum value item in the queue. ### find-min() my $min-value-item = $heap.find-min(); Returns a minimum value item in the queue. ### is-empty() returns Bool:D while (not $heap.is-empty()) { // YOUR CODE } Returns whether the queue is empty or not. ### clear() $heap.clear(); Deletes all items in the queue. CAUTION ======= Don't insert both numerical items and stringified items into the same queue. It will cause mixing of lexicographical order and numerical order. AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. This algorithm is from Atkinson, Michael D., et al. "Min-max heaps and generalized priority queues." Communications of the ACM 29.10 (1986): 996-1000.
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 perl6: - latest install: - rakudobrew build-zef - zef --debug --depsonly --/test install . script: - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm-MinMaxHeap [ReadmeFromPod] ; disable = true filename = lib/Algorithm/MinMaxHeap.pm6 [PruneFiles] ; match = ^ 'xt/'
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/06-find-min.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::MinMaxHeap; { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(2); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); is $heap.find-min, 0; } { my class State { also does Algorithm::MinMaxHeap::Comparable[State]; has Int $.value; has $.payload; submethod BUILD(:$!value) { } method compare-to(State $s) { if (self.value == $s.value) { return Order::Same; } if (self.value > $s.value) { return Order::More; } if (self.value < $s.value) { return Order::Less; } } } my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; $heap.insert(State.new(value => 0)); $heap.insert(State.new(value => 1)); $heap.insert(State.new(value => 2)); $heap.insert(State.new(value => 3)); $heap.insert(State.new(value => 4)); $heap.insert(State.new(value => 5)); $heap.insert(State.new(value => 6)); $heap.insert(State.new(value => 7)); $heap.insert(State.new(value => 8)); is $heap.find-min.value, 0; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/04-pop-min.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::MinMaxHeap; { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(2); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); my @actual; while (not $heap.is-empty()) { @actual.push($heap.pop-min); } is @actual, [0,1,2,3,4,5,6,7,8], "It should return ascending array"; } { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(1); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); my @actual; while (not $heap.is-empty()) { @actual.push($heap.pop-min); } is @actual, [0,1,1,3,4,5,6,7,8], "Given a input including duplicated items. It should return ascending array"; } { my class State { also does Algorithm::MinMaxHeap::Comparable[State]; has Int $.value; has $.payload; submethod BUILD(:$!value) { } method compare-to(State $s) { if (self.value == $s.value) { return Order::Same; } if (self.value > $s.value) { return Order::More; } if (self.value < $s.value) { return Order::Less; } } } my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; $heap.insert(State.new(value => 0)); $heap.insert(State.new(value => 1)); $heap.insert(State.new(value => 2)); $heap.insert(State.new(value => 3)); $heap.insert(State.new(value => 4)); $heap.insert(State.new(value => 5)); $heap.insert(State.new(value => 6)); $heap.insert(State.new(value => 7)); $heap.insert(State.new(value => 8)); my @actual; while (not $heap.is-empty()) { @actual.push($heap.pop-min.value); } is @actual, [0,1,2,3,4,5,6,7,8], "It should return ascending array"; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/05-find-max.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::MinMaxHeap; { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(2); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); is $heap.find-max, 8; } { my class State { also does Algorithm::MinMaxHeap::Comparable[State]; has Int $.value; has $.payload; submethod BUILD(:$!value) { } method compare-to(State $s) { if (self.value == $s.value) { return Order::Same; } if (self.value > $s.value) { return Order::More; } if (self.value < $s.value) { return Order::Less; } } } my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; $heap.insert(State.new(value => 0)); $heap.insert(State.new(value => 1)); $heap.insert(State.new(value => 2)); $heap.insert(State.new(value => 3)); $heap.insert(State.new(value => 4)); $heap.insert(State.new(value => 5)); $heap.insert(State.new(value => 6)); $heap.insert(State.new(value => 7)); $heap.insert(State.new(value => 8)); is $heap.find-max.value, 8; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/02-insert.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::MinMaxHeap; use Algorithm::MinMaxHeap::Comparable; subtest { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(2); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); is $heap.nodes[0] < $heap.nodes[3], True; is $heap.nodes[0] < $heap.nodes[4], True; is $heap.nodes[0] < $heap.nodes[5], True; is $heap.nodes[0] < $heap.nodes[6], True; is $heap.nodes[1] > $heap.nodes[7], True; is $heap.nodes[1] > $heap.nodes[8], True; is $heap.nodes[0], 0; is max($heap.nodes[1], $heap.nodes[2]), 8; }, "Given a constructor with a Int parameter, it should insert Int items"; subtest { my $heap = Algorithm::MinMaxHeap[Int].new; dies-ok { $heap.insert(1.5); } }, "Given a constructor with a Int parameter, it shouldn't insert Rat items"; subtest { my subset MyCool of Cool where Int|Num|Rat; my $heap = Algorithm::MinMaxHeap[MyCool].new; $heap.insert(0); $heap.insert(1.1e0); $heap.insert(2); $heap.insert(3.1e0); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7.1); $heap.insert(8); is $heap.nodes[0] < $heap.nodes[3], True; is $heap.nodes[0] < $heap.nodes[4], True; is $heap.nodes[0] < $heap.nodes[5], True; is $heap.nodes[0] < $heap.nodes[6], True; is $heap.nodes[1] > $heap.nodes[7], True; is $heap.nodes[1] > $heap.nodes[8], True; is $heap.nodes[0], 0; is max($heap.nodes[1], $heap.nodes[2]), 8; }, "Given a constructor with a MyCool(i.e. Int|Num|Rat) parameter, It should insert Int/Num/Rat items"; subtest { my subset MyCool of Cool where Int|Num|Rat; my $heap = Algorithm::MinMaxHeap[MyCool].new; dies-ok { $heap.insert("Perl6 is fun"); } }, "Given a constructor with a MyCool(i.e. Int|Num|Rat) parameter, It shouldn't insert Str items"; subtest { my class State { also does Algorithm::MinMaxHeap::Comparable[State]; has Int $.value; has $.payload; submethod BUILD(:$!value) { } method compare-to(State $s) { if (self.value == $s.value) { return Order::Same; } if (self.value > $s.value) { return Order::More; } if (self.value < $s.value) { return Order::Less; } } } my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; $heap.insert(State.new(value => 8)); $heap.insert(State.new(value => 0)); $heap.insert(State.new(value => 1)); $heap.insert(State.new(value => 2)); $heap.insert(State.new(value => 3)); $heap.insert(State.new(value => 4)); $heap.insert(State.new(value => 5)); $heap.insert(State.new(value => 6)); $heap.insert(State.new(value => 7)); is $heap.nodes[0].compare-to($heap.nodes[3]) == Order::Less, True; is $heap.nodes[0].compare-to($heap.nodes[4]) == Order::Less, True; is $heap.nodes[0].compare-to($heap.nodes[5]) == Order::Less, True; is $heap.nodes[0].compare-to($heap.nodes[6]) == Order::Less, True; is $heap.nodes[1].compare-to($heap.nodes[7]) == Order::More, True; is $heap.nodes[1].compare-to($heap.nodes[8]) == Order::More, True; is $heap.nodes[0].value, 0; is max($heap.nodes[1].value, $heap.nodes[2].value), 8; }, "Given a constructor with a Algorithm::MinMaxHeap::Comparable parameter, It should insert Algorithm::MinMaxHeap::Comparable items"; subtest { my class State { also does Algorithm::MinMaxHeap::Comparable[State]; has Int $.value; has $.payload; submethod BUILD(:$!value) { } method compare-to(State $s) { if (self.value == $s.value) { return Order::Same; } if (self.value > $s.value) { return Order::More; } if (self.value < $s.value) { return Order::Less; } } } my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; dies-ok { $heap.insert(1); } }, "Given a constructor with a Algorithm::MinMaxHeap::Comparable parameter, It shouldn't insert Int items"; done-testing;
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/08-clone.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::MinMaxHeap; { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(2); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); is $heap.nodes.elems, 9; my $clone-heap = $heap.clone; is $clone-heap.nodes, $heap.nodes; $heap.clear(); is $clone-heap.nodes.elems, 9; } { my class State { also does Algorithm::MinMaxHeap::Comparable[State]; has Int $.value; has $.payload; submethod BUILD(:$!value) { } method compare-to(State $s) { if (self.value == $s.value) { return Order::Same; } if (self.value > $s.value) { return Order::More; } if (self.value < $s.value) { return Order::Less; } } } my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; $heap.insert(State.new(value => 0)); $heap.insert(State.new(value => 1)); $heap.insert(State.new(value => 2)); $heap.insert(State.new(value => 3)); $heap.insert(State.new(value => 4)); $heap.insert(State.new(value => 5)); $heap.insert(State.new(value => 6)); $heap.insert(State.new(value => 7)); $heap.insert(State.new(value => 8)); is $heap.nodes.elems, 9; my $clone-heap = $heap.clone; is $clone-heap.nodes, $heap.nodes; $heap.clear(); is $clone-heap.nodes.elems, 9; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/07-clear.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::MinMaxHeap; { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(2); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); is $heap.nodes.elems, 9; $heap.clear(); is $heap.nodes.elems, 0; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::MinMaxHeap; lives-ok { my $heap = Algorithm::MinMaxHeap[Int].new; } lives-ok { my $heap = Algorithm::MinMaxHeap[Cool].new } lives-ok { my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; } lives-ok { my $heap = Algorithm::MinMaxHeap[Str].new } lives-ok { my $heap = Algorithm::MinMaxHeap[Rat].new } lives-ok { my $heap = Algorithm::MinMaxHeap[Num].new } lives-ok { my $heap = Algorithm::MinMaxHeap[Real].new } lives-ok { my $heap = Algorithm::MinMaxHeap[Any].new } lives-ok { my $heap = Algorithm::MinMaxHeap[Mu].new } lives-ok { my $heap = Algorithm::MinMaxHeap[Instant].new } done-testing;
### ---------------------------------------------------- ### -- Algorithm::MinMaxHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/03-pop-max.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::MinMaxHeap; { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(2); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); my @actual; while (not $heap.is-empty()) { @actual.push($heap.pop-max); } is @actual, [8,7,6,5,4,3,2,1,0], "It should return descending array"; } { my $heap = Algorithm::MinMaxHeap[Int].new; $heap.insert(0); $heap.insert(1); $heap.insert(1); $heap.insert(3); $heap.insert(4); $heap.insert(5); $heap.insert(6); $heap.insert(7); $heap.insert(8); my @actual; while (not $heap.is-empty()) { @actual.push($heap.pop-max); } is @actual, [8,7,6,5,4,3,1,1,0], "Given a input including duplicated items. It should return descending array"; } { my class State { also does Algorithm::MinMaxHeap::Comparable[State]; has Int $.value; has $.payload; submethod BUILD(:$!value) { } method compare-to(State $s) { if (self.value == $s.value) { return Order::Same; } if (self.value > $s.value) { return Order::More; } if (self.value < $s.value) { return Order::Less; } } } my $heap = Algorithm::MinMaxHeap[Algorithm::MinMaxHeap::Comparable].new; $heap.insert(State.new(value => 0)); $heap.insert(State.new(value => 1)); $heap.insert(State.new(value => 2)); $heap.insert(State.new(value => 3)); $heap.insert(State.new(value => 4)); $heap.insert(State.new(value => 5)); $heap.insert(State.new(value => 6)); $heap.insert(State.new(value => 7)); $heap.insert(State.new(value => 8)); my @actual; while (not $heap.is-empty()) { @actual.push($heap.pop-max.value); } is @actual, [8,7,6,5,4,3,2,1,0], "It should return descending array"; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::NaiveBayes ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: META6.json ### ---------------------------------------------------- { "author": "cpan:TITSUKI", "authors": [ "Itsuki Toyota" ], "build-depends": [ ], "depends": [ ], "description": "A Raku Naive Bayes classifier implementation", "license": "Artistic-2.0", "name": "Algorithm::NaiveBayes", "perl": "6.c", "provides": { "Algorithm::NaiveBayes": "lib/Algorithm/NaiveBayes.pm6", "Algorithm::NaiveBayes::Classifiable": "lib/Algorithm/NaiveBayes/Classifiable.pm6", "Algorithm::NaiveBayes::Classifier::Bernoulli": "lib/Algorithm/NaiveBayes/Classifier/Bernoulli.pm6", "Algorithm::NaiveBayes::Classifier::Multinomial": "lib/Algorithm/NaiveBayes/Classifier/Multinomial.pm6", "Algorithm::NaiveBayes::Document": "lib/Algorithm/NaiveBayes/Document.pm6", "Algorithm::NaiveBayes::Model": "lib/Algorithm/NaiveBayes/Model.pm6", "Algorithm::NaiveBayes::ModelUpdatable": "lib/Algorithm/NaiveBayes/ModelUpdatable.pm6", "Algorithm::NaiveBayes::Vocabulary": "lib/Algorithm/NaiveBayes/Vocabulary.pm6" }, "resources": [ ], "source-url": "git://github.com/titsuki/raku-Algorithm-NaiveBayes.git", "tags": [ ], "test-depends": [ ], "version": "0.0.5" }
### ---------------------------------------------------- ### -- Algorithm::NaiveBayes ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2016, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::NaiveBayes ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: README.md ### ---------------------------------------------------- [![Build Status](https://travis-ci.org/titsuki/raku-Algorithm-NaiveBayes.svg?branch=master)](https://travis-ci.org/titsuki/raku-Algorithm-NaiveBayes) NAME ==== Algorithm::NaiveBayes - A Raku Naive Bayes classifier implementation SYNOPSIS ======== EXAMPLE1 -------- use Algorithm::NaiveBayes; my $nb = Algorithm::NaiveBayes.new(solver => Algorithm::NaiveBayes::Multinomial); $nb.add-document("Chinese Beijing Chinese", "China"); $nb.add-document("Chinese Chinese Shanghai", "China"); $nb.add-document("Chinese Macao", "China"); $nb.add-document("Tokyo Japan Chinese", "Japan"); my $model = $nb.train; my @result = $model.predict("Chinese Chinese Chinese Tokyo Japan"); @result.say; # [China => -8.10769031284391 Japan => -8.90668134500126] EXAMPLE2 -------- use Algorithm::NaiveBayes; my $nb = Algorithm::NaiveBayes.new(solver => Algorithm::NaiveBayes::Bernoulli); $nb.add-document("Chinese Beijing Chinese", "China"); $nb.add-document("Chinese Chinese Shanghai", "China"); $nb.add-document("Chinese Macao", "China"); $nb.add-document("Tokyo Japan Chinese", "Japan"); my $model = $nb.train; my @result = $model.predict("Chinese Chinese Chinese Tokyo Japan"); @result.say; # [Japan => -3.81908500976888 China => -5.26217831993216] DESCRIPTION =========== Algorithm::NaiveBayes is a Raku Naive Bayes classifier implementation. CONSTRUCTOR ----------- my $nb = Algorithm::NaiveBayes.new(); # default solver is Multinomial my $nb = Algorithm::NaiveBayes.new(%options); ### OPTIONS * `solver => Algorithm::NaiveBayes::Multinomial|Algorithm::NaiveBayes::Bernoulli` METHODS ------- ### add-document multi method add-document(%attributes, Str $label) multi method add-document(Str @words, Str $label) multi method add-document(Str $text, Str $label) Adds a document used for training. `%attributes` is the key-value pair, where key is the word and value is the frequency of occurrence of the word in the document. `@words` is the bag-of-words. The bag-of-words is represented as a multiset of words occurrence in the document. `$text` is the plain text of the document. It will be splitted by whitespaces and processed as the bag-of-words internally. ### train method train(--> Algorithm::NaiveBayes::Model) Starts training and returns an Algorithm::NaiveBayes::Model instance. AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. This algorithm is from Manning, Christopher D., Prabhakar Raghavan, and Hinrich Schutze. Introduction to information retrieval. Vol. 1. No. 1. Cambridge: Cambridge university press, 2008.
### ---------------------------------------------------- ### -- Algorithm::NaiveBayes ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: .travis.yml ### ---------------------------------------------------- os: - linux - osx language: perl6 perl6: - latest install: - rakudobrew build-zef - zef --debug --depsonly --/test install . script: - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::NaiveBayes ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm-NaiveBayes [ReadmeFromPod] ; disable = true filename = lib/Algorithm/NaiveBayes.pm6 [PruneFiles] ; match = ^ 'xt/'
### ---------------------------------------------------- ### -- Algorithm::NaiveBayes ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::NaiveBayes; { use Algorithm::NaiveBayes::Vocabulary; my $vocab = Algorithm::NaiveBayes::Vocabulary.new(attributes => {"pong" => 3}); is $vocab.attributes, {"pong" => 3}; } { use Algorithm::NaiveBayes::Vocabulary; my $vocab = Algorithm::NaiveBayes::Vocabulary.new(:text("pong pong pong")); is $vocab.attributes, {"pong" => 3}; } { use Algorithm::NaiveBayes::Vocabulary; my $vocab = Algorithm::NaiveBayes::Vocabulary.new(:words(Array[Str].new("pong", "pong", "pong"))); is $vocab.attributes, {"pong" => 3}; } { use Algorithm::NaiveBayes::Document; my $doc = Algorithm::NaiveBayes::Document.new(attributes => {"pong" => 3}); is $doc.vocabulary.attributes, {"pong" => 3}; } { use Algorithm::NaiveBayes::Document; my $doc = Algorithm::NaiveBayes::Document.new(text => "pong pong pong"); is $doc.vocabulary.attributes, {"pong" => 3}; } { use Algorithm::NaiveBayes::Document; my $doc = Algorithm::NaiveBayes::Document.new(words => Array[Str].new("pong", "pong", "pong")); is $doc.vocabulary.attributes, {"pong" => 3}; } { my $nb = Algorithm::NaiveBayes.new(solver => Algorithm::NaiveBayes::Multinomial); $nb.add-document("Chinese Beijing Chinese", "China"); $nb.add-document("Chinese Chinese Shanghai", "China"); $nb.add-document("Chinese Macao", "China"); $nb.add-document("Tokyo Japan Chinese", "Japan"); my $model = $nb.train; is $model.word-given-class("Chinese", "China"), 3/7, "P(Chinese|China)"; is $model.word-given-class("Tokyo", "China"), 1/14, "P(Tokyo|China)"; is $model.word-given-class("Japan", "China"), 1/14, "P(Japan|China)"; my @result = $model.predict("Chinese Chinese Chinese Tokyo Japan"); is @result[0].key, "China"; is-approx @result[0].value, log(3/4 * (3/7) ** 3 * 1/14 * 1/14), "P(China|doc)"; is @result[1].key, "Japan"; is-approx @result[1].value, log(1/4 * (2/9) ** 3 * 2/9 * 2/9), "P(Japan|doc)"; } { my $nb = Algorithm::NaiveBayes.new(solver => Algorithm::NaiveBayes::Bernoulli); $nb.add-document("Chinese Beijing Chinese", "China"); $nb.add-document("Chinese Chinese Shanghai", "China"); $nb.add-document("Chinese Macao", "China"); $nb.add-document("Tokyo Japan Chinese", "Japan"); my $model = $nb.train; is $model.word-given-class("Chinese", "China"), 4/5, "P(Chinese|China)"; is $model.word-given-class("Japan", "China"), 1/5, "P(Japan|China)"; is $model.word-given-class("Tokyo", "China"), 1/5, "P(Tokyo|China)"; is $model.word-given-class("Beijing", "China"), 2/5, "P(Beijing|China)"; is $model.word-given-class("Shanghai", "China"), 2/5, "P(Shanghai|China)"; is $model.word-given-class("Macao", "China"), 2/5, "P(Macao|China)"; my @result = $model.predict("Chinese Chinese Chinese Tokyo Japan"); is @result[0].key, "Japan"; is-approx @result[0].value, log(1/4 * 2/3 * 2/3 * 2/3 * (1 - 1/3) * (1 - 1/3) * (1 - 1/3)), "P(Japan|doc)"; is @result[1].key, "China"; is-approx @result[1].value, log(3/4 * 4/5 * 1/5 * 1/5 * (1 - 2/5) * (1 - 2/5) * (1 - 2/5)), "P(China|doc)"; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::SetUnion ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: META6.json ### ---------------------------------------------------- { "auth" : "titsuki", "authors" : [ "titsuki" ], "build-depends" : [ ], "depends" : [ ], "description" : "a perl6 implementation for solving the disjoint set union problem (a.k.a. Union-Find Tree)", "license" : "Artistic-2.0", "name" : "Algorithm::SetUnion", "perl" : "6.c", "provides" : { "Algorithm::SetUnion" : "lib/Algorithm/SetUnion.pm6", "Algorithm::SetUnion::Node" : "lib/Algorithm/SetUnion/Node.pm6" }, "resources" : [ ], "source-url" : "git://github.com/titsuki/p6-Algorithm-SetUnion.git", "tags" : [ ], "test-depends" : [ ], "version" : "0.0.1" }
### ---------------------------------------------------- ### -- Algorithm::SetUnion ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2016, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::SetUnion ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: README.md ### ---------------------------------------------------- [![Build Status](https://travis-ci.org/titsuki/p6-Algorithm-SetUnion.svg?branch=master)](https://travis-ci.org/titsuki/p6-Algorithm-SetUnion) NAME ==== Algorithm::SetUnion - a perl6 implementation for solving the disjoint set union problem (a.k.a. Union-Find Tree) SYNOPSIS ======== use Algorithm::SetUnion; my $set-union = Algorithm::SetUnion.new(size => 4); $set-union.union(0,1); $set-union.union(1,2); my $root = $set-union.find(0); DESCRIPTION =========== Algorithm::SetUnion is a perl6 implementation for solving the disjoint set union problem (a.k.a. Union-Find Tree). CONSTRUCTOR ----------- my $set-union = Algorithm::SetUnion.new(%options); ### OPTIONS * `size => $size` Sets the number of disjoint sets. METHODS ------- ### find(Int $index --> Int:D) my $root = $set-union.find($index); Returns the name(i.e. root) of the set containing element `$index`. ### union(Int $left-index, Int $right-index --> Bool:D) $set-union.union($left-index, $right-index); Unites sets containing element `$left-index` and `$right-index`. If sets are equal, it returns False otherwise True. AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. This algorithm is from Tarjan, Robert Endre. "A class of algorithms which require nonlinear time to maintain disjoint sets." Journal of computer and system sciences 18.2 (1979): 110-127.
### ---------------------------------------------------- ### -- Algorithm::SetUnion ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: .travis.yml ### ---------------------------------------------------- os: - linux language: perl6 perl6: - latest install: - rakudobrew build-zef - zef --debug --depsonly --/test install . script: - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::SetUnion ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm-SetUnion [ReadmeFromPod] ; disable = true filename = lib/Algorithm/SetUnion.pm6 [PruneFiles] ; match = ^ 'xt/'
### ---------------------------------------------------- ### -- Algorithm::SetUnion ### -- Licenses: Artistic-2.0 ### -- Authors: titsuki ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::SetUnion; lives-ok { Algorithm::SetUnion.new(size => 0); } lives-ok { Algorithm::SetUnion.new(size => 100000); } { my $set-union = Algorithm::SetUnion.new(size => 5); $set-union.union(0,1); is $set-union.find(0) == $set-union.find(1), True; } { my $set-union = Algorithm::SetUnion.new(size => 5); $set-union.union(0,1); $set-union.union(1,2); is $set-union.find(0) == $set-union.find(1), True; is $set-union.find(1) == $set-union.find(2), True; } { my $set-union = Algorithm::SetUnion.new(size => 5); $set-union.union(0,1); $set-union.union(2,3); is $set-union.find(0) == $set-union.find(1), True; is $set-union.find(2) == $set-union.find(3), True; is $set-union.find(0) == $set-union.find(2), False; is $set-union.find(0) == $set-union.find(3), False; is $set-union.find(1) == $set-union.find(2), False; is $set-union.find(1) == $set-union.find(3), False; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::SkewHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Jeff Ober ### -- File: META6.json ### ---------------------------------------------------- { "perl": "6.c", "name": "Algorithm::SkewHeap", "auth": "github:sysread", "version": "0.0.1", "description": "A fast, flexible min heap", "authors": ["Jeff Ober"], "license": "Artistic-2.0", "provides": {"Algorithm::SkewHeap" : "lib/Algorithm/SkewHeap.pm6"}, "depends": [], "build-depends": [], "test-depends": [], "tags": [], "source-url": "git://github.com/sysread/p6-algorithm-skewheap.git" }
### ---------------------------------------------------- ### -- Algorithm::SkewHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Jeff Ober ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::SkewHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Jeff Ober ### -- File: README.md ### ---------------------------------------------------- NAME ==== Algorithm::SkewHeap - a mergable min heap VERSION ======= 0.0.1 SYNOPSIS ======== use Algorithm::SkewHeap; my $heap = Algorithm::SkewHeap.new; for (1 .. 1000).pick(1000) -> $n { $heap.put($n); } until $heap.is-empty { my $n = $heap.take; } $heap.merge($other-heap); DESCRIPTION =========== A skew heap is a type of heap based on a binary tree in which all operations are based on merging subtrees, making it possible to quickly combine multiple heaps, while still retaining speed and efficiency. Ammortized performance is O(log n) or better (see [https://en.wikipedia.org/wiki/Skew_heap](https://en.wikipedia.org/wiki/Skew_heap)). SORTING ======= Items in the heap are returned with the lowest first. Comparisons are done with the greater than operator, which may be overloaded as needed for types intended to be used in the heap. class Algorithm::SkewHeap ------------------------- SkewHeap class ### method size ```perl6 method size() returns Int ``` Returns the number of items in the heap ### method is-empty ```perl6 method is-empty() returns Bool ``` Returns true when the heap is empty ### method top ```perl6 method top() returns Any ``` Returns the top item in the heap without removing it. ### method take ```perl6 method take() returns Any ``` Removes and returns the top item in the heap. ### method put ```perl6 method put( $value ) returns Int ``` Adds a new item to the heap. Returns the new size of the heap. ### method merge ```perl6 method merge( Algorithm::SkewHeap $other ) returns Int ``` Destructively merges with another heap. The other heap should be considered unusable afterward. Returns the new size of the heap. ### method explain ```perl6 method explain() returns Nil ``` Prints the structure of the heap for debugging purposes.
### ---------------------------------------------------- ### -- Algorithm::SkewHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Jeff Ober ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 sudo: false notifications: email: false perl6: - latest install: - rakudobrew build-zef - zef --deps-only install .
### ---------------------------------------------------- ### -- Algorithm::SkewHeap ### -- Licenses: Artistic-2.0 ### -- Authors: Jeff Ober ### -- File: t/basics.p6.t ### ---------------------------------------------------- use v6.c; use Test; use lib 'lib'; use Algorithm::SkewHeap; my $size = 100; my @nums = (1..$size).pick($size); isa-ok my $heap = Algorithm::SkewHeap.new, 'Algorithm::SkewHeap', 'ctor'; is $heap.size, 0, 'size'; ok $heap.is-empty, 'is-empty'; for @nums -> $num { ok $heap.put($num), 'put'; } is $heap.size, $size, 'size'; ok !$heap.is-empty, '!is-empty'; my $prev; my $count = $heap.size; while !$heap.is-empty { is $heap.size, $count, "size: $count" or bail-out; --$count; my $item = $heap.take // $heap.explain; ok $item, "take: $item"; if ($prev.DEFINITE) { ok $item >= $prev, "$item >= $prev"; } $prev = $item; } is $heap.size, 0, 'size'; ok $heap.is-empty, 'is-empty'; done-testing;
### ---------------------------------------------------- ### -- Algorithm::Soundex ### -- Licenses: Artistic-2.0 ### -- Authors: Jonathan Leto ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:raku-community-modules", "authors": [ "Jonathan Leto" ], "build-depends": [ ], "depends": [ ], "description": "Soundex algorithms in Raku", "license": "Artistic-2.0", "name": "Algorithm::Soundex", "perl": "6.*", "provides": { "Algorithm::Soundex": "lib/Algorithm/Soundex.rakumod" }, "resources": [ ], "source-url": "https://github.com/raku-community-modules/Algorithm-Soundex.git", "tags": [ ], "test-depends": [ ], "version": "0.2" }
### ---------------------------------------------------- ### -- Algorithm::Soundex ### -- Licenses: Artistic-2.0 ### -- Authors: Jonathan Leto ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::Soundex ### -- Licenses: Artistic-2.0 ### -- Authors: Jonathan Leto ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/raku-community-modules/Algorithm-Soundex/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Soundex/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-Soundex/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Soundex/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-Soundex/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Soundex/actions) NAME ==== Algorithm::Soundex - Soundex algorithms in Raku SYNOPSIS ======== ```raku use Algorithm::Soundex; my Algorithm::Soundex $s .= new; my $soundex = $s.soundex("Leto"); say "The soundex of Leto is $soundex"; ``` DESCRIPTION =========== Currently this module contains the American Soundex algorithm, implemented in Raku If you would like to add other Soundex algorithms, Patches Welcome! AUTHOR ====== Jonathan Leto COPYRIGHT AND LICENSE ===================== Copyright 2011 - 2017 Jonathan Leto Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Algorithm::Soundex ### -- Licenses: Artistic-2.0 ### -- Authors: Jonathan Leto ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm::Soundex [ReadmeFromPod] filename = lib/Algorithm/Soundex.rakumod [UploadToZef] [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- Algorithm::Soundex ### -- Licenses: Artistic-2.0 ### -- Authors: Jonathan Leto ### -- File: t/00-basic.rakutest ### ---------------------------------------------------- use Test; use Algorithm::Soundex; plan 3; my Algorithm::Soundex $s .= new(); isa-ok($s, Algorithm::Soundex); my $soundex = $s.soundex("Robert"); is($soundex, 'R163', 'soundex of Robert'); $soundex = $s.soundex(""); is($soundex, '', 'soundex of nothing is nothing'); # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::Soundex ### -- Licenses: Artistic-2.0 ### -- Authors: Jonathan Leto ### -- File: lib/Algorithm/Soundex.rakumod ### ---------------------------------------------------- class Algorithm::Soundex { method soundex ($string --> Str ) { return '' unless $string; my $soundex = $string.substr(0,1).uc; gather { take $soundex; my $fakefirst = ''; $fakefirst = "de " if $soundex ~~ /^ <[AEIOUWH]> /; "$fakefirst$string".lc.trans('wh' => '') ~~ / ^ [ [ | <[ bfpv ]>+ { take 1 } | <[ cgjkqsxz ]>+ { take 2 } | <[ dt ]>+ { take 3 } | <[ l ]>+ { take 4 } | <[ mn ]>+ { take 5 } | <[ r ]>+ { take 6 } ] || . ]+ $ { take 0,0,0 } /; }.flat.[0,2,3,4].join } } =begin pod =head1 NAME Algorithm::Soundex - Soundex algorithms in Raku =head1 SYNOPSIS =begin code :lang<raku> use Algorithm::Soundex; my Algorithm::Soundex $s .= new; my $soundex = $s.soundex("Leto"); say "The soundex of Leto is $soundex"; =end code =head1 DESCRIPTION Currently this module contains the American Soundex algorithm, implemented in Raku If you would like to add other Soundex algorithms, Patches Welcome! =head1 AUTHOR Jonathan Leto =head1 COPYRIGHT AND LICENSE Copyright 2011 - 2017 Jonathan Leto Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: META6.json ### ---------------------------------------------------- { "name": "Algorithm::SpiralMatrix", "description": "Various Raku Sequences for spirals in matrix (two-dimensional arrays).", "version": "0.6.0", "perl": "6.d", "authors": [ "Michal Jurosz" ], "auth": "github:mj41", "depends": [], "build-depends": [], "test-depends": [ "Test", "Test::META" ], "provides": { "Algorithm::SpiralMatrix": "lib/Algorithm/SpiralMatrix.rakumod" }, "support": { "bugtracker": "https://github.com/mj41/Algorithm-SpiralMatrix/issues", "license": "https://www.apache.org/licenses/LICENSE-2.0" }, "license": "Apache-2.0", "tags": [ "algorithm", "bidimensional", "sequence", "array" ], "production": 1, "source-url": "git://github.com/mj41/Algorithm-SpiralMatrix.git", "raku": "6.d", "source-type": "git" }
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: LICENSE ### ---------------------------------------------------- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: README.md ### ---------------------------------------------------- # Algorithm::SpiralMatrix Various Raku Sequences for spirals in matrix (two-dimensional arrays). For overview see [docs/test-output.md](docs/test-output.md) and [docs/distance-variants.md](docs/distance-variants.md). ## Synopsis ```raku use Algorithm::SpiralMatrix; my $i = 1; for square_distance(order => 'clockwise') -> ($x,$y) { say "{$i++} $x,$y"; last if $i > 25; } ``` will print ``` 1 0,0 2 0,-1 3 1,0 4 0,1 5 -1,0 6 1,-1 8 -1,1 9 -1,-1 ... 24 -2,2 25 -2,-2 ```` ## Description This module provides implementation of algorithms to generate various spiral sequences in matrix (two-dimensional array). ## Related links * [zero2cx/spiral-matrix](https://github.com/zero2cx/spiral-matrix) (Python) * [bangjunyoung/SpiralMatrixSharp](https://github.com/bangjunyoung/SpiralMatrixSharp) (F#) * [Exercism: spiral-matrix](https://github.com/exercism/problem-specifications/blob/master/exercises/spiral-matrix/description.md) ## Installation Rakudo Raku distribution contains *zef*. Use zef install Algorithm::SpiralMatrix If you have a local copy of this repository use zef install . in the module directory. ## Support Feel free to share your suggestions, patches or comment [https://github.com/mj41/Algorithm-SpiralMatrix/issues](https://github.com/mj41/Algorithm-SpiralMatrix/issues). ## Licence and Copyright This is free software. Please see the [LICENCE file](LICENSE). © Michal Jurosz, 2019
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: .travis.yml ### ---------------------------------------------------- services: - docker install: - docker pull jjmerelo/test-perl6 - docker images - docker run -t --entrypoint=/bin/sh jjmerelo/test-perl6 -c 'apk update && apk upgrade && apk add openssl-dev' - docker run -t --entrypoint=/bin/sh jjmerelo/test-perl6 -c 'raku --version; which zef; zef --installed list' script: - docker run -t -v $TRAVIS_BUILD_DIR:/test --entrypoint=/bin/sh jjmerelo/test-perl6 -c 'zef install . --deps-only; zef --verbose install . --/test; TEST_ALL=1 prove6 -v t'
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: docs/distance-variants.md ### ---------------------------------------------------- # Spiral Sequences 'distance:*' Return sequence coordinates in spiral order. Start from (0,0). Variant 'distance:clockwise' of spiral sequence continue with top (0,-1), right (1,0), bottom (0,1) and left (-1,0). Then top-right (1,-1), bottom-right, ... ## Example for 'distance::clockwise' Variant 'distance::clockwise' starts with 0,0 and continue with most nearby elements in clockwise order. Note that for example distance from 0,0 to 1,0 is shorten than to from 0,0 to 1,1 as (1^2+0^2)^1/2 <(1^2+1^2)^1/2. The first five elements ``` 2 5 1 3 4 ``` next four ``` 9 2 6 5 1 3 8 4 7 ``` and all others to fill 5x5 matrix. ``` 25 21 10 14 22 20 9 2 6 15 13 5 1 3 11 19 8 4 7 16 24 18 12 17 23 ``` ## Example for 'distance::x-y' Order 'x-y' start in top-left corner (minimal value of 'x' and minimal value of 'y'), continue raising 'x' first and 'y' later. Basical this is useful in case you would like to process two dimensional array that is serialize to one dimensional (Buf) as [x,y] so ``` [0,0],..,[$x.end,0],[0,1],..,[$x.end,$y.max] ``` . The first five elements ``` 2 3 1 4 5 ``` next four ``` 6 2 7 3 1 4 8 5 9 ``` ## Algorithm explanation Lets start with hardcoded begin of the sequence: magenta, red, blue. ![3x3](./img/distance-variants-3x3.png) We can continue with 4x red, 4x blue, 8x green ![5x5](./img/distance-variants-5x5.png) but let's first skip two layers to visualize the pattern clearly. You see 4x red will be the first and 4x blue the last. It's the same also one, two or more steps from the core. ![9x9-a](./img/distance-variants-9x9-a.png) Lets skip to the outer most layer first to visualize that we have again eight dark green positions. And near them also two more free space before we read the blue corner. ![9x9-b](./img/distance-variants-9x9-b.png) And before we reach the blue corner there are also normal green and light green positions. ![9x9-c](./img/distance-variants-9x9-c.png) Now we can return back to see that dark green emerged two layers sooner. Whole pattern and algorithm is visualized by colors in these order: magenta, red, green from dark to light and finally blue. ![9x9](./img/distance-variants-9x9.png) Now finally simplified ('clockwise' order only) Raku implementation of the core loop as can be found in [Algorithm::SpiralMatrix](../lib/Algorithm/SpiralMatrix.rakumod): ```raku unit module Algorithm::SpiralMatrix; multi sub square3x3-reds-order('clockwise') { ( 0,-1), ( 1, 0), ( 0, 1), (-1, 0); } multi sub square3x3-blues-order('clockwise') { ( 1,-1), ( 1, 1), (-1, 1), (-1,-1); } multi sub big-squares-reds-order('clockwise', $shift) { (0,-$shift), ($shift,0), (0,$shift), (-$shift,0); } multi sub big-squares-greens-order('clockwise', $shift, $tone) { (+$tone, -$shift), (+$shift, -$tone), (+$shift, +$tone), ( +$tone,+$shift), ( -$tone,+$shift), (-$shift, +$tone), (-$shift, -$tone), ( -$tone,-$shift); } multi sub big-squares-blues-order('clockwise', $shift) { ($shift,-$shift), ($shift,$shift), (-$shift,$shift), (-$shift,-$shift); } sub square_distance( :$order = 'clockwise' ) is export { # See docs/distance-variants.md to understand the algorithm # and the colors in comments below. gather { # 1x1 take (0,0); # magenta # 3x3 take $_ for square3x3-reds-order($order); # red take $_ for square3x3-blues-order($order); # red # 5x5, 7x7, ... my $shift = 2; loop { take $_ for big-squares-reds-order($order,$shift); # red for 1..^$shift -> $tone { take $_ for big-squares-greens-order($order,$shift,$tone); # green tone } take $_ for big-squares-blues-order($order,$shift); # blue $shift++; } } } ```
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: docs/test-output.md ### ---------------------------------------------------- <!-- use './tool/gen-docs-test-output.raku > docs/test-output.md' to regenerate this file --> Test [t/var-distance.rakutest](../t/var-distance.rakutest) output: ``` ok 1 - distance:clockwise square 11x11 # # 121 117 109 101 93 82 86 94 102 110 118 # 116 81 77 69 61 50 54 62 70 78 111 # 108 76 49 45 37 26 30 38 46 71 103 # 100 68 44 25 21 10 14 22 39 63 95 # 92 60 36 20 9 2 6 15 31 55 87 # 85 53 29 13 5 1 3 11 27 51 83 # 91 59 35 19 8 4 7 16 32 56 88 # 99 67 43 24 18 12 17 23 40 64 96 # 107 75 48 42 34 28 33 41 47 72 104 # 115 80 74 66 58 52 57 65 73 79 112 # 120 114 106 98 90 84 89 97 105 113 119 # ok 2 - distance:clockwise rectangle 11x5, ratio 2 # # 55 45 35 31 27 22 24 28 32 42 52 # 51 41 21 15 9 4 6 12 18 38 48 # 47 37 17 11 3 1 2 10 16 36 46 # 50 40 20 14 8 5 7 13 19 39 49 # 54 44 34 30 26 23 25 29 33 43 53 # ok 3 - distance:x-y square 11x11 # # 118 110 102 94 86 82 87 95 103 111 119 # 112 78 70 62 54 50 55 63 71 79 113 # 104 72 46 38 30 26 31 39 47 73 105 # 96 64 40 22 14 10 15 23 41 65 97 # 88 56 32 16 6 2 7 17 33 57 89 # 83 51 27 11 3 1 4 12 28 52 84 # 90 58 34 18 8 5 9 19 35 59 91 # 98 66 42 24 20 13 21 25 43 67 99 # 106 74 48 44 36 29 37 45 49 75 107 # 114 80 76 68 60 53 61 69 77 81 115 # 120 116 108 100 92 85 93 101 109 117 121 # ok 4 - distance:x-y rectangle 11x5, ratio 2 # # 52 42 32 28 24 22 25 29 33 43 53 # 48 38 18 12 6 4 7 13 19 39 49 # 46 36 16 10 2 1 3 11 17 37 47 # 50 40 20 14 8 5 9 15 21 41 51 # 54 44 34 30 26 23 27 31 35 45 55 # 1..4 ``` Test [t/line.rakutest](../t/line.rakutest) output: ``` ok 1 - distance:clockwise line 11x3 # # 0 0 0 0 0 0 0 0 0 0 0 # 11 9 7 5 3 1 2 4 6 8 10 # 0 0 0 0 0 0 0 0 0 0 0 # ok 2 - distance:clockwise line 3x11 # # 0 10 0 # 0 8 0 # 0 6 0 # 0 4 0 # 0 2 0 # 0 1 0 # 0 3 0 # 0 5 0 # 0 7 0 # 0 9 0 # 0 11 0 # ok 3 - distance:x-y line 11x3 # # 0 0 0 0 0 0 0 0 0 0 0 # 10 8 6 4 2 1 3 5 7 9 11 # 0 0 0 0 0 0 0 0 0 0 0 # ok 4 - distance:clockwise line 3x11 # # 0 10 0 # 0 8 0 # 0 6 0 # 0 4 0 # 0 2 0 # 0 1 0 # 0 3 0 # 0 5 0 # 0 7 0 # 0 9 0 # 0 11 0 # 1..4 ```
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: t/var-distance.rakutest ### ---------------------------------------------------- use Test; use Algorithm::SpiralMatrix; use lib 't/lib'; use ASMTestCommon; { my $out_matrix = dump_matrix( &square_distance, 11, 11, 250, :order('clockwise') ); is( $out_matrix, qq:to/END/.chomp, 121 117 109 101 93 82 86 94 102 110 118 116 81 77 69 61 50 54 62 70 78 111 108 76 49 45 37 26 30 38 46 71 103 100 68 44 25 21 10 14 22 39 63 95 92 60 36 20 9 2 6 15 31 55 87 85 53 29 13 5 1 3 11 27 51 83 91 59 35 19 8 4 7 16 32 56 88 99 67 43 24 18 12 17 23 40 64 96 107 75 48 42 34 28 33 41 47 72 104 115 80 74 66 58 52 57 65 73 79 112 120 114 106 98 90 84 89 97 105 113 119 END 'distance:clockwise square 11x11' ); diag "\n$out_matrix\n"; } { my $out_matrix = dump_matrix( &rectangle_distance, 11, 5, 250, :ratio(2), :order('clockwise') ); is( $out_matrix, qq:to/END/.chomp, 55 45 35 31 27 22 24 28 32 42 52 51 41 21 15 9 4 6 12 18 38 48 47 37 17 11 3 1 2 10 16 36 46 50 40 20 14 8 5 7 13 19 39 49 54 44 34 30 26 23 25 29 33 43 53 END 'distance:clockwise rectangle 11x5, ratio 2' ); diag "\n$out_matrix\n"; } { my $out_matrix = dump_matrix( &square_distance, 11, 11, 250, :order('x-y') ); is( $out_matrix, qq:to/END/.chomp, 118 110 102 94 86 82 87 95 103 111 119 112 78 70 62 54 50 55 63 71 79 113 104 72 46 38 30 26 31 39 47 73 105 96 64 40 22 14 10 15 23 41 65 97 88 56 32 16 6 2 7 17 33 57 89 83 51 27 11 3 1 4 12 28 52 84 90 58 34 18 8 5 9 19 35 59 91 98 66 42 24 20 13 21 25 43 67 99 106 74 48 44 36 29 37 45 49 75 107 114 80 76 68 60 53 61 69 77 81 115 120 116 108 100 92 85 93 101 109 117 121 END 'distance:x-y square 11x11' ); diag "\n$out_matrix\n"; } { my $out_matrix = dump_matrix( &rectangle_distance, 11, 5, 250, :ratio(2), :order('x-y') ); is( $out_matrix, qq:to/END/.chomp, 52 42 32 28 24 22 25 29 33 43 53 48 38 18 12 6 4 7 13 19 39 49 46 36 16 10 2 1 3 11 17 37 47 50 40 20 14 8 5 9 15 21 41 51 54 44 34 30 26 23 27 31 35 45 55 END 'distance:x-y rectangle 11x5, ratio 2' ); diag "\n$out_matrix\n"; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: t/00-meta.rakutest ### ---------------------------------------------------- use Test; use Test::META; plan 1; meta-ok;
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use v6; use Test; use-ok "Algorithm::SpiralMatrix"; done-testing;
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: t/line.rakutest ### ---------------------------------------------------- use Test; use Algorithm::SpiralMatrix; use lib 't/lib'; use ASMTestCommon; { my $out_matrix = dump_matrix( &rectangle_line, 11, 3, 50, :direction('x'), :order('clockwise') ); is( $out_matrix, qq:to/END/.chomp, 0 0 0 0 0 0 0 0 0 0 0 11 9 7 5 3 1 2 4 6 8 10 0 0 0 0 0 0 0 0 0 0 0 END 'distance:clockwise line 11x3' ); diag "\n$out_matrix\n"; } { my $out_matrix = dump_matrix( &rectangle_line, 3, 11, 50, :direction('y'), :order('clockwise') ); is( $out_matrix, qq:to/END/.chomp, 0 10 0 0 8 0 0 6 0 0 4 0 0 2 0 0 1 0 0 3 0 0 5 0 0 7 0 0 9 0 0 11 0 END 'distance:clockwise line 3x11' ); diag "\n$out_matrix\n"; } { my $out_matrix = dump_matrix( &rectangle_line, 11, 3, 50, :direction('x'), :order('x-y') ); is( $out_matrix, qq:to/END/.chomp, 0 0 0 0 0 0 0 0 0 0 0 10 8 6 4 2 1 3 5 7 9 11 0 0 0 0 0 0 0 0 0 0 0 END 'distance:x-y line 11x3' ); diag "\n$out_matrix\n"; } { my $out_matrix = dump_matrix( &rectangle_line, 3, 11, 50, :direction('y'), :order('x-y') ); is( $out_matrix, qq:to/END/.chomp, 0 10 0 0 8 0 0 6 0 0 4 0 0 2 0 0 1 0 0 3 0 0 5 0 0 7 0 0 9 0 0 11 0 END 'distance:clockwise line 3x11' ); diag "\n$out_matrix\n"; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: t/lib/ASMTestCommon.rakumod ### ---------------------------------------------------- unit module ASMTestCommon; sub dump_matrix( $seq, $size_x, $size_y, $max_iterations=1000, *%seq_params ) is export { my $i = 0; my $off_x = ($size_x - 1) / 2; my $off_y = ($size_y - 1) / 2; my @arr; for &$seq(|%seq_params) -> ($x,$y) { #say "{$i.fmt('%3d')} {$x.fmt('%3d')},{$y.fmt('%3d')}"; fail "Error $x,$y ({$x+$off_x,$y+$off_y}) already has value {@arr[$y+$off_y][$x+$off_x]}" with @arr[$y+$off_y][$x+$off_x]; last if $x+$off_x > $size_x and $y+$off_y > $size_y; $i++; @arr[$y+$off_y][$x+$off_x] = $i if $x+$off_x >= 0 and $x+$off_x < $size_x and $y+$off_y >= 0 and $y+$off_y < $size_y; last if $i >= $max_iterations; } my $out_matrix; for 0..^$size_y -> $y { for 0..^$size_x -> $x { @arr[$y][$x] //= 0 } } $out_matrix = @arr.fmt("%3d","\n"); return $out_matrix; }
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: examples/spiral-print.raku ### ---------------------------------------------------- use SpiralMatrix; my $i = 1; for square_distance(order => 'clockwise') -> ($x,$y) { say "{$i++} $x,$y"; last if $i > 25; }
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: lib/Algorithm/SpiralMatrix.rakumod ### ---------------------------------------------------- unit module Algorithm::SpiralMatrix; multi sub square3x3-reds-order('clockwise') { ( 0,-1), ( 1, 0), ( 0, 1), (-1, 0); } multi sub square3x3-blues-order('clockwise') { ( 1,-1), ( 1, 1), (-1, 1), (-1,-1); } multi sub big-squares-reds-order('clockwise', $shift) { (0,-$shift), ($shift,0), (0,$shift), (-$shift,0); } multi sub big-squares-greens-order('clockwise', $shift, $tone) { (+$tone, -$shift), (+$shift, -$tone), (+$shift, +$tone), ( +$tone,+$shift), ( -$tone,+$shift), (-$shift, +$tone), (-$shift, -$tone), ( -$tone,-$shift); } multi sub big-squares-blues-order('clockwise', $shift) { ($shift,-$shift), ($shift,$shift), (-$shift,$shift), (-$shift,-$shift); } multi sub square3x3-reds-order('x-y') { ( 0,-1), (-1, 0), ( 1, 0), ( 0, 1); } multi sub square3x3-blues-order('x-y') { (-1,-1), ( 1,-1), (-1, 1), ( 1, 1); } multi sub big-squares-reds-order('x-y', $shift) { (0,-$shift), (-$shift,0), ($shift,0), (0,$shift); } multi sub big-squares-greens-order('x-y', $shift, $tone) { ( -$tone,-$shift), (+$tone, -$shift), (-$shift, -$tone), (+$shift, -$tone), (-$shift, +$tone), (+$shift, +$tone), ( -$tone,+$shift), ( +$tone,+$shift); } multi sub big-squares-blues-order('x-y', $shift) { (-$shift,-$shift), ($shift,-$shift), (-$shift,$shift), ($shift,$shift); } sub square_distance( :$order = 'clockwise' ) is export { # See docs/distance-variants.md to understand the algorithm # and the colors in comments below. gather { # 1x1 take (0,0); # magenta # 3x3 take $_ for square3x3-reds-order($order); # red take $_ for square3x3-blues-order($order); # red # 5x5, 7x7, ... my $shift = 2; loop { take $_ for big-squares-reds-order($order,$shift); # red for 1..^$shift -> $tone { take $_ for big-squares-greens-order($order,$shift,$tone); # green tone } take $_ for big-squares-blues-order($order,$shift); # blue $shift++; } } } # ToDo - Duplication below - maybe macro would help. # multi sub line( 'x', 'clockwise' ) { gather { take (0,0); my $shift = 1; loop { take (+$shift,0); take (-$shift,0); $shift++; } } } multi sub line( 'y', 'clockwise' ) { gather { take (0,0); my $shift = 1; loop { take (0, -$shift); take (0, +$shift); $shift++; } } } multi sub line( 'x', 'x-y' ) { gather { take (0,0); my $shift = 1; loop { take (-$shift,0); take (+$shift,0); $shift++; } } } multi sub line( 'y', 'x-y' ) { line( 'y', 'clockwise' ); } multi sub rectangle_line( :$direction, :$order='clockwise' ) is export { line( $direction, $order ); } sub rectangle_distance( :$ratio, :$order=Nil ) is export { return line('x',$order) if $ratio == Inf; return line('y',$order) if $ratio == 0; my $iter := square_distance(:$order).iterator; my @buffer; gather { take $iter.pull-one; # 0,0 for 1..* -> $dist { my $dist_x = $dist; my $dist_y = $dist / $ratio; for [email protected] -> $index { next if @buffer[$index] ~~ Empty; my ($x,$y) = @buffer[$index][0,1]; if $x.abs > $dist_x or $y.abs > $dist_y { #say "$x,$y <-- buffer[{$index}], {$x.abs} > $dist_x or {$y.abs} > {$dist_y}"; next; } #say "$x,$y <-- used from buffer[{$index}]"; @buffer[$index] = Empty; take ($x,$y); } #say "buffer end"; loop { my ($x,$y) = $iter.pull-one; if $x.abs > $dist_x or $y.abs > $dist_y { push @buffer, ($x,$y); #say "$x,$y <-- buffered, {$x.abs} > $dist_x or {$y.abs} > {$dist_y}"; if $x.abs > $dist_x && $y.abs > $dist_y { #say "$x, $y both coords over dist, {$x.abs} > $dist_x and {$y.abs} > {$dist_y}"; last; } next; } #say "$x,$y <-- used, {$x.abs} <= $dist_x or {$y.abs} <= {$dist_y}"; take ($x,$y); } #say "LP end"; } } }
### ---------------------------------------------------- ### -- Algorithm::SpiralMatrix ### -- Licenses: Apache-2.0 ### -- Authors: Michal Jurosz ### -- File: tool/gen-docs-test-output.raku ### ---------------------------------------------------- #!/usr/bin/env raku sub get_out($cmd) { my $proc = run $cmd.split(" "), :out, :merge; my $captured-output = $proc.out.slurp: :close; my $exit-code = $proc.exitcode; fail "cmd '$cmd'\nexit-code {$exit-code}: $captured-output" if $exit-code; return $captured-output; } say "<!-- use './tool/gen-docs-test-output.raku > docs/test-output.md' to regenerate this file -->"; for 'var-distance','line' -> $t-file-base { my $t-file-rel-path = "t/{$t-file-base}.rakutest"; say "Test [{$t-file-rel-path}](../{$t-file-rel-path}) output:"; say '```'; my $cmd = "raku -Ilib -It/lib {$t-file-rel-path}"; say get_out($cmd); say '```'; say "\n"; CATCH { say $_.perl } }
### ---------------------------------------------------- ### -- Algorithm::Tarjan ### -- Licenses: Artistic ### -- Authors: Richard Hainsworth aka finanalyst ### -- File: META6.json ### ---------------------------------------------------- { "authors" : [ "Richard Hainsworth aka finanalyst" ], "build-depends" : [], "depends" : [], "description" : "Find cycles in a directed graph using Tarjan's strongly connected component algorithm", "name" : "Algorithm::Tarjan", "perl" : "6.c", "provides" : { "Algorithm::Tarjan" : "lib/Algorithm/Tarjan.pm6" }, "resources" : [], "source-url" : "git://github.com/finanalyst/p6-Algorithm-Tarjan.git", "test-depends" : ["Test" ], "version" : "0.01", "license": "Artistic" }
### ---------------------------------------------------- ### -- Algorithm::Tarjan ### -- Licenses: Artistic ### -- Authors: Richard Hainsworth aka finanalyst ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::Tarjan ### -- Licenses: Artistic ### -- Authors: Richard Hainsworth aka finanalyst ### -- File: README.md ### ---------------------------------------------------- # p6-Algorithm-Tarjan A perl6 implementation of Tarjan's algorithm for finding strongly connected components in a directed graph. More information can be found at wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm. If there is a cycle, then it will be within a strongly connected component. This implies that the absence of strongly connected components (other than a node with itself) means there are no cycles. It is possible there may be no cycles, but a strongly connected component may still exist (if I have interpreted the theory correctly). I was interested in the absence of cycles. ``` use Algorithm::Tarjan; my Algorithm::Tarjan $a .= new(); my %h; # code to fill %h node->[successor nodes] $a.init(%h); say 'There are ' ~ $a.find-cycles() ~ ' cycle(s) in the input graph'; ``` If there is a need for the sets of strongly connected components, they can be retrieved from $a.strongly-connected (an array of node names).
### ---------------------------------------------------- ### -- Algorithm::Tarjan ### -- Licenses: Artistic ### -- Authors: Richard Hainsworth aka finanalyst ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 perl6: - latest install: - rakudobrew build-zef - zef --debug install .
### ---------------------------------------------------- ### -- Algorithm::Tarjan ### -- Licenses: Artistic ### -- Authors: Richard Hainsworth aka finanalyst ### -- File: t/basic.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::Tarjan; my Algorithm::Tarjan $a .= new(); isa-ok $a, Algorithm::Tarjan, 'module loads'; my %h = ( a => <b c d e f>, b => <g h>, c => <i j g>, d => (), e => (), f => (), g => <k l m>, h => (), i => (), j => (), k => (), l => (), m => () ); lives-ok { $a.init( %h ) }, 'test graph, no cycles loads'; lives-ok { $a.strong-components()}, 'get strong components without dying'; is-deeply $a.strongly-connected.flat, (), 'trivial list of strong components'; %h = ( a => <b c d e f>, b => <g h>, c => <i j g>, d => (), e => (), f => (), g => <k l m> ); lives-ok { $a.init( %h ) }, 'test graph, no cycles loads, but missing nodes in hash'; $a.strong-components(); is-deeply $a.strongly-connected.flat, (), 'trivial list of strong components'; is $a.find-cycles, 0, 'no cycles in graph'; %h = ( a => <b c d e f>, b => <g h>, c => <i j g>, d => (), e => (), f => (), g => <k l m>, h => (), i => (), j => (), k => (), l => (), m => ('a', ) ); $a.init( %h ); $a.strong-components(); is-deeply $a.strongly-connected.list, ['a, b, c, g, m'], 'list of strong components in graph'; is $a.find-cycles, 1, 'A cycle in graph'; %h = ( a => ('b', ), b => ('c', ), c => ('a', ), d => <b c e>, e => <d f>, f => <c g>, g => ('f',), h => <e g h> ); $a.init( %h ); $a.strong-components(); is-deeply $a.strongly-connected.list, ['a, b, c', 'f, g', 'd, e'], 'deals with graph in Wikipedia article'; is $a.find-cycles, 3, 'Three cycles in graph'; %h = ( MinModel => <a b c>, a => <a1 b2>, a1 => (), b => ('b1',), b1 => <a1 b3 b4 b5>, b2 => <b3 b4 c>, b3 => (), b4 => (), b5 => (), c => ('c1',), c1 => <c2 b1 a b3 b4>, c2 => () ); done-testing();
### ---------------------------------------------------- ### -- Algorithm::TernarySearchTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:titsuki", "authors": [ "Itsuki Toyota" ], "build-depends": [ ], "depends": [ ], "description": "the algorithm which blends trie and binary search tree", "license": "Artistic-2.0", "name": "Algorithm::TernarySearchTree", "perl": "6.c", "provides": { "Algorithm::TernarySearchTree": "lib/Algorithm/TernarySearchTree.pm6", "Algorithm::TernarySearchTree::Node": "lib/Algorithm/TernarySearchTree/Node.pm6" }, "resources": [ ], "source-url": "https://github.com/titsuki/raku-Algorithm-TernarySearchTree.git", "tags": [ ], "test-depends": [ ], "version": "0.0.5" }
### ---------------------------------------------------- ### -- Algorithm::TernarySearchTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2016, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::TernarySearchTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/titsuki/raku-Algorithm-TernarySearchTree/actions/workflows/test.yml/badge.svg)](https://github.com/titsuki/raku-Algorithm-TernarySearchTree/actions) NAME ==== Algorithm::TernarySearchTree - the algorithm which blends trie and binary search tree SYNOPSIS ======== use Algorithm::TernarySearchTree; my $tst = Algorithm::TernarySearchTree.new(); $tst.insert("Perl6 is fun"); $tst.insert("Perl5 is fun"); my $false-flag = $tst.contains("Kotlin is fun"); # False my $true-flag = $tst.contains("Perl6 is fun"); # True my $matched = $tst.partial-match("Perl. is fun"); # set("Perl5 is fun","Perl6 is fun") my $not-matched = $tst.partial-match("...lin is fun"); # set() DESCRIPTION =========== Algorithm::TernarySearchTree is a implementation of the ternary search tree. Ternary search tree is the algorithm which blends trie and binary search tree. CONSTRUCTOR ----------- ### new my $tst = Algorithm::TernarySearchTree.new(); METHODS ------- ### insert(Str $key) $tst.insert($key); Inserts the key to the tree. ### contains(Str $key) returns Bool:D my $flag = $tst.contains($key); Returns whether given key exists in the tree. ### partial-match(Str $fuzzy-key) returns Set:D my Set $matched = $tst.partial-match($fuzzy-key); Searches partially matched keys in the tree. If you want to match any character except record separator(hex: 0x1e), you can use dot symbol. For example, the query "Perl." matches "Perla", "Perl5", "Perl6", and so on. METHODS NOT YET IMPLEMENTED --------------------------- near-search, traverse, and so on. AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. This algorithm is from Bentley, Jon L., and Robert Sedgewick. "Fast algorithms for sorting and searching strings." SODA. Vol. 97. 1997.
### ---------------------------------------------------- ### -- Algorithm::TernarySearchTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm::TernarySearchTree [ReadmeFromPod] filename = lib/Algorithm/TernarySearchTree.pm6 [UploadToZef] [Badges] provider = github-actions/test.yml
### ---------------------------------------------------- ### -- Algorithm::TernarySearchTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/03-contains.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::TernarySearchTree; { my $tst = Algorithm::TernarySearchTree.new(); $tst.insert("cat"); $tst.insert("bug"); $tst.insert("cats"); $tst.insert("up"); is $tst.contains("cat"), True, 'It should contains "cat"'; is $tst.contains("bug"), True, 'It should contains "bug"'; is $tst.contains("cats"), True, 'It should contains "cats"'; is $tst.contains("up"), True, 'It should contains "up"'; is $tst.contains("dog"), False, 'It shouldn\'t contains "dog"'; is $tst.contains("cbug"), False, 'It shouldn\'t contains "cbug"'; is $tst.contains("cup"), False, 'It shouldn\'t contains "cup"'; is $tst.contains("bu"), False, 'It shouldn\'t contains "bu"'; } { my $tst = Algorithm::TernarySearchTree.new(); $tst.insert(""); is $tst.contains(""), False, 'It shouldn\'t contains empty string'; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::TernarySearchTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/02-insert.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::TernarySearchTree; { my $tst = Algorithm::TernarySearchTree.new(); $tst.insert("cat"); is $tst.root.split-char, "c", 'It should store "cat"'; is $tst.root.eqkid.split-char, "a", 'It should store "cat"'; is $tst.root.eqkid.eqkid.split-char, "t", 'It should store "cat"'; } { my $tst = Algorithm::TernarySearchTree.new(); $tst.insert(""); is $tst.root, Any, 'It shouldn\'t store empty string'; } { my $tst = Algorithm::TernarySearchTree.new(); $tst.insert("cat"); $tst.insert("bug"); $tst.insert("cats"); $tst.insert("up"); # $ means record separator # c # / | \ # b a u # | | | # u t p # | | | # g $ $ # | \ # $ s # | # $ is $tst.root.split-char, "c", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.lokid.split-char, "b", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.lokid.eqkid.split-char, "u", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.lokid.eqkid.eqkid.split-char, "g", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.lokid.eqkid.eqkid.eqkid.split-char, '30'.chr, 'It should store "cat", "bug", "cats", "up"'; is $tst.root.eqkid.split-char, "a", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.eqkid.eqkid.split-char, "t", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.eqkid.eqkid.eqkid.split-char, '30'.chr, 'It should store "cat", "bug", "cats", "up"'; is $tst.root.eqkid.eqkid.eqkid.hikid.split-char, "s", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.eqkid.eqkid.eqkid.hikid.eqkid.split-char, '30'.chr, 'It should store "cat", "bug", "cats", "up"'; is $tst.root.hikid.split-char, "u", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.hikid.eqkid.split-char, "p", 'It should store "cat", "bug", "cats", "up"'; is $tst.root.hikid.eqkid.eqkid.split-char, '30'.chr, 'It should store "cat", "bug", "cats", "up"'; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::TernarySearchTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/04-partial-match.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::TernarySearchTree; { my $tst = Algorithm::TernarySearchTree.new(); $tst.insert("cat"); $tst.insert("bug"); $tst.insert("cats"); $tst.insert("up"); is-deeply $tst.partial-match("."),set(), "It should match any strings with length 1"; is-deeply $tst.partial-match(".."),set("up"), "It should match any strings with length 2"; is-deeply $tst.partial-match("..."),set("cat","bug"), "It should match any strings with length 3"; is-deeply $tst.partial-match("...."),set("cats"), "It should match any strings with length 4"; is-deeply $tst.partial-match("....."),set(), "It should match any strings with length 5"; is-deeply $tst.partial-match("cat."),set("cats"), 'It should match "cats"'; is-deeply $tst.partial-match(".ats"),set("cats"), 'It should match "cats"'; is-deeply $tst.partial-match("c.ts"),set("cats"), 'It should match "cats"'; is-deeply $tst.partial-match("c..s"),set("cats"), 'It should match "cats"'; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::TernarySearchTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use-ok 'Algorithm::TernarySearchTree'; use-ok 'Algorithm::TernarySearchTree::Node'; use Algorithm::TernarySearchTree; lives-ok { my $tst = Algorithm::TernarySearchTree.new(); } done-testing;
### ---------------------------------------------------- ### -- Algorithm::Treap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:titsuki", "authors": [ "Itsuki Toyota" ], "build-depends": [ ], "depends": [ ], "description": "randomized search tree", "license": "Artistic-2.0", "name": "Algorithm::Treap", "perl": "6.c", "provides": { "Algorithm::Treap": "lib/Algorithm/Treap.pm6", "Algorithm::Treap::Node": "lib/Algorithm/Treap/Node.pm" }, "resources": [ ], "source-url": "https://github.com/titsuki/raku-Algorithm-Treap.git", "tags": [ ], "test-depends": [ ], "version": "0.10.3" }
### ---------------------------------------------------- ### -- Algorithm::Treap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2015, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::Treap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/titsuki/raku-Algorithm-Treap/actions/workflows/test.yml/badge.svg)](https://github.com/titsuki/raku-Algorithm-Treap/actions) NAME ==== Algorithm::Treap - randomized search tree SYNOPSIS ======== use Algorithm::Treap; # store Int key my $treap = Algorithm::Treap[Int].new; $treap.insert(0, 0); $treap.insert(1, 10); $treap.insert(2, 20); $treap.insert(3, 30); $treap.insert(4, 40); my $value = $treap.find-value(3); # 30 my $first-key = $treap.find-first-key(); # 0 my $last-key = $treap.find-last-key(); # 4 # delete $treap.delete(4); # store Str key my $treap = Algorithm::Treap[Str].new; $treap.insert('a', 0); $treap.insert('b', 10); $treap.insert('c', 20); $treap.insert('d', 30); $treap.insert('e', 40); my $value = $treap.find-value('a'); # 0 my $first-key = $treap.find-first-key(); # 'a' my $last-key = $treap.find-last-key(); # 'e' # delete $treap.delete('c'); DESCRIPTION =========== Algorithm::Treap is a implementation of the Treap algorithm. Treap is the one of the self-balancing binary search tree. It employs a randomized strategy for maintaining balance. CONSTRUCTOR ----------- ### new my $treap = Algorithm::Treap[::KeyT].new(%options); Sets either one of the type objects(Int or Str) for `::KeyT` and some `%options`, where `::KeyT` is a type of insertion items to the treap. #### OPTIONS * `order-by => TOrder::ASC|TOrder::DESC` Sets key order `TOrder::ASC` or `TOrder::DESC` in the treap. Default is `TOrder::ASC`. METHODS ------- ### insert $treap.insert($key, $value); Inserts the key-value pair to the treap. If the treap already has the same key, it overwrites existing one. ### delete $treap.delete($key); Deletes the node associated with the key from the treap. ### find-value my $value = $treap.find-value($key); Returns the value associated with the key in the treap. When it doesn't hit any keys, it returns type object Any. ### find my $node = $treap.find($key); Returns the instance of the Algorithm::Treap::Node associated with the key in the treap. When it doesn't hit any keys, it returns type object Any. ### find-first-key my $first-key = $treap.find-first-key(); Returns the first key in the treap. ### find-last-key my $last-key = $treap.find-last-key(); Returns the last key in the treap. METHODS NOT YET IMPLEMENTED =========================== join, split, finger-search, sort AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. The algorithm is from Seidel, Raimund, and Cecilia R. Aragon. "Randomized search trees." Algorithmica 16.4-5 (1996): 464-497.
### ---------------------------------------------------- ### -- Algorithm::Treap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm::Treap [ReadmeFromPod] filename = lib/Algorithm/Treap.pm6 [UploadToZef] [Badges] provider = github-actions/test.yml
### ---------------------------------------------------- ### -- Algorithm::Treap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/06-find-last-key.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::Treap; { my $treap = Algorithm::Treap[Int].new; $treap.insert(0,1); $treap.insert(9,2); $treap.insert(20,3); $treap.insert(30,4); $treap.insert(40,5); my $actual = $treap.find-last-key(); my $expected = 40; is $actual, $expected, "It should get maximum key in numerical order (asc)"; } { my $treap = Algorithm::Treap[Int].new(order-by => TOrder::DESC); $treap.insert(0,1); $treap.insert(9,2); $treap.insert(20,3); $treap.insert(30,4); $treap.insert(40,5); my $actual = $treap.find-last-key(); my $expected = 0; is $actual, $expected, "It should get maximum key in numerical order (desc)"; } { my $treap = Algorithm::Treap[Str].new; $treap.insert('0',1); $treap.insert('9',2); $treap.insert('20',3); $treap.insert('30',4); $treap.insert('40',5); my $actual = $treap.find-last-key(); my $expected = '9'; is $actual, $expected, "It should get maximum key in lexicographical order (asc)"; } { my $treap = Algorithm::Treap[Str].new(order-by => TOrder::DESC); $treap.insert('0',1); $treap.insert('9',2); $treap.insert('20',3); $treap.insert('30',4); $treap.insert('40',5); my $actual = $treap.find-last-key(); my $expected = '0'; is $actual, $expected, "It should get maximum key in lexicographical order (desc)"; } { my $treap = Algorithm::Treap[Int].new; my $actual = $treap.find-last-key(); my $expected = Any; is $actual, $expected, "It should return Any when it doesn't hit any keys"; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::Treap ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/02-insert.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::Treap; { my $treap = Algorithm::Treap[Str].new; dies-ok { $treap.insert(0, 99); }, "It should quit insertion and die when it violates type constraints"; } { my $treap = Algorithm::Treap[Int].new; $treap.insert(0, 99); my $actual = $treap.root.value; my $expected = 99; is $actual, $expected, "It should insert an Int item"; } { my $treap = Algorithm::Treap[Str].new; $treap.insert('aho-corasick', 99); my $actual = $treap.root.value; my $expected = 99; is $actual, $expected, "It should insert an Str item"; } { my $treap = Algorithm::Treap[Int].new; $treap.insert(0, 99); $treap.insert(0, 101); my $actual = $treap.root.value; my $expected = 101; is $actual, $expected, "It should overwrite an item"; } { my $treap = Algorithm::Treap[Int].new; $treap.insert(0, 0, Num(0.51)); $treap.insert(1, 1, Num(1.0)); $treap.insert(2, 2, Num(0.28)); $treap.insert(3, 3, Num(0.52)); $treap.insert(4, 4, Num(0.24)); is $treap.root.key, 1, "It should insert an item with keeping heap order"; is $treap.root.left-child.key, 0, "It should insert an item with keeping heap order"; is $treap.root.right-child.key, 3, "It should insert an item with keeping heap order"; is $treap.root.right-child.left-child.key, 2, "It should insert an item with keeping heap order"; is $treap.root.right-child.right-child.key, 4, "It should insert an item with keeping heap order"; } { my $treap = Algorithm::Treap[Int].new; $treap.insert(0, 0, Num(1.0)); $treap.insert(1, 1, Num(0.9)); $treap.insert(2, 2, Num(0.8)); $treap.insert(3, 3, Num(0.7)); $treap.insert(4, 4, Num(0.6)); $treap.insert(3, 3, Num(0.5)); is $treap.root.key, 0, "It should overwrite an item with keeping heap order"; is $treap.root.right-child.key, 1, "It should overwrite an item with keeping heap order"; is $treap.root.right-child.right-child.key, 2, "It should overwrite an item with keeping heap order"; is $treap.root.right-child.right-child.right-child.key, 4, "It should overwrite an item with keeping heap order"; is $treap.root.right-child.right-child.right-child.left-child.key, 3, "It should overwrite an item with keeping heap order"; } done-testing;