Mathematica:使用CheckboxBar生成一个字符串

时间:2016-09-24 15:16:58

标签: wolfram-mathematica

我开始时有一些很长的东西,很烦人这样写

Manipulate[
thetext = Switch[Total[obj],
0, Text["", {0, 5}],
1, Text["How", {0, 5}],
2, Text["Does One", {0, 5}],
4, Text["Use CheckboxBar", {0, 5}],
8, Text["=A=", {0, 5}],

3, Text["How Does One", {0, 5}],
5, Text["How Use CheckboxBar", {0, 5}],
9, Text["How =A=", {0, 5}],
6, Text["Does One Use CheckboxBar", {0, 5}],
10, Text["Does One =A=", {0, 5}],
12, Text["Use CheckboxBar =A=", {0, 5}],

7, Text["How Does One Use CheckboxBar", {0, 5}],
11, Text["How Does One =A=", {0, 5}],
13, Text["How Use CheckboxBar =A=", {0, 5}],
14, Text["Does One Use CheckboxBar =A=", {0, 5}],

15, Text["How Does One Use CheckboxBar =A=", {0, 5}]];

Graphics[thetext],
{{obj, {1, 2, 4, 8}, "Text"}, {1 -> "How", 2 -> "Does One", 
4 -> "Use CheckBoxBar", 8 -> "=A="}, CheckboxBar}] 

但我很快意识到我可能用四位二进制数替换1,2,4,8,即0000 = 0,1101 = 11等。所以我写了这个函数:

g[{d_, f_, g_, h_}] := 
StringJoin[
If[d == 1, "d", ""], If[f == 1, "f", ""], If[g == 1, "g", ""], If[h == 1, "h", ""]];

工作正常。但是,CheckboxBar会生成一个仅包含已检查条目的列表。除此之外,已检查条目的顺序将根据您首先检查的顺序而变化。

问题:我应该如何创建一个比我现在更简洁/更简洁的功能。最好使用checkboxbar,因为这是我的任务中的要求。没有checkboxbar也可以,因为我的作业没有对我的代码简洁程度进行评分。我只是想为了改进而改进它。

1 个答案:

答案 0 :(得分:0)

CheckboxBar具有(有时令人讨厌的)属性,它将按照您单击框的顺序将元素添加到列表中。为了克服这个限制,您可以向投入CheckboxBar的列表元素添加一些数字,并使用这些数字来排序阶段。假设我有阶段phrases = {"I ", "guess ", "this ", "works?"},那么我想像这样调用CheckboxBar:

CheckboxBar[
  Dynamic[stringList],
  {
    {{1}, "I "} -> "I ",
    {{2}, "guess "} -> "guess ",
    {{3}, "this "} -> "this ",
    {{4}, "works?"} -> "works?"
  }
]

接下来,您可以通过第一个元素(即stringList)对SortBy[stringList, First]进行排序,然后通过Apply ing(@@)将元素串在一起来获取字符串StringJoin到要组合的字符串列表。总而言之,我提出了这个解决方案:

DynamicModule[{
  stringList = {},
  phrases = {"I ", "guess ", "this ", "works?"}
},
  Column[{
    CheckboxBar[
      Dynamic[stringList], 
      MapIndexed[{#2, #1} -> #1 &, phrases]
    ],
    Dynamic[StringJoin @@ SortBy[stringList, First][[All, 2]]]
  }]
]

修改

如果需要,您还可以在Dynamic的第二个参数中处理排序。这可能有点清洁(虽然有点难以理解):

DynamicModule[{
  stringList = {},
  phrases = {"I ", "guess ", "this ", "works?"}
},
  Column[{
    CheckboxBar[
      Dynamic[
        stringList,
        Function[{val, expr}, stringList = SortBy[val, First]]
      ], 
      MapIndexed[{#2, #1} -> #1 &, phrases]
    ],
    Dynamic[StringJoin @@ stringList[[All, 2]]]
  }]
]