Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial import.

  • Loading branch information...
commit 87f8f973e9a6aa50313a3d40f0153262af7093fa 1 parent 0a55c3e
rneeser authored
View
2  AUTHORS
@@ -0,0 +1,2 @@
+Authors:
+ Rudolph Neeser <rudy.neeser@gmail.com>
View
674 COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
View
356 README
@@ -0,0 +1,356 @@
+ CL-HEAP
+ -------
+
+CL-HEAP is a Common Lisp library that provides efficient priority
+queue and heap implementations. Heaps are tree data structure in which
+any child, c, of a parent, p, obeys the relation p R c, for some
+relation R (often less-than or greater-than). Heaps can be used
+directly as priority queues, and are important components of many
+algorithms, like those for finding shortest paths and calculating
+minimum spanning trees.
+
+The library is simple to use. Here's an example covering most of the
+priority queue functionality:
+
+(defparameter *queue* (make-instance 'cl-heap:priority-queue))
+
+(cl-heap:enqueue *queue* 'test 15) ; Enqueue the item with the priority of 15.
+(cl-heap:enqueue *queue* 'this -5)
+(cl-heap:enqueue *queue* 'a 10)
+(cl-heap:enqueue *queue* 'is 5)
+
+(cl-heap:peep-at-queue *queue*) => 'this
+
+(cl-heap:dequeue *queue*) => 'this
+(cl-heap:dequeue *queue*) => 'is
+(cl-heap:dequeue *queue*) => 'a
+(cl-heap:dequeue *queue*) => 'test
+
+The library provides an implementation of an array-based binary heap -
+offering O(log(n)) times for most operations - and the Fibonacci
+heap. While any sequence of arbitrary operations on a Fibonacci heap
+occur in amortised logarithmic time, many common operations occur in
+constant and amortised constant time. See below for further
+details. The Fibonacci heap should generally be your heap of choice
+from this library.
+
+
+ Installation and Usage
+ ----------------------
+
+CL-HEAP depends on XLUNIT, which is used to perform unit
+testing. CL-HEAP has been tested and is known to run on SBCL. If
+you've tried this on other compilers and it runs successfully, please
+let me know. The library can be installed using ASDF-INSTALL:
+
+(require 'asdf-install)
+(asdf-install:install 'cl-heap)
+
+And the library can then be loaded with ASDF:
+
+(asdf:oos 'asdf:load-op 'cl-heap)
+
+ Test Suite
+ ----------
+
+CL-HEAP comes with a test suite. The tests for the various classes can
+be performed as follows:
+
+(xlunit:textui-test-run (xlunit:get-suite cl-heap:fibonacci-test))
+(xlunit:textui-test-run (xlunit:get-suite cl-heap:binary-test))
+(xlunit:textui-test-run (xlunit:get-suite cl-heap:priority-queue-test))
+
+
+ The PRIORITY-QUEUE Class
+ ------------------------
+
+This priority queue is a container for items in which all the items
+are sorted by some given priority. We implement the priority queue
+using a Fibonacci heap.
+
+MAKE-INSTANCE accepts the argument :sort-fun to provide the function
+which the items' priorities are sorted by. This defaults to #'<, which
+will cause the queue to always return the item of lowest priority.
+
+(ENQUEUE queue item priority)
+ Adds the item to the queue at the given priority. Returns a
+ list containing first the item's priority, then the item
+ itself. Running time: O(1)
+
+(DEQUEUE queue)
+ Removes the item of lowest priority from the queue. Running
+ time: amortised O(log(n))
+
+(PEEP-AT-QUEUE queue)
+ Returns the item of lowest priority from the queue, without
+ modifying the queue. Running time: O(1)
+
+(EMPTY-QUEUE queue)
+ Removes all items from the queue. Returns the heap. Running
+ time: O(1)
+
+(QUEUE-SIZE queue)
+ Returns the number of items in the queue. Running time: O(1)
+
+
+ The HEAP Class
+ --------------
+
+HEAP provides functionality common to the two heap classes implement
+by CL-HEAP. Each heap implementation accepts at least two arguments to
+MAKE-INSTANCE: :key and :sort-fun. :sort-fun supplies the function to
+be used when comparing two objects to each other, and defaults to
+#'<. :key gives a function which should be first applied to the
+elements in the HEAP before comparing them using the sorting
+function. :key defaults to #'identity. These functions can be accessed
+using HEAP-KEY and HEAP-SORTING-FUNCTION.
+
+Both of the heap implementations obey the same interface:
+
+(HEAP-KEY heap)
+ Returns the function passed as the :key argument to the heap.
+
+(HEAP-SORTING-FUNCTION heap)
+ Returns the function used to sort the elements in the heap.
+
+(HEAP-SIZE heap)
+ Returns the number of elements in the heap.
+
+(EMPTY-HEAP heap)
+ Removes all items from the heap, and returns the heap.
+
+(IS-EMPTY-HEAP-P heap)
+ Returns true iff the heap contains no elements.
+
+(ADD-TO-HEAP heap item)
+ Adds the given item to the heap. Returns two values: first
+ the item itself, and then some index-key which can be used by
+ DECREASE-KEY and DELETE-KEY to identify which values should
+ be affected by these operations. See below for an example.
+
+(ADD-ALL-TO-HEAP heap items)
+ Adds all items in the list to the heap, as if by repeated
+ calls to ADD-TO-HEAP. ADD-ALL-TO-HEAP can often be
+ implemented more efficiently, though, than by merely
+ executing consecutive calls to ADD-TO-HEAP directly. Returns
+ the heap object.
+
+(PEEP-AT-HEAP heap)
+ Returns the minimum item in the heap, without modifying the
+ heap.
+
+(POP-HEAP heap)
+ Removes the smallest item in the heap, and returns it.
+
+(MERGE-HEAPS first second)
+ Returns a new heap which contains all the items in both
+ heaps. Only heaps which use the same HEAP-KEY and
+ HEAP-SORTING-FUNCTION can be merged, otherwise a HEAP-ERROR
+ is signalled.
+
+(NMERGE-HEAPS first second)
+ Destructively creates a new heap which contains the items in
+ both heaps. Only heaps which use the same HEAP-KEY and
+ HEAP-SORTING-FUNCTION can be merged, otherwise a HEAP-ERROR
+ is signalled.
+
+(DECREASE-KEY heap item-index value)
+ Allows you to specify an item in the heap whose value should
+ be decreased. ITEM-INDEX is the second value returned by
+ ADD-TO-HEAP, and VALUE should be smaller than the items
+ current value, or a KEY-ERROR will be signalled. Returns the
+ heap. See below for an example.
+
+(DELETE-FROM-HEAP heap item-index)
+ Allows you to specify an arbitrary item to remove from the
+ heap. ITEM-INDEX is the second value returned by ADD-TO-HEAP.
+
+DECREASE-KEY requires that HEAP-KEY is either the function IDENTITY,
+or a function that accepts an optional second argument, which will be
+the value of the new key. For instance, if the elements in the heap
+are lists, and they are to be sorted by the first element in the list,
+an appropriate HEAP-KEY could be:
+
+(lambda (item &optional new-value)
+ (if new-value
+ (setf (first item) new-value)
+ (first item)))
+
+Of course, if DECREASE-KEY is not going to be used, then #'first
+itself could simply be used as the HEAP-KEY.
+
+
+ The BINARY-HEAP Class
+ ---------------------
+
+BINARY-HEAP is constructed in the typical fashion, using an array. The
+BINARY-HEAP MAKE-INSTANCE call accepts an extra argument, :size, which
+sets the data array's initial size.
+
+Note that DECREASE-KEY and DELETE-FROM-HEAP are not very useful
+operations on this heap: while they work, the required index-keys may
+be invalidated as soon as any heap operation is performed. If you do
+want to make use of DELETE-FROM-HEAP or DECREASE-KEY, consider using
+FIBONACCI-HEAP instead.
+
+BINARY-HEAP provides an extra function to the above API:
+
+(BINARY-HEAP-EXTENSION-FACTOR heap)
+ The percentage at which the space allocated for data in the
+ heap should grow at once that space has been exceeded. This
+ defaults to 50.
+
+Here are the Big-Oh running times for the heap API, where n and m are
+the sizes of various heaps.
+
+(HEAP-SIZE heap) => O(1)
+
+(EMPTY-HEAP heap) => O(1)
+
+(IS-EMPTY-HEAP-P heap) => O(1)
+
+(ADD-TO-HEAP heap item) => O(log(n))
+
+(ADD-ALL-TO-HEAP heap items) => O(n)
+
+(PEEP-AT-HEAP heap) => O(1)
+
+(POP-HEAP heap) => O(log(n))
+
+(MERGE-HEAPS first second) => O(n + m + log(n + m))
+
+(NMERGE-HEAPS first second) => O(m + log(n + m))
+
+(DECREASE-KEY heap item-index value) => O(log(n))
+
+(DELETE-FROM-HEAP heap item-index) => O(log(n))
+
+
+ The FIBONACCI-HEAP Class
+ ------------------------
+
+The details of the Fibonacci heap are given in "Fibonacci Heaps and
+Their Uses in Improved Network Optimization Algorithms", by Fredman
+and Tarjan (see references below).
+
+The Fibonacci heap has some interesting time constraints, and should
+generally be used instead of BINARY-HEAP.
+
+Here are the Big-Oh running times for the heap API, where n and m are
+the sizes of various heaps.
+
+(HEAP-SIZE heap) => O(1)
+
+(EMPTY-HEAP heap) => O(1)
+
+(IS-EMPTY-HEAP-P heap) => O(1)
+
+(ADD-TO-HEAP heap item) => O(1)
+
+(ADD-ALL-TO-HEAP heap items) => O(n)
+
+(PEEP-AT-HEAP heap) => O(1)
+
+(POP-HEAP heap) => amortised O(log(n))
+
+(MERGE-HEAPS first second) => O(m + n)
+
+(NMERGE-HEAPS first second) => O(1)
+
+(DECREASE-KEY heap item-index value) => amortised O(1)
+
+(DELETE-FROM-HEAP heap item-index) => amortised O(1), except where
+ the deleted item was the minimum
+ item, in which case it is
+ amortised O(log(n))
+
+
+ Examples of Use
+ ---------------
+
+A heap can be created quite simply:
+
+(defparameter *heap* (make-instance 'cl-heap:fibonacci-heap))
+
+This will create a heap where the elements are ordered using
+#'<. Elements can be added one at a time using ADD-TO-HEAP:
+
+(cl-heap:add-to-heap *heap* 1)
+
+or, in a batch.
+
+(cl-heap:add-all-to-heap *heap* '(6 4 7 3 2 0))
+
+The minimum item in this heap can easily by seen using PEEP-AT-HEEP,
+which will not modify the heap in any way:
+
+(cl-heap:peep-at-heap *heap*) => 0
+
+The minimum item can be removed from the heap using POP-HEAP:
+
+(cl-heap:pop-heap *heap*) => 0
+
+Heaps can be used to sort items:
+
+(let ((heap (make-instance 'cl-heap:fibonacci-heap)))
+ (cl-heap:add-all-to-heap heap (loop for i from 1 upto 10 collect (random 100)))
+ (loop while (not (cl-heap:is-empty-heap-p heap)) collect (cl-heap:pop-heap heap)))
+
+=> (14 19 30 32 38 64 74 90 96 98)
+
+A max-heap can be constructed as follows:
+
+(defparameter *heap* (make-instance 'cl-heap:fibonacci-heap :sort-fun #'>))
+
+And this will order things from most to least:
+
+(let ((heap (make-instance 'cl-heap:fibonacci-heap :sort-fun #'>)))
+ (cl-heap:add-all-to-heap heap (loop for i from 1 upto 10 collect (random 100)))
+ (loop while (not (cl-heap:is-empty-heap-p heap)) collect (cl-heap:pop-heap heap)))
+
+=> (69 68 64 60 37 34 30 7 6 1)
+
+The heaps can contain arbitrary items. For instance, a heap whose
+elements are all lists can be constructed as follows:
+
+(defparameter *heap* (make-instance 'cl-heap:fibonacci-heap :key #'first))
+(cl-heap:add-to-heap *heap* (list 5 'some 'arbitrary 'data))
+(cl-heap:add-to-heap *heap* (list 4 'other 'data))
+(cl-heap:pop-heap *heap*) => (4 other data)
+
+DECREASE-KEY and DELETE-FROM-HEAP can be used as follows:
+
+(defparameter *heap* (make-instance 'cl-heap:fibonacci-heap))
+(cl-heap:add-all-to-heap *heap* '(5 3 4 2 1))
+(let ((item-index (second (multiple-value-list (cl-heap:add-to-heap *heap* 10)))))
+ (format t "Smallest item: ~A~%" (cl-heap:peep-at-heap *heap*))
+ (cl-heap:decrease-key *heap* item-index 0)
+ (format t "Smallest item: ~A~%" (cl-heap:peep-at-heap *heap*)))
+
+=> nil
+Smallest item: 1
+Smallest item: 0
+
+ License
+ -------
+
+CL-HEAP is free software: you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by the
+Free Software Foundation, either version 3 of the License, or (at your
+option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+ References
+ ----------
+
+M. L. Fredman and R. E. Tarjan. 1987. "Fibonacci Heaps and Their Uses
+in Improved Network Optimizxation Algorithms". Journal of the
+Association for Computing Machinery, Vol 34, No 3. pp 596 - 615
View
256 binary-heap.lisp
@@ -0,0 +1,256 @@
+;;; Copyright 2009 Rudolph Neeser <rudy.neeser@gmail.com>.
+;;;
+;;; This file is part of CL-HEAP
+;;;
+;;; CL-HEAP is free software: you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; CL-HEAP is distributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with CL-HEAP. If not, see <http://www.gnu.org/licenses/>.
+
+;;;----------------------------------------------------------------
+
+(in-package #:cl-heap)
+
+;;;--------------------------------------------------------------------
+
+(defclass binary-heap (heap)
+ ((data :initform nil
+ :documentation "The heap's stored data.")
+ (extension-factor :initform 50
+ :accessor binary-heap-extension-factor
+ :documentation "The percentage at which the space
+ allocated for data in the heap should grow at
+ once that space has been exceeded."))
+ (:documentation "An implementation of a classic binary heap. This
+ uses the standard array-based implementation."))
+
+(defmethod initialize-instance :after ((heap binary-heap) &key (size 50))
+ (with-slots (data) heap
+ (setf data (make-array size :adjustable t :fill-pointer 0))))
+
+;;;--------------------------------------------------------------------
+;;; Unexported functions
+
+(declaim (inline children-positions))
+(defun children-positions (position)
+ (declare (type fixnum position))
+ (check-type position (integer 0 *))
+ (values (1+ (* position 2))
+ (+ 2 (* position 2))))
+
+(declaim (inline parent-position))
+(defun parent-position (position)
+ (declare (type fixnum position))
+ (check-type position (integer 0 *))
+ (values (floor (/ (1- position) 2))))
+
+(defgeneric percolate-down (heap position)
+ (:documentation "Used to move a value in the DATA array of a
+ BINARY-HEAP down the parent-child relationship hierarchy, and so
+ preserve heap-ordering.")
+ (:method ((heap binary-heap) (position fixnum))
+ (with-slots (data) heap
+ (labels ((choose-one (lhs rhs)
+ ;; Of two nodes, returns the "least"
+ (cond
+ ((>= rhs (length data))
+ lhs)
+ ((compare-items heap
+ (aref data lhs)
+ (aref data rhs))
+ lhs)
+ (t
+ rhs))))
+ (multiple-value-bind (left-child right-child)
+ (children-positions position)
+ (when (and (< (children-positions position)
+ (length data))
+ (not
+ (and (compare-items heap
+ (aref data position)
+ (aref data left-child))
+ (or
+ (>= (1+ (children-positions position)) (length data))
+ (compare-items heap
+ (aref data position)
+ (aref data right-child))))))
+ (let ((chosen (choose-one left-child right-child)))
+ (rotatef (aref data position)
+ (aref data chosen))
+ (percolate-down heap chosen))))))))
+
+(defgeneric percolate-up (heap position)
+ (:method ((heap binary-heap) (position fixnum))
+ (with-slots (data) heap
+ (cond
+ ((and (/= position 0)
+ (not (compare-items heap
+ (aref data
+ (parent-position position))
+ (aref data position))))
+ (rotatef (aref data position)
+ (aref data (parent-position position)))
+ (percolate-up heap (parent-position position)))
+ (t
+ position)))))
+
+
+;;;--------------------------------------------------------------------
+;;; Exported functions
+
+(defmethod heap-size ((heap binary-heap))
+ (length (slot-value heap 'data)))
+
+(defmethod empty-heap ((heap binary-heap))
+ "Clears the heap. A constant time operation."
+ (with-slots (data) heap
+ (setf (fill-pointer data) 0))
+ heap)
+
+(defmethod is-empty-heap-p ((heap binary-heap))
+ (with-slots (data) heap
+ (= (length data) 0)))
+
+(defmethod peep-at-heap ((heap binary-heap))
+ "Returns the minimum object of the heap, without updating the
+heap. This is an O(1) operation."
+ (with-slots (data) heap
+ (when (plusp (length data))
+ (aref data 0))))
+
+(defmethod add-to-heap ((heap binary-heap) item)
+ "Inserts an item into a BINARY-HEAP. This is O(log(n)), n being the
+number of items in the heap."
+ (with-slots (data
+ (factor extension-factor)) heap
+ (vector-push-extend item data (ceiling (* (/ factor 100) (length data))))
+ (values item (percolate-up heap (1- (length data))))))
+
+(defmethod pop-heap ((heap binary-heap))
+ "Removes the minimum item from the heap. This is an O(log(n))
+operation, where n is the number of items in the heap."
+ (with-slots (data) heap
+ (when (plusp (length data))
+ (let ((top (aref data 0)))
+ ;; Place the last element into the root
+ (setf (aref data 0) (aref data (1- (length data))))
+ (decf (fill-pointer data))
+ (percolate-down heap 0)
+ top))))
+
+(defmethod add-all-to-heap ((heap binary-heap) (items list))
+ "Adds all the items in the list into the BINARY-HEAP. This is a
+O(n + log(n)) = O(n) operation. Returns the BINARY-HEAP."
+ (with-slots (data
+ (factor extension-factor)) heap
+ ;; Add all items, which is linear time since no sorting occurs here.
+ (loop for item in items
+ do (vector-push-extend item data (ceiling (* (/ factor 100) (length data)))))
+ (loop for position from (parent-position (1- (length data))) downto 0
+ do (percolate-down heap position)))
+ heap)
+
+
+(defmethod merge-heaps ((first binary-heap) (second binary-heap))
+ "Non-destructively merges two BINARY-HEAPs. This is an O(n + m +
+log(n + m)) operation, n and m being the zies of the two heaps."
+ (unless (and (eq (heap-sorting-function first) (heap-sorting-function second))
+ (eq (heap-key first) (heap-key second)))
+ (error 'heap-error :message
+ "The two heaps do not using the same sorting function or key."))
+ (with-slots ((first-data data)) first
+ (with-slots ((second-data data)) second
+ (let* ((length (+ (length first-data) (length second-data)))
+ (result (make-instance 'binary-heap
+ :size length
+ :sort-fun (heap-sorting-function first)
+ :key (heap-key first))))
+ (with-slots (data) result
+ (setf (fill-pointer data) length
+ (subseq data 0 (length first-data)) first-data
+ (subseq data (length first-data)) second-data)
+ (when (plusp (length data))
+ (loop for position from (parent-position (1- (length data))) downto 0
+ do (percolate-down result position))))
+ result))))
+
+(defmethod nmerge-heaps ((first binary-heap) (second binary-heap))
+ "Destructively merges two BINARY-HEAPs, and returns the
+result. Where n and m are the sizes of each queue, this is an order
+O(m + log(n + m) operation, unless an array resize is required, for
+which it becomes O(n + m + log(n + m))."
+ (unless (and (eq (heap-sorting-function first) (heap-sorting-function second))
+ (eq (heap-key first) (heap-key second)))
+ (error 'heap-error
+ :message "The two heaps do not using the same sorting function or key."))
+ (with-slots ((first-data data)) first
+ (with-slots ((second-data data)) second
+ (let ((original-length (length first-data))
+ (length (+ (length first-data) (length second-data))))
+ (when (< (length first-data) length)
+ (adjust-array first-data length))
+ (setf (fill-pointer first-data) length
+ (subseq first-data 0 original-length) first-data
+ (subseq first-data original-length) second-data)
+ (when (plusp (length first-data))
+ (loop for position from (parent-position (1- (length first-data))) downto 0
+ do (percolate-down first position))))
+ first)))
+
+(defmethod decrease-key ((heap binary-heap) (item-index fixnum) value)
+ "Deceases the key of the item pointed to by ITEM-INDEX. The index is
+ returned as the second value of ADD-TO-HEAP. The value of the item
+ at the index is changed to VALUE, which should be less than its old
+ value. This operation is O(log(n)), with n being the number of items
+ in the heap. Note that using a binary heap is not ideal for this
+ operation, since the item pointed to by any given index can be
+ changed by performing any heap operation. This function is provided
+ mostly for completeness."
+ (check-type item-index (integer 0 *))
+ (with-slots (data sort-fun key) heap
+ (unless (funcall sort-fun value (funcall key (aref data item-index)))
+ (error 'key-error
+ :message
+ (format nil
+ "The given value (~a) must be less than the current value (~a)."
+ value (funcall key (aref data item-index)))))
+ (cond
+ ((not (eq (heap-key heap) #'identity))
+ (handler-case (funcall (heap-key heap)
+ (aref data item-index)
+ value)
+ (error (e)
+ (declare (ignore e))
+ (error 'key-error))))
+ (t
+ (setf (aref data item-index) value)))
+ (percolate-up heap item-index))
+ heap)
+
+(defmethod delete-from-heap ((heap binary-heap) (item-index fixnum))
+ "Deltes an item from the heap. ITEM-INDEX is an index representing
+ the value to remove, and is the second value returned from
+ ADD-TO-HEAP. Note that running most HEAP functions can modify which
+ value is pointed to by ITEM-INDEX, so this function is given mostly
+ for completeness. Use a Fibonacci heap if this functionality is
+ important to you. This operation completes in O(log(n)) time, where
+ n is the number of items in the heap."
+ (check-type item-index (integer 0 *))
+ (with-slots (data) heap
+ (when (plusp (length data))
+ ;; Place the last element into this position
+ (setf (aref data item-index) (aref data (1- (length data))))
+ (decf (fill-pointer data))
+ (percolate-down heap item-index)
+ heap)))
+
+
+;;;--------------------------------------------------------------------
View
42 cl-heap.asd
@@ -0,0 +1,42 @@
+;;; -*- Mode: Lisp; -*-
+;;;
+;;; Copyright 2009 Rudolph Neeser <rudy.neeser@gmail.com>
+;;;
+;;; This file is part of CL-HEAP
+;;;
+;;; CL-HEAP is free software: you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; CL-HEAP is distributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with CL-HEAP. If not, see <http://www.gnu.org/licenses/>.
+
+;;;----------------------------------------------------------------
+
+
+(defpackage #:cl-heap-asdf
+ (:use :common-lisp :asdf))
+
+(in-package #:cl-heap-asdf)
+
+(defsystem :cl-heap
+ :description "An implementation of heap and priority queue data structures."
+ :version "0.1"
+ :author "Rudy Neeser <rudy.neeser@gmail.com>"
+ :license "GPLv3"
+ :depends-on (:xlunit)
+ :serial t
+ :components ((:file "package")
+ (:file "condition")
+ (:file "heap")
+ (:file "binary-heap")
+ (:file "fibonacci-heap")
+ (:file "priority-queue")
+ (:file "tests")))
+
View
34 condition.lisp
@@ -0,0 +1,34 @@
+;;; Copyright 2009 Rudolph Neeser <rudy.neeser@gmail.com>.
+;;;
+;;; This file is part of CL-HEAP
+;;;
+;;; CL-HEAP is free software: you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; CL-HEAP is distributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with CL-HEAP. If not, see <http://www.gnu.org/licenses/>.
+
+;;;----------------------------------------------------------------
+
+(in-package #:cl-heap)
+
+;;;----------------------------------------------------------------
+
+(define-condition heap-error (error)
+ ((message :initform "An error has occured while using this data structure."
+ :initarg :message
+ :reader heap-error-message))
+ (:documentation "The base condition type for all errors that should
+ generally be thrown in the CL-HEAP package.")
+ (:report (lambda (condition stream)
+ (format stream (heap-error-message condition)))))
+
+(define-condition key-error (heap-error)
+ ((message :initform "When using DECREASE-KEY, the HEAP-KEY function should always take two arguments.")))
View
393 fibonacci-heap.lisp
@@ -0,0 +1,393 @@
+;;; Copyright 2009 Rudolph Neeser <rudy.neeser@gmail.com>.
+;;;
+;;; This file is part of CL-HEAP
+;;;
+;;; CL-HEAP is free software: you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; CL-HEAP is distributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with CL-HEAP. If not, see <http://www.gnu.org/licenses/>.
+
+;;;----------------------------------------------------------------
+
+(in-package #:cl-heap)
+
+;;;----------------------------------------------------------------
+
+(defclass fibonacci-heap (heap)
+ ((root :initform nil
+ :documentation "The minimum element in the tree.")
+ (count :initform 0
+ :documentation "The number of items in the heap."))
+ (:documentation "A heap made up of item-disjoint, heap-ordered
+ trees. Has some good time constraints on various heap operations."))
+
+;;;----------------------------------------------------------------
+
+(defclass node ()
+ ((item :initform nil
+ :initarg :item
+ :accessor node-item)
+ (parent :initform nil
+ :accessor node-parent)
+ (child :initform nil
+ :accessor node-child)
+ (rank :initform 0
+ :accessor node-rank
+ :documentation "The number of children the node has.")
+ (marked :initform nil
+ :accessor node-marked-p
+ :documentation "Used to implement cascading cuts.")
+ (next :initform nil
+ :accessor node-next)
+ (last :initform nil
+ :accessor node-last))
+ (:documentation "A class used for storing data in a FIBONACCI-HEAP."))
+
+(defmethod initialize-instance :after ((node node) &key)
+ (with-slots (next last) node
+ (setf next node
+ last node)))
+
+(defmethod print-object ((node node) stream)
+ (print-unreadable-object (node stream :type t :identity t)
+ (format stream "Item: ~a" (slot-value node 'item))))
+
+;;;----------------------------------------------------------------
+;;; Unexported functions for handling nodes.
+
+(defgeneric unmark-node (node)
+ (:method ((node node))
+ (setf (node-marked-p node) nil)))
+
+(defgeneric mark-node (node)
+ (:method ((node node))
+ (setf (node-marked-p node) t)))
+
+(defgeneric is-node-root-p (node)
+ (:method ((node node))
+ (null (node-parent node))))
+
+(defgeneric concatenate-node-lists (lhs rhs)
+ (:method ((lhs node) (rhs null))
+ lhs)
+ (:method ((lhs null) (rhs node))
+ rhs)
+ (:method ((lhs node) (rhs node))
+ (with-slots ((lhs-next next)
+ (lhs-last last)
+ (lhs-item item)) lhs
+ (with-slots ((rhs-next next)
+ (rhs-last last)
+ (rhs-item item)) rhs
+ (psetf (node-next lhs) rhs
+ (node-last (node-next lhs)) (node-last rhs)
+ (node-last rhs) lhs
+ (node-next (node-last rhs)) (node-next lhs))))
+ lhs))
+
+
+(defgeneric delete-node (node)
+ (:documentation "Deletes this node from the linked list that it
+ represents, and returns the new list. Nulls the node's parent, and
+ resets its rank if appropriate.")
+ (:method ((node null))
+ nil)
+ (:method ((node node))
+ (with-slots (next last parent) node
+ (let ((result (when (not (eq next node))
+ next)))
+ (when result ; There was something to delete.
+ (psetf (node-last next) last
+ (node-next last) next
+ next node
+ last node))
+ (when parent ; Remove the item from any parents.
+ (decf (node-rank parent))
+ (when (eq (node-child parent) node)
+ (setf (node-child parent) result))
+ (setf parent nil))
+ result))))
+
+
+
+(defmacro do-each-node ((symbol node) &body body)
+ (let ((node node)
+ (last (gensym))
+ (next (gensym)))
+ `(when ,node
+ (loop
+ with ,last = (node-last ,node)
+ for ,symbol = ,node then ,next
+ for ,next = (node-next ,node) then (node-next ,next)
+ while (not (eq ,symbol ,last))
+ do (progn
+ ,@body)
+ finally (progn
+ ,@body)))))
+
+
+;;;--------------------
+;;; Unexported functions
+
+(defgeneric meld (one two)
+ (:documentation "Joins together two fibonacci heaps."))
+
+;; This should not increase the heap's count of its items, since it's
+;; used in areas such as linking, where this must not occur.
+(defmethod meld ((heap fibonacci-heap) (item node))
+ "Adds a node to the heap."
+ (with-slots (root) heap
+ (cond
+ ((null root)
+ (setf root item))
+ ((compare-items heap (node-item root) (node-item item))
+ (setf root (concatenate-node-lists root item)))
+ (t
+ (setf root (concatenate-node-lists item root)))))
+ heap)
+
+;; This should adjust the heap's count of its children, since it's use
+;; only makes sense in places where more items are added.
+(defmethod meld ((heap1 fibonacci-heap) (heap2 fibonacci-heap))
+ (with-slots ((heap1-root root)
+ (heap1-count count)) heap1
+ (with-slots ((heap2-root root)
+ (heap2-count count)) heap2
+ (setf heap1-root (concatenate-node-lists heap1-root heap2-root))
+ (unless (compare-items heap1 (node-item heap1-root) (node-item heap2-root))
+ (setf heap1-root heap2-root
+ heap1-count (+ heap1-count heap2-count))))))
+
+(defgeneric link (heap node-one node-two)
+ (:documentation "Places node-two as a child of node-one if
+ node-one's item is smaller, or vice versa.")
+ (:method ((heap fibonacci-heap) (node-one node) (node-two node))
+ (with-slots ((one-child child)
+ (one-item item)
+ (one-rank rank)) node-one
+ (with-slots ((two-child child)
+ (two-item item)
+ (two-rank rank)) node-two
+ (cond
+ ((compare-items heap one-item two-item)
+ (delete-node node-two)
+ (unless (is-node-root-p node-two)
+ (unmark-node node-two))
+ (setf one-child (concatenate-node-lists one-child node-two)
+ (node-parent node-two) node-one)
+ (incf one-rank)
+ node-one)
+ (t
+ (delete-node node-one)
+ (setf two-child (concatenate-node-lists two-child node-one)
+ (node-parent node-one) node-two)
+ (incf two-rank)
+ node-two))))))
+
+(defgeneric cut-node (heap node)
+ (:documentation "Cuts a child from its parent and makes and places
+ it in the root list.")
+ (:method ((heap fibonacci-heap) (node node))
+ (let ((parent (node-parent node)))
+ (with-slots (root) heap
+ (delete-node node)
+ (concatenate-node-lists root node)
+ (cond
+ ((and parent (not (is-node-root-p parent)) (node-marked-p parent))
+ (cut-node heap parent))
+ ((and parent (not (is-node-root-p parent)))
+ (mark-node parent)
+ heap))))))
+
+
+;;;----------------------------------------------------------------
+;;; Exported Functions
+
+(defmethod empty-heap ((heap fibonacci-heap))
+ "Clears all items from the heap. This is a constant time operation."
+ (with-slots (root count) heap
+ (setf root nil
+ count 0))
+ heap)
+
+(defmethod is-empty-heap-p ((heap fibonacci-heap))
+ (unless (slot-value heap 'root)
+ t))
+
+(defmethod heap-size ((heap fibonacci-heap))
+ (slot-value heap 'count))
+
+(defmethod add-to-heap ((heap fibonacci-heap) item)
+ "Adds an item to a Fibonacci-heap. This is a constant time
+operation. Returns the item added to the heap."
+ (let ((node (make-instance 'node :item item)))
+ (meld heap node)
+ (incf (slot-value heap 'count))
+ (values item node)))
+
+(defmethod add-all-to-heap ((heap fibonacci-heap) (items list))
+ "Adds the following list of items into the heap. This is an O(n) operation."
+ (with-slots (count) heap
+ (loop for i in items
+ do (progn
+ (meld heap (make-instance 'node :item i))
+ (incf count))))
+ heap)
+
+(defmethod peep-at-heap ((heap fibonacci-heap))
+ "See the heap's minimum value without modifying the heap. This is a
+constant time operation."
+ (with-slots (root) heap
+ (when root
+ (node-item root))))
+
+(defmethod pop-heap ((heap fibonacci-heap))
+ "Remove the minimum element in the tree. This has an amortised
+running time of O(log(n)), where n is the number of items in the
+heap."
+ (unless (is-empty-heap-p heap)
+ (let ((item (peep-at-heap heap)))
+ (with-slots (root count) heap
+ ;; Delete the minimum.
+ (concatenate-node-lists root (node-child root))
+ (setf root (delete-node root))
+ (when root
+ (let ((ranks (make-array (ceiling (log count 2)) :initial-element nil))
+ (min nil))
+ ;; Merge all trees of the same rank.
+ (labels ((sort-node (node)
+ (let ((position (node-rank node)))
+ (cond
+ ((aref ranks position)
+ (let ((new (link heap node (aref ranks position))))
+ (setf (aref ranks position) nil)
+ (sort-node new)))
+ (t
+ (setf (aref ranks position) node))))))
+ (do-each-node (node root)
+ ;; The newly added nodes should not have a parent
+ (setf (node-parent node) nil)
+ (delete-node node)
+ (sort-node node)))
+ (loop for tree across ranks
+ do (when (not (null tree))
+ (cond
+ ((null min)
+ (setf min tree))
+ ((compare-items heap
+ (node-item min)
+ (node-item tree))
+
+ (setf min (concatenate-node-lists min tree)))
+ (t
+ (setf min (concatenate-node-lists tree min))))))
+ (setf root min)))
+ (decf (slot-value heap 'count))
+ item))))
+
+
+(defmethod nmerge-heaps ((first fibonacci-heap) (second fibonacci-heap))
+ "Destructively marges the two heaps. This is a constant time
+operation."
+ (with-slots ((first-root root)
+ (first-key key)
+ (first-fun sort-fun)) first
+ (with-slots ((second-root root)
+ (second-key key)
+ (second-fun sort-fun)) second
+ (unless (and (eq first-key second-key)
+ (eq first-fun second-fun))
+ (error 'heap-error :message "These two heaps were constructed using different
+ access keys and sorting functions."))))
+ (meld first second)
+ first)
+
+(defmethod merge-heaps ((first fibonacci-heap) (second fibonacci-heap))
+ "Returns the merge of the two given heaps. This operation runs in
+O(n + m), where n and m are the number of items in each heap."
+ (with-slots ((first-root root)
+ (first-key key)
+ (first-fun sort-fun)) first
+ (with-slots ((second-root root)
+ (second-key key)
+ (second-fun sort-fun)) second
+ (unless (and (eq first-key second-key)
+ (eq first-fun second-fun))
+ (error 'heap-error :message "These two heaps were constructed using different
+ access keys and sorting functions."))
+ (let ((result (make-instance 'fibonacci-heap
+ :sort-fun first-fun
+ :key first-key)))
+ (labels ((add-from-level (node-list)
+ (when node-list
+ (do-each-node (node node-list)
+ (add-from-level (node-child node))
+ (add-to-heap result (node-item node))))))
+ (add-from-level first-root)
+ (add-from-level second-root))
+ result))))
+
+;;; This method decreases the node's key, removes the node from the
+;;; tree and adds it to the root list (unless this is of course where
+;;; the node originally was.
+(defmethod decrease-key ((heap fibonacci-heap) (item-index node) value)
+ "Changes the value of an item represented by the ITEM-INDEX to
+ VALUE. This index is returned as the second argument to
+ ADD-TO-HEAP. This is an amortised constant time operation."
+ (with-slots (key sort-fun) heap
+ (unless (funcall sort-fun value (funcall key (node-item item-index)))
+ (error 'key-error :message
+ (format nil "The given value (~a) must be less than the current value (~a)."
+ value (funcall key (node-item item-index)))))
+ (if (eq key #'identity)
+ (setf (node-item item-index) value)
+ (handler-case
+ (funcall key (node-item item-index) value)
+ (error (e)
+ (declare (ignore e))
+ (error 'key-error))))
+ (cond
+ ;; A child of something. See if cascading cuts should occur.
+ ((node-parent item-index)
+ (let ((parent (node-parent item-index)))
+ (delete-node item-index)
+ (meld heap item-index)
+ (when (not (is-node-root-p parent))
+ (if (node-marked-p parent)
+ (cut-node heap parent)
+ (mark-node parent)))))
+ (t ; In the list with the root.
+ (with-slots (root) heap
+ (unless (compare-items heap (node-item root) (node-item item-index))
+ (setf root item-index))))))
+ heap)
+
+(defmethod delete-from-heap ((heap fibonacci-heap) (item-index node))
+ "Removes an item from the heap, as pointed to by item-index. This
+ operation is amortised O(1), unless the item removed is the minimum item, in
+ which case the operation is equivalent to a POP-HEAP."
+ (with-slots (root count) heap
+ (let ((parent (node-parent item-index)))
+ (cond
+ ((eq root item-index)
+ (pop-heap heap))
+ (t
+ (do-each-node (child (node-child item-index))
+ (setf (node-parent child) nil))
+ ;; Add children to root level.
+ (concatenate-node-lists root (node-child item-index))
+ (delete-node item-index)
+ (decf count)))
+ (when (and parent (not (is-node-root-p parent)))
+ (if (node-marked-p parent)
+ (cut-node heap parent)
+ (mark-node parent)))))
+ heap)
View
229 finonacci-heap.lisp
@@ -0,0 +1,229 @@
+(declaim (optimize (speed 0) (debug 3) (safety 3)))
+(in-package #:cl-heap)
+
+(defclass fibonacci-heap (heap)
+ ((root :initform nil
+ :documentation "The minimum element in the tree.")
+ (count :initform 0
+ :documentation "The number of items in the heap."))
+ (:documentation "A heap made up of item-disjoint, heap-ordered
+ trees. Has some good time constraints on various heap operations."))
+
+(defclass node ()
+ ((item :initform nil
+ :initarg :item
+ :accessor node-item)
+ (parent :initform nil)
+ (child :initform nil
+ :accessor node-child)
+ (rank :initform 0
+ :accessor node-rank
+ :documentation "The number of children the node has.")
+ (marked :initform 0)
+ (next :initform nil
+ :accessor node-next)
+ (last :initform nil
+ :accessor node-last)))
+
+(defmethod initialize-instance :after ((node node) &key)
+ (with-slots (next last) node
+ (setf next node
+ last node)))
+
+(defmethod print-object ((node node) stream)
+ (print-unreadable-object (node stream :type t :identity t)
+ (format stream "~a" (slot-value node 'item))))
+
+
+
+
+;;;----------------------------------------------------------------
+;;; Unexported functions for handling nodes.
+
+(defgeneric concatenate-node-lists (lhs rhs)
+ (:method ((lhs node) (rhs null))
+ lhs)
+ (:method ((lhs null) (rhs node))
+ rhs)
+ (:method ((lhs node) (rhs node))
+ (with-slots ((lhs-next next)
+ (lhs-last last)
+ (lhs-item item)) lhs
+ (with-slots ((rhs-next next)
+ (rhs-last last)
+ (rhs-item item)) rhs
+ (format t "~C~CHave got ~A and ~A~%" #\tab #\tab lhs rhs)
+ (psetf (node-next (node-last lhs)) rhs
+ (node-last rhs) (node-last lhs)
+ (node-next (node-last rhs)) lhs
+ (node-last lhs) (node-last rhs))))
+ (format t "~C~Cconcat to ~A (other is ~A)~%" #\tab #\tab lhs rhs)
+ lhs))
+
+(defgeneric make-node-single (node)
+ (:documentation "Make the node point to a list with only itself as a member.")
+ (:method ((node node))
+ (with-slots (next last) node
+ (setf next node
+ last node))
+ node))
+
+(defgeneric delete-node (node)
+ (:documentation "Deletes this node from the linked list that it
+ represents, and returns the new list.")
+ (:method ((node null))
+ nil)
+ (:method ((node node))
+ (with-slots (next last) node
+ (let ((result next))
+ (cond
+ ((eq next node) ;Only a single thing in this list, itself.
+ nil)
+ (t
+ (psetf (node-last next) last
+ (node-next last) next
+ next node
+ last node)
+ result))))))
+
+
+
+(defmacro do-each-node ((symbol node) &body body)
+ (let ((node node)
+ (last (gensym))
+ (next (gensym)))
+ `(loop
+ with ,last = (node-last ,node)
+ for ,symbol = ,node then ,next
+ for ,next = (node-next ,node) then (node-next ,next)
+ while (not (eq ,symbol ,last))
+ do (progn
+ ,@body)
+ finally (progn
+ ,@body))))
+
+
+;;;--------------------
+;;; Unexported functions
+
+(defgeneric meld (one two)
+ (:documentation "Joins together two fibonacci heaps."))
+
+(defmethod meld ((heap fibonacci-heap) (item node))
+ "Adds a node to the heap."
+ (with-slots (root) heap
+ (cond
+ ((null root)
+ (setf root item))
+ ((compare-items heap (node-item root) (node-item item))
+ (setf root (concatenate-node-lists root item)))
+ (t
+ (setf root (concatenate-node-lists item root)))))
+ heap)
+
+(defgeneric link (heap node-one node-two)
+ (:documentation "Places node-two as a child of node-one if
+ node-one's item is smaller, or vice versa.")
+ (:method ((heap fibonacci-heap) (node-one node) (node-two node))
+ (with-slots ((one-child child)
+ (one-item item)
+ (one-rank rank)) node-one
+ (with-slots ((two-child child)
+ (two-item item)
+ (two-rank rank)) node-two
+ (cond
+ ((compare-items heap one-item two-item)
+ (delete-node node-two)
+ (setf one-child (concatenate-node-lists one-child node-two))
+ (setf one-rank (max one-rank (1+ two-rank)))
+ (format t "Have linked ~A and ~A~%" node-one node-two)
+ node-one)
+ (t
+ (delete-node node-one)
+ (setf two-child (concatenate-node-lists two-child node-one))
+ (setf two-rank (max two-rank (1+ one-rank)))
+ (format t "Have linked ~A and ~A~%" node-two node-one)
+ node-two))))))
+
+;;;----------------------------------------------------------------
+;;; Exported Functions
+
+(defmethod empty-heap ((heap fibonacci-heap))
+ (with-slots (root count) heap
+ (setf root nil
+ count 0))
+ heap)
+
+(defmethod is-empty-heap-p ((heap fibonacci-heap))
+ (unless (slot-value heap 'root)
+ t))
+
+(defmethod heap-size ((heap fibonacci-heap))
+ (slot-value heap 'count))
+
+(defmethod add-to-heap ((heap fibonacci-heap) item)
+ "Adds an item to a Fibonacci-heap. This is a constant time
+oepration. Returns the item added to the heap."
+ (meld heap (make-instance 'node :item item))
+ (incf (slot-value heap 'count))
+ item)
+
+(defmethod add-all-to-heap ((heap fibonacci-heap) (items list))
+ (with-slots (count) heap
+ (loop for i in items
+ do (progn
+ (meld heap (make-instance 'node :item i))
+ (incf count))))
+ heap)
+
+(defmethod peep-at-heap ((heap fibonacci-heap))
+ (with-slots (root) heap
+ (when root
+ (node-item root))))
+
+(defmethod pop-heap ((heap fibonacci-heap))
+ (unless (is-empty-heap-p heap)
+ (let ((item (peep-at-heap heap)))
+ (with-slots (root) heap
+ ;; Delete the minimum.
+ (concatenate-node-lists root (node-child root))
+ (setf root (delete-node root))
+ (when root
+ (let ((ranks (make-array 50 :initial-element nil))
+ (min nil))
+ ;; Merge all trees of the same rank.
+ (labels ((sort-node (node)
+ (let ((position (node-rank node)))
+ (format t "Looking at ~A in position ~A~%" node position)
+ (cond
+ ((aref ranks position)
+ (format t "~CBut ~a is there already.~%"
+ #\Tab (aref ranks position))
+ (let ((new (link heap node (aref ranks position))))
+ (setf (aref ranks position) nil)
+ (sort-node new)))
+ (t
+ (format t "placing in ~A~%" position)
+ (setf (aref ranks position) node))))))
+ (do-each-node (node root)
+ (format t "Loop!~%")
+ (sort-node node)))
+ (format t "Ranks ~a~%" ranks)
+ (loop for tree across ranks
+ do (when (not (null tree))
+ (cond
+ ((null min)
+ (format t "init min to ~A~%" tree)
+ (setf min tree))
+ ((compare-items heap
+ (node-item min)
+ (node-item tree))
+ (format t "Setting min to ~A (1)~%" tree)
+ (setf min (concatenate-node-lists min tree)))
+ (t
+ (format t "Setting min to ~A (2)~%" tree)
+ (setf min (concatenate-node-lists tree min))))))
+ (format t "Have root ~A and min ~A~%" root min)
+ (setf root min)))
+ (decf (slot-value heap 'count))
+ item))))
View
118 heap.lisp
@@ -0,0 +1,118 @@
+;;; Copyright 2009 Rudolph Neeser <rudy.neeser@gmail.com>.
+;;;
+;;; This file is part of CL-HEAP
+;;;
+;;; CL-HEAP is free software: you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; CL-HEAP is distributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with CL-HEAP. If not, see <http://www.gnu.org/licenses/>.
+
+;;;----------------------------------------------------------------
+
+(in-package #:cl-heap)
+
+;;;--------------------------------------------------------------------
+;;; Some useful definitions: Through the use of SORT-FUN, each HEAP
+;;; can be used as either a min or a max heap, or even as something
+;;; abstract by defining an arbitrary total relation on the objects
+;;; being inserted into the heap. For any relation R and two items x
+;;; and y for which x R y is a true, we will call x the lesser of the
+;;; two items.
+;;; --------------------------------------------------------------------
+
+(defclass heap ()
+ ((sort-fun :initform #'<
+ :reader heap-sorting-function
+ :initarg :sort-fun
+ :documentation "The function used to apply an order to
+ elements in the heap.")
+ (key :initform #'identity
+ :reader heap-key
+ :initarg :key
+ :documentation "A function used to obtain the elements which
+ should be compared to give an order to the items in the
+ heap."))
+ (:documentation "The base type of the two HEAP implementations."))
+
+;;;--------------------------------------------------------------------
+;;; Exported functions.
+
+(defgeneric heap-size (heap)
+ (:documentation "Returns the number of elements in the heap."))
+
+(defgeneric add-to-heap (heap item)
+ (:documentation "Inserts an item into the given HEAP data
+ structure. Returns two values: first, the item added, and then an
+ index-key which can be used to identify the item for DECREASE-KEY
+ and DELETE-FROM-HEAP operations."))
+
+
+(defgeneric add-all-to-heap (heap items)
+ (:documentation "Adds a list of items to a HEAP. This can typically
+ be done more efficiently than by using repeated calls to
+ ADD-TO-HEAP, since the heap order only needs to be reinstated after
+ all of the items have been inserted, rather than maintained through
+ each operation. Returns the heap object."))
+
+(defgeneric peep-at-heap (heap)
+ (:documentation "Returns the heap's root, without modifying the
+ heap. Returns nil if the heap is empty."))
+
+(defgeneric pop-heap (heap)
+ (:documentation "Removes the top element from the heap and returns
+ it."))
+
+(defgeneric empty-heap (heap)
+ (:documentation "Removes all contents from the given heap. Returns the heap."))
+
+(defgeneric is-empty-heap-p (heap)
+ (:documentation "Returns true iff the given heap is empty."))
+
+(defgeneric merge-heaps (first second)
+ (:documentation "Returns a new heap that is the merged copy of those
+ given here. Can only merge heaps which use the same key and sorting
+ function. The two arguments are nt modified by this function."))
+
+(defgeneric nmerge-heaps (first second)
+ (:documentation "Destructively updates the arguments to contain the
+ merge of both heaps, which is then returned. Can only merge heaps
+ which use the same key and sorting function."))
+
+(defgeneric decrease-key (heap item-index value)
+ (:documentation "Decreases the value of the item represented by
+ ITEM-INDEX. ITEM-INDEX is the index returned by ADD-TO-HEAP for a
+ particular item. VALUE is the item's new value, and this must be
+ \"less\" than its old value. Returns the heap."))
+
+
+(defgeneric delete-from-heap (heap item-index)
+ (:documentation "Removes the item from the heap represented by the
+ ITEM-INDEX. This index is returned as the second value of
+ ADD-TO-HEAP. Returns the heap."))
+
+;;;--------------------------------------------------------------------
+;;; Unexported functions
+
+(defgeneric compare-items (heap parent child)
+ (:documentation "Compares two items, using the HEAP's SORT-FUN and
+ KEY functions.")
+ (:method ((heap heap) parent child)
+ (with-slots (sort-fun key) heap
+ (funcall sort-fun (funcall key parent) (funcall key child)))))
+
+;;;--------------------------------------------------------------------
+;;; Various implementation details
+
+(defmethod print-object ((heap heap) stream)
+ (print-unreadable-object (heap stream :type t :identity t)
+ (with-slots (key sort-fun) heap
+ (format stream "Size: ~A" (heap-size heap)))))
+
View
51 package.lisp
@@ -0,0 +1,51 @@
+;;; Copyright 2009 Rudolph Neeser <rudy.neeser@gmail.com>
+;;;
+;;; This file is part of CL-HEAP
+;;;
+;;; CL-HEAP is free software: you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; CL-HEAP is distributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with CL-HEAP. If not, see <http://www.gnu.org/licenses/>.
+
+;;;----------------------------------------------------------------
+
+(defpackage #:cl-heap
+ (:use #:common-lisp)
+ (:export #:heap
+ #:binary-heap
+ #:fibonacci-heap
+ #:heap-key
+ #:heap-sorting-function
+ #:add-to-heap
+ #:add-all-to-heap
+ #:peep-at-heap
+ #:pop-heap
+ #:heap-size
+ #:empty-heap
+ #:is-empty-heap-p
+ #:merge-heaps
+ #:nmerge-heaps
+ #:decrease-key
+ #:delete-from-heap
+ #:binary-heap-extension-factor
+ #:priority-queue
+ #:empty-queue
+ #:queue-size
+ #:peep-at-queue
+ #:dequeue
+ #:enqueue
+ #:heap-error
+ #:key-error
+ #:fibonacci-test
+ #:binary-test
+ #:priority-queue-test)
+ (:documentation "An implementation of heap and priority queue data structures."))
+
View
72 priority-queue.lisp
@@ -0,0 +1,72 @@
+;;; Copyright 2009 Rudolph Neeser <rudy.neeser@gmail.com>
+;;;
+;;; This file is part of CL-HEAP
+;;;
+;;; CL-HEAP is free software: you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; CL-HEAP is distributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with CL-HEAP. If not, see <http://www.gnu.org/licenses/>.
+
+;;;----------------------------------------------------------------
+
+(in-package #:cl-heap)
+
+;;;----------------------------------------------------------------
+
+(defclass priority-queue ()
+ ((heap))
+ (:documentation "A simple priority queue implementaiton, based on a
+ Fibonacci heap."))
+
+(defmethod initialize-instance :after ((queue priority-queue) &key (sort-fun #'<))
+ (with-slots (heap) queue
+ (setf heap (make-instance 'fibonacci-heap :key #'first :sort-fun sort-fun))))
+
+;;;----------------------------------------------------------------
+
+(declaim (inline enqueue))
+(defgeneric enqueue (queue item priority)
+ (:documentation "Adds an item with a given priority on to the
+ queue. Returns a list containing first the priority, then the
+ item. This is a constant time operation.")
+ (:method ((queue priority-queue) item priority)
+ (with-slots (heap) queue
+ (values (add-to-heap heap (list priority item))))))
+
+(declaim (inline dequeue))
+(defgeneric dequeue (queue)
+ (:documentation "Removes an element from the front of the queue and
+ returns it. This is an amortised O(log(n)) operation.")
+ (:method (queue)
+ (with-slots (heap) queue
+ (second (pop-heap heap)))))
+
+(declaim (inline peep-at-queue))
+(defgeneric peep-at-queue (queue)
+ (:documentation "Returns the element at the front of the queue,
+ without modifying the queue. This is a constant time operation.")
+ (:method ((queue priority-queue))
+ (with-slots (heap) queue
+ (second (peep-at-heap heap)))))
+
+(declaim (inline empty-queue))
+(defgeneric empty-queue (queue)
+ (:documentation "Removes all items from the queue. This is a constant time operation.")
+ (:method ((queue priority-queue))
+ (with-slots (heap) queue
+ (empty-heap heap))))
+
+(declaim (inline queue-size))
+(defgeneric queue-size (queue)
+ (:documentation "Returns the number of elements in the queue.")
+ (:method ((queue priority-queue))
+ (with-slots (heap) queue
+ (heap-size heap))))
View
367 tests.lisp
@@ -0,0 +1,367 @@
+;;; Copyright 2009 Rudolph Neeser <rudy.neeser@gmail.com>
+;;;
+;;; This file is part of CL-HEAP
+;;;
+;;; CL-HEAP is free software: you can redistribute it and/or modify
+;;; it under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation, either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; CL-HEAP is distributed in the hope that it will be useful,
+;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;;; GNU General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with CL-HEAP. If not, see <http://www.gnu.org/licenses/>.
+
+;;;----------------------------------------------------------------
+
+(in-package #:cl-heap)
+
+;;;----------------------------------------------------------------
+;;; Some general test functionss.
+
+(defun test-merging (test-object heap-type)
+ (with-slots (heap) test-object
+ (let ((heap2 (make-instance heap-type)))
+ (add-all-to-heap heap2 '(4 1 5 3 6 2 7))
+ (add-all-to-heap heap '(11 9 12 8 10 13))
+ (let ((merged (merge-heaps heap heap2)))
+ ;; Ensure that all three heaps still exist.
+ (loop for i from 1 to 13 do (xlunit:assert-equal i (pop-heap merged)))
+ (loop for i from 1 to 7 do (xlunit:assert-equal i (pop-heap heap2)))
+ (loop for i from 8 to 13 do (xlunit:assert-equal i (pop-heap heap)))))
+ (let ((max-heap (make-instance heap-type :sort-fun #'>))
+ (empty-heap (make-instance heap-type)))
+ ;; Assert that a condition is thrown when the heaps differ in
+ ;; key functions.
+ (add-all-to-heap max-heap '(5 6 7 8))
+ (add-all-to-heap heap '(1 2 3 4))
+ (xlunit:assert-condition 'heap-error (merge-heaps heap max-heap))
+ ;; Ensure that nothing happens when merging empty heaps.
+ (merge-heaps heap empty-heap)
+ (merge-heaps empty-heap heap)
+ (merge-heaps empty-heap empty-heap))
+ ;; Ensure that destructive merging works.
+ (let ((heap2 (make-instance heap-type)))
+ (add-all-to-heap heap2 '(4 1 5 3 6 2 7))
+ (empty-heap heap)
+ (add-all-to-heap heap '(11 9 12 8 10 13))
+ (let ((merged (nmerge-heaps heap heap2)))
+ ;; Ensure that all three heaps still exist.
+ (loop for i from 1 to 13
+ do (xlunit:assert-equal i (pop-heap merged)))))))
+
+(defun test-empty (test)
+ (with-slots (heap) test
+ (xlunit:assert-eql 0 (heap-size heap))
+ (add-to-heap heap 1)
+ (xlunit:assert-eql 1 (heap-size heap))
+ (empty-heap heap)
+ (xlunit:assert-eql 0 (heap-size heap))))
+
+(defun test-adding (test)
+ (with-slots (heap) test
+ (xlunit:assert-eql 0 (heap-size heap))
+ (add-all-to-heap heap '(3 7 1 8 2 6 9 4 10 5))
+ (xlunit:assert-eql 10 (heap-size heap))
+ (xlunit:assert-eql 1 (peep-at-heap heap))
+ (xlunit:assert-eql 10 (heap-size heap))
+ (loop for i from 1 to 10
+ do (xlunit:assert-eql i (pop-heap heap)))))
+
+;;;----------------------------------------------------------------
+
+;;; This class just does some sanity testing with the priority
+;;; queue. The priority queue is just a fibonacci heap, and so most of
+;;; the testing will be done for that class.
+(defclass priority-queue-test (xlunit:test-case)
+ (queue))
+
+(defmethod xlunit:set-up ((test priority-queue-test))
+ (with-slots (queue) test
+ (setf queue (make-instance 'priority-queue))))
+
+(defmethod xlunit:tear-down ((test priority-queue-test))
+ (with-slots (queue) test
+ (empty-queue queue)
+ (setf queue nil)))
+
+;;;----------------------------------------------------------------
+
+(xlunit:def-test-method order-test ((test priority-queue-test))
+ "A trivial test to just ensure some sanity with the priority queue."
+ (with-slots (queue) test
+ (enqueue queue 'test 15)
+ (enqueue queue 'this -5)
+ (enqueue queue 'a 10)
+ (enqueue queue 'is 5)
+
+ (xlunit:assert-equal (dequeue queue) 'this)
+ (xlunit:assert-equal (dequeue queue) 'is)
+ (xlunit:assert-equal (dequeue queue) 'a)
+ (xlunit:assert-equal (dequeue queue) 'test)))
+
+;;;----------------------------------------------------------------
+;;;----------------------------------------------------------------
+
+(defclass fibonacci-test (xlunit:test-case)
+ (heap
+ node1
+ node2))
+
+(defmethod xlunit:set-up ((test fibonacci-test))
+ (with-slots (heap node1 node2) test
+ (setf heap (make-instance 'fibonacci-heap))
+ (setf node1 (make-instance 'node :item 1))
+ (setf node2 (make-instance 'node :item 'a))
+ (concatenate-node-lists node1 (make-instance 'node :item 4))
+ (concatenate-node-lists node1 (make-instance 'node :item 3))
+ (concatenate-node-lists node1 (make-instance 'node :item 2))
+ (concatenate-node-lists node2 (make-instance 'node :item 'd))
+ (concatenate-node-lists node2 (make-instance 'node :item 'c))
+ (concatenate-node-lists node2 (make-instance 'node :item 'b))))
+
+(defmethod xlunit:tear-down ((test fibonacci-test))
+ (with-slots (heap node1 node2) test
+ (empty-heap heap)
+ (setf heap nil
+ node1 nil
+ node2 nil)))
+
+;;;----------------------------------------------------------------
+
+(xlunit:def-test-method test-size ((test fibonacci-test))
+ "Ensures that the heap's size makes sense as items are added and
+removed."
+ (with-slots (heap) test
+ (loop for i from 1 upto 1000
+ do
+ (add-to-heap heap (random 10000))
+ (xlunit:assert-equal (heap-size heap) i))
+ (pop-heap heap)
+ (xlunit:assert-equal (heap-size heap) 999)
+ (loop for i from 998 downto 0
+ do
+ (pop-heap heap)
+ (xlunit:assert-equal (heap-size heap) i))))
+
+(xlunit:def-test-method test-node-lists ((test fibonacci-test))
+ "Ensures that the nodes in a heap act as circular lists."
+ (with-slots (node1 node2) test
+ (xlunit:assert-equal (node-item node1) 1)
+ (xlunit:assert-equal (node-item (node-next node1)) 2)
+ (xlunit:assert-equal (node-item (node-next (node-next node1))) 3)
+ (xlunit:assert-equal (node-item (node-next (node-next (node-next node1)))) 4)
+ (xlunit:assert-equal (node-item (node-next (node-next (node-next (node-next node1))))) 1)
+
+ (xlunit:assert-equal (node-item (node-last node1)) 4)
+ (xlunit:assert-equal (node-item (node-last (node-last node1))) 3)
+ (xlunit:assert-equal (node-item (node-last (node-last (node-last node1)))) 2)
+ (xlunit:assert-equal (node-item (node-last (node-last (node-last (node-last node1))))) 1)
+
+ (concatenate-node-lists node1 node2)
+ (loop
+ for answer in '(1 a b c d 2 3 4)
+ for actual = node1 then (node-next actual)
+ for i from 1 to 10
+ do
+ (xlunit:assert-equal answer (node-item actual)))
+ (xlunit:assert-equal 4 (node-item (node-last node1)))))
+
+(xlunit:def-test-method test-node-deletes ((test fibonacci-test))
+ "Ensures that the nodes have things properly deleted."
+ (with-slots (node1) test
+ (let ((second (node-next node1)))
+ (delete-node second)
+ (do-each-node (n node1)
+ (xlunit:assert-not-eql n second))
+ (setf (node-child node1) (make-instance 'node :item 10)
+ (node-rank node1) 1
+ (node-parent (node-child node1)) node1)
+ (delete-node (node-child node1))
+ (xlunit:assert-equal 0 (node-rank node1)))))
+
+(xlunit:def-test-method test-iteration ((test fibonacci-test))
+ "Ensures that a node list can be iterated through, while having items removed."
+ (with-slots (node1) test
+ (let ((items (list 1 2 3 4)))
+ (do-each-node (n node1)
+ (xlunit:assert-equal (pop items) (node-item n))
+ (delete-node n))
+ (xlunit:assert-true (null items)))))
+
+(xlunit:def-test-method test-iteration-null ((test fibonacci-test))
+ "Ensures that we do not attempt to iterate on nil, which would give
+an error."
+ (do-each-node (child nil)
+ nil))
+
+(xlunit:def-test-method test-delete ((test fibonacci-test))
+ (with-slots (heap) test
+ (let ((keys (loop for i in '(0 1 3 2 4 5)
+ collect (second (multiple-value-list (add-to-heap heap i))))))
+ (pop-heap heap)
+ (pop keys)
+ ;; test deleting the min.
+ (delete-from-heap heap (pop keys))
+ (xlunit:assert-equal (peep-at-heap heap) 2)
+ ;; Delete the non-min item.
+ (delete-from-heap heap (pop keys))
+ (xlunit:assert-equal 2 (pop-heap heap))
+ (xlunit:assert-equal 4 (pop-heap heap))
+ (xlunit:assert-equal 5 (pop-heap heap)))))
+
+
+(xlunit:def-test-method test-cascade ((test fibonacci-test))
+ "Ensures that cascading cuts occur as required. Builds up a tree and
+goes through it, testing everything's rank. Then removes some items
+and retests the ranks."
+ (with-slots (heap) test
+ (add-all-to-heap heap (loop for i from 1 upto 20 collect i))
+ (xlunit:assert-eql 1 (pop-heap heap))
+ (with-slots (root) heap
+ (xlunit:assert-equal (node-rank root) 0)
+ (xlunit:assert-equal (node-rank (node-next root)) 4)
+ (xlunit:assert-equal (node-rank (node-next (node-next root))) 1)
+ (delete-from-heap heap
+ (node-child (node-next (node-child (node-next root)))))
+ (delete-from-heap heap
+ (node-child (node-child
+ (node-next
+ (node-child (node-next root))))))
+ (delete-from-heap heap
+ (node-child (node-child (node-next (node-child (node-next root))))))
+ (xlunit:assert-equal (node-rank root) 0)
+ (xlunit:assert-equal (node-rank (node-next root)) 1)
+ (xlunit:assert-equal (node-rank (node-next (node-next root))) 0)
+ (xlunit:assert-equal (node-rank (node-next (node-next (node-next root)))) 0)
+ (xlunit:assert-equal (node-rank
+ (node-next (node-next (node-next (node-next root))))) 3)
+ (xlunit:assert-equal (node-rank
+ (node-next (node-next
+ (node-next (node-next (node-next root)))))) 1))))
+
+(xlunit:def-test-method test-decrease-key ((test fibonacci-test))
+ (with-slots (heap) test
+ (let ((keys (loop for i in '(2 3 4 1 5 6)
+ collect (multiple-value-bind (val key) (add-to-heap heap i)
+ (declare (ignore val))
+ key))))
+ ;; Check that decreasing a key in the root lists works.
+ (decrease-key heap (pop keys) 0)
+ (xlunit:assert-equal (pop-heap heap) 0)
+ ;; Testing for when we have a parent
+ (decrease-key heap (pop keys) 0)
+ (xlunit:assert-equal (pop-heap heap) 0)
+ ;; Test for errors
+ (xlunit:assert-condition 'key-error (decrease-key heap (pop keys) 5))
+ (xlunit:assert-equal (pop-heap heap) 1)
+ ;; Test for when a non IDENTITY KEY is used.
+ (let ((heap (make-instance 'fibonacci-heap :key #'(lambda (item &optional val)
+ (if val
+ (setf (first item) val)
+ (first item))))))
+ (let ((keys (loop for i in (list (list 4 'a) (list 1 'b) (list 3 'c))
+ collect (multiple-value-bind (val key) (add-to-heap heap i)
+ (declare (ignore val))
+ key))))
+ (force-output)
+ (decrease-key heap (first keys) -1)
+ (xlunit:assert-equal (second (pop-heap heap)) 'a)))
+ ;; Test that an error is thrown from decrease-key
+ (let* ((heap (make-instance 'fibonacci-heap :key #'first))
+ (key (second (multiple-value-list (add-to-heap heap '(1 a))))))
+ (xlunit:assert-condition 'key-error (decrease-key heap key 0))))))
+
+(xlunit:def-test-method test-merge ((test fibonacci-test))
+ (test-merging test 'fibonacci-heap))
+
+(xlunit:def-test-method test-adding ((test fibonacci-test))
+ (test-adding test))
+
+(xlunit:def-test-method test-empty ((test fibonacci-test))
+ (test-empty test))
+
+
+;;;----------------------------------------------------------------
+;;;----------------------------------------------------------------
+
+(defclass binary-test (xlunit:test-case)
+ (heap))
+
+(defmethod xlunit:set-up ((test binary-test))
+ (with-slots (heap) test
+ (setf heap (make-instance 'binary-heap))))
+
+(defmethod xlunit:tear-down ((test binary-test))
+ (with-slots (heap) test
+ (setf heap nil)))
+
+;;;----------------------------------------------------------------
+
+(xlunit:def-test-method test-positions ((test binary-test))
+ "Tests the functions which determine where in the array the children
+and parents are."
+ ;; This tests some parent sanity checks.
+ (xlunit:assert-eql 0 (parent-position 1))
+ (xlunit:assert-eql 0 (parent-position 2))
+ (xlunit:assert-eql 1 (parent-position 3))
+ ;; Now we just check that the values of calculate child and parent positions agree.
+ (loop for i from 0 to 100
+ do (multiple-value-bind (left right)
+ (children-positions i)
+ (xlunit:assert-eql i (parent-position left))
+ (xlunit:assert-eql i (parent-position right)))))
+
+(xlunit:def-test-method test-adding-popping ((test binary-test))
+ (test-adding test))
+
+(xlunit:def-test-method test-empty ((test binary-test))
+ (test-empty test))
+
+(xlunit:def-test-method test-merge ((test binary-test))
+ (test-merging test 'binary-heap))
+
+(xlunit:def-test-method test-decrease-key ((test binary-test))
+ (with-slots (heap) test
+ (let* ((to-add '(1 2 3 4 5 6))
+ (keys (loop for i in to-add
+ collect (multiple-value-bind (val key) (add-to-heap heap i)
+ (declare (ignore val))
+ key))))
+ ;; Check that decreasing a key in the root lists works.
+ (decrease-key heap (pop keys) -1)
+ (xlunit:assert-equal (pop-heap heap) -1)
+ ;; Testing for when we have a parent
+ (empty-heap heap)
+ (add-all-to-heap heap to-add)
+ (decrease-key heap (pop keys) -1)
+ (xlunit:assert-equal (pop-heap heap) -1)
+ ;; Test for errors
+ (empty-heap heap)
+ (add-all-to-heap heap to-add)
+ (xlunit:assert-condition 'key-error (decrease-key heap (pop keys) 5))
+ (xlunit:assert-equal (pop-heap heap) 1)
+ ;; Test for when a non IDENTITY KEY is used.
+ (let* ((heap (make-instance 'binary-heap :key #'(lambda (item &optional val)
+ (if val
+ (setf (first item) val)
+ (first item))))))
+ (add-all-to-heap heap (list (list 2 'a) (list 1 'b) (list 3 'c)))
+ (xlunit:assert-equal (second (pop-heap heap)) 'b))
+ ;; Test that an error is thrown from decrease-key
+ (let* ((heap (make-instance 'binary-heap :key #'first))
+ (key (second (multiple-value-list (add-to-heap heap '(1 a))))))
+ (xlunit:assert-condition 'key-error (decrease-key heap key 0))))))
+
+(xlunit:def-test-method test-delete ((test binary-test))
+ (with-slots (heap) test
+ (add-all-to-heap heap '( 1 2 3 4 5 6))
+ (delete-from-heap heap 0)
+ (loop for i from 2 to 6 do (xlunit:assert-equal (pop-heap heap) i))))
+
+
+;;;----------------------------------------------------------------
+;;;----------------------------------------------------------------
Please sign in to comment.