Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I don't know if you have test cases, try the code below. It is a dynamic-programming approach.</p> <pre><code>1] exp: given 1/2^i, find the largest i as exp. Eg. 1/32 returns 5. 2] max: 10^exp where exp=i. 3] create an array of size max+1 to hold all possible sums of the elements of V. Actually the array holds the indexes, since that's what you want. 4] dynamically compute the sums (all invalids remain null) 5] the last while loop finds the nearest correct answer. </code></pre> <p>Here is the code:</p> <pre><code>public class Subset { public static List&lt;Integer&gt; subsetSum(double[] V, double r) { int exp = exponent(V); int max = (int) Math.pow(10, exp); //list to hold all possible sums of the elements in V List&lt;Integer&gt; indexes[] = new ArrayList[max + 1]; indexes[0] = new ArrayList();//base case //dynamically compute the sums for (int x=0; x&lt;V.length; x++) { int u = (int) (max*V[x]); for(int i=max; i&gt;=u; i--) if(null != indexes[i-u]) { List&lt;Integer&gt; tmp = new ArrayList&lt;Integer&gt;(indexes[i - u]); tmp.add(x); indexes[i] = tmp; } } //find the best answer int i = (int)(max*r); int j=i; while(null == indexes[i] &amp;&amp; null == indexes[j]) { i--;j++; } return indexes[i]==null || indexes[i].isEmpty()?indexes[j]:indexes[i]; }// subsetSum private static int exponent(double[] V) { double d = V[V.length-1]; int i = (int) (1/d); String s = Integer.toString(i,2); return s.length()-1; }// summation public static void main(String[] args) { double[] V = {1/2.,1/4.,1/8.,1/16.,1/32.}; double r = 0.6, s=0.3,t=0.256652; System.out.println(subsetSum(V,r));//[0, 3, 4] System.out.println(subsetSum(V,s));//[1, 3] System.out.println(subsetSum(V,t));//[1] } }// class </code></pre> <p>Here are results of running the code:</p> <pre><code>For 0.600000 get 0.593750 =&gt; [0, 3, 4] For 0.300000 get 0.312500 =&gt; [1, 3] For 0.256652 get 0.250000 =&gt; [1] For 0.700000 get 0.687500 =&gt; [0, 2, 3] For 0.710000 get 0.718750 =&gt; [0, 2, 3, 4] </code></pre>
    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.
    2. 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