S
S
selbi2017-10-23 19:08:56
PHP
selbi, 2017-10-23 19:08:56

How to find an algorithm?

Dear colleagues, I can not solve the problem in any way, I ask for help. I'm developing a study project, and there I need to do the following:
Given:
$array = [1, 2, 3, 4, 5];
Result:
1 | 2 | 3
1 | 2 | 4
1 | 2 | 5
1 | 3 | 4
1 | 3 | 5
1 | 4 | 5
2 | 3 | 4
2 | 3 | 5
2 | 4 | 5
3 | 4 | 5
There is the above array of numbers (for example, there are actually words there, but I don’t think it matters). From this array, you need to get all kinds of strings consisting of 3 numbers. Only the order is very important, it must not be violated, that is, as in an array and 5 | 2 | 1, for example, we cannot do. In words, I know how this is done, the above is an example of all possible options, but I don’t know how to describe it in the code. The bottom line is that we take the first 2 elements (1 and 2 are obtained) and substitute the 3rd element from the remaining elements of the array, so we get 1|2|n where n are all the elements of the array that did not fall into the first 2 places, then we take 1| 3|n, 1|4|n and so on until the end.
PS There should not be any duplicates, that is, 1|1|n, for example, we cannot do.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2017-10-23
@selbi

If the number 3 is hardcoded, the simplest is a triple loop

для i = [0..n—2)
  для j = [i+1..n−1)
    для k = [j+1..n)

If it is not rigid, then we get this.
Initially, the array is initialized with the numbers 0, 1, 2. A step is such a complex operation.
We add one to the last element. If it is greater than n−1, then we rotate the second iteration of the loop - we add 1 to the penultimate one, if it is greater than n−2, we rotate the third one.
If the loop went through the entire array and never ended, the iteration is over. Otherwise, we go forward along the array and fill the tail with numbers a[i]+1, a[i]+2…

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question