Jump to content

Two sum: Difference between revisions

3,039 bytes added ,  7 years ago
Line 14:
[http://stackoverflow.com/questions/8334981/find-pair-of-numbers-in-array-that-add-to-given-sum Stack Overflow: Find pair of numbers in array that add to given sum]
<br/><br/>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
 
 
Nesting concatMap yields the cartesian product of the list with itself, and functions passed to '''map''' have access to the (1-based) array index in their second argument. Returning '''{ }''' where the y index is lower than or equal to the x index ignores the 'lower triangle' of the cartesian grid, skipping mirror-image and duplicate number pairs. Returning '''{ }''' where a sum condition is not met similarly acts as a filter – all of the empty lists in the map result are eliminated by the concat.
 
<lang AppleScript>-- summingPairIndices :: Int -> [Int] -> [[Int]]
on summingPairIndices(n, xs)
script
-- productFilter :: [a] -> [b] -> [[a, b]]
on productFilter(xs, ys)
script product
on lambda(x, ix)
script filter
on lambda(y, iy)
if iy ≤ ix then
{} -- ignore - mirror-image pairs
else
if n = (x + y) then
-- Solution found, and
-- AppleScript indices are 1-based
{{ix - 1, iy - 1}}
else
{} -- eliminated from map by concat
end if
end if
end lambda
end script
concatMap(filter, ys)
end lambda
end script
concatMap(product, xs)
end productFilter
end script
result's productFilter(xs, xs)
end summingPairIndices
 
 
-- TEST
on run
summingPairIndices(21, [0, 2, 11, 19, 90])
--> {{1, 3}}
end run
 
 
 
-- GENERIC LIBRARY FUNCTIONS
 
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
script append
on lambda(a, b)
a & b
end lambda
end script
foldl(append, {}, map(f, xs))
end concatMap
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to lambda(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to lambda(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property lambda : f
end script
end if
end mReturn</lang>
 
{{Out}}
<lang AppleScript>{{1, 3}}</lang>
 
 
 
=={{header|C sharp|C#}}==
9,659

edits

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