0

This function that performs random apportionment works

Apal[v_, s_] := 
  Module[{vv = v, ss = s}, 
    p = vv/Total[vv]; (*probability to draw an object*)
    r = Range[Length[vv]]; (* nomber og groups *)
    rc = RandomChoice[p -> r, ss];(* give an object to a group at each draw *)
    Counts[rc] (* count of the number of objects *)
      ns = r /. Counts[rc]
      (* extraction in increasing order of the number of object for each group *)
  ]

as shown by

Apal[{12, 34, 13, 53, 67, 86, 44}, 128]

and

Total[Apal[{12, 34, 13, 53, 67, 86, 44}, 128]

which gives always 128.

But it prints some warnings

Set::write: Tag Times in <|5->26,6->32,4->26,2->17,7->16,1->6,3->5|> {6,18,31,38,58} is Protected.

I wonder where is my mistake and if there are no how to turn off the warnings.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
cyrille.piatecki
  • 4,582
  • 13
  • 26
  • 3
    Missing ; after first Counts[rc] – Carl Woll Jul 10 '17 at 21:17
  • @CarlWoll's answer should be most useful to you and you should consider changing your question. However, if you ever do need to turn of warning messages, you can use Off or Quiet. For example Off[Set::write] will turn off all Set::write messages, wich would be a very bad idea, though. – JEM_Mosig Jul 10 '17 at 21:44
  • The 1st Counts[rc] should be removed. The value it returns is never used. – m_goldberg Jul 10 '17 at 21:47

1 Answers1

2

The issue is a simple syntax error. However, it would be nice to have an easy method to find the syntax error. One idea is to use TracePrint:

TracePrint[Apal[{12,34,13,53,67,86,44}, 128], _Set]

vv$165781=Unevaluated[{12,34,13,53,67,86,44}]

vv$165781={12,34,13,53,67,86,44}

ss$165781=Unevaluated[128]

ss$165781=128

p=vv\$165781/Total[vv\$165781]

p={4/103,34/309,13/309,53/309,67/309,86/309,44/309}

r=Range[Length[vv$165781]]

r={1,2,3,4,5,6,7}

rc=RandomChoice[p->r,ss$165781]

rc={5,4,4,5,6,5,1,6,6,5,3,4,5,6,4,5,4,7,6,4,7,6,1,7,7,7,7,6,7,5,6,6,5,5,1,2,7,4,7,4,5,7,5,7,3,7,5,4,7,6,6,4,4,5,4,4,6,7,6,2,7,5,4,6,5,4,2,7,2,6,5,5,6,7,6,6,6,6,5,5,6,7,7,6,5,7,4,6,2,5,5,6,5,6,4,3,6,4,5,6,6,6,6,6,4,5,7,7,7,2,5,4,6,6,6,6,7,5,7,6,6,6,5,4,5,3,7,6}

Counts[rc] ns=r/. Counts[rc]

Counts[rc] ns={3,6,4,21,29,39,26}

Set::write: Tag Times in <|5->29,4->21,6->39,1->3,3->4,7->26,2->6|> ns is Protected.

{3, 6, 4, 21, 29, 39, 26}

As you can see in the TracePrint output, the message is generated because of the line:

Counts[rc] nc = ...

A couple other ideas. One is to print the stack when a message occurs:

TracePrint[
    Apal[{12,34,13,53,67,86,44}, 128],
    _Message,
    TraceAction->(Print[Stack[_][[-3]]]&)
]

Counts[rc] ns={7,12,5,16,25,40,23}

Set::write: Tag Times in <|4->16,6->40,7->23,5->25,1->7,2->12,3->5|> ns is Protected.

{7, 12, 5, 16, 25, 40, 23}

Another is to just click on the ... to the left of the message, and then click on "Show Stack Trace". You will see the problematic Set expression in the stack trace.

Carl Woll
  • 130,679
  • 6
  • 243
  • 355