Given an array literal, I would like to create a hash where the keys are the elements from the array and the values are arrays containing the other / remaining elements.
Input:
[1, 2, 3]
Output:
{1=>[2, 3], 2=>[1, 3], 3=>[1, 2]}
It's easy if I introduce a variable:
arr = [1, 2, 3]
arr.map { |i| [i, arr - [i]] }.to_h
But with an array literal, the only solution I could come up with involves instance_exec
or instance_eval
, which seems hackish:
[1, 2, 3].instance_exec { map { |i| [i, self - [i]] } }.to_h
Am I overlooking a built-in method or an obvious solution? group_by
, combination
, permutation
and partition
don't seem to help.
We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.
Consider an array A of n integers. Determine if array A can be split into three consecutive parts such that sum of each part is equal. If yes then print any index pair(i, j) such that sum(arr[0..i]) = sum(arr[i+1..
We are required to write a JavaScript function that takes in an array of literals and a number and splits the array (first argument) into groups each of length n (second argument) and returns the two-dimensional array thus formed.
I've come up with something like this:
[1,2,3].permutation.to_a.map{ |e| [e.shift, e] }.to_h
However this has a flaw: it assigns the same key many times, but since you don't care about the sequence of the elements inside this might be a "good enough" solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With