{"id":95155,"date":"2017-01-10T07:00:00","date_gmt":"2017-01-10T22:00:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/oldnewthing\/?p=95155"},"modified":"2023-09-05T16:05:15","modified_gmt":"2023-09-05T23:05:15","slug":"20170110-00","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20170110-00\/?p=95155","title":{"rendered":"Applying a permutation to a vector, part 5"},"content":{"rendered":"<p>Our <a href=\"https:\/\/blogs.msdn.microsoft.com\/oldnewthing\/20170102-00\/?p=95095\"> <code>apply_<wbr \/>permutation<\/code> function<\/a> assumes that the integers form a valid permutation. Let&#8217;s add error checking.<\/p>\n<p>There are two ways the integers could fail to be a permutation: One is that the collection includes a value that is out of range. The other problem case is that all the values are in range, but a value appears more than once. We can detect that when we encounter a single-element cycle when we expected a longer cycle. (Another way of looking at it is that we detect the error when we discover that we&#8217;re about to move an item for the second time, because the permutation application algorithm is supposed to move each item only once.)<\/p>\n<pre>template&lt;typename Iter1, typename Iter2&gt;\r\nvoid\r\napply_permutation(\r\n    Iter1 first,\r\n    Iter1 last,\r\n    Iter2 indices)\r\n{\r\n using T = typename std::iterator_traits&lt;Iter1&gt;::value_type;\r\n using Diff = typename std::iterator_traits&lt;Iter2&gt;::value_type;\r\n Diff length = std::distance(first, last);\r\n for (Diff i = 0; i &lt; length; i++) {\r\n  Diff current = i;\r\n  while (i != indices[current]) {\r\n   Diff next = indices[current];\r\n   <span style=\"border: solid 1px currentcolor; border-bottom: none;\">if (next &lt; 0 || next &gt;= length) {                       <\/span>\r\n   <span style=\"border: 1px currentcolor; border-style: none solid;\"> throw std::range_error(\"Invalid index in permutation\");<\/span>\r\n   <span style=\"border: 1px currentcolor; border-style: none solid;\">}                                                       <\/span>\r\n   <span style=\"border: 1px currentcolor; border-style: none solid;\">if (next == current) {                                  <\/span>\r\n   <span style=\"border: 1px currentcolor; border-style: none solid;\"> throw std::range_error(\"Not a permutation\");           <\/span>\r\n   <span style=\"border: solid 1px currentcolor; border-top: none;\">}                                                       <\/span>\r\n   swap(first[current], first[next]);\r\n   indices[current] = current;\r\n   current = next;\r\n  }\r\n  indices[current] = current;\r\n }\r\n}\r\n<\/pre>\n<p>(I added the <code>typename<\/code> keyword at the suggestion of commenter ildjarn. And I used <code>std::distance<\/code> to calculate the distance between two iterators. The second change was not technically necessary because <code>std::distance<\/code> is defined as subtraction when the iterators are random-access, but if you&#8217;re going to go with the standard library, you may as well go all the way, right?)<\/p>\n<p>I switched to the swapping version of the algorithm because that allows me to ensure a useful exit condition in the case of exception: If an exception occurs, the elements in <code>[first, last)<\/code> have been permuted in an unspecified manner. Even though the resulting order is unspecified, you at least know that no items were lost. It&#8217;s the same set of items, just in some other order. The indices, on the other hand, are left in an unspecified state. They won&#8217;t be a permutation of the original indices.<\/p>\n<p>But wait, we can even restore the <code>indices<\/code> to a permutation of their former selves:\u00b9 We can take the duplicate index and drop it back into <code>indices[i]<\/code>. That entry optimistically was set to the value we expected to find when we reached the end of the cycle. If we never find that value, then we can put the value we actually found into that slot, thereby correcting our optimistic assumption.<\/p>\n<pre>template&lt;typename Iter1, typename Iter2&gt;\r\nvoid\r\napply_permutation(\r\n    Iter1 first,\r\n    Iter1 last,\r\n    Iter2 indices)\r\n{\r\n using T = typename std::iterator_traits&lt;Iter1&gt;::value_type;\r\n using Diff = typename std::iterator_traits&lt;Iter2&gt;::value_type;\r\n Diff length = std::distance(first, last);\r\n for (Diff i = 0; i &lt; length; i++) {\r\n  Diff current = i;\r\n  while (i != indices[current]) {\r\n   Diff next = indices[current];\r\n   if (next &lt; 0 || next &gt;= length) {\r\n    <span style=\"border: solid 1px currentcolor;\">indices[i] = next;<\/span>\r\n    throw std::range_error(\"Invalid index in permutation\");\r\n   }\r\n   if (next == current) {\r\n    <span style=\"border: solid 1px currentcolor;\">indices[i] = next;<\/span>\r\n    throw std::range_error(\"Not a permutation\");\r\n   }\r\n   swap(first[current], first[next]);\r\n   indices[current] = current;\r\n   current = next;\r\n  }\r\n  indices[current] = current;\r\n }\r\n}\r\n<\/pre>\n<p>\u00b9 This is valuable because it improves post-mortem debuggability: You can inspect the <code>indices<\/code> to look for the out-of-range or duplicate index.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Error checking.<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-95155","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>Error checking.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/95155","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=95155"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/95155\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=95155"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=95155"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=95155"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}