[Jprogramming] Count and say

'Jon Hough' via Programming programming at jsoftware.com
Fri Sep 2 04:42:59 UTC 2016


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 at .('1'&=@:{.))
twos=. (3 : '2&}.y')[(tt`to at .('1'&=@:{.))
f=. (ones`twos at .((0&{) = (1&{)))`ones at .(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?


More information about the Programming mailing list