Small bug in my verb. This is the correct code:
convert =: 4 : 0
rows =. x
text =. y
len =. # y
if. 0 = len do. ''
elseif. 1 = len do. text
elseif. 1 = rows do. text
elseif. 1 do.
k=. 0
l=. 0
res =. ''
NB. loop through the rows
while. (k < rows) *. k < len do.
res =. res, k{text
NB. how much to increment. first and last rows are special
NB. cases, inner rows switch the increment.
nextMax =. (2 * rows) - 2
rm1 =. rows - 1
l1 =. ((+:@:(rm1&-))`(nextMax&[)@.((rm1&=)+.(0&=))) k
l2 =. ((+:)`(nextMax&[)@.((rm1&=)+.(0&=)))k
NB. first incremented value
nextIndex =. k + l1
NB. flag indicates which increment to use.
flag =. 1
while. nextIndex < len do.
res =. res, nextIndex{text
flag =. (flag = 0)
if. flag do. nextIndex =. nextIndex + l1
else. nextIndex =. nextIndex + l2
end.
end.
k =. k + 1 NB. increment the row
end.
res
end.
)
NB. example:
4 convert 'PAYPALISHIRING'
PINALSIGYAHRPI
Here converting to a zigzag with 4 rows.
This result looks right, looking at the zigzag below: (hopefully the formatting
wont be too messed up).
0 : 0
P I N
A L S I G
Y A H R
P I
)
--------------------------------------------
On Tue, 9/27/16, 'Jon Hough' via Programming <[email protected]> wrote:
Subject: [Jprogramming] Zig Zag problem
To: "Programming Forum" <[email protected]>
Date: Tuesday, September 27, 2016, 9:02 PM
This is a programming challenge from
here: https://leetcode.com/problems/zigzag-conversion/
The challenge is to convert a string into a "zig zag"
formation with the given number of rows.
e.g. (from the link)
PAYPALISHIRING is transformed into PAHNAPLSIIGYIR (the link
explains clearly this transformation)
This is my solution, which works.
NB. Convert text into a zigzag text.
NB. x: number of row (positive integer)
NB. y: string text
convert =: 4 : 0
rows =. x
text =. y
len =. # y
if. 0 = len do. ''
elseif. 1 = len do. text
elseif. 1 = rows do. text
elseif. 1 do.
k=. 0
l=. 0
res =. ''
NB. loop through the rows
while. (k < rows) *. k < len do.
res =. res, k{text
NB. how much to increment. first and last rows are special
NB. cases, inner rows switch the increment.
nextMax =. (2 * rows) - 2
rm1 =. rows - 1
l1 =.
((+:@:(rm1&-))`(nextMax&[)@.((rmo&=)+.(0&=)))
k
l2 =. ((+:)`(nextMax&[)@.((rm1&=)+.(0&=)))k
NB. first incremented value
nextIndex =. k + l1
NB. flag indicates which increment to use.
flag =. 1
while. nextIndex < len do.
res =. res, nextIndex{text
flag =. (flag = 0)
if. flag do. nextIndex =. nextIndex + l1
else. nextIndex =. nextIndex + l2
end.
end.
k =. k + 1 NB. increment the row
end.
res
end.
)
3 convert 'PAYPALISHIRING'
It's an interesting challenge and I'm sure there is a much
nicer way to do this in J...
Regards,
Jon
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm