Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for splitting array into (element => remaining elements) pairs

Tags:

ruby

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.

like image 914
Stefan Avatar asked May 08 '15 10:05

Stefan


People also ask

Which method is used to split two arrays?

We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.

How do you split an array into 3 parts?

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..

How do you split an array into a group?

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.


1 Answers

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.

like image 120
Piotr Kruczek Avatar answered Nov 15 '22 19:11

Piotr Kruczek