I am trying to see if there is a functional approach to the problem that I am trying to do. The way I’m doing it right now is very imperative and using variables a lot.
I am trying to implement Order One crossover for Genetic Algorithm.
Input: two lists of integers of the same length (9)
list_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list_2 = [9, 3, 7, 8, 2, 6, 5, 1, 4]
Procedure:
Choose two random numbers between 0 and 8 (the length of one list minus one), say, 3 and 6
Make an empty list (or list with a placeholder) of length 9, say result = [nil, nil, nil, nil, nil, nil, nil, nil, nil]
From list_1, take the elements from index 3 and 6, therefore [4, 5, 6, 7], and put it in the result list at the same, index, so becomes [nil, nil, nil, 4, 5, 6, 7, nil, nil]
From list_2, starting from index 6 + 1, and iterate in circular fashion, take an element that is not present yet in result list and append it in a cycle. Sorry if this doesn’t make sense, but basically, since from list_2, the elements starting from index 6 + 1 and cycling it, will be 1, 4, 9, 3, 7, 8, 2, 6, 5, and since we will be taking only numbers that are not present in result, so we will be taking only 1, 9, 3, 8, 2. I have to append these numbers to result starting from index 6 + 1, in circular fashion:
[nil, nil, nil, 4, 5, 6, 7, nil, nil]
[nil, nil, nil, 4, 5, 6, 7, 1, nil]
[nil, nil, nil, 4, 5, 6, 7, 1, 9]
[3, nil, nil, 4, 5, 6, 7, 1, 9]
[3, 8, nil, 4, 5, 6, 7, 1, 9]
[3, 8, 2, 4, 5, 6, 7, 1, 9]
Also, should I post questions like this on Elixir forum or Stack Overflow? Sorry if I shouldn’t post this here.
Looking at the description (without analysing it too much) it looks like it’s an algorithm that’s supposed to work on arrays. Using lists to do the work of an array, you’re going to have a bad time.
In theory, lookup performance (in our case). Maps are O(log n), while lists are O(n). However, I ran some benchmarks and it wasn’t until both parents contained upwards of 120 elements that p1_contrib_set started to seriously beat out p1_contrib in the worst case. At shorter lengths p1_contrib performed better.