0

I need to generate 2D array in rails from a set of given strings. For example:

days =[ "Monday",
     "Tuesday",
     "Wednesday",
  ]

Now I want to create a 2D array and the data in this array will be fill by using days string in random manner.

Example:

[monday, tuesday, wednesday],
[tuesday, wednesday, monday]
...

and so on depends on given dimensions

How to do it?

Edit

I tried this

# global variable
@@test_array = %w(:sunday :monday :tuesday)

def get_data(row, col)
 @data_field =  @@test_array.permutation.to_a(col)
return @data_field.slice!(row)

If I pass row:1 and col:1 It is working but If i pass a big number like 20 in rows and column it is storing null in database.

Edit-2

days = ["monday, "tuesday"]
rows = 3
col = 3

It should return (one of the possible solution due to random generation)

[[monday, tuesday, monday],[tuesday, monday, tuesday], [monday, monday, tuesday]]

1 Answer 1

2

You can use Array#permutation if you don't want repetetions in the subarrays.

  • col1 ∈ [1; 3]
  • row2 ∈ [0; 3]
days.permutation(col).to_a.slice(0, row)

Demonstration

If you want repetitions in the subarrays, you can use Array#repeated_permutation.

  • col ∈ [1; 3]
  • row ∈ [0; 33(= 27)]:
days.repeated_permutation(col).to_a.slice(0, row)

Demonstration

If you want repetitions in the subarrays and also expand your column number to the custom, independent from length of the original array number, you can use Array#repeated_combination.

  • col ∈ [1; ∞3 )
  • row ∈ [0; colcol]:
days.repeated_combination(col).to_a.slice(0, row)

Demonstration


1 col is the number of elements in each subarray.
2 row is the number of subarrays in the desired 2D array.
3 The upper bound is specified as to represent that this value is not bounded by the length of the original array.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! But where can i apply the limit of rows and column?
@AmitPal: Well, with specified argument from 1 to the length you can control the number of columns, the number of rows can be cut off with slice method.
@AmitPal: Well, as I said, you can specify argument from 1 to length, in your case, from 1 to 3. It is all about possible combinations, you can't build 20 different combinations from 3 values – 3! = 3*2*1 = 6. So, you can have maximum 2d array of 3x6 and minimum of 1x1( or just empty array, if it counts).
I think you misunderstood me. I wanted to generate a matrix from the set of given string with a given dimension. Please have a look at the Edit-2 section
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.