Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A divide and conquer algorithm is only beneficial if you can either eliminate some work with it, or if you can parallelize the divided work parts accross several computation units. In your case, the first option is possible with an already sorted dataset, other answers may have addressed the problem.</p> <p>For the second solution, the algorithm name is map reduce, which split the dataset in several subsets, distribute the subsets to as many threads or processes, and gather the results to "compile" them (the term is actually "reduce") in a meaningful result. In your setting, it means that each thread will scan its own slice of the array to count the items, and return its result to the "reduce" thread, which will add them up to return the final result. <em>This solution is only interesting for large datasets though.</em></p> <p>There are questions dealing with mapreduce and c++ on SO, but I'll try to give you a sample implementation here:</p> <pre><code>#include &lt;utility&gt; #include &lt;thread&gt; #include &lt;boost/barrier&gt; constexpr int MAP_COUNT = 4; int mresults[MAP_COUNT]; boost::barrier endmap(MAP_COUNT + 1); void mfunction(int start, int end, int rank ){ int count = 0; for (int i= start; i &lt; end; i++) if ( integers[i] == x) count++; mresult[rank] = count; endmap.wait(); } int rfunction(){ int count = 0; for (int i : mresults) { count += i; } return count; } int mapreduce(){ vector&lt;thread &amp;&gt; mthreads; int range = integers.size() / MAP_COUNT; for (int i = 0; i &lt; MAP_COUNT; i++ ) mthreads.push_back(thread(bind(mfunction, i * range, (i+1) * range, i))); endmap.wait(); return rfunction(); } </code></pre> <p>Once the <code>integers</code> vector has been populated, you call the <code>mapreduce</code> function defined above, which should return the expected result. As you can see, the implementation is very specialized:</p> <ul> <li>the map and reduce functions are specific to your problem,</li> <li>the number of threads used for map is static,</li> <li>I followed your style and used global variables,</li> <li>for convenience, I used a <code>boost::barrier</code> for synchronization</li> </ul> <p>However this should give you an idea of the algorithm, and how you could apply it to similar problems. </p> <p><em>caveat: code untested</em>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload