(道歉男生代碼,這是我用繩子在Mathematica中的第一次努力,所以我留在我的思想-AS-I-去了,也有一些註釋掉的調試/追蹤值)
charcountsvec[s_String, c_String] := Table[
If[StringTake[s, {i, i}] == c, 1, 0]
, {i, 1, StringLength[s]}
];
oddchars[s_String] := StringTake[s, {1, -1, 2}]; (*pick out odd chars*)
evenchars[s_String] := StringTake[s, {2, -1, 2}];
validatestr[str_String] :=
Block[{evencounts, oddcounts, answer1, answer2 (*, odds, evens*)},
evencounts = [email protected][(*evens=*)evenchars[str], "1"];
oddcounts = [email protected][(*odds=*)oddchars[str], "1"];
(*my interpretation of "number of 1's in odd positions the same as in even positions"*)
answer1 = Last[oddcounts] == Last[evencounts];
(*my interpretation of "for every..string...whether number of 1's in even/odd positions is not equal"*)
answer2 = Fold[And, True,
MapThread[Unequal, {Most[oddcounts], Most[evencounts]}]];
{str, And[answer1, answer2](*,odds,evens,oddcounts,evencounts,answer1,answer2*)}
];
測試:
validatestr/@{"100001","101101","100100","100000","000000"}
{{ 「100001」,TRUE},{ 「101101」,TRUE},{ 「100100」,FALSE},{ 「100000」, FALSE},{ 「000000」,FALSE}}
validatestr["0000001"](*odd length string pukes, and returns False*)
期間的(本地)評價在[428]:= MapThread :: MPTC:在位置{2物體的尺寸不兼容,1}和{2 ,2} MapThread [不等式,{{0,0,0},{0,0}}];維度是{3}和{2}。 >>
(Local)Out [432] = {「0000001」,False}
對於「000011」結果是否可以? – 2011-03-01 02:54:42
@belisarius這應該是False,因爲1的數目在第一個偶數和第一個奇數條目中是相同的。我的代碼錯誤(可能是特殊情況)的情況是「00」。聲稱是真實的,但違反規則,我們至少需要一個1。 – 2011-03-01 22:24:18
我發表了評論,然後意識到它是如此。但忘了刪除評論。對不起,謝謝 – 2011-03-01 22:40:01