Convert this below array into matrix
Array
let ptsArray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
Matrix
0 1 2 3 4 5
6 7 8 9 10 11
12 13 14 15 16 17
To find adjacent points in uniderectional like an below image
Expected output
(0,1) (0,6)
(1,2) (1,7)
(2,3) (2,8)
(3,4) (3,9)
(4,5) (4,10)
(5,11)
(6,7) (6,12)
(7,8) (7,13)
(8,9) (8,14)
(9,10) (9,15)
(10,11) (10,16)
(11,17)
(12,13)
(13,14)
(14,15)
(15,16)
(16,17)
My failed approach
for i in 0..<pointsArray.count-1{
if (i+1)%6 == 0 && i != 0{
print("Connection ((i),(i+6))")
nodesArray[i].addConnection(to: nodesArray[i+6], bidirectional: true, weight: 1)
}
if i>=pointsArray.count-6{
print("Connection ((i),(i+1))")
nodesArray[i].addConnection(to: nodesArray[i+1], bidirectional: true, weight: 1)
}
else{
print("Connection ((i),(i+1)) ((i),(i+6))")
nodesArray[i].addConnection(to: nodesArray[i+1], bidirectional: true, weight: 1)
nodesArray[i].addConnection(to: nodesArray[i+6], bidirectional: true, weight: 1)
}
}
Output:
Connection (0,1) (0,6)
Connection (1,2) (1,7)
Connection (2,3) (2,8)
Connection (3,4) (3,9)
Connection (4,5) (4,10)
Connection (5,11)
Connection (5,6) (5,11)
Connection (6,7) (6,12)
Connection (7,8) (7,13)
Connection (8,9) (8,14)
Connection (9,10) (9,15)
Connection (10,11) (10,16)
Connection (11,17)
Connection (11,12) (11,17)
Connection (12,13)
Connection (13,14)
Connection (14,15)
Connection (15,16)
Connection (16,17)
2
Answers
In the desired output, I guess that it’s missing
(9,15)
,(10,11)
,(10,16)
and that(10,15)
isn’t valid.If we think about your desired output, we notice something.
Let’s name width = 6, it’s the "width" of your matrix.
We see the pattern:
(value, value + 1)
,(value, value + width)
With some excluded tests: does (value + width) exists ? And we are not at the end of the width.
Let’s, with a little reduce method:
I used "index", because in fact, points are in order here, but it could be any value, no? So let’s use the index instead.
So, with something a little more generic:
Use:
Another approach – convert your
ptsArray
into a 2-D matrix:You can now get the right and down values (if they exist) like this:
and this will print out the results:
Here’s a simple view controller that let’s you tap any number to show the "right and down" matches:
It looks like this:
Tapping any number will highlight the pair:
Tapping a "highlighted" number will "un-highlight" all numbers.