Reducing by steps
Description:
Data: an array of integers, a function f of two variables and an init value.
Example: a = [2, 4, 6, 8, 10, 20], f(x, y) = x + y; init = 0
Output: an array of integers, say r, such that
r = [r[0] = f(init, a[0]), r[1] = f(r[0], a[1]), r[2] = f(r[1], a[2]), ...]
With our example: r = [2, 6, 12, 20, 30, 50]
Task:
Write the following functions of two variables
- som : (x, y) -> x + y
- mini : (x, y) -> min(x, y)
- maxi : (x, y) -> max(x, y)
- lcmu : (x, y) -> lcm(abs(x), abs(y) (see note for lcm)
- gcdi : (x, y) -> gcd(abs(x), abs(y) (see note for gcd)
and
function
oper_array(fct, arr, init)
(or operArray or oper-array) wherefct
is the function of two variables to apply to the arrayarr
(fct will be one ofsom, mini, maxi, lcmu or gcdi
)init
is the initial value
Examples:
a = [18, 69, -90, -78, 65, 40]
oper_array(gcd, a, a[0]) => [18, 3, 3, 3, 1, 1]
oper_array(lcm, a, a[0]) => [18, 414, 2070, 26910, 26910, 107640]
oper_array(sum, a, 0) => [18, 87, -3, -81, -16, 24]
oper_array(min, a, a[0]) => [18, 18, -90, -90, -90, -90]
oper_array(max, a, a[0]) => [18, 69, 69, 69, 69, 69]
Notes:
The form of the parameter
fct
in oper_array (or operArray or oper-array) changes according to the language. You can see each form according to the language in "Your test cases".AFAIK there are no corner cases, everything is as nice as possible.
lcm and gcd see: https://en.wikipedia.org/wiki/Least_common_multiple https://en.wikipedia.org/wiki/Greatest_common_divisor
you could google "reduce function (your language)" to have a general view about the reduce functions.
In Shell bash, arrays are replaced by strings.
In OCaml arrays are replaced by lists.
Similar Kata:
Stats:
Created | Mar 21, 2016 |
Published | Mar 21, 2016 |
Warriors Trained | 19904 |
Total Skips | 5087 |
Total Code Submissions | 22444 |
Total Times Completed | 4522 |
Ruby Completions | 115 |
Python Completions | 964 |
JavaScript Completions | 1203 |
CoffeeScript Completions | 17 |
Haskell Completions | 174 |
Clojure Completions | 39 |
Java Completions | 305 |
C# Completions | 170 |
Elixir Completions | 96 |
C++ Completions | 225 |
PHP Completions | 99 |
TypeScript Completions | 91 |
Crystal Completions | 10 |
F# Completions | 45 |
C Completions | 191 |
OCaml Completions | 47 |
Rust Completions | 231 |
Swift Completions | 122 |
Go Completions | 313 |
R Completions | 34 |
Nim Completions | 19 |
Shell Completions | 20 |
Kotlin Completions | 94 |
Julia Completions | 32 |
Scala Completions | 88 |
Reason Completions | 5 |
Racket Completions | 21 |
VB Completions | 23 |
Prolog Completions | 16 |
Pascal Completions | 7 |
Lua Completions | 36 |
Perl Completions | 10 |
Raku Completions | 7 |
Elm Completions | 6 |
D Completions | 5 |
Erlang Completions | 8 |
Factor Completions | 7 |
Total Stars | 306 |
% of votes with a positive feedback rating | 84% of 675 |
Total "Very Satisfied" Votes | 502 |
Total "Somewhat Satisfied" Votes | 129 |
Total "Not Satisfied" Votes | 44 |