Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <h2>Play with compute function (line 10) to change cost functions and check out different results.</h2>
<br>
<button onclick='run()'>Run Again</button>
<br>
<hr>
<canvas id="canvas" width="500px" height="500px">
</canvas>
<hr>
            
          
!
            
              body span, button{
  display: block;
}

button{
  padding: 8px 10px;
  border: solid 4px rgba(5,150,50,1);
  background: #401f80;
  color: white;
  cursor: pointer;
}
            
          
!
            
              'use strict';

//	Declare number of sides of Polygon
var _N = 4;


//	Cost function for every candidate polygon
//	Comment cost statement to disable particular constraint
//	Multiply score components with scalar to add weight
Polygon.prototype.compute = function(){
	var c = this.corner;
	//	Length of each sides
	var l1 = dist(c[0].pt, c[1].pt)
	var l2 = dist(c[1].pt, c[2].pt)
	var l3 = dist(c[2].pt, c[3].pt)
	var l4 = dist(c[0].pt, c[3].pt)

	//	Length of Diagonal
	var diag1 = dist(c[0].pt, c[2].pt)
	var diag2 = dist(c[1].pt, c[3].pt)

	//	Cost for unequal side length
	this.score = Math.abs(l2 - l1) + Math.abs(l3 - l2) + Math.abs(l3 - l4) + Math.abs(l4 - l1)

	//	Add cost for diagonal to side ratio for square shape
	this.score += Math.abs(l1*1.414 - diag1) + Math.abs(l4*1.414 - diag2)

	//	Add cost for Diagonal length
	this.score += Math.abs(141.4 - diag2)

	// 	Making one side horizontal
	// this.score += Math.abs(c[0].pt[1] - c[1].pt[1])*1.5	//	Increased weight

	//	Fixing one vertex 'X' value
	this.score += Math.abs(c[0].pt[0] - 100)
	//	Fixing one sides 'Y' value
	this.score += Math.abs(c[0].pt[1] - 100)
}

function run(){
  //	Population size of 50
  var world = new Population(50)

  world.computeAll()
  //  Number of Generations
  for(var gen = 0; gen<=2000; gen ++){
    world.sort()

    // if(gen % 100 == 0)
    // 	console.log(gen, world.citizen[0].score, world.citizen[0].corner)
    var child = world.child()
    world.next(child)
    //	Replace last 10 worst solution with random
    world.add(10)
  }
  var c = world.citizen[0].corner;
  console.log( "Best score =>", world.citizen[0].score)
  //	Display 4 vertices of best solution
  for(var i=0; i<4; i++)
    console.log(c[i].pt, "Length => ", dist(c[i].pt, c[(i+1)%4].pt))

  //	Plot top  solution. Winner is plotted in red border.
  
  c2.clearRect(0,0,500,500)
  for(var i=0; i<5; i++)
    plot(world.citizen[i].corner, i)
}





function Point(n, limit) {
	this.pt = [];
	for(var i = 0; i<n; i++){
		var r = Math.random()*(limit[1]-limit[0]) + limit[0];
		this.pt.push(r)
	}

	this.mutate = function(mutation){
		for(var i = 0; i<n; i++){
			var m = (Math.random() - 0.5)*mutation*(limit[1]-limit[0])/100;
			this.pt[i] += m;
			this.pt[i] = Math.max(Math.min(this.pt[i], limit[1]), limit[0])
		}
	}
	this.copy = function(){
		var tmp = new Point(n, limit);
		for(var i = 0; i<n; i++){
			tmp.pt[i] = this.pt[i]
		}
		return tmp;
	}
}

function dist(p1, p2){
	return Math.sqrt((p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1])*(p1[1] - p2[1]))
}
function Polygon(side, limit, mutation){
	mutation /=100;
	this.corner = [];
	this.score = null;
	for(var i = 0; i<side; i++){
		this.corner.push(new Point(2, limit))
	}

	this.mutate = function(){
		for(var i = 0; i<side; i++){
			if(Math.random() < mutation){
				var m = this.score/7;
				m = Math.min(m, 10)
				// m = Math.max(m, 0.5)
				// console.log(m)
				this.corner[i].mutate(m)
			}
		}
	}

	this.copy = function(){
		var tmp = new Polygon(side, limit, mutation*100);
		for(var i = 0; i<side; i++){
			tmp.corner[i] = this.corner[i].copy()
		}
		tmp.score = this.score;
		return tmp;
	}
}

var canvas = document.querySelector('#canvas')
var c2 = canvas.getContext('2d');
function plot(corner, i){
	c2.fillStyle = '#f00';
	c2.beginPath();
	c2.strokeStyle="black";
	c2.lineWidth = 3
	if(i == 0){
		c2.strokeStyle="red";
		c2.lineWidth = 5
	}
	c2.moveTo(corner[0].pt[0], corner[0].pt[1]);
	for(var i = 1; i<4; i++)
		c2.lineTo(corner[i].pt[0], corner[i].pt[1]);

	c2.closePath();
	// c2.fill();
	c2.stroke()
}

function Population(N){
	this.citizen = []
	for(var i = 0; i<N; i++){
		this.citizen.push(new Polygon(_N, [0, 500], 60))
	}

	this.child = function(){
		var tmp = new Population(N)
		for(var i = 0; i<N; i++){
			tmp.citizen[i] = this.citizen[i].copy()
			tmp.citizen[i].mutate()
		}
		return tmp;
	}
	this.computeAll = function(){
		for( i = 0; i<N; i++){
			// console.log(this.citizen[i])
			this.citizen[i].compute()
		}
	}

	this.sort = function(){
		for(var i = 0; i < N -1; i++){
			for(var j = i; j < N; j++){
				// console.log(i, j, this.citizen.length)
				if(this.citizen[j].score < this.citizen[i].score){
					var tmp = this.citizen[j].copy()
					this.citizen[j] =  this.citizen[i].copy()
					this.citizen[i] = tmp
				}
			}
		}
	}

	this.add = function(l){
		var t = this.citizen.length
		if(Math.random() < 0.001)
			this.citizen[t - l - 1] = this.citizen[0].copy()
		for(var i = l; i>0; i--){
			if(Math.random() > 0.01)
				continue ;
			this.citizen[t - i] = new Polygon(_N, [0, 500], 50)
			this.citizen[t - i].compute()
		}
		
	}

	this.next = function(child){
		child.computeAll()
		for(var i = 0; i < N; i++){
			if(child.citizen[i].score < this.citizen[i].score)
				this.citizen[i] = child.citizen[i]
		}

	}
}


run()



            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console