0

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
*) 
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Joe
  • 1,467
  • 7
  • 13

1 Answers1

2

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]]}]]).

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
  • 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? – Joe Mar 11 '18 at 23:36
  • @Joe, on the use of Rule[] (->) vs. RuleDelayed[] (:>), see this or this. – J. M.'s missing motivation Mar 12 '18 at 00:23