First Elixir Solution
1. Two Sum Easy Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] defmodule Solution do @spec two_sum(nums :: [integer], target :: integer) :: [integer] def two_sum(nums, target) do [head | tail] = nums two_sum(head, tail, 0, 1, target) end def two_sum(current, [head | tail], current_index, head_index, target) when head + current == target do [current_index, head_index] end def two_sum(current, [head | tail], current_index, head_index, target) do answer = two_sum(current, head, current_index + 1, head_index + 1, target) if answer == [] do two_sum(current, tail, head_index, head_index + 1, target) else answer end end def two_sum(current, [], current_index, head_index, target) do [] end end
A screenshot shows the LeetCode “Two Sum” problem beside a recursive Elixir solution. The joke is that a beginner’s first Elixir attempt is presented next to a deceptively simple programming exercise, inviting experienced developers to scrutinize the unusual recursion and pattern matching. It is used as a reaction to asking for code review after solving a beginner problem in an unfamiliar language. EN: A screenshot shows the LeetCode “Two Sum” problem beside a recursive Elixir solution. The joke is that a beginner’s first Elixir attempt is presented next to a deceptively simple programming exercise, inviting experienced developers to scrutinize the unusual recursion and pattern matching. It is used as a reaction to asking for code review after solving a beginner problem in an unfamiliar language.
- @ithueti / 6293 2022-05-14
- Type
- image
- Size
- 800×387 · 38.6 KiB
- Mood
- self-deprecating, nerdy
- Language
- en
- Added