See http://code.jsoftware.com/wiki/Essays/Advent_Of_Code#Part_1_10

Henry Rich

On 9/2/2016 12:42 AM, 'Jon Hough' via Programming wrote:
This is a leetcode question:
https://leetcode.com/problems/count-and-say/
Description:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

I thought it would be fun to tackle this in J...



NB. Leetcode algorithm problem 38. Count and Say
countandsay =: 3 : 0
max=: y
str=: ''
tt=. 3 :'str=:str,''22'''
to=. 3 :'str=:str,''21'''
ot=. 3 :'str=:str,''12'''
oo=. 3 :'str=:str,''11'''

ones=. (3 : '1&}.y')[(ot`oo@.('1'&=@:{.))
twos=. (3 : '2&}.y')[(tt`to@.('1'&=@:{.))
f=. (ones`twos@.((0&{) = (1&{)))`ones@.(1&=@:#)^:(0&<@:#)^:_
ctr=: 0
val=. ((3 : 'str')[f)^:(3 : 'ctr<max[str=:''''[ctr=:>:ctr')^:_ '1'
)

countandsay 5 NB. test value 5

My main goal for this solution was figuring out how to do it with no while or 
for loops.
Anything more terse?
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to