Two sum: Difference between revisions
Content added Content deleted
(Added Algol 68) |
(→{{header|J}}: alternative approach for retrieving indicies) |
||
Line 429: | Line 429: | ||
<lang J>twosum=: ;@{.@(a:,~ ($ <@#: I.@,)@([ = +/~@]))</lang> |
<lang J>twosum=: ;@{.@(a:,~ ($ <@#: I.@,)@([ = +/~@]))</lang> |
||
'''Alternative approach''' |
|||
An alternative method for identifying and returning non-duplicate indicies of the pairs follows. |
|||
<lang j> 21 (= +/~) 0 2 11 19 90 |
|||
0 0 0 0 0 |
|||
0 0 0 1 0 |
|||
0 0 0 0 0 |
|||
0 1 0 0 0 |
|||
0 0 0 0 0</lang> |
|||
The array is symmetrical so we can zero one half to remove duplicate pairs and then retrieve the remaining indicies using sparse array functionality. |
|||
<lang j>zeroLowerTri=: * [: </~ i.@# |
|||
getIdx=: 4 $. $. |
|||
twosum_alt=: getIdx@zeroLowerTri@(= +/~)</lang> |
|||
Testing ... |
|||
<lang j> 21 twosum_alt 0 2 11 19 90 |
|||
1 3</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |