<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="284413" data-post-id="284413">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rvirding" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rvirding/120/1409_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rvirding
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Creator of Erlang</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Thank you, that helped me find my mistake: I had written <code>for _ &lt; 1..100</code> instead of <code>for _ &lt;- 1..100</code></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="284413" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/56">Post #55</a>
	                </div>
	            </div>
              <div id="likers-container-284413" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="284413"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #55"></div>
  </section>
</div>
    <div class="postbit" id="284423" data-post-id="284423">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="code-shoily" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/code-shoily/120/8052_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  code-shoily
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I have just finished Chapter 3. It seems like further refactoring or Chapter 2 by introducing one new form of generalization.</p>
<p>However I did struggle to understand the difference between genotype and phenotype. I looked into the formal definition of the latter and got confused.</p>
<p>I am going to take another exploration on these two terms and update this comment with whatever I learn, otherwise move on with chapter 4 tomorrow. It’s be cool if anyone can eli5 me though.</p>
<p>It was an enjoyable chapter, some nice refresher on Elixir, and the way concepts are introduced in very small chunk is quite nice.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="284423" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/57">Post #56</a>
	                </div>
	            </div>
              <div id="likers-container-284423" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="284423"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #56"></div>
  </section>
</div>
    <div class="postbit" id="284463" data-post-id="284463">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="stevensonmt" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stevensonmt/120/20503_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  stevensonmt
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I think I’m going to stop with my posts of my “study notes”. If anyone cares to see them as a sort of terrible Cliff’s notes for the book the file is <a href="https://github.com/stevensonmt/genetic_algorithms_in_elixir/blob/main/notes.md" rel="noopener nofollow ugc">here</a>.</p>
<p>My thoughts on chapter 4:</p>
<ul>
<li>Constraint problems – TIL the term for that type of problem, really the entire motivation for me to pick up this book was frustration at solving the Einstein’s house problem on Exercism</li>
</ul>
<p>I would have thought that creating a module attribute with a map or ETS table for looking up profits and weights would be the obvious solution, but I always feel clever when I make use of <code>zip</code> functions. In this case you end up zipping over the collection every time you call the fitness function, so caching the weights and profits for later access is probably a better approach.</p>
<p>Stylistic bike-shedding alert:</p>
<blockquote>
<p><code>zip -&gt; map -&gt; sum</code> can be rewritten as <code>zip_reduce</code></p>
</blockquote>
<p>If all cargo can fit the problem is trivial, so using the total available profit for ALL cargo as a termination criteria seems odd … which was apparently the author’s point LOL.</p>
<h3><a name="p-284463-penalty-functions-1" class="anchor" href="#p-284463-penalty-functions-1" aria-label="Heading link" rel="nofollow"></a>Penalty Functions</h3>
<p>I’d like to see the penalty function defined as a private function independent of the fitness function, even if it’s only ever called by the fitness function. This would make it easier to generalize the fitness function and even include a flag in <code>opts</code> to apply a penalty or not.</p>
<h3><a name="p-284463-termination-criteria-2" class="anchor" href="#p-284463-termination-criteria-2" aria-label="Heading link" rel="nofollow"></a>Termination Criteria</h3>
<blockquote>
<p>The goal is to produce the best solution possible, even when you don’t know that it’s the absolute best.</p>
</blockquote>
<p>This concept throws me off. I’m used to thinking a fundamental concept of pure functional programming that states any function passed a given input always returns the same output. It seems that you could give a genetic algo some input and end up with slightly different output. I suppose any function interfacing with <code>:rand</code> must be impure.</p>
<p>Possible errors in OneMax example for average fitness threshold. Since population is a list of Chromosome structs, you need to first map the population to an enumerable of just genes before calculating average fitness.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">avg = population |&gt; Enum.map(&amp;Map.get(&amp;1, :genes)) |&gt; Enum.map(&amp;(Enum.sum(&amp;1) / length(&amp;1)))
</code></pre>
<p>I might be wrong, but it seem to me that all three termination criteria converge on 42 and never terminate b/c the fitness function is just the sum and the Genetic module sorts by <code>&gt;=</code> after applying the fitness function. To achieve convergence to minimum the fitness function needs to be changed to <code>Enum.sum(choromosome.genes) * -1</code>. The average is trickier. Perhaps <code>Genetic.evaluate/3</code> should be passed a sorter function in addition to the fitness function. This could be included in <code>opts</code> keyword list.</p>
<p>Tracking time since last improvement → light bulb moment for me.</p>
<p>Schema and theorems and heuristics, oh my! Getting into the fancy words now. <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<p>With multiple factor optimization applying weights to various factors makes me think these weights should be passed to the fitness function in <code>opts</code>. Maybe require something like <code>fitness_factors</code> with guards to catch that all keys in <code>opts.fitness_factors</code> are fields in <code>chromosome</code>.</p>
<p>Perceptual data – ranking cannot be calculated mathematically but ranking by user can transform into mathematical fitness via interactive fitness functions that require user input. Coming from a background of constantly interfacing with people to acquire, weight, and sort various types of information for deductive processing, this type of data is much more interesting to me.</p>
<p><a class="mention" href="/u/code-shoily" rel="nofollow">@code-shoily</a> – regarding genotype vs phenotype, think of it as the encoded data vs the data itself. For the ship cargo example, the phenotype refers to the collection of crates defined by their weight and profit, but the genotype is just the list of ones and zeroes that encode which crates are selected.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="284463" data-batch-url="/posts/batch_likers">
                        3
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/58">Post #57</a>
	                </div>
	            </div>
              <div id="likers-container-284463" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="284463"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #57"></div>
  </section>
</div>
    <div class="postbit" id="284841" data-post-id="284841">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rvirding" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rvirding/120/1409_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rvirding
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Creator of Erlang</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Yay! I have finally completed chapter 1, no it wasn’t difficult just couldn’t find the time. Anyway I have been amusing myself with translating it from Elixir to Erlang. Pretty straight forward  once you realise exactly how all the <code>Enum</code> functions work. My goal is to NOT use Elixir libraries but only standard Erlang stuff. We shall see how it goes in later chapters, especially when migrating from <code>mix</code> to <code>rebar3</code>.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="284841" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/59">Post #58</a>
	                </div>
	            </div>
              <div id="likers-container-284841" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="284841"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #58"></div>
  </section>
</div>
    <div class="postbit" id="284965" data-post-id="284965">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="seanmor5" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/seanmor5/120/20610_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  seanmor5
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Author of Genetic Algorithms in Elixir</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I am glad to see so many people enjoying the book <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<p>If you end up with questions or find errata you can let me know. I don’t have a ton of time but I can try to help. If you enjoy the book, please leave a review on <a href="https://www.amazon.com/Genetic-Algorithms-Elixir-Problems-Evolution-ebook/dp/B091M4QJXZ/ref=sr_1_1?crid=228B9496W8JRX&amp;keywords=genetic+algorithms+in+elixir&amp;qid=1681397781&amp;sprefix=genetic+algorithms+in+elixir%2Caps%2C110&amp;sr=8-1" rel="noopener nofollow ugc">Amazon</a>. It really helps!</p>
<p>Finally, in a little bit I hope to be able to share something for the next Machine Learning focused book club <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="284965" data-batch-url="/posts/batch_likers">
                        6
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/60">Post #59</a>
	                </div>
	            </div>
              <div id="likers-container-284965" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="284965"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #59"></div>
  </section>
</div>
    <div class="postbit" id="286068" data-post-id="286068">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="stevensonmt" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stevensonmt/120/20503_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  stevensonmt
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Sorry for letting the momentum slow on this thread. Life, <img src="https://forum.elixirforum.com/images/emoji/apple/person_shrugging.png?v=15" title=":person_shrugging:" class="emoji" alt=":person_shrugging:" loading="lazy" width="20" height="20"></p>
<p>Here are my thoughts on chapter 5 to try and get things moving again.</p>
<h2><a name="p-286068-selection-is-biased-sampling-is-it-1" class="anchor" href="#p-286068-selection-is-biased-sampling-is-it-1" aria-label="Heading link" rel="nofollow"></a>Selection is biased sampling (is it?)</h2>
<ul>
<li>Selection rate might be an important factor for the Sudoku problem …</li>
</ul>
<blockquote>
<p>Not sure I agree that selection and statistical sampling are variations on the same theme. Statistical sampling is an attempt to define or describe a population based on a limited number of individuals. Selection is about applying a definition or description to individuals to create the population you want.</p>
</blockquote>
<ul>
<li>High selection rates should slow convergence but improve diversity (I think)</li>
</ul>
<h2><a name="p-286068-importance-of-selection-pressure-2" class="anchor" href="#p-286068-importance-of-selection-pressure-2" aria-label="Heading link" rel="nofollow"></a>Importance of Selection Pressure</h2>
<ul>
<li>Selection pressure of 1 is fully random? I would have thought selection pressure of 1 was fully elite while a pressure of 0 was fully randm.</li>
</ul>
<blockquote>
<p>One extreme, when there is no selection pressure, is completely stochastic so that the search acts just like the Monte Carlo method [8], randomly sampling the space of feasible solutions.</p>
</blockquote>
<ul>
<li>
<p><a href="https://ecs.wgtn.ac.nz/foswiki/pub/Main/TechnicalReportSeries/ECSTR09-10.pdf" rel="noopener nofollow ugc">https://ecs.wgtn.ac.nz/foswiki/pub/Main/TechnicalReportSeries/ECSTR09-10.pdf</a></p>
</li>
<li>
<p>Higher selection pressure leads to faster convergence</p>
</li>
</ul>
<h2><a name="p-286068-types-of-selection-3" class="anchor" href="#p-286068-types-of-selection-3" aria-label="Heading link" rel="nofollow"></a>Types of Selection</h2>
<p>I don’t understand how rewards based selection differs from fitness based selection. Feels like you’re just shifting the fitness function to some mapping or reducing function that accumulates rewards and then determining fitness based on those rewards. I guess it doesn’t matter that I don’t understand the difference since the author says the book will only use fitness based selection strategies.</p>
<p>One thing I’ve been struck by in reading this book is how many times I read something and think, “Why not do this instead?” or “Would it make sense to also do this?” and then the next page answers that exact question. For instance, this is from my notes made while reading chapter 5:</p>
<blockquote>
<p>Creating a Selection Toolbox<br>
CODE! Nice way to implement multiple strategies for the library. I think I still struggle with when to implement behaviours versus hard coding for things like this. Ideally I think <code>Toolbox</code> module would define some sort of behaviour for implementing strategies. So maybe there’s a <code>selection</code> callback but also a <code>mutation</code> and <code>crossover</code> callback. Then you implement some defaults with like <code>Toolbox.Selection</code> module but users of the lib can extend with their own versions without having to touch the lib code.</p>
</blockquote>
<p>In chapter 6 there is absolutely a Toolbox.Crossover module being introduced.</p>
<h2><a name="p-286068-adjusting-the-selection-rate-4" class="anchor" href="#p-286068-adjusting-the-selection-rate-4" aria-label="Heading link" rel="nofollow"></a>Adjusting the Selection Rate</h2>
<pre data-code-wrap="elixir"><code class="lang-elixir">n = round(length(population) * select_rate)
n = if rem(n, 2) == 0, do: n, else: n + 1
</code></pre>
<p>looks weird to me. I don’t like the immediate rebinding. I’d rewrite as something like:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">n =
  case round(length(population) * select_rate) do
    x when rem(x, 2) == 0 -&gt; x
    x -&gt; x + 1
  end
</code></pre>
<p>In getting the diff between population and parents, is using <code>MapSet</code> intermediate structure more efficient than just <code>Enum.filter</code>? I would guess only noticeably so for very large population/parent sizes.</p>
<blockquote>
<p>Roulette selection is by far the slowest and most difficult algorithm to implement</p>
</blockquote>
<p>Why would that be the case? Seems like it would have been a way to speed up convergence in tournament by weighting competitors towards more fit individuals.</p>
<p>Regarding implementation of roulette I prefer the <code>Stream.repeatedly(...) |&gt; Enum.take(n)</code> pattern. I also don’t like the implementation for the “roulette wheel spin” because I believe it will be influenced by the order in which chromosomes are placed in the list. I think a more precise way of doing “weighted random” selection would be something like</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">population
|&gt; Enum.reduce([], fn chromosome, weighted_population -&gt; Enum.reduce(1..chromosome.fitness, weighted_population, fn _ -&gt; [chromosome | weighted_population] end) end)
|&gt; Enum.random()
</code></pre>
<p>I do recognize this is not an efficient implementation but it avoids unintentionally favoring items at the beginning of the list.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="286068" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/61">Post #60</a>
	                </div>
	            </div>
              <div id="likers-container-286068" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="286068"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #60"></div>
  </section>
</div>
    <div class="postbit" id="286090" data-post-id="286090">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="polvalente" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/polvalente/120/33450_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  polvalente
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Nx Core Team</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>For the “weighted random” selection, if using Nx, the Nx.Random.choice function accepts an optional probability tensor that can be constructed from the fitness functions, instead of generating a flat list from those ranges. You’d have something like the code below. I’m not exactly sure of what a chromosome actually contains, but this just represents an arbitrary map with the fitness key present <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<pre data-code-wrap="elixir"><code class="lang-elixir">iex(1)&gt; Mix.install [:nx]
:ok
iex(2)&gt; key = Nx.Random.key(System.system_time())
#Nx.Tensor&lt;
  u32[2]
  [391705150, 368691609]
&gt;
iex(3)&gt; chromosomes = [%{data: :a, fitness: 9}, %{data: :b, fitness: 1}]
[%{data: :a, fitness: 9}, %{data: :b, fitness: 1}]
iex(4)&gt; fitness = chromosomes |&gt; Enum.map(&amp; &amp;1.fitness) |&gt; Nx.tensor()
#Nx.Tensor&lt;
  s64[2]
  [9, 1]
&gt;
iex(5)&gt; probs = Nx.divide(fitness, Nx.sum(fitness))
#Nx.Tensor&lt;
  f32[2]
  [0.8999999761581421, 0.10000000149011612]
&gt;
iex(6)&gt; idx = Nx.tensor([0, 1])
#Nx.Tensor&lt;
  s64[2]
  [0, 1]
&gt;
iex(7)&gt; {idx, new_key} = Nx.Random.choice(key, idx, probs, samples: 5)
{#Nx.Tensor&lt;
   s64[5]
   [0, 1, 0, 0, 0]
 &gt;,
 #Nx.Tensor&lt;
   u32[2]
   [3343452330, 3272391746]
 &gt;}
iex(8)&gt; idx |&gt; Nx.to_list() |&gt; Enum.map(&amp;Enum.at(chromosomes, &amp;1))
[
  %{data: :a, fitness: 9},
  %{data: :b, fitness: 1},
  %{data: :a, fitness: 9},
  %{data: :a, fitness: 9},
  %{data: :a, fitness: 9}
]
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="286090" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/62">Post #61</a>
	                </div>
	            </div>
              <div id="likers-container-286090" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="286090"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #61"></div>
  </section>
</div>
    <div class="postbit" id="286091" data-post-id="286091">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="stevensonmt" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stevensonmt/120/20503_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  stevensonmt
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>That’s pretty nice. What’s the <code>key</code> parameter doing in the <code>Nx.Random.choice/4</code> call?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="286091" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/63">Post #62</a>
	                </div>
	            </div>
              <div id="likers-container-286091" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="286091"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #62"></div>
  </section>
</div>
    <div class="postbit" id="286092" data-post-id="286092">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="polvalente" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/polvalente/120/33450_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  polvalente
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Nx Core Team</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Nx.Random is built on top of a stateless PRNG concept, so the key is what carries the state forward, but in a functional way. In general, the functions you’ll normally use will <code>Nx.Random.split</code> the key so that it can be used for whatever inside, and the other half is passed forward.</p>
<p>You can think of it as if each <code>:rand</code> call returned a new seed for you to pass into <code>:rand.seed</code> before calling the next function, in a deterministic way.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="286092" data-batch-url="/posts/batch_likers">
                        3
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/64">Post #63</a>
	                </div>
	            </div>
              <div id="likers-container-286092" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="286092"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #63"></div>
  </section>
</div>
    <div class="postbit" id="286761" data-post-id="286761">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="stevensonmt" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/stevensonmt/120/20503_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  stevensonmt
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Finished chapter 6. Super interesting and I appreciated the invitation to do implementations of other crossover strategies as an exercise. Here are my implementations for messy single point, multipoint, and cycle crossover strategies. Could do with some guards/specs because the implementations depend on the chromosome definition used in the book. Tips/critiques welcome!</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def messy_single_point(p1, p2) do
    cx1 = :rand.uniform(length(p1.genes) - 1)
    cx2 = :rand.uniform(length(p2.genes) - 1)
    {h1, t1} = Enum.split(p1.genes, cx1)
    {h2, t2} = Enum.split(p2.genes, cx2)
    c1 = h1 ++ t2
    c2 = h2 ++ t1
    {%Chromosome{genes: c1, size: length(c1)}, %Chromosome{genes: c2, size: length(c2)}}
  end

  def multipoint(p1, p2, k) do
    cxs =
      Stream.repeatedly(fn -&gt; :rand.uniform(length(p1.genes) - 1) end)
      |&gt; Enum.take(k)

    cxs
    |&gt; Enum.reduce({p1.genes, p2.genes}, fn cx, {c1, c2} -&gt;
      [{h1, t1}, {h2, t2}] = Enum.map([c1, c2], &amp;Enum.split(&amp;1, cx))
      {h1 ++ t2, h2 ++ t1}
    end)
    |&gt; Tuple.to_list()
    |&gt; Enum.map(fn genes -&gt; %Chromosome{genes: genes, size: length(genes)} end)
    |&gt; List.to_tuple()
  end

  def cycle(p1, p2) do
    [arr1, arr2] =
      [p1.genes, p2.genes]
      |&gt; Enum.map(fn list -&gt;
        list |&gt; Enum.with_index() |&gt; Map.new(fn {v, k} -&gt; {k, v} end)
      end)

    cycle_helper(arr1, arr2, 0, %{}, %{})
  end

  defp cycle_helper(arr1, arr2, ndx, c1, c2) do
    if arr1[ndx] in Map.values(c1) do
      cycle_completed(arr1, arr2, c1, c2)
    else
      v1 = Map.get(arr1, ndx)
      v2 = Map.get(arr2, ndx)
      c1 = Map.put(c1, ndx, v1)
      c2 = Map.put(c2, ndx, v2)
      ndx = find_index(v1, arr2)
      cycle_helper(arr1, arr2, ndx, c1, c2)
    end
  end

  defp cycle_completed(arr1, arr2, c1, c2) do
    [{arr2, c1}, {arr1, c2}]
    |&gt; Enum.map(fn {p, c} -&gt;
      p
      |&gt; Enum.reduce(c, fn {k, v}, acc -&gt;
        Map.put_new(acc, k, v)
      end)
    end)
    |&gt; Enum.map(fn map -&gt; map |&gt; Enum.sort_by(fn {k, _v} -&gt; k end) |&gt; Enum.map(&amp;elem(&amp;1, 1)) end)
    |&gt; Enum.map(fn genes -&gt; %Chromosome{genes: genes, size: length(genes)} end)
    |&gt; List.to_tuple()
  end

  defp find_index(val, arr) do
    arr |&gt; Enum.find(fn {_k, v} -&gt; v == val end) |&gt; elem(0)
  end
</code></pre>
<p>I leaned heavily on <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5676484/" rel="noopener nofollow ugc">this paper</a> for the cycle implementation, and of course the author’s own <a href="https://hexdocs.pm/genex/operators-crossover.html#messy-single-point-crossover" rel="noopener nofollow ugc">Genex lib</a> for the messy single point implementation.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="286761" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/genetic-algorithms-in-elixir-book-club/54827/65">Post #64</a>
	                </div>
	            </div>
              <div id="likers-container-286761" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="286761"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #64"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <a class="load-more-button" data-turbo-stream="true" href="/topics/54827/load_more?page=7">Load more posts (8 remaining)</a>
</div></template></turbo-stream>