instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
port this code from PHP to Ruby: ```php function minAbsoluteSumDiff($nums1, $nums2) { $n = count($nums1); $total = 0; $max_diff = 0; $mod = pow(10, 9) + 7; $sorted_nums1 = $nums1; sort($sorted_nums1); for ($i = 0; $i < $n; $i++) { $diff = abs($nums1[$i] - $nums2[$i]); $total...
dolphin
translate this code to Lua: ```erlang critical_connections(N, Connections) -> dfs(0, -1, 0, lists:duplicate(N, -1), create_graph(Connections, dict:new()), []). dfs(Node, Parent, Depth, Rank, Graph, Result) -> NewRank = lists:sublist(Rank, Node - 1) ++ [Depth] ++ lists:nthtail(Node, Rank), Neighbors = dict:...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** ...
dolphin
Please write the following solution using c++: You are given two strings `current` and `correct` representing two **24-hour times**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. In on...
dolphin
translate this code to python: ```erlang % Function to calculate minimum mutation min_mutation(StartGene, EndGene, Bank) -> Q = queue:from_list([StartGene]), Visited = sets:new([StartGene]), Depth = 0, bfs(Q, Visited, Depth, EndGene, Bank). % Helper function to perform BFS bfs(Q, Visited, Depth, EndGen...
dolphin
port this code to Go: ```fsharp let countPossibleRoutes (locations: int []) (start: int) (finish: int) (fuel: int) : int = let n = locations.Length let dp = Array2D.zeroCreate n (fuel+1) for i = 0 to fuel do if abs(locations.[start] - locations.[finish]) <= i then dp.[start, i] <- 1 ...
dolphin
Please explain the following problem in detail and provide code in Swift: You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day. On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you ca...
dolphin
port this code from Lua to F#: ```lua function findTheCity(n, edges, distanceThreshold) local distance = {} for i=1,n do distance[i] = {} for j=1,n do distance[i][j] = 1e5 end end for _, edge in ipairs(edges) do distance[edge[1]+1][edge[2]+1] = edge[3] ...
dolphin
convert this code from Julia to c++: ```julia function flip_matrix_rows(matrix) count = 0 for i in 1:size(matrix, 1) if matrix[i, 1] == 0 flip_row(matrix, i) end for j in 2:size(matrix, 2) if matrix[i, j] != matrix[i, 1] continue end ...
dolphin
port this code from Objective-C to c++: ```objc NSArray *charsInAllWords(NSArray *words) { NSMutableSet *charSet = [NSMutableSet setWithArray:[words[0] componentsSeparatedByString:@""]]; for (NSInteger i = 1; i < words.count; i++) { NSMutableSet *currCharSet = [NSMutableSet setWithArray:[words[i] compon...
dolphin
Please explain the following problem in detail and provide code in Mojo: We are playing the Guessing Game. The game will work as follows: 1. I pick a number between `1` and `n`. 2. You guess a number. 3. If you guess the right number, **you win the game**. 4. If you guess the wrong number, then I will tell you whe...
dolphin
Please write the following solution using python: A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is...
dolphin
Please explain the reasoning behind the following solution and provide code in Perl: You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. Both robots initially start at `(0, 0)...
dolphin
convert this code from ANSI C to TypeScript: ```c #include <stdio.h> int lcm(int a, int b) { int temp = a; while (temp % b != 0) { temp += a; } return temp; } int count_lcm_subarrays(int nums[], int n, int k) { int count = 0; for (int i = 0; i < n; i++) { int curr_lcm = nums[i]...
dolphin
Please focus on the functionality of this problem and provide code in Rust: You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation **any** number of times: * **Replace** a character `oldi` o...
dolphin
port this code from Scheme to Rust: ```scheme (define (last-remaining n) (define (helper direction head remaining step) (cond [(= remaining 1) head] [(or direction (odd? remaining)) (helper (not direction) (+ head step) (quotient remaining 2) (* step 2))] [else (helper (n...
dolphin
Please focus on the efficiency of this problem and provide code in Groovy: You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the **MKAverage** for the stream. The **MKAverage** can be calculated using these steps: 1. If the number of the e...
dolphin
Please focus on the algorithm of this problem and provide code in python: Given the `root` of a binary tree, return _the sum of values of nodes with an **even-valued grandparent**_. If there are no nodes with an **even-valued grandparent**, return `0`. A **grandparent** of a node is the parent of its parent if it exis...
dolphin
Please focus on the algorithm of this problem and provide code in javascript: You are given a **0-indexed** array of strings `words` and a 2D array of integers `queries`. Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that star...
dolphin
Please explain the following problem in detail and provide code in Lua: Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses subs...
dolphin
Please focus on the efficiency of this problem and provide code in Lisp: Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`. It is **guaranteed** that there will be a rectangle with a sum no larger than `k`. **Example 1:** **...
dolphin
Please explain the reasoning behind the following solution and provide code in Groovy: Given the `root` of a binary tree and a node `u` in the tree, return _the **nearest** node on the **same level** that is to the **right** of_ `u`_, or return_ `null` _if_ `u` _is the rightmost node in its level_. **Example 1:** **I...
dolphin
translate this code to Kotlin: ``` def max_size_slices(slices) { def max_sum(memo, slices, start, end, n) { if (n == 0) { return 0 } if (end - start + 1 < n * 2) { return -99999999 } if (memo[start][n] != -1) { return memo[start][n] ...
dolphin
Please explain the following problem in detail and provide code in Julia: You are given an integer `n` indicating the number of people in a network. Each person is labeled from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `restrictions`, where `restrictions[i] = [xi, yi]` means that person `xi` ...
dolphin
Please explain the following problem in detail and provide code in Perl: Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-...
dolphin
port this code to Ruby: ```go func searchInsert(nums []int, target int) int { left, right := 0, len(nums)-1 for left <= right { mid := left + (right-left)/2 if nums[mid] == target { return mid } if nums[mid] < target { left = mid + 1 } else { ...
dolphin
Please explain the following problem in detail and provide code in Kotlin: You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element ...
dolphin
Please explain the following problem in detail and provide code in Mojo: Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`. An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`. **Example 1:** ...
dolphin
convert this code from Erlang to F#: ```erlang %% @doc Calculates the number of beautiful subarrays in an array %% @spec beautiful_subarrays([integer()]) -> integer() beautiful_subarrays(Nums) -> Odd = lists:seq(1, 20, 1), Even = lists:seq(1, 20, 1), Even0 = lists:map(fun(_) -> 0 end, Even), Even1 = lis...
dolphin
Please write the following solution using Lisp: Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly `two` or `zero` sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: You are given a **positive** integer `k`. You are also given: * a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and * a 2D integer array `colConditions` of size `m` where `colConditio...
dolphin
Please focus on the efficiency of this problem and provide code in Perl: Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all ...
dolphin
Please explain the reasoning behind the following solution and provide code in PHP: You are given an array of transactions `transactions` where `transactions[i] = [fromi, toi, amounti]` indicates that the person with `ID = fromi` gave `amounti $` to the person with `ID = toi`. Return _the minimum number of transaction...
dolphin
Please explain the following problem in detail and provide code in Swift: As the ruler of a kingdom, you have an army of wizards at your command. You are given a **0-indexed** integer array `strength`, where `strength[i]` denotes the strength of the `ith` wizard. For a **contiguous** group of wizards (i.e. the wizards...
dolphin
translate this code from Elixir to C#: ```elixir defmodule Solution do def min_arrays(nums) do def gcd(a, b) do if b == 0, do: a, else: gcd(b, rem(a, b)) end total_gcd = Enum.reduce(nums, &gcd/2) if total_gcd == 1 do 2 else 1 end end end ```
dolphin
Please explain the following problem in detail and provide code in Object Pascal: You are given a **0-indexed** integer array `nums`. An index `i` is part of a **hill** in `nums` if the closest non-equal neighbors of `i` are smaller than `nums[i]`. Similarly, an index `i` is part of a **valley** in `nums` if the closes...
dolphin
port this code from PHP to Scala: ```php function is_prime(int $n): bool { if ($n <= 1) { return false; } for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { return false; } } return true; } function count_prime_set_bits(int $left, int $right): int { $co...
dolphin
Please write the following solution using Visual Basic .NET: You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: You are given a **0-indexed** integer array `nums`. The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`. The **xor-beauty** of the array is the XORing of **the effective values of al...
dolphin
translate this code to Lua: ```rust fn valid_word_square(words: &Vec<String>) -> bool { for i in 0..words.len() { for j in 0..words[i].len() { if j >= words.len() || i >= words[j].len() || words[i].as_bytes()[j] != words[j].as_bytes()[i] { return false; } } ...
dolphin
Please focus on the efficiency of this problem and provide code in Haskell: There is a garden of `n` flowers, and each flower has an integer beauty value. The flowers are arranged in a line. You are given an integer array `flowers` of size `n` and each `flowers[i]` represents the beauty of the `ith` flower. A garden i...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: You are given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`. The points form a polygon when joined sequentially. Return `true` if this polygon is [convex](http://en.wikipedia.org/wiki/Convex_polygon) an...
dolphin
convert this code from PHP to TypeScript: ```php function countDifferences($a, $b) { $count = 0; for ($i = 0; $i < strlen($a); $i++) { if ($a[$i] != $b[$i]) { $count++; } if ($count > 2) { return $count; } } return $count; } function findMatchingW...
dolphin
Please write the following solution using F#: There is a directed graph of `n` nodes with each node labeled from `0` to `n - 1`. The graph is represented by a **0-indexed** 2D integer array `graph` where `graph[i]` is an integer array of nodes adjacent to node `i`, meaning there is an edge from node `i` to each node in...
dolphin
Please explain the following problem in detail and provide code in Perl: You are given a **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i....
dolphin
Please explain the reasoning behind the following solution and provide code in C#: There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially **turned off**. You are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][co...
dolphin
Please focus on the functionality of this problem and provide code in F#: You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells. * If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell. * If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell. You ...
dolphin
Please explain the reasoning behind the following solution and provide code in Scala: There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between v...
dolphin
Please write the following solution using Groovy: There is a row of `n` houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of...
dolphin
Please focus on the algorithm of this problem and provide code in Visual Basic .NET: Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules: * The number of unique characters in the substring must be less than or equal to `maxLetters`. * The substring size must b...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array. Return _the leng...
dolphin
Please write the following solution using Object Pascal: Consider a function that implements an algorithm **similar** to [Binary Search](https://leetcode.com/explore/learn/card/binary-search/). The function has two input parameters: `sequence` is a sequence of integers, and `target` is an integer value. The purpose of ...
dolphin
Please focus on the efficiency of this problem and provide code in Objective-C: Given an integer array `nums` that **does not contain** any zeros, find **the largest positive** integer `k` such that `-k` also exists in the array. Return _the positive integer_ `k`. If there is no such integer, return `-1`. **Example 1...
dolphin
Please focus on the functionality of this problem and provide code in Groovy: Given a **positive** integer `n`, return _the smallest positive integer that is a multiple of **both**_ `2` _and_ `n`. **Example 1:** **Input:** n = 5 **Output:** 10 **Explanation:** The smallest multiple of both 5 and 2 is 10. **Example 2...
dolphin
Please focus on the efficiency of this problem and provide code in F#: You are given an integer array `digits`, where each element is a digit. The array may contain duplicates. You need to find **all** the **unique** integers that follow the given requirements: * The integer consists of the **concatenation** of **t...
dolphin
Please write the following solution using Dart: You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls....
dolphin
convert this code from PHP to c++: ```php function min_moves($nums) { $min_element = min($nums); $moves = 0; for ($i = 0; $i < count($nums); $i++) { $moves += $nums[$i] - $min_element; } return $moves; } ```
dolphin
Please write the following solution using javascript: Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`. The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following r...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or ...
dolphin
convert this code to Object Pascal: ```dart int addDigits(int num) { return 1 + (num - 1) % 9; } ```
dolphin
Please explain the following problem in detail and provide code in Fortran: You are given two string arrays `creators` and `ids`, and an integer array `views`, all of length `n`. The `ith` video on a platform was created by `creator[i]`, has an id of `ids[i]`, and has `views[i]` views. The **popularity** of a creator ...
dolphin
translate this code to PHP: ```python def find_K(nums): s = set(nums) k = -1 for num in nums: if -num in s: k = max(k, abs(num)) return k ```
dolphin
Please focus on the algorithm of this problem and provide code in Perl: You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point `[0, 0]`, and you are given a destination point `target = [xtarget, ytarget]` that you are trying to get to. There are several ghosts on the map with their st...
dolphin
Please explain the following problem in detail and provide code in TypeScript: A generic microwave supports cooking times for: * at least `1` second. * at most `99` minutes and `99` seconds. To set the cooking time, you push **at most four digits**. The microwave normalizes what you push as four digits by **prepe...
dolphin
port this code to python: ```javascript function minimumSpeed(n, hour, dist) { if (n > Math.ceil(hour)) return -1; let low = 1, high = 1e7, mid, speed; while (low <= high) { mid = low + Math.floor((high - low) / 2); let time = 0; for (let i = 0; i < n; ++i) { time +=...
dolphin
Please explain the reasoning behind the following solution and provide code in python: It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. ...
dolphin
port this code to c++: ```mojo sub get_last_moment(n: int, k: int, time: List[List[int]]) -> int { var left = PriorityQueue.new() for j in 0..k-1 { left.push((time[j][0] + time[j][2], j)) } var right = PriorityQueue.new() var n = n while n > 0 { while !right.empty() and right.top...
dolphin
convert this code from Fortran to Scheme: ```fortran type TreeNode integer :: val type(TreeNode), pointer :: left => null(), right => null() end type TreeNode function longest_consecutive(root) result(max_length) type(TreeNode), pointer :: root integer :: max_length(1) max_length = 0 call longe...
dolphin
Please explain the following problem in detail and provide code in Clojure: You are given an array of integers `nums`. You are also given an integer `original` which is the first number that needs to be searched for in `nums`. You then do the following steps: 1. If `original` is found in `nums`, **multiply** it by t...
dolphin
port this code from Scala to Fortran: ``` import scala.collection.mutable.ListBuffer object Solution { def pathsWithMaxScore(board: Array[String]): Array[Int] = { val n = board.length val dp = Array.fill(n)(Array.fill(n)(0)) val cnt = Array.fill(n)(Array.fill(n)(0)) dp(n-1)(n-1) = 0 cnt(n-1)(n-1)...
dolphin
Please write the following solution using c++: **Reversing** an integer means to reverse all its digits. * For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**. Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` t...
dolphin
Please explain the reasoning behind the following solution and provide code in Lisp: Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array. Implement the `WordDistance` class: * `WordDistance(Stri...
dolphin
Please write the following solution using Fortran: You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. Calcul...
dolphin
convert this code from Visual Basic .NET to Scala: ```vb.net Function MinNonExpressibleInteger(nums As Integer()) As Integer Dim result As Integer = 1 Array.Sort(nums) For Each num As Integer In nums If num > result Then Exit For End If result += num Next Return r...
dolphin
Please explain the reasoning behind the following solution and provide code in Visual Basic .NET: We are given a list `schedule` of employees, which represents the working time for each employee. Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order. Return the list of finit...
dolphin
port this code from Ruby to R: ```ruby def maximum_requests(n, requests) req_size = requests.length max_requests = 0 (1 << req_size).times do |i| net_transfers = Array.new(n, 0) count = 0 req_size.times do |j| if i & (1 << j) != 0 net_transfers[requests[...
dolphin
translate this code from Fortran to Groovy: ```fortran function can_convert(sx, sy, tx, ty) result(res) integer, intent(in) :: sx, sy, tx, ty logical :: res if (sx>tx .or. sy>ty) then res = .false. return end if do while (tx>0 .and. ty>0) if (tx>ty) then tx = tx...
dolphin
port this code to Dart: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> void helper(char* num, int target, int pos, long long currVal, long long prevVal, char* currExpr, char** res, int* returnSize); char** addOperators(char* num, int target, int* returnSize) { *returnSize = 0; char** res = (c...
dolphin
Please explain the reasoning behind the following solution and provide code in java: Consider a function that implements an algorithm **similar** to [Binary Search](https://leetcode.com/explore/learn/card/binary-search/). The function has two input parameters: `sequence` is a sequence of integers, and `target` is an in...
dolphin
convert this code to Mojo: ```lua function removeDuplicates(nums) if #nums == 0 then return 0 end local i = 1 for j = 2, #nums do if nums[j] ~= nums[i] then i = i + 1 nums[i] = nums[j] end end return i end ```
dolphin
port this code to Erlang: ```go package main import "fmt" func findArray(pref []int) []int { arr := []int{pref[0]} for i := 1; i < len(pref); i++ { arr = append(arr, pref[i] ^ pref[i - 1]) } return arr } func main() { pref := []int{5, 2, 0, 3, 1} fmt.Println(findArray(pref)) // Output...
dolphin
convert this code to Perl: ```swift func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double { var nums1 = nums1 var nums2 = nums2 if nums1.count > nums2.count { return findMedianSortedArrays(nums2, nums1) } let x = nums1.count let y = nums2.count var low = 0 ...
dolphin
Please write the following solution using Dart: Given an integer `n`, return all the **strobogrammatic numbers** that are of length `n`. You may return the answer in **any order**. A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down). **Example 1:** **Input:...
dolphin
Please explain the following problem in detail and provide code in Perl: Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer[j] % answer[i] == 0` If...
dolphin
translate this code to F#: ```javascript function maxDistance(nums1, nums2) { let i = 0, j = 0, maxDist = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] > nums2[j]) { ++i; } else { maxDist = Math.max(maxDist, j - i); ++j; } } re...
dolphin
convert this code to Erlang: ```lisp (defun min-absolute-sum-diff (nums1 nums2) (let ((n (length nums1)) (total 0) (max-diff 0) (mod (+ (expt 10 9) 7)) (sorted-nums1 (sort (copy-seq nums1) #'<))) (dotimes (i n) (let ((diff (abs (- (elt nums1 i) (elt nums2 i)))) (p...
dolphin
convert this code to Kotlin: ```Fortran function largest_even_sum(nums, k) result(ans) integer, dimension(:), intent(in) :: nums integer, intent(in) :: k integer :: odds(size(nums)), evens(size(nums)) integer :: ans, i, j, sum j = 0 do i = 1, size(nums) if (mod(nums(i), 2) == 0) the...
dolphin
Please focus on the efficiency of this problem and provide code in Visual Basic .NET: Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_. **Note**: * A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second...
dolphin
port this code to Kotlin: ```rust fn length_longest_path(input: &str) -> i32 { let mut dir_length_stack: Vec<i32> = Vec::new(); let mut max_file_length = 0; let lines: Vec<&str> = input.split('\n').collect(); for line in lines { let level = line.chars().filter(|&c| c == '\t').count() as i32; ...
dolphin
Please explain the following problem in detail and provide code in Elixir: You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person. The **population** of some year `x` is the number of people alive during that year. The `ith` person is cou...
dolphin
Please focus on the functionality of this problem and provide code in Go: You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are al...
dolphin
Please write the following solution using c++: A **confusing number** is a number that when rotated `180` degrees becomes a different number with **each digit valid**. We can rotate digits of a number by `180` degrees to form new digits. * When `0`, `1`, `6`, `8`, and `9` are rotated `180` degrees, they become `0`,...
dolphin
translate this code from Visual Basic .NET to Lisp: ```vb.net Function FindSecondsToTransform(s As String) As Integer Dim cnt_0 As Integer = 0 Dim cnt_1 As Integer = 0 For Each c As Char In s If c = "0" Then cnt_0 += 1 Else cnt_1 += 1 End If Next Retur...
dolphin
Please write the following solution using java: You are given an integer `n` denoting the number of nodes of a **weighted directed** graph. The nodes are numbered from `0` to `n - 1`. You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a **directed** edge fr...
dolphin
Please explain the following problem in detail and provide code in F#: Given a year `year` and a month `month`, return _the number of days of that month_. **Example 1:** **Input:** year = 1992, month = 7 **Output:** 31 **Example 2:** **Input:** year = 2000, month = 2 **Output:** 29 **Example 3:** **Input:** year ...
dolphin
Please focus on the efficiency of this problem and provide code in Elixir: Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 6...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: You are given a string `s`, which contains stars `*`. In one operation, you can: * Choose a star in `s`. * Remove the closest **non-star** character to its **left**, as well as remove the star itself. Return _the string after **al...
dolphin
port this code to python: ```vb.net Public Function BoomerangPoints(points As Integer()()) As Boolean Dim x1, x2, x3, y1, y2, y3 As Integer x1 = points(0)(0) y1 = points(0)(1) x2 = points(1)(0) y2 = points(1)(1) x3 = points(2)(0) y3 = points(2)(1) Dim slope1 As Double = (y2 - y1) / (x2 -...
dolphin
Please write the following solution using Swift: Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. **Note:** You can only move either down or right at any point in time. **Example 1:** **Input:** grid = \[\[1,3,1...
dolphin
port this code to Ruby: ```lisp (defun count-arithmetic-triplets (nums diff) (let ((count 0) (mp (make-hash-table))) (dolist (num nums) (when (gethash (- num diff) mp) (incf count (gethash (- num diff) mp))) (setf (gethash num mp 0) (1+ (gethash num mp 0))))) count) ```
dolphin