{"id":10771,"date":"2016-08-17T10:40:41","date_gmt":"2016-08-17T10:40:41","guid":{"rendered":"http:\/\/www.lexicalscope.com\/blog\/?p=10771"},"modified":"2018-01-15T15:39:57","modified_gmt":"2018-01-15T15:39:57","slug":"java-code-for-generating-permutations-of-a-list-using-heaps-algorithm","status":"publish","type":"post","link":"https:\/\/www.lexicalscope.com\/blog\/2016\/08\/17\/java-code-for-generating-permutations-of-a-list-using-heaps-algorithm\/","title":{"rendered":"Java code for generating permutations of a list using Heap&#8217;s algorithm"},"content":{"rendered":"<p>Java code for generating permutations of a list using Heap&#8217;s algorithm.<\/p>\n<pre lang=\"java\">\r\n\/**\r\n * Uses Heap's algorithm to produce all permutations of a given list.\r\n * We use an iterator to avoid having to use too much memory.\r\n *\r\n * @author t.wood\r\n *\r\n * Copyright 2016 Tim Wood\r\n *\r\n * Permission is hereby granted, free of charge, to any person \r\n * obtaining a copy of this software and associated documentation \r\n * files (the \"Software\"), to deal in the Software without restriction,\r\n * including without limitation the rights to use, copy, modify, merge,\r\n * publish, distribute, sublicense, and\/or sell copies of the Software,\r\n * and to permit persons to whom the Software is furnished to do so, \r\n * subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be \r\n * included in all copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\r\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \r\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE \r\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n * \r\n * @param <T> The type of item being permuted\r\n * @param <R> The type resulting from decorating the permutation\r\n *\/\r\npublic final class PermutationIterator<T,R> implements Iterator<R> {\r\n    private final Function<List<T>, R> defensiveDecorator;\r\n    private final List<T> a;\r\n    private R pending;\r\n\r\n    private final int[] skel;\r\n    private int i;\r\n\r\n    \/**\r\n     * An iterator of permutations\r\n     *\r\n     * @param a the list to permute\r\n     * @param decorator a decorator to apply to the permutation, a defensive copy\r\n     *                  of the permutation is taken before it is passed to the decorator\r\n     *\/\r\n    public PermutationIterator(final List<T> a, final Function<List<T>,R> decorator) {\r\n        defensiveDecorator = t -> decorator.apply(new ArrayList<>(t));\r\n        pending = defensiveDecorator.apply(a);\r\n        this.a = new ArrayList<>(a);\r\n        skel = new int[a.size()];\r\n        i = 0;\r\n    }\r\n\r\n    @Override public boolean hasNext() {\r\n        return pending != null;\r\n    }\r\n\r\n    @Override public R next() {\r\n        if(pending == null) {\r\n            throw new IndexOutOfBoundsException();\r\n        }\r\n        final R result = pending;\r\n        pending = permute();\r\n        return result;\r\n    }\r\n\r\n    private R permute() {\r\n        while(i < a.size()) {\r\n            if (skel[i] < i) {\r\n                if (even(i)) {\r\n                    swap(a, 0, i);\r\n                } else {\r\n                    swap(a, skel[i], i);\r\n                }\r\n                skel[i] += 1;\r\n                i = 0;\r\n                return defensiveDecorator.apply(a);\r\n            } else {\r\n                skel[i] = 0;\r\n                i += 1;\r\n            }\r\n        }\r\n        return null;\r\n    }\r\n\r\n    private void swap(final List<T> a, final int i0, final int i1) {\r\n        final T t = a.get(i0);\r\n        a.set(i0, a.get(i1));\r\n        a.set(i1, t);\r\n    }\r\n\r\n    private boolean even(final int i) {\r\n        return i % 2 == 0;\r\n    }\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Java code for generating permutations of a list using Heap&#8217;s algorithm. \/** * Uses Heap&#8217;s algorithm to produce all permutations of a given list. * We use an iterator to avoid having to use too much memory. * * @author &hellip; <a href=\"https:\/\/www.lexicalscope.com\/blog\/2016\/08\/17\/java-code-for-generating-permutations-of-a-list-using-heaps-algorithm\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[16],"tags":[],"class_list":["post-10771","post","type-post","status-publish","format-standard","hentry","category-algorithms"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p2e3P7-2NJ","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/posts\/10771","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/comments?post=10771"}],"version-history":[{"count":5,"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/posts\/10771\/revisions"}],"predecessor-version":[{"id":11105,"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/posts\/10771\/revisions\/11105"}],"wp:attachment":[{"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/media?parent=10771"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/categories?post=10771"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.lexicalscope.com\/blog\/wp-json\/wp\/v2\/tags?post=10771"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}