Two sum: Difference between revisions
→AppleScript Functional: Tidied. Added note on indices.
(→{{header|AppleScript}}: Added an idiomatic solution.) |
(→AppleScript Functional: Tidied. Added note on indices.) |
||
Line 87:
{{Trans|JavaScript}}
{{Trans|Haskell}}
Nesting concatMap or (>>=) (flip concatMap) yields the cartesian product of the list with itself. Skipping products where the y index is lower than the x index (see the use of 'drop' below) ignores the 'lower triangle' of the cartesian grid, excluding mirror-image and duplicate number pairs.
Note that this draft assumes that the task and target output are specified in terms of the prevailing convention of zero-based indices.
<lang AppleScript>-- sumTo :: Int -> [Int] -> [(Int, Int)]▼
on sumTwo(n, xs)▼
AppleScript, unusually, happens to make internal use of one-based indices, rigid adherence to which would, of course, in this case, simply produce the wrong result :-)
set ixs to zip(enumFromTo(0, |length|(xs) - 1), xs)
script ijIndices
on |λ|(ix)
set {i, x} to ix
script jIndices
on |λ|(jy)
set {j, y} to jy
if (x + y) = n then
{{i, j}}
Line 110 ⟶ 115:
end |λ|
end script
|>>=|(drop(i + 1, ixs), jIndices)
end |λ|
end script
|>>=|(ixs, ijIndices)
end
▲-- TEST ----------------------------------------------------------------------
---------------------------- TEST --------------------------
on run
--> {{1, 3}
end run
-- (>>=) :: Monad m => m a -> (a -> m b) -> m b
on |>>=|(xs, f)
concat(map(f, xs))
end |>>=|
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
Line 140 ⟶ 146:
end |λ|
end script
if length of xs > 0 and class of (item 1 of xs) is string then
set empty to ""
Line 148 ⟶ 154:
foldl(append, empty, xs)
end concat
-- drop :: Int -> a -> a
on drop(n, a)
Line 161 ⟶ 167:
end if
end drop
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
Line 175 ⟶ 181:
return lst
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
Line 187 ⟶ 193:
end tell
end foldl
-- length :: [a] -> Int
on |length|(xs)
length of xs
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
Line 204 ⟶ 210:
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
Line 213 ⟶ 219:
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
Line 225 ⟶ 231:
end if
end mReturn
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
Line 238 ⟶ 244:
<lang AppleScript>{{1, 3}, {2, 5}}</lang>
----
===Idiomatic===
Like the "Functional" script above, this returns multiple solutions when they're found. However it assumes a sorted list, as per the clarified task description, which allows some optimisation of the search. Also, the indices returned are 1-based, which is the AppleScript norm.
|