Jump to content

Two sum: Difference between revisions

→‎{{header|J}}: alternative approach for retrieving indicies
(Added Algol 68)
(→‎{{header|J}}: alternative approach for retrieving indicies)
Line 429:
 
<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}}==
892

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.