0
$\begingroup$

I'm trying to generate simple Row-Column headings for the Josephus survivor problem, but I can't get the column heading "Survivor" to display. As far as I can tell, I'm dong what is required from the documentation and I suspect I'm doing something trivially wrong but I just can't see it.

I got a workaround by using Grid, Table and then prepending a {"","Survivor"} pair, but it's hardly elegant.

survivor[n_] := Range[n] //. {a_, b_, z___} -> {z, a} // First
survivor /@ Range[5] // 
 TableForm[#, TableHeadings -> {Range[5], {"Survivor"}}] &
(*  
1|1
2|1
3|3
4|1
5|3
*) 
$\endgroup$
2
$\begingroup$

After modifying your function slightly:

SetAttributes[survivor, Listable];
survivor[n_Integer] := First[Range[n] //. {a_, b_, z___} :> {z, a}]

here is how to get the table you want:

TableForm[{survivor[Range[5]]} // Transpose, TableHeadings -> {Range[5], {"Survivor"}}]

output

In a nutshell: TableForm[] needs a two-dimensional list, and you were trying to feed it a one-dimensional one (compare Length[Dimensions[survivor[Range[5]]]] and Length[Dimensions[{survivor[Range[5]]}]]).

$\endgroup$
  • $\begingroup$ thx - the 1D vs 2D hint has given me something to chew on. On a side note - I'm still learning about -> vs :> is there anything i should note about your use of :> rather than -> when you modified my original function? AFAIK there's no change in behaviour or is it needed for the Listable attribute? $\endgroup$ – Joe Mar 11 '18 at 23:36
  • $\begingroup$ @Joe, on the use of Rule[] (->) vs. RuleDelayed[] (:>), see this or this. $\endgroup$ – J. M. will be back soon Mar 12 '18 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.