[Jprogramming] Count and say
'Mike Day' via Programming
programming at jsoftware.com
Fri Sep 2 12:10:45 UTC 2016
Checking my attempt with the function in the essay cited, I see that
there's a misprint there.
The value of i should be '1113213211', not '1113122113', assuming i is
meant to be
,@((# , {.);.1~ (~: |.!.0))^:7 "."0 ,'1' NB. numeric result...
1 1 1 3 2 1 3 2 1 1
It's always good to learn - I hadn't noticed the useful idiom |.!.0 before.
So, fwiw, my attempt was, working on a numeric vector rather than a string,
,@:((# , ~.);.1)~ (1 , 2 ~:/\ ])
I suspect (1 , 2 ~:/\ ]) is less efficient than that idiom, and realise
that {.
does less work than ~.
Thanks,
Mike
On 02/09/2016 10:09, Henry Rich wrote:
> 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 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?
>> ----------------------------------------------------------------------
>> For information about J forums see http://www.jsoftware.com/forums.htm
>
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus
More information about the Programming
mailing list