Mathematica使用锁定位生成二进制数

时间:2015-12-28 22:48:27

标签: algorithm binary wolfram-mathematica

我有一个非常具体的Mathematica问题。我试图围绕某些锁定的'生成所有二进制数字。位。我使用字符串值列表来表示哪些位被锁定,例如{" U"," U," L"," U"},其中U是"解锁"可变位和L是"锁定"不可变的位。我从一个已经格式化为前一个列表的随机二进制数的临时列表开始,例如{0,1, 1 ,0},其中 1 是锁定位。我需要找到 1 位保持不变的所有剩余二进制数。我已经递归地,迭代地,并且两者结合而没有结果地解决了这个问题。这是我在大学里进行的研究。

我正在构建二进制数的基本10形式的列表。我意识到这段代码是完全错误的。这只是一次尝试。

    Do[
      If[bits[[pos]] == "U", 
        AppendTo[returnList, myFunction[bits, temp, pos, returnList]]; ],
    {pos, 8, 1}]

    myFunction[bits_, bin_, pos_, rList_] :=
      Module[{binary = bin, current = Length[bin], returnList = rList},
        If[pos == current,
          Return[returnList],
          If[bits[[current]] == "U",
          (*If true*)
            If[! MemberQ[returnList, FromDigits[binary, 2]],
            (*If true*)
              AppendTo[returnList, FromDigits[binary, 2]];
              binary[[current]] = Abs[binary[[current]] - 1],
            (*If false*)
              binary[[current]] = 0;
              current = current - 1]; ,
          (*If false*)
            current = current - 1];
          returnList = myFunction[bits, binary, pos, returnList];  
        Return[returnList]]]

3 个答案:

答案 0 :(得分:2)

您可以使用Foldbits = {"U", "U", "L", "U"}; Fold[ Function[{running, next}, Insert[running, 1, next]], #, Position[bits, "L"]] & /@ Tuples[{0, 1}, Count["U"]@bits] (* {{0, 0, 1, 0}, {0, 0, 1, 1}, {0, 1, 1, 0}, {0, 1, 1, 1}, {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 1, 0}, {1, 1, 1, 1}} *) 仅生成您感兴趣的位集。

image

希望这有帮助。

答案 1 :(得分:1)

myFunction[bits_] := Module[{length, num, range, all, pattern},
  length = Length[bits];
  num = 2^length;
  range = Range[0, num - 1]; 
  all = PadLeft[IntegerDigits[#, 2], length] & /@ range;
  pattern = bits /. {"U" -> _, "L" -> 1};
  Cases[all, pattern]]

bits = {"U", "U", "L", "U"};

myFunction[bits]
{{0, 0, 1, 0}, {0, 0, 1, 1}, {0, 1, 1, 0}, {0, 1, 1, 1},
 {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 1, 0}, {1, 1, 1, 1}}

答案 2 :(得分:1)

 FromDigits[#, 2] & /@ % 
  

{{1,0,1,1,1,0,0,1,0,1,0,0,0,0,0,0,1,1,0,0,0,1,1 ,      0,0,1,0,0,1,0,1,0},{1,0,1,1,1,0,0,1,0,1,0,0,0,      0,0,0,1,1,0,0,0,1,1,0,0,1,0,0,1,1,1,0},{1,0,1,      1,1,0,0,1,0,1,0,0,0,0,0,0,1,1,1,0,0,1,1,0,0,     1,0,0,1,0,1,0},{1,0,1,1,1,0,0,1,0,1,0,0,0,0,0,     0,1,1,1,0,0,1,1,0,0,1,0,0,1,1,0,0},...

 <% @sectors.uniq.each do |sector| %>
       <li>
        <%= link_to sectors_path(name: sector.name) do %>
            <i class="<%= sector.logo_awesome %>"></i> <%= sector.name %>
       <% end %>
       </li>
    <% end %>`
  

{3108030026,3108030030,3108038218,3108038222,3108095562,   3108095566,3108103754,3108103758,3141584458,3141584462,   3141592650,3141592654,3141649994,3141649998,3141658186,   3141658190}