Note that there are some explanatory texts on larger screens.

plurals
  1. POFast way to place bits for puzzle
    primarykey
    data
    text
    <p>There is a puzzle which I am writing code to solve that goes as follows.</p> <p>Consider a binary vector of length n that is initially all zeros. You choose a bit of the vector and set it to 1. Now a process starts that sets the bit that is the greatest distance from any 1 bit to $1$ (or an arbitrary choice of furthest bit if there is more than one). This happens repeatedly with the rule that no two 1 bits can be next to each other. It terminates when there is no more space to place a 1 bit. The goal is to place the initial 1 bit so that as many bits as possible are set to 1 on termination.</p> <p>Say n = 2. Then wherever we set the bit we end up with exactly one bit set.</p> <p>For n = 3, if we set the first bit we get 101 in the end. But if we set the middle bit we get 010 which is not optimal.</p> <p>For n = 4, whichever bit we set we end up with two set.</p> <p>For n = 5, setting the first gives us 10101 with three bits set in the end.</p> <p>For n = 7, we need to set the third bit to get 1010101 it seems. </p> <p>I have written code to find the optimal value but it does not scale well to large n. My code starts to get slow around n = 1000 but I would like to solve the problem for n around 1 million.</p> <pre><code>#!/usr/bin/python from __future__ import division from math import * def findloc(v): count = 0 maxcount = 0 id = -1 for i in xrange(n): if (v[i] == 0): count += 1 if (v[i] == 1): if (count &gt; maxcount): maxcount = count id = i count = 0 #Deal with vector ending in 0s if (2*count &gt;= maxcount and count &gt;= v.index(1) and count &gt;1): return n-1 #Deal with vector starting in 0s if (2*v.index(1) &gt;= maxcount and v.index(1) &gt; 1): return 0 if (maxcount &lt;=2): return -1 return id-int(ceil(maxcount/2)) def addbits(v): id = findloc(v) if (id == -1): return v v[id] = 1 return addbits(v) #Set vector length n=21 max = 0 for i in xrange(n): v = [0]*n v[i] = 1 v = addbits(v) score = sum([1 for j in xrange(n) if v[j] ==1]) # print i, sum([1 for j in xrange(n) if v[j] ==1]), v if (score &gt; max): max = score print max </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.
 

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