Others have posted solutions, so I'll provide:
(A) A different fundamental strategem
(B) A generalizing extension
The final generalized extension is a bit cryptic (as a result of my "session
programming" m.o.) so a bit of exegesis:
First, we will use monadic amend as the fundamental strategem:
fb =: verb define
z =. ":&.> y
z =. (#. |: 0 = 3 5 |/ y) } z , |: (#z) $ ,: ;: 'Fizz Buzz
FizzBuzz'
;:^:_1 z
)
fb i. 5
FizzBuzz 1 2 Buzz 4
Translating that to tacit:
fbT =: [: ;:^:_1 ([: #.@:|: 0 = 3 5 |/ ])`(":&.> , [: |: # $
(,:<;._1 ' Fizz Buzz FizzBuzz')"_)}
fbT i. 5
FizzBuzz 1 2 Buzz 4
Now we can write an adverb that will generalize the solution, and use it to
generate our specific FizzBuzz:
Fb =: adverb define
'fac rplc' =. 2 ([: (,&<~ ;)/@:|:@:}. ] (; */)~&:;/@|:@#~ [
#.^:_1: i.@:(^ #)) m
[: ;:^:_1 ((1 + #fac) | 1 + 1 i:"1~ 0 = fac |~/~ ])`(":&.> , [:
|: # $ (,: rplc)"_) }
)
(3 5 ;"_1 ;: 'Fizz Buzz') NB. Adverb's argument structure
+-+----+
|3|Fizz|
+-+----+
|5|Buzz|
+-+----+
(3 5 ;"_1 ;: 'Fizz Buzz') Fb NB. Output of adverb
[: ;:^:_1 (4 | 1 + 1 i:"1~ 0 = 5 3 15 |~/~ ])`(":&.> , [: |: # $
(,:<;._1 ' Buzz Fizz FizzBuzz')"_)}
(3 5 ;"_1 ;: 'Fizz Buzz') Fb i. 5
FizzBuzz 1 2 Fizz 4
And extend the adverb to make the the interface more convenient:
FB =: adverb define
if. (# *.&:(=&2) {:) $ m do.
'fac rplc' =. 2 ([: (,&<~ ;)/@:|:@:}. ] (; */)~&:;/@|:@#~ [
#.^:_1: i.@:(^ #)) m
[: ;:^:_1 ((1 + #fac) | 1 + 1 i:"1~ 0 = fac |~/~ ])`(":&.> ,
[: |: # $ (,: rplc)"_) }
else.
m 2 : '(n ;"_1 ;:^:(0 = L.) m)' FB
end.
)
3 5 'Fizz Buzz' FB i. 5
FizzBuzz 1 2 Fizz 4
I wonder if f~/~ or |:@:(f/~) could be optimized.
-Dan
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm