instruction_seed
stringlengths
29
40.5k
source
stringclasses
6 values
port this code from Ruby to Clojure: ```ruby def min_time_to_eat_grains(hens, grains) hens.sort! grains.sort! left, right = 0, 10**9 while left < right mid = left + (right - left) / 2 can_eat = true i = 0 for grain in grains if i >= hens.length ...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: You are painting a fence of `n` posts with `k` different colors. You must paint the posts following these rules: * Every post must be painted **exactly one** color. * There **cannot** be three or more **consecutive** posts with t...
dolphin
convert this code to Elixir: ```javascript function brokenCalc(startValue, target) { let operations = 0; while (target > startValue) { target = (target % 2 === 0) ? target / 2 : target + 1; operations++; } return operations + startValue - target; } ```
dolphin
port this code to c++: ```erlang -module(max_tastiness). -export([max_tastiness/2]). max_tastiness(Price, K) -> SortedPrice = lists:sort(Price), LenPrice = length(Price), MaxTastiness = 0, MaxIndex = LenPrice - K + 1, max_tastiness(SortedPrice, MaxIndex, K, MaxTastiness, LenPrice - 1). max_tastin...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes: * At the first minute, color **any** arbitrary un...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball. In one operation, you can move **one** ball from a box to an adjac...
dolphin
translate this code to Kotlin: ```cpp #include <string> std::string largestMerge(std::string word1, std::string word2) { std::string merge = ""; while (!word1.empty() || !word2.empty()) { if (word1 > word2) { merge += word1[0]; word1 = word1.substr(1); } else { ...
dolphin
Please explain the reasoning behind the following solution and provide code in Clojure: Given a string `s`, encode the string such that its encoded length is the shortest. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. `k` should be...
dolphin
Please focus on the functionality of this problem and provide code in javascript: Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_. You must write an algori...
dolphin
Please focus on the algorithm of this problem and provide code in Object Pascal: 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** `(...
dolphin
Please write the following solution using ANSI C: You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of...
dolphin
convert this code to Fortran: ```objective-c #define MOD 1000000007 int numberOfWays(int target, int **types, int typesSize, int *typesColSize){ int* dp = calloc(target + 1, sizeof(int)); dp[0] = 1; for (int i = 0; i < typesSize; i++) { int* dptmp = calloc(target + 1, sizeof(int)); for (int...
dolphin
translate this code from Mojo to Julia: ``` sub least_square_sum(n) { my @dp = (Inf) x ($n + 1); $dp[0] = 0; for my $i (1..$n) { my $j = 1; while ($j * $j <= $i) { $dp[$i] = min($dp[$i], $dp[$i - $j * $j] + 1); $j += 1; } } return $dp[$n]; } ```
dolphin
port this code to c++: ```swift func maxTarget(nums: [Int], key: Int) -> Int { var counter = [Int: Int]() var maxTarget = -1 var maxCount = -1 for i in 0..<nums.count-1 { if nums[i] == key { if let count = counter[nums[i+1]] { counter[nums[i+1]] = count + 1 ...
dolphin
Please write the following solution using javascript: You are given an integer array `nums`. You should move each element of `nums` into one of the two arrays `A` and `B` such that `A` and `B` are non-empty, and `average(A) == average(B)`. Return `true` if it is possible to achieve that and `false` otherwise. **Note...
dolphin
Please write the following solution using Go: Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` charac...
dolphin
Please explain the following problem in detail and provide code in Kotlin: Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.) _(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smalle...
dolphin
Please focus on the functionality of this problem and provide code in Go: Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._ * In other words, if the number of positive integers in `nums` is `pos` and the number ...
dolphin
convert this code from Rust to Lua: ```rust fn min_operations(nums: Vec<i32>) -> i32 { let n = nums.len(); let mut idx0 = -1; for i in 0..n { if nums[i] == 0 { idx0 = i as i32; break; } } let mut cnt1 = 0; let mut cnt2 = 0; for i in 1..n { i...
dolphin
Please focus on the efficiency of this problem and provide code in TypeScript: You are given an integer array `values` where values\[i\] represents the value of the `ith` sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them. The score of a pair (`i < j`) of sightseeing spots is ...
dolphin
Please write the following solution using Fortran: Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`. The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. You must writ...
dolphin
Please focus on the functionality of this problem and provide code in PHP: You are given an `m x n` integer matrix `mat` and an integer `target`. Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. Return _t...
dolphin
Please write the following solution using javascript: You are given the `root` of a **binary tree** with `n` nodes. Each node is assigned a unique value from `1` to `n`. You are also given an array `queries` of size `m`. You have to perform `m` **independent** queries on the tree where in the `ith` query you do the fo...
dolphin
Please explain the reasoning behind the following solution and provide code in Ruby: 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 up...
dolphin
port this code to Lua: ```rust fn divisibility_array(word: &str, m: i32) -> Vec<i32> { let mut div = Vec::new(); let mut value = 0; for c in word.chars() { value = (value * 10 + (c as i32 - '0' as i32)) % m; div.push(if value == 0 { 1 } else { 0 }); } div } ```
dolphin
port this code to Fortran: ```lua function maxDistToClosest(seats) local n = #seats local maxDist = 0 local lastPerson = -1 for i=1,n do if seats[i] == 1 then if lastPerson == -1 then maxDist = i else maxDist = math.max(maxDist, math.floor...
dolphin
convert this code to c++: ```ruby def longest_beautiful_substring(word) vowels = ['a', 'e', 'i', 'o', 'u'] max_len = 0 curr_len = 0 seen = Set.new word.each_char do |char| if !vowels.include?(char) if seen.length == 5 max_len = [max_len, curr_len].max ...
dolphin
port this code to python: ```c #include<stdio.h> #include<math.h> int longestWellPerformingInterval(int* hours, int hoursSize){ int sum = 0, longest = 0; int first_sum_index[hoursSize]; for(int i=0; i<hoursSize; i++){ int hour = hours[i]; if(hour > 8) sum += 1; else ...
dolphin
Please write the following solution using Rust: You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`. The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (...
dolphin
Please explain the reasoning behind the following solution and provide code in TypeScript: A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacen...
dolphin
Please explain the following problem in detail and provide code in Lua: You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`. Return _the nu...
dolphin
translate this code to Swift: ```haskell minSwaps :: [Int] -> Int minSwaps nums = ones - maxOnes where ones = sum nums (maxOnes, _, _) = foldl (\(maxOnes, currOnes, left) num -> let currOnes' = currOnes + num in if length nums - left + 1 > ones then (max maxOnes (currOnes' - nums !! ...
dolphin
Please focus on the algorithm of this problem and provide code in Scala: Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced p...
dolphin
Please explain the following problem in detail and provide code in Haskell: Given two sparse vectors, compute their dot product. Implement class `SparseVector`: * `SparseVector(nums)` Initializes the object with the vector `nums` * `dotProduct(vec)` Compute the dot product between the instance of _SparseVector_ a...
dolphin
Please explain the reasoning behind the following solution and provide code in Go: You are given an integer array `nums` and an integer `k`. For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. The **score** of `nums` is the difference between the maximum and ...
dolphin
Please focus on the efficiency of this problem and provide code in Mojo: The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters. * For example, the beauty of `"abaacc "` is `3 - 1 = 2`. Given a string `s`, return _the sum of **beauty** of all of its subst...
dolphin
port this code from Julia to TypeScript: ```julia function knightProbability(n::Int, k::Int, row::Int, column::Int)::Float64 memo = [[[-1.0 for i in 0:k] for j in 0:n-1] for k in 0:n-1] return helper(n, k, row, column, memo) end function helper(n::Int, k::Int, row::Int, column::Int, memo::Array{Array{Array{Flo...
dolphin
Please explain the reasoning behind the following solution and provide code in c++: You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river. A frog, initially on the first stone, wants to travel to the last stone and then return to th...
dolphin
Please focus on the functionality of this problem and provide code in Groovy: On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard....
dolphin
Please explain the following problem in detail and provide code in java: You are given an integer array `nums` consisting of `2 * n` integers. You need to divide `nums` into `n` pairs such that: * Each element belongs to **exactly one** pair. * The elements present in a pair are **equal**. Return `true` _if nums...
dolphin
Please write the following solution using Perl: Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of...
dolphin
Please explain the following problem in detail and provide code in Groovy: You are given an array of strings `words` and a string `chars`. A string is **good** if it can be formed by characters from chars (each character can only be used once). Return _the sum of lengths of all good strings in words_. **Example 1:**...
dolphin
port this code from c++ to Visual Basic .NET: ```cpp #include <vector> using namespace std; vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) { int m = mat.size(); int n = mat[0].size(); vector<vector<int>> answer(m, vector<int>(n, 0)); for (int i = 0; i < m; ++i) { for (int ...
dolphin
Please write the following solution using Go: You are given a binary array `nums` and an integer `k`. A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`. Return _the minimum number of **k-bit flips** ...
dolphin
port this code from Lua to PHP: ```lua function AuthenticationManager(timeToLive) local tokens = {} local function generate(tokenId, currentTime) tokens[tokenId] = currentTime + timeToLive end local function renew(tokenId, currentTime) if tokens[tokenId] == nil or tokens[tokenId] <= currentTime then ...
dolphin
convert this code from Groovy to Kotlin: ```groovy class TreeNode { int val; TreeNode left, right; TreeNode(int x) {val = x;} } int sumEvenGrandparent(TreeNode root, TreeNode parent = null, TreeNode grandparent = null) { if (root == null) return 0; int sum = grandparent && grandparent.val % 2 == 0 ...
dolphin
Please write the following solution using C#: Given two integer arrays `nums1` and `nums2` of length `n`, count the pairs of indices `(i, j)` such that `i < j` and `nums1[i] + nums1[j] > nums2[i] + nums2[j]`. Return _the **number of pairs** satisfying the condition._ **Example 1:** **Input:** nums1 = \[2,1,2,1\], nu...
dolphin
Please write the following solution using Kotlin: You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix. To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will ...
dolphin
Please explain the reasoning behind the following solution and provide code in Julia: You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` an...
dolphin
Please explain the reasoning behind the following solution and provide code in TypeScript: Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that: * `0 <= i, j, k, l < n` * `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0` **Example ...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Exam...
dolphin
Please focus on the functionality of this problem and provide code in c++: 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 start a...
dolphin
port this code to Scala: ```dart class NumMatrix { List<List<int>> dp; NumMatrix(List<List<int>> matrix) { final m = matrix.length; final n = matrix[0].length; dp = List.generate(m + 1, (_) => List.filled(n + 1, 0)); for (var i = 1; i <= m; i++) { for (var j = 1; j <= n; j++) { ...
dolphin
Please write the following solution using Elixir: You are given a **0-indexed** string array `words`. Two strings are **similar** if they consist of the same characters. * For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`. * However, `"abacba "` and `"bcfd "`...
dolphin
port this code from Lisp to Erlang: ``` (defun count-avg-nodes (root) (let ((total-nodes 0)) (labels ((dfs (node) (when node (let ((left-result (dfs (node-left node))) (right-result (dfs (node-right node)))) (let ((left-sum (car left-result...
dolphin
translate this code to ANSI C: ````php function maxNonOverlapping($nums, $target) { $prefix_sum = array(0 => 0); $sum = 0; $count = 0; foreach ($nums as $num) { $sum += $num; if (array_key_exists($sum - $target, $prefix_sum)) { $count = max($count, 1 + $prefix_sum[$sum - $tar...
dolphin
translate this code to python: ```dart import 'dart:collection'; List<List<int>> reconstructMatrix(int upper, int lower, List<int> colsum) { int n = colsum.length; List<List<int>> matrix = List.generate(2, (index) => List.filled(n, 0)); for (int i = 0; i < n; i++) { if (colsum[i] == 2) { matrix[0][i] =...
dolphin
port this code to Scheme: ```julia function reverse_bits(n::UInt32)::UInt32 res = 0 for i in 0:31 res = res << 1 res = res | (n & 1) n = n >> 1 end return res end ```
dolphin
Please focus on the algorithm of this problem and provide code in PHP: Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1...
dolphin
port this code to Julia: ```c #include <stdio.h> #include <string.h> int longestSubstring(char* s, int k) { if (!s || k <= 0) return 0; int char_count[26] = {0}; int len = strlen(s); for (int i = 0; i < len; ++i) ++char_count[s[i] - 'a']; for (int i = 0; i < 26; ++i) ...
dolphin
convert this code from Swift to Rust: ```swift import Foundation func maxSumSubmatrix(_ matrix: [[Int]], _ k: Int) -> Int { let rows = matrix.count let cols = matrix[0].count var max_sum = Int.min for l in 0..<cols { var sums = [Int](repeating: 0, count: rows) for r in l..<cols { ...
dolphin
Please explain the reasoning behind the following solution and provide code in Object Pascal: Given an integer array `arr`, count how many elements `x` there are, such that `x + 1` is also in `arr`. If there are duplicates in `arr`, count them separately. **Example 1:** **Input:** arr = \[1,2,3\] **Output:** 2 **Expl...
dolphin
port this code to F#: ```rust fn min_max_deletions(nums: &Vec<i32>) -> i32 { let n = nums.len(); let (mut min_index, mut max_index) = (0, 0); for i in 1..n { if nums[i] < nums[min_index] { min_index = i; } if nums[i] > nums[max_index] { max_index = i; ...
dolphin
Please explain the following problem in detail and provide code in TypeScript: Given a `time` represented in the format `"HH:MM "`, form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. You may assume the given input string is always valid. For example, `"...
dolphin
Please focus on the efficiency of this problem and provide code in Swift: A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"ab...
dolphin
convert this code to Groovy: ```ruby require 'heapq' def count_rectangles(rectangles, points) res = Array.new(points.length, 0) pq = PriorityQueue.new visited = Array.new(rectangles.length, false) rectangles.each_with_index do |rect, i| pq.push([0, 0, rect[0], rect[1], i], 0) end whil...
dolphin
Please focus on the functionality of this problem and provide code in java: You are given a string `s` containing lowercase English letters, and a matrix `shift`, where `shift[i] = [directioni, amounti]`: * `directioni` can be `0` (for left shift) or `1` (for right shift). * `amounti` is the amount by which string...
dolphin
convert this code to python: ```go func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) } func gcdOfStrings(str1 string, str2 string) string { n1, n2 := len(str1), len(str2) gcdLen := gcd(n1, n2) substring := str1[:gcdLen] if strings.Repeat(substring, n1/gcdLen) == str...
dolphin
Please write the following solution using Elixir: You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal t...
dolphin
convert this code to Swift: ```mojo sub kBigIndices(nums as int[], k as int) as int n = len(nums) left = [0] * n right = [0] * n for i in 1..n-1 do if nums[i] > nums[i-1] then left[i] = left[i-1] + 1 end j = n - i - 1 if nums[j] < nums[j+1] then ...
dolphin
convert this code to Swift: ```fsharp let rec closestValue (root: TreeNode) (target: float) = let mutable closest = root.val let mutable current = root while current IsNot null do if abs(target - closest) > abs(target - current.val) then closest <- current.val current <- if targe...
dolphin
Please explain the reasoning behind the following solution and provide code in Scheme: Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head. **Example 1:** **Input:** head = \[1,2,3,4,5\], n = 2 **Output:** \[1,2,3,5\] **Example 2:** **Input:** head = \[1\], n = 1 **...
dolphin
Please explain the reasoning behind the following solution and provide code in python: Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each rep...
dolphin
Please explain the reasoning behind the following solution and provide code in ANSI C: Given an array `arr` of positive integers, consider all binary trees such that: * Each node has either `0` or `2` children; * The values of `arr` correspond to the values of each **leaf** in an in-order traversal of the tree. * ...
dolphin
translate this code to Visual Basic .NET: ```scala def cellRange(s: String): List[String] = { val r1 = s(1).toString.toInt val r2 = s(4).toString.toInt val c1 = s(0).toString.charAt(0) - 'A' + 1 val c2 = s(3).toString.charAt(0) - 'A' + 1 var res = List[String]() for (c <- c1 to c2; r <- r1 ...
dolphin
translate this code to ANSI C: ```pascal function boolean_expression_evaluation(expression: string): boolean; var stack: array of boolean; sub_expr, sub_exprs: array of boolean; i: integer; begin setlength(stack, 0); i := 1; while i <= length(expression) do begin case expression[i] of 't': stac...
dolphin
Please explain the following problem in detail and provide code in C#: Given a palindromic string of lowercase English letters `palindrome`, replace **exactly one** character with any lowercase English letter so that the resulting string is **not** a palindrome and that it is the **lexicographically smallest** one poss...
dolphin
Please focus on the functionality of this problem and provide code in Rust: You are given several logs, where each log contains a unique ID and timestamp. Timestamp is a string that has the following format: `Year:Month:Day:Hour:Minute:Second`, for example, `2017:01:01:23:59:59`. All domains are zero-padded decimal num...
dolphin
translate this code to Kotlin: ```erlang % Definition of a binary tree node -record(tree, {val, left = null, right = null}). longest_consecutive_sequence(null, LongestPath) -> 0; longest_consecutive_sequence(#tree{val=Val, left=Left, right=Right}=Node, LongestPath) -> LeftPath = longest_consecutive_sequence(Le...
dolphin
Please write the following solution using javascript: Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array `stones`, where `stones[i]` is the **value** of the `ith` stone. Alice and Bob take turns, with **Alice** starting fir...
dolphin
Please explain the reasoning behind the following solution and provide code in Lua: You are given an array of integers `distance`. You start at the point `(0, 0)` on an **X-Y plane,** and you move `distance[0]` meters to the north, then `distance[1]` meters to the west, `distance[2]` meters to the south, `distance[3]`...
dolphin
Please explain the following problem in detail and provide code in Objective-C: A room is represented by a **0-indexed** 2D binary matrix `room` where a `0` represents an **empty** space and a `1` represents a space with an **object**. The top left corner of the room will be empty in all test cases. A cleaning robot s...
dolphin
port this code from Groovy to Elixir: ```groovy import java.util.PriorityQueue List<Integer> oceanView(List<Integer> heights) { int n = heights.size() List<Integer> oceanView = [] int maxHeight = 0 for (int i = n-1; i >= 0; i--) { if (heights[i] > maxHeight) { maxHeight = heights[i]...
dolphin
convert this code from Fortran to Ruby: ```fortran function maxSubArray(nums) result(max_sum) integer, intent(in) :: nums(:) integer :: max_sum, current_sum, i max_sum = nums(1) current_sum = nums(1) do i = 2, size(nums) current_sum = max(current_sum + nums(i), nums(i)) max_sum = ma...
dolphin
Please focus on the efficiency of this problem and provide code in c++: Given two integers `n` and `k`, construct a list `answer` that contains `n` different positive integers ranging from `1` to `n` and obeys the following requirement: * Suppose this list is `answer = [a1, a2, a3, ... , an]`, then the list `[|a1 - ...
dolphin
Please explain the following problem in detail and provide code in Julia: You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers. All gardens have **at...
dolphin
port this code to Go: ```scheme (define (min-operations nums) (let ((min-prefix 0) (prefix 0)) (do ((i 0 (+ i 1))) ((= i (length nums))) (set! prefix (+ prefix (list-ref nums i))) (set! min-prefix (min min-prefix prefix))) (if (< min-prefix 0) (- min-prefix) 0))) ``...
dolphin
translate this code from Julia to Erlang: ```julia using DataStructures function min_product_kth(nums1::Vector{Int}, nums2::Vector{Int}, k::Int)::Int n1 = length(nums1) n2 = length(nums2) lo = nums1[1] * nums2[1] hi = nums1[n1] * nums2[n2] while lo < hi mid = lo + (hi - lo) ÷ 2 coun...
dolphin
Please focus on the algorithm of this problem and provide code in Swift: You are given a **0-indexed** integer array `nums`. Rearrange the values of `nums` according to the following rules: 1. Sort the values at **odd indices** of `nums` in **non-increasing** order. * For example, if `nums = [4,**1**,2,**3**]` ...
dolphin
Please explain the following problem in detail and provide code in Lua: The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), f...
dolphin
translate this code to java: ```dart class Solution { int minDeletions(List<String> strs) { int n = strs.length; int m = strs[0].length; int deletions = 0; for (int j = 0; j < m; j++) { for (int i = 1; i < n; i++) { if (strs[i][j].compareTo(strs[i - 1][j]) < 0) { deletions++; ...
dolphin
Please focus on the functionality of this problem and provide code in Erlang: Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows * `a, b` are ...
dolphin
convert this code to Mojo: ```lisp (defun min-minutes (garbage travel) (let ((time-garbage (list 0 0 0)) (time-travel (list 0 0 0))) (dotimes (i (length garbage)) (let ((g (nth i garbage)) (m (count #\M g)) (p (count #\P g)) (q (count #\G g))) (incf (nth 0...
dolphin
translate this code to Dart: ```vb.net Public Function GetSmallerAngle(hour As Integer, minutes As Integer) As Double Dim hourAngle As Double = (hour Mod 12 + minutes / 60) * 30 Dim minuteAngle As Double = minutes * 6 Dim angle As Double = Math.Abs(hourAngle - minuteAngle) Return Math.Min(angle, 360 - a...
dolphin
translate this code from Object Pascal to Lua: ```pascal type TNodeState = (nsUnvisited, nsVisited, nsSafe, nsUnsafe); function SafeNodes(graph: TArray<TArray<Integer>>): TArray<Integer>; var n, i: Integer; safeNodes: TList<Integer>; visitedNodes, unsafeNodes: TDictionary<Integer, TNodeState>; procedure DFS...
dolphin
convert this code to Lua: ``` class Cashier def __init__(self, n: int, discount: int, products: array, prices: array) -> Self self.n = n self.discount = discount self.customer_count = 0 self.prices_map = {} for i in range(len(products)): self.prices_map[products[...
dolphin
Please write the following solution using Objective-C: You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * ...
dolphin
Please write the following solution using F#: We are given `n` different types of `stickers`. Each sticker has a lowercase English word on it. You would like to spell out the given string `target` by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than on...
dolphin
Please write the following solution using PHP: Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack....
dolphin
Please explain the following problem in detail and provide code in Perl: There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, ...
dolphin