Abhinay - 4 months ago 16

Ruby Question

I might be asking a silly question here. So, I trying to apply addition and subtraction on one or more item of an array using Ruby. The problem is I want to do all possible operation(either + 1 or - 1) on each item of an array.

for ex: if

`ary = [1,2]`

What I am trying to achieve is an array:

`[[1+1, 2+1],[1-1,2-1], [1+1, 2-1], [1-1, 2+1]]`

basically all possible operations on item

`[++, --, +-, -+]`

I first thought permutation could solve this issue but its only gives samples :

`[['+', '-'], ['-', '+']]`

I am not sure if this could be solved by applying a formula to get all sample space from probability. Also, I do know that assigning

`1`

`+`

`0`

`-`

`[00, 01, 10, 11]`

What should I do programmatically in order to achieve the same, Can someone guide me to the right track?

P.S.: length of array can vary.

Answer

The problem is I want to do all possible operation(either + 1 or - 1) on each item of an array.

You can put all operations in one array and numbers in the second. Then you can iterate over them to cover all cases:

```
operations = %i(+ -)
data = [1, 2, 3]
data.each do |x|
data.each do |y|
operations.each do |operation|
p "#{x} #{operation} #{y} = #{x.send(operation, y)}"
end
end
end
```

This script will produce the following output:

```
"1 + 1 = 2"
"1 - 1 = 0"
"1 + 2 = 3"
"1 - 2 = -1"
"1 + 3 = 4"
"1 - 3 = -2"
"2 + 1 = 3"
"2 - 1 = 1"
"2 + 2 = 4"
"2 - 2 = 0"
"2 + 3 = 5"
"2 - 3 = -1"
"3 + 1 = 4"
"3 - 1 = 2"
"3 + 2 = 5"
"3 - 2 = 1"
"3 + 3 = 6"
"3 - 3 = 0"
```

If you want to do operations against 1 and not against all elements from the input array, you can do it in the following way:

```
operations = %i(+ -)
data = [1, 2, 3]
data.each do |x|
operations.each do |operation|
p "#{x} #{operation} #{1} = #{x.send(operation, 1)}"
end
end
```

which will give:

```
"1 + 1 = 2"
"1 - 1 = 0"
"2 + 1 = 3"
"2 - 1 = 1"
"3 + 1 = 4"
"3 - 1 = 2"
```