Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a working (though not thoroughly tested) JavaScript solution.</p> <p>It essentially uses dynamic scripting to build the brute-force stacked for-loops (ordered combinations) to get the starting indexes for each group in the array.</p> <pre><code>var A = [1,2,3,4,5,6,7,8,9,10]; var G = 3; function find(line, groups) { var length = line.length; var mean = line.sum() / groups; var temp = [0]; var bestsad = 4294967295; var beststarts = []; var dynamic = "var x0 = 0; "; for(var i=1; i&lt;groups; i++) { dynamic += "for(var x" + i + "=x" + (i-1) + "+1;x" + i + "&lt;" + length + ";x" + i + "++) "; temp.push("x" + i); } dynamic += "{ var sad = getSAD(line, mean, [" + temp.join(",") + "]);"; dynamic += "if(sad &lt; bestsad) { bestsad = sad; beststarts = [" + temp.join(",") + "] ;} }" eval(dynamic); console.log("Best SAD " + bestsad); console.log("Best Start Indexes " + beststarts); return beststarts; } function getSAD(line, mean, starts) { var sums = []; var sad; for(var i = 0; i &lt; starts.length-1; i++) { var idx = i; sums.push(line.slice(starts[idx], starts[i+1]).sum()); } sums.push(line.slice(starts[starts.length-1]).sum()); sad = sums.sad(mean); return sad; } Array.prototype.sum = function() { var result = 0; for(var i=0; i&lt;this.length; i++) result += this[i]; return result; } Array.prototype.sad = function(mean) { var result = 0; for(var i=0; i&lt;this.length; i++) result += Math.abs(this[i] - mean); return result; } find(A, G); </code></pre> <p>Here's what the script that the <strong>var dynamic</strong> variable/string holds/executes.</p> <pre><code>var x0 = 0; for(var x1=x0+1;x1&lt;10;x1++) for(var x2=x1+1;x2&lt;10;x2++) { var sad = getSAD(line, mean, [0,x1,x2]); if(sad &lt; bestsad) { bestsad = sad; beststarts = [0,x1,x2] ; } } </code></pre> <p>Why not just use group index vector + recursion? For this type of recursive problem the iterative method is optimal. Admittedly the overhead (and added complexity) from the dynamic scripting would negate any benefit on small arrays, but when working with actual data (large arrays) it'll churn out answers faster.</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. This table or related slice is empty.
    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