Intersection

by evgkch

HTML

<canvas id="canvas"></canvas>

JavaScript

const ORDER = 1 << 9

const random = segment => () => Math.floor(Math.random() * segment)

const sign = Math.sign

const createRandomPoint = random => new Int32Array([random(), random()])

const createRandomLine = random => [
	createRandomPoint(random),
  createRandomPoint(random)
]

const createRandomLinesList = random => length => Array.from({ length }, () => createRandomLine(random))

const createLinesList = createRandomLinesList(random(ORDER));

console.time('createRandomLinesList')
const linesList = createLinesList(1000)
console.timeEnd('createRandomLinesList')

const area = (a, b, c) => a[0] * (b[1] - c[1]) - a[1] * (b[0] - c[0]) + (b[0] * c[1] - b[1] * c[0]);

const isIntersect = (ab, cd) =>
	(sign(area(ab[0], ab[1], cd[0])) !== sign(area(ab[0], ab[1], cd[1]))) && 
  (sign(area(cd[0], cd[1], ab[0])) !== sign(area(cd[0], cd[1], ab[1])))
  
console.time('experiment')
let length = linesList.length,
    count = 0;
    
for (i = 0; i < length; i++) {
	for (j = 0; j < length; j++) {  	
  	if (i !== j) {
    	if (isIntersect(linesList[i], linesList[j]))
      	count++
    }
  }
}
console.timeEnd('experiment')
console.log(count / 2)

function render(linesList) {
	const canvas = document.getElementById('canvas')
  canvas.width = ORDER
  canvas.height = ORDER
  const ctx = canvas.getContext('2d')
  ctx.beginPath()
  linesList.forEach(line => {
    ctx.moveTo(...line[0]);
    ctx.lineTo(...line[1]);
    ctx.stroke();
  })
  ctx.closePath()
}

render(linesList)