<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>0x &#187; Algorithms</title>
	<atom:link href="http://efesx.com/category/cpp/algorithms/feed/" rel="self" type="application/rss+xml" />
	<link>http://efesx.com</link>
	<description>Technical &#38; low level</description>
	<lastBuildDate>Mon, 30 Apr 2012 17:39:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Enumerating permutations</title>
		<link>http://efesx.com/2009/11/14/enumerating-permutations/</link>
		<comments>http://efesx.com/2009/11/14/enumerating-permutations/#comments</comments>
		<pubDate>Sat, 14 Nov 2009 09:59:18 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[Algorithms]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=597</guid>
		<description><![CDATA[There are exactly n! different permutations of n numbers. This challenge was about writing a function which is able to enumerate all these permutations, i.e. function permute(n, idx) which is able to return permutation with index idx of n numbers. The requirement is of course that all these permutations must be unique &#8211; this is [...]]]></description>
			<content:encoded><![CDATA[<p>There are exactly n! different permutations of n numbers. <a href="http://www.algorithm.co.il/blogs/index.php/programming/small-programming-challenge-no-5-generating-a-permutation/">This challenge</a> was about writing a function which is able to enumerate all these permutations, i.e. function permute(n, idx) which is able to return permutation with index idx of n numbers. The requirement is of course that all these permutations must be unique &#8211; this is in order to go over all possible permutations.</p>
<p><span id="more-597"></span>Here&#8217;s my solution to this problem, along with a test program:</p>
<pre class="brush: cpp; title: ; notranslate">#include &lt;set&gt;
#include &lt;string&gt;
#include &lt;vector&gt;
#include &lt;iostream&gt;
#include &lt;iterator&gt;
#include &lt;algorithm&gt;

// ---- generate permutation according to idx ----

std::vector&lt;unsigned&gt; permute (unsigned n, unsigned idx) {
    std::vector&lt;unsigned&gt; res(n);
    // I would love idx to be 1-based:
    idx += 1;
    // init the vector such that res[i]=i
    for (size_t i=0;i&lt;res.size();++i)
        res[i] = i;
    // now lets create the permutation
    for (unsigned curr=0;curr&lt;res.size();++curr) {
        std::swap(res[n-1-curr], res[idx % (n-curr)]);
        idx /= n-curr;
    }
    return res;
}

// ---- auxiliary, computes a factorial in compile time ----

template &lt;unsigned N&gt;
struct fact {
    static const unsigned result = N * fact&lt;N-1&gt;::result;
};

template &lt;&gt;
struct fact&lt;0&gt; {
    static const unsigned result = 1;
};

// ---- test program ----

int main () {
    const unsigned n = 5; // size we're checking

    std::set&lt;std::vector&lt;unsigned&gt; &gt; s;
    for (unsigned i=fact&lt;n&gt;::result;i;--i) {
        // compute current permutation
        std::vector&lt;unsigned&gt; v = permute(n, i);
        // print it
        std::copy(v.begin(), v.end(),
            std::ostream_iterator&lt;unsigned&gt;(std::cout, &quot; &quot;));
        std::cout &lt;&lt; std::endl;
        // verify uniqueness:
        if (s.find(v) != s.end()) {
            std::cout &lt;&lt; &quot;Dupe!&quot; &lt;&lt; std::endl;
            return 1;
        }
        s.insert(v);
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2009/11/14/enumerating-permutations/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Reset an array in constant time</title>
		<link>http://efesx.com/2009/11/05/reset-an-array-in-constant-time/</link>
		<comments>http://efesx.com/2009/11/05/reset-an-array-in-constant-time/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 21:56:26 +0000</pubDate>
		<dc:creator>rmn</dc:creator>
				<category><![CDATA[Algorithms]]></category>

		<guid isPermaLink="false">http://cplusplus.co.il/?p=562</guid>
		<description><![CDATA[Ever wondered how to reset an entire array of N elements in a constant slice of time? This post will introduce the algorithm along with an implementation. Let me lay out the problem. There&#8217;s an array of N integers. We would like to be able to reset that array (set all elements to zero), in [...]]]></description>
			<content:encoded><![CDATA[<p>Ever wondered how to reset an entire array of N elements in a constant slice of time? This post will introduce the algorithm along with an implementation.</p>
<p>Let me lay out the problem. There&#8217;s an array of N integers. We would like to be able to reset that array (set all elements to zero), in a set amount of time &#8211; regardless of the value of N. The reset operation should take the same amount of time whether it operates on 100 elements or 10,000 of them.</p>
<p><span id="more-562"></span>Like many other algorithms and data structures in computer science, we will require a little more allocated memory (3 times more, to be exact. Still O(N) space) to make such unreasonable request actually feasible. The first piece of memory is going to be our data section and hold all N elements. The other two arrays will be called &#8220;forward&#8221; and &#8220;backward&#8221; and will be used to check if a certain index is in use or not. Here&#8217;s a sketch of the setup, along with a detailed algorithm:</p>
<div id="attachment_565" class="wp-caption aligncenter" style="width: 310px"><a href="http://efesx.com/wp-content/uploads/2009/11/constant-time-array-reset.png"><img src="http://efesx.com/wp-content/uploads/2009/11/constant-time-array-reset-300x165.png" alt="Data structures sketch" title="Constant time reset of an array" width="300" height="165" class="size-medium wp-image-565" /></a><p class="wp-caption-text">Needed data structures to allow O(1) reset of an array.</p></div>
<p>For every added element in index id, we are going to do the following (&#8220;used&#8221; is the number of elements in use since last reset):</p>
<ul>
<li>forward[id] = used</li>
<li>backward[used] = id</li>
<li>used++</li>
</ul>
<p>Analyzing this algorithm we can verify that: index id is in use IFF (<a href="http://en.wikipedia.org/wiki/If_and_only_if">if and only if</a>) 0 <= forward[id] &#038;&#038; forward[id] < used &#038;&#038; backward[forward[id]] == id. This is because we know that all the elements in "backward" with indices 0 to used-1 have been set by us since the last reset.</p>
<p>Consequently, all we need to do in a reset operation is set the "used" variable to zero.</p>
<p>Here's a proper implementation of such an array, for the integer case, just as an example:</p>
<pre class="brush: cpp; title: ; notranslate">// &#8212; array.hpp &#8212;

#include &lt;stdexcept&gt;
#include &lt;boost/shared_array.hpp&gt;

class Array {
    public:
        explicit Array (unsigned size);

        // All operations are done in constant O(1) time.
        void reset ();
        int  get   (unsigned id) const;
        void set   (unsigned id, int i);

    protected:
        bool used  (unsigned id) const;
        bool check (unsigned id) const throw(std::out_of_range);

        unsigned size_, used_;
        boost::shared_array&lt;int&gt; arr_;
        boost::shared_array&lt;unsigned&gt; forward_, backward_;

    private:
        // no implementation for these:
        Array (const Array &amp;arr);
        Array &amp;operator= (const Array &amp;arr);
};

// &#8212; array.cc &#8212;

template &lt;typename T&gt;
boost::shared_array&lt;T&gt; make_shared_arr (size_t size) {
    // this is crucial for exception safety.
    // see: http://www.gotw.ca/gotw/056.htm
    return boost::shared_array&lt;T&gt;(new T[size]);
}

Array::Array (unsigned size)
 : size_(size), used_(0), arr_(make_shared_arr&lt;int&gt;(size)),
   forward_(make_shared_arr&lt;unsigned&gt;(size)),
   backward_(make_shared_arr&lt;unsigned&gt;(size)) { }

void Array::reset () {
    used_ = 0;
}

int Array::get (unsigned id) const {
    if (check(id) &amp;&amp; used(id))
        return arr_[id];
    return 0;
}

void Array::set (unsigned id, int i) {
    if (check(id) &amp;&amp; !used(id) &amp;&amp; ++used_)
        forward_[backward_[used_-1] = id] = used_-1;
    arr_[id] = i;
}

bool Array::used (unsigned id) const {
    if (forward_[id] &gt;= used_)
        return false;
    return backward_[forward_[id]] == id;
}

bool Array::check (unsigned id) const throw(std::out_of_range) {
    if (id &gt;= size_)
        throw std::out_of_range(&quot;Index too big!&quot;);
    return true;
}

// &#8212; main.cc &#8212;

#include &lt;iostream&gt;

int main () {
    Array a(3);
    a.set(2,1);
    std::cout &lt;&lt; a.get(2) &lt;&lt; std::endl;
    a.reset();
    std::cout &lt;&lt; a.get(2) &lt;&lt; std::endl;
    return a.get(1);
}</pre>
<p>You will have to forgive me for the somewhat obscure implementation of the set() method. I was going for a minimal number of implementation lines - all in the spirit of <a href="http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming">Spartan Programming</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://efesx.com/2009/11/05/reset-an-array-in-constant-time/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>

