instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
translate this code to Julia: ```haskell maxScoreSightseeingPair :: [Int] -> Int maxScoreSightseeingPair values = let maxScoreLeft i = maximum $ take i values `zip` [0..i] & map (\(v, i) -> v + i) in maximum $ values `zip` [0..] & map (\(v, j) -> maxScoreLeft j + v - j) ```
dolphin
Please explain the reasoning behind the following solution and provide code in Rust: Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the ...
dolphin
Please explain the following problem in detail and provide code in Rust: Given a 2D matrix `matrix`, handle multiple queries of the following types: 1. **Update** the value of a cell in `matrix`. 2. Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, co...
dolphin
Please explain the following problem in detail and provide code in Fortran: The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight ...
dolphin
translate this code from Swift to Visual Basic .NET: ```swift func findComplement(_ num: Int) -> Int { var bitLength = 0 var mask = num while mask > 0 { mask >>= 1 bitLength += 1 } let allOnes = (1 << bitLength) - 1 return num ^ allOnes } ```
dolphin
translate this code from Elixir to ANSI C: ```elixir defmodule MaxGeneticDifference do def max_genetic_difference(parents, queries) do max_bit = 17 tr = [%{0 => 0, 1 => 0}] root = -1 def insert(x, tr) do u = 0 for i <- :lists.reverse(Enum.to_list(0..max_bit-1)) do v = (x >>> i) &&...
dolphin
Please write the following solution using Julia: Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` repre...
dolphin
Please explain the following problem in detail and provide code in javascript: You are given two **0-indexed** integer arrays `nums` and `removeQueries`, both of length `n`. For the `ith` query, the element in `nums` at the index `removeQueries[i]` is removed, splitting `nums` into different segments. A **segment** is...
dolphin
convert this code to c++: ```rust use std::collections::VecDeque; #[derive(Clone)] pub struct Node { pub val: i32, pub children: Vec<Node>, } impl Node { pub fn new(val: i32, children: Vec<Node>) -> Node { Node { val, children } } } pub fn level_order(root: Option<Box<Node>>) -> Vec<Vec<i32>>...
dolphin
Please write the following solution using Lua: A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obt...
dolphin
Please focus on the algorithm of this problem and provide code in Swift: You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`. Return _the smallest character in_ `letters` _that is lexicographic...
dolphin
Please focus on the functionality of this problem and provide code in Lua: You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**. The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` ...
dolphin
Please write the following solution using PHP: You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome. Return _the length of the maximum length **awesome substring** of_ `s`. **Example 1:** **Input:** s = "32424...
dolphin
convert this code to Dart: ```groovy def lengthOfLongestSubstring(String s) { int left = 0 int right = 0 int maxLength = 0 Set<Character> characters = new HashSet<>() while (right < s.length()) { if (!characters.contains(s[right])) { characters.add(s[right]) maxLengt...
dolphin
Please explain the following problem in detail and provide code in Lua: Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be ...
dolphin
Please explain the following problem in detail and provide code in Lisp: You are given an array of positive integers `price` where `price[i]` denotes the price of the `ith` candy and a positive integer `k`. The store sells baskets of `k` **distinct** candies. The **tastiness** of a candy basket is the smallest absolut...
dolphin
Please focus on the algorithm of this problem and provide code in Go: You are given two **sorted** arrays of distinct integers `nums1` and `nums2.` A **valid path** is defined as follows: * Choose array `nums1` or `nums2` to traverse (from index-0). * Traverse the current array from left to right. * If you are ...
dolphin
Please write the following solution using R: There are `n` persons numbered from `0` to `n - 1` and a door. Each person can enter or exit through the door once, taking one second. You are given a **non-decreasing** integer array `arrival` of size `n`, where `arrival[i]` is the arrival time of the `ith` person at the d...
dolphin
port this code to Ruby: ```groovy def checkRecord(String s) { def late = 0, absent = 0 for (char c : s.toCharArray()) { if (c == 'A') { absent += 1 late = 0 } else if (c == 'L') { late += 1 } else { late = 0 } if (absent >=...
dolphin
translate this code to Clojure: ```mojo sub MOVE_SUBTREE($root, $p, $q) { if $p == $q { return $root; } my $sub_tree = FIND_SUBTREE($root, $p); if IS_DESCENDANT($q, $p) { return $root; } if $sub_tree { $root = REMOVE_SUBTREE($root, $p); } else { $sub_tree = $p...
dolphin
translate this code from Object Pascal to Perl: ```pascal program Solution; type TInterval = record left, right: Integer; end; TIntervalArray = array of TInterval; function MinGroups(intervals: TIntervalArray): Integer; var i, end_time: Integer; pq: array of Integer; begin SetLength(p...
dolphin
convert this code to Go: ```perl sub count_similar_pairs { my $words = shift; my $count = 0; for (my $i = 0; $i < scalar @{$words}-1; $i++) { for (my $j = $i+1; $j < scalar @{$words}; $j++) { my %set1 = map { $_ => 1 } split //, $words->[$i]; my %set2 = map { $_ => 1 } split ...
dolphin
Please write the following solution using javascript: You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the r...
dolphin
port this code from c++ to Visual Basic .NET: ```cpp #include <vector> using namespace std; vector<int> findRedundantConnection(vector<vector<int>>& edges) { vector<int> parent(edges.size() + 1); for (int i = 1; i <= edges.size(); ++i) { parent[i] = i; } for (const auto& edge : edges) { ...
dolphin
translate this code from c++ to Lua: ```cpp bool sumGame(string num) { int n = num.size(); int sum1 = 0, sum2 = 0, cnt1 = 0, cnt2 = 0; for (int i = 0; i < n / 2; i++) { if (num[i] == '?') cnt1++; else sum1 += num[i] - '0'; } for (int i = n / 2; i < n; i++) { if (num[i] == '...
dolphin
translate this code to Lisp: ```fsharp open System.Collections.Generic let displayTable (orders : string[][]) = let tables = Dictionary<int, Dictionary<string, int>>() let foodSet = HashSet<string>() for order in orders do let tableNumber = int order.[1] let foodItem = order.[2] if...
dolphin
port this code from F# to Visual Basic .NET: ```fsharp let ways(grid: int[][], m: int, n: int, i: int, j: int, k: int, sum: int, dp: int[][][]) = if i = m - 1 && j = n - 1 then if (sum + grid.[i].[j]) % k = 0 then 1 else 0 else if dp.[i].[j].[sum] = -1 then let mutable ans = 0 ...
dolphin
port this code to R: ```cpp struct TreeNode { int val; TreeNode* left; TreeNode* right; }; TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { TreeNode* successor = nullptr; while (root != nullptr) { if (root->val > p->val) { successor = root; root = root->left...
dolphin
Please focus on the algorithm of this problem and provide code in Lisp: You are given several `boxes` with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., ...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. * For example, The integer `5` is `"101 "` in binary and its **complement** is `...
dolphin
Please explain the following problem in detail and provide code in Clojure: Given a string `s` and an integer `k`, return _the length of the longest_ _substring_ _of_ `s` _that contains at most_ `k` _**distinct** characters_. **Example 1:** **Input:** s = "eceba ", k = 2 **Output:** 3 **Explanation:** The substring ...
dolphin
Please write the following solution using Object Pascal: The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "`...
dolphin
port this code to Julia: ```python def minimumCapability(nums, k): n, l, r = len(nums), 1, 10**9 while l < r: mid = l + (r - l) // 2 i, cnt = 0, 0 for j in range(n): if nums[j] <= mid: cnt += 1 i = j + 2 while i + 1 < n and (i =...
dolphin
Please explain the following problem in detail and provide code in Scala: A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. * For example, the below binary watch...
dolphin
Please explain the following problem in detail and provide code in TypeScript: Given a string `s` of zeros and ones, _return the maximum score after splitting the string into two **non-empty** substrings_ (i.e. **left** substring and **right** substring). The score after splitting a string is the number of **zeros** i...
dolphin
port this code from Mojo to C#: ``` sub REMOVE_COVERED_INTERVALS(@intervals) { my $n = @intervals.elems; my @sorted_intervals = sort { $^a[0] <=> $^b[0] || $^b[1] <=> $^a[1] }, @intervals; my $count = 1; my $max_right = @sorted_intervals[0][1]; for (1..^$n) -> $i { if @sorted_intervals[$i][...
dolphin
Please explain the following problem in detail and provide code in C#: Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after re...
dolphin
Please focus on the functionality of this problem and provide code in Kotlin: You are given two arrays of positive integers, `boxes` and `warehouse`, representing the heights of some boxes of unit width and the heights of `n` rooms in a warehouse respectively. The warehouse's rooms are labelled from `0` to `n - 1` from...
dolphin
Please focus on the functionality of this problem and provide code in Fortran: Given a string `s`, return _the number of segments in the string_. A **segment** is defined to be a contiguous sequence of **non-space characters**. **Example 1:** **Input:** s = "Hello, my name is John " **Output:** 5 **Explanation:** T...
dolphin
Please write the following solution using C#: Given two strings: `s1` and `s2` with the same size, check if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. In other words `s2` can break `s1` or vice-versa. A string `x` can break string `y` (both of size `n`) if `x[i] >= y[i]` (...
dolphin
Please write the following solution using Objective-C: Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... ...
dolphin
Please explain the following problem in detail and provide code in ANSI C: You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface: * `ImmutableListNode`: An interface of immutable linked list, you are given the head of the list. You need to use ...
dolphin
convert this code to Scala: ```java public int[] smallerNumbersThanCurrent(int[] nums) { int[] result = new int[nums.length]; for (int i = 0; i < nums.length; i++) { int count = 0; for (int j = 0; j < nums.length; j++) { if (i != j && nums[j] < nums[i]) { count++; ...
dolphin
Please write the following solution using TypeScript: You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly....
dolphin
translate this code to Go: ```swift func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] { var nums = nums.sorted() var result = [[Int]]() for i in 0..<nums.count-3 { if i > 0 && nums[i] == nums[i-1] { continue } for j in i+1..<nums.count-2 { if j > i+1 && nu...
dolphin
Please explain the reasoning behind the following solution and provide code in R: There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing...
dolphin
Please explain the following problem in detail and provide code in TypeScript: There is a long table with a line of plates and candles arranged on top of it. You are given a **0-indexed** string `s` consisting of characters `'*'` and `'|'` only, where a `'*'` represents a **plate** and a `'|'` represents a **candle**. ...
dolphin
Please explain the following problem in detail and provide code in Lua: There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of lengt...
dolphin
Please explain the following problem in detail and provide code in Haskell: You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this fact...
dolphin
Please explain the following problem in detail and provide code in Clojure: Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:**...
dolphin
translate this code to TypeScript: ```fsharp open System.Collections.Generic let networkDelayTime (times: int[][]) (n: int) (k: int) = let graph = Dictionary<int, (int * int) list> () for u, v, w in times do if graph.ContainsKey(u) then graph.[u] <- (v, w) :: graph.[u] else ...
dolphin
port this code to Dart: ```lisp (defun leads-to-destination (n edges source destination) (setq graph (make-hash-table)) (dolist (edge edges) (let ((u (first edge)) (v (second edge))) (push v (gethash u graph)))) (setq visited (make-list n :initial-element 0)) (dfs source graph visited destin...
dolphin
port this code from F# to R: ```fsharp let singleNumber(nums:int[]) = let mutable ones = 0 let mutable twos = 0 for n in nums do ones <- (ones ^ n) &&& (complement twos) twos <- (twos ^ n) &&& (complement ones) ones ```
dolphin
Please explain the reasoning behind the following solution and provide code in Go: We call a positive integer **special** if all of its digits are **distinct**. Given a **positive** integer `n`, return _the number of special integers that belong to the interval_ `[1, n]`. **Example 1:** **Input:** n = 20 **Output:**...
dolphin
Please explain the following problem in detail and provide code in Objective-C: You are given two integer arrays `nums1` and `nums2`. You are tasked to implement a data structure that supports queries of two types: 1. **Add** a positive integer to an element of a given index in the array `nums2`. 2. **Count** the nu...
dolphin
Please write the following solution using PHP: A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is **valid** if **any** of the following conditions is **true**: * It is `()`. * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid parentheses string...
dolphin
Please write the following solution using Elixir: Given an integer `n`, return the `nth` digit of the infinite integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]`. **Example 1:** **Input:** n = 3 **Output:** 3 **Example 2:** **Input:** n = 11 **Output:** 0 **Explanation:** The 11th digit of the sequence 1, ...
dolphin
Please write the following solution using Elixir: There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you. You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rule...
dolphin
Please explain the following problem in detail and provide code in Go: **Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary**...
dolphin
Please explain the reasoning behind the following solution and provide code in F#: There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `ed...
dolphin
Please write the following solution using javascript: Given an integer array `nums` of size `n`, return _the number with the value **closest** to_ `0` _in_ `nums`. If there are multiple answers, return _the number with the **largest** value_. **Example 1:** **Input:** nums = \[-4,-2,1,4,8\] **Output:** 1 **Explanatio...
dolphin
translate this code to Fortran: ```dart class DinnerPlates { int capacity; List<List<int>> stacks; DinnerPlates(int capacity) { this.capacity = capacity; this.stacks = List<List<int>>(); } void push(int val) { int i = 0; while (i < stacks.length && stacks[i].length == capacity) { i++;...
dolphin
Please focus on the functionality of this problem and provide code in Elixir: Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size `groupSize`, and consists of `groupSize` consecutive cards. Given an integer array `hand` where `hand[i]` is the value written on t...
dolphin
translate this code from Scala to Clojure: ```scala import scala.util.Random class Solution(nums: Array[Int]) { private val original: Array[Int] = nums.clone() def reset(): Array[Int] = { original.clone() } def shuffle(): Array[Int] = { val shuffled: Array[Int] = original.clone() for (i <- shuff...
dolphin
Please explain the following problem in detail and provide code in Haskell: There is a room with `n` bulbs labeled from `1` to `n` that all are turned on initially, and **four buttons** on the wall. Each of the four buttons has a different functionality where: * **Button 1:** Flips the status of all the bulbs. * *...
dolphin
Please write the following solution using PHP: A password is said to be **strong** if it satisfies all the following criteria: * It has at least `8` characters. * It contains at least **one lowercase** letter. * It contains at least **one uppercase** letter. * It contains at least **one digit**. * It contain...
dolphin
Please focus on the functionality of this problem and provide code in ANSI C: You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a **limit** on the **number of boxes** and the **total weight** that it can carry. You are given an array `boxes`, where `boxe...
dolphin
Please explain the reasoning behind the following solution and provide code in Haskell: Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. ...
dolphin
Please focus on the algorithm of this problem and provide code in Visual Basic .NET: You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n...
dolphin
Please explain the following problem in detail and provide code in Fortran: A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a...
dolphin
Please explain the following problem in detail and provide code in Lisp: There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** dist...
dolphin
translate this code from Kotlin to Clojure: ```kotlin fun longestArithmeticSubsequence(nums: IntArray): Int { val n = nums.size if (n < 3) return n val dp = Array<MutableMap<Int, Int>>(n) { mutableMapOf() } var maxLength = 2 for (i in 0 until n) { for (j in i+1 until n) { ...
dolphin
Please focus on the functionality of this problem and provide code in Groovy: A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subg...
dolphin
Please explain the reasoning behind the following solution and provide code in Mojo: Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only **one repeated number** in `nums`, return _this repeated number_. You must solve the problem **without...
dolphin
Please write the following solution using Groovy: You are standing at position `0` on an infinite number line. There is a destination at position `target`. You can make some number of moves `numMoves` so that: * On each move, you can either go left or right. * During the `ith` move (starting from `i == 1` to `i =...
dolphin
port this code to c++: ```scala def latestStep(arr: Array[Int], m: Int): Int = { val n = arr.length val binaryString = Array.fill(n)(0) var latestStep = -1 var groupStart = -1 for (i <- 0 until n) { binaryString(arr(i) - 1) = 1 if (groupStart == -1 && binaryString.count(_ == 1) == m) { groupSt...
dolphin
Please explain the following problem in detail and provide code in Ruby: There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directiona...
dolphin
port this code to Objective-C: ```fortran function count_and_triples(nums) result(count) integer, intent(in) :: nums(:) integer :: n, i, j, k, mask, bit_count, count n = size(nums) count = 0 do i = 0, 30 mask = 2**i bit_count = 0 do j = 1, n if (iand(nums(j), mask...
dolphin
port this code from Perl to Clojure: ```perl sub is_prime { my $n = shift; return 0 if $n <= 1; for my $i (2 .. int(sqrt($n))) { return 0 if $n % $i == 0; } return 1; } sub count_prime_set_bits { my ($left, $right) = @_; my $count = 0; for my $i ($left .. $right) { my $b...
dolphin
translate this code from C# to Perl: ```csharp public int MaxDistance(int[][] arrays) { int maxDist = 0; int minVal = arrays[0][0]; int maxVal = arrays[0][arrays[0].Length - 1]; for (int i = 1; i < arrays.Length; i++) { maxDist = Math.Max(maxDist, Math.Max(Math.Abs(arrays[i][arrays[i].Lengt...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`. Find _the smallest set of vertices fro...
dolphin
Please explain the reasoning behind the following solution and provide code in C#: You are given a **0-indexed** string `s` consisting of only lowercase English letters, where each letter in `s` appears **exactly** **twice**. You are also given a **0-indexed** integer array `distance` of length `26`. Each letter in th...
dolphin
Please explain the following problem in detail and provide code in Visual Basic .NET: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the `MinStack` class: * `MinStack()` initializes the stack object. * `void push(int val)` pushes the element `val` onto ...
dolphin
Please write the following solution using Scheme: You are given several `boxes` with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes,...
dolphin
translate this code from Fortran to F#: ```fortran function concatenationValue(nums) result(res) integer, dimension(:), intent(inout) :: nums integer :: res, n, i character(len=10) :: num1, num2 res = 0 do while (size(nums) > 0) n = size(nums) if (n == 1) then res = res +...
dolphin
Please focus on the algorithm of this problem and provide code in Dart: You are given a **0-indexed** 1-dimensional (1D) integer array `original`, and two integers, `m` and `n`. You are tasked with creating a 2-dimensional (2D) array with `m` rows and `n` columns using **all** the elements from `original`. The element...
dolphin
port this code to Ruby: ```lua -- Definition for a Node. -- function Node(val, next, random) -- this.val = val -- this.next = next -- this.random = random -- end function copyRandomList(head) if not head then return nil end local curr = head while curr do local temp = N...
dolphin
Please write the following solution using Lisp: Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to...
dolphin
Please focus on the algorithm of this problem and provide code in TypeScript: 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 `colConditions[i] = [l...
dolphin
Please write the following solution using python: Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string. Implement the Stri...
dolphin
translate this code to PHP: ```go package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func longestConsecutive(root *TreeNode) int { var longestConsecutivePathUtil func(node *TreeNode, maxLength *int) int longestConsecutivePathUtil = func(node *TreeNode, maxLength *int) ...
dolphin
Please write the following solution using R: You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point and one move consists of walking one s...
dolphin
Please explain the following problem in detail and provide code in Haskell: Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of cand...
dolphin
Please write the following solution using Scala: You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2`...
dolphin
translate this code from C# to Visual Basic .NET: ```csharp public static string KthLargestNumber(string[] nums, int k) { Array.Sort(nums, (a, b) => a.Length == b.Length ? a.CompareTo(b) : a.Length - b.Length); return nums[nums.Length - k]; } ```
dolphin
Please explain the following problem in detail and provide code in TypeScript: There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the...
dolphin
Please write the following solution using Scala: You are given an integer `n` indicating there are `n` people numbered from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `meetings` where `meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi` have a meeting at `timei`. A person ...
dolphin
translate this code from Elixir to Julia: ```elixir defmodule Matchsticks do def makesquare(matchsticks) do if length(matchsticks) < 4 do false else total = Enum.sum(matchsticks) if rem(total, 4) != 0 do false else target = div(total, 4) matchsticks = Enum.sort(...
dolphin
convert this code from Clojure to C#: ``` MajorityChecker: - arr: array of integers - tree: TreeNode MajorityChecker(arr): - construct tree from arr query(left, right, threshold): - return query_helper(0, left, right, threshold) query_helper(node, left, right, threshold): - if node is None: - return -1 - if lef...
dolphin
Please write the following solution using Julia: Given an `m x n` integer matrix `grid` where each entry is only `0` or `1`, return _the number of **corner rectangles**_. A **corner rectangle** is four distinct `1`'s on the grid that forms an axis-aligned rectangle. Note that only the corners need to have the value `1...
dolphin