### Path repulsion 2.0 ðŸ‘£

More wandering walkers on a lonely stroll avoid crossing paths like in Path repulsion ðŸ‘£, but now they're not crossing fences and possibly sticking to existing paths and this turtle populates and repopulates using a number of strategies.

Path repulsion 2.0 ðŸ‘£
Path repulsion 2.0 ðŸ‘£ (variation)
Path repulsion 2.0 ðŸ‘£ (variation)
Path repulsion 2.0 ðŸ‘£ (variation)

```// Forked from "Path repulsion ðŸ‘£" by Jurgen
// https://turtletoy.net/turtle/a3bc45f018

// Path repulsion. Created by Jurgen Westerhof 2024

const seed = 'Empty seed is random every run.'; //type=string The seed to use for all Math.random() calls
const size = 90; //min=10 max=100 step=1 The size of the drawing
const population = 1; //min=0 max=4 step=.01 Multiplier of walker population per area
const populator = 4; //min=0 max=7 step=1 (Random, InOutCircular, ImplosionCircular, InOutMarginCircular, Centrifuge, Vortex, Bi-Directional Vortex, Squared) Specifies how to populate the scene
const pencils = 1; //min=1 max=10 step=1 The number of different colored pensils to use in a plot. Be sure to supply the same seed for different channels.
const drawPencil = 1; //min=1 max=10 step=1 The color to plot. Be sure to supply the same seed for different pencils.
const draw = 0; //min=0 max=2 step=1 (All, Fenced, Non-fenced) Set this to fenced or unfenced if you want to use different pens to plot inside or outside the fence
const repulsion = 1.29; //min=1 max=3 step=.01 The distance of proximity detection for existing paths
const repopulate = 20; //min=0 max=100 step=1 How many times to repopulate after a generatation of walkers has run out of space to walk
const repopulator = 5; //min=0 max=7 step=1 (Random, InOutCircular, ImplosionCircular, InOutMarginCircular, Centrifuge, Vortex, Bi-Directional Vortex, Squared) Specifies how to repopulate the scene
const reverseWhenDone = 1; //min=0 max=1 step=1 (No, Yes) When a walker reached a dead end continue to walk from the path origin in the other direction
const sticky = 1; //min=0 max=1 step=1 (No, Yes) After the first proximity hit stick to the path the walker avoids and any other path it encounters in the future
const fence = 1; //min=0 max=10 step=1 (None, Circle, Line, Triangle, Square, Pentagon, Hexagon, Heptagon, Octagon, Nonagon, Decagon) The scape of an optional fence
const fenceRadius = .66; //min=0 max=1 step=.01 The size of the optional fence
const fenceRepulsion = 1; //min=.5 max=4 step=.01 The distance for proximity detection of the fence
const maxIterations = 0; //min=0 max=400 step=1 Maximum iterations to draw, 0 or empty value means no limit
const drawWalkersAsOne = 0; //min=0 max=1 step=1 (No, Yes) Setting this to YES will postpone drawing until every path is calculated so a plotter can draw continuous lines for the walkers

const config = {
populationMultiplier: population**2,
populator: populator,
repopulator: repopulator,
channels: pencils,
drawChannel: Math.min(drawPencil, pencils),
drawFenced: draw < 2,
drawUnfenced: draw != 1,
size: size,
repulsion: repulsion,
sticky: sticky == 1,
repopulate: repopulate,
reverseWhenDone: reverseWhenDone == 1,
fence: fence,
fenceRepulsion: Math.max(repulsion / 2, fenceRepulsion),
walkerDirectionLength: fence == 0? repulsion: Math.min(Math.max(repulsion / 2, fenceRepulsion), repulsion),
maxIterations: maxIterations, //Math.abs(parseInt((maxIterations == ''?'0':maxIterations).replace(/\D/g,''))),
drawWalkersAsOne: drawWalkersAsOne == 1,
};

// Seedable random number generator by David Bau: http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html
!function(a,b,c,d,e,f,g,h,i){function j(a){var b,c=a.length,e=this,f=0,g=e.i=e.j=0,h=e.S=[];for(c||(a=[c++]);d>f;)h[f]=f++;for(f=0;d>f;f++)h[f]=h[g=s&g+a[f%c]+(b=h[f])],h[g]=b;(e.g=function(a){for(var b,c=0,f=e.i,g=e.j,h=e.S;a--;)b=h[f=s&f+1],c=c*d+h[s&(h[f]=h[g=s&g+b])+(h[g]=b)];return e.i=f,e.j=g,c})(d)}function k(a,b){var c,d=[],e=typeof a;if(b&&"object"==e)for(c in a)try{d.push(k(a[c],b-1))}catch(f){}return d.length?d:"string"==e?a:a+"\0"}function l(a,b){for(var c,d=a+"",e=0;e<d.length;)b[s&e]=s&(c^=19*b[s&e])+d.charCodeAt(e++);return n(b)}function m(c){try{return o?n(o.randomBytes(d)):(a.crypto.getRandomValues(c=new Uint8Array(d)),n(c))}catch(e){return[+new Date,a,(c=a.navigator)&&c.plugins,a.screen,n(b)]}}function n(a){return String.fromCharCode.apply(0,a)}var o,p=c.pow(d,e),q=c.pow(2,f),r=2*q,s=d-1,t=c["seed"+i]=function(a,f,g){var h=[];f=1==f?{entropy:!0}:f||{};var o=l(k(f.entropy?[a,n(b)]:null==a?m():a,3),h),s=new j(h);return l(n(s.S),b),(f.pass||g||function(a,b,d){return d?(c[i]=a,b):a})(function(){for(var a=s.g(e),b=p,c=0;q>a;)a=(a+c)*d,b*=d,c=s.g(1);for(;a>=r;)a/=2,b/=2,c>>>=1;return(a+c)/b},o,"global"in f?f.global:this==c)};if(l(c[i](),b),g&&g.exports){g.exports=t;try{o=require("crypto")}catch(u){}}else h&&h.amd&&h(function(){return t})}(this,[],Math,256,6,52,"object"==typeof module&&module,"function"==typeof define&&define,"random");
Math.seedrandom(seed == ''? (new Date().getTime()): seed);

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(1);

// Global code will be evaluated once.
init();
const turtle = new Turtle();

const MODE_INACTIVE = 0;
const MODE_NORMAL = 1;
const MODE_REVERSE = 2;

class Walker {
constructor(turtle, position, direction, maxTurn = Math.PI /2, turnResolution = Math.PI / 360) {
this.t = turtle;
this.p = position;
this.d = direction;
this.mt = maxTurn;
this.tr = turnResolution;
this.mode = MODE_NORMAL;
this.startPosition = position.map(v => v);
this.otherDirection = V.scale(direction, -1);
this.scene = null;

this.fenced = false;

this.turnPreference = Math.random() < .5? 1: -1;
this.channel = (config.channels * Math.random() | 0) + 1;

this.stickTo = null;

this.history = [this.p];
this.postPath = [this.p];
this.ignoreHistoryLength = (config.repulsion / config.walkerDirectionLength | 0) + 1;
}
tryCandidates() {
if(config.sticky && this.stickTo !== null) {
const turnSteps = (this.mt / this.tr) | 0
for(let t = -turnSteps * this.tr; t < turnSteps * this.tr; t += this.tr) {
const rotatedD = V.trans(V.rot2d(this.stickTo*t), this.d);
const candidateP = V.add(this.p, rotatedD);
if(!this.scene.proximityToRegistered(candidateP, this.history.slice(-this.ignoreHistoryLength), config.repulsion)) {
return [candidateP, rotatedD];
}
}
return false;
}

for(let sign = 1; sign >= -1; sign-=2) {
for(let t = 0; t <= this.mt; t += this.tr) {
const rotatedD = V.trans(V.rot2d(this.turnPreference*sign*t), this.d);
const candidateP = V.add(this.p, rotatedD);
if(!this.scene.proximityToRegistered(candidateP, this.history.slice(-this.ignoreHistoryLength), config.repulsion)) {
if(t > 0 && config.sticky) {
this.stickTo = -sign;
}
return [candidateP, rotatedD];
}
}
}
return false;
}
step() {
if(this.mode === MODE_INACTIVE) return;
this.t.jump(this.p);

const candidateP_RotatedD = this.tryCandidates();

if(candidateP_RotatedD === false) {
if(this.mode == MODE_REVERSE || !config.reverseWhenDone) {
this.mode = 0;
return;
}
this.p = this.startPosition;
this.d = this.otherDirection;
this.stickTo = null;
this.postPath = this.postPath.reverse();
this.history = this.history.slice(0, this.ignoreHistoryLength).reverse();
this.mode = MODE_REVERSE;
return this.step();
}
this.p = candidateP_RotatedD[0];
this.d = candidateP_RotatedD[1];
if(
!config.drawWalkersAsOne
&&
this.channel == config.drawChannel
&&
((config.drawFenced && this.fenced) || (config.drawUnfenced && !this.fenced))
) {
this.t.goto(this.p);
}
this.postPath.push(this.p);
this.history.push(this.p);
this.scene.registerPoint(this.p);
}
setScene(scene) {
this.scene = scene;
}
}

class WalkerScene {
constructor(s, binSize = 2) {
this.walkers = [];
this.s = s;
this.binSize = binSize;
this.bins = [];
for(let x = -120; x <= 120; x++) {
const xBin = (x/binSize)|0;
if(this.bins[xBin] == undefined) this.bins[xBin] = [];
for(let y = -120; y <= 120; y++) {
const yBin = (y/binSize)|0;
if(this.bins[xBin][yBin] == undefined) this.bins[xBin][yBin] = [];
}
}
this.fencePoints = [];
this.registered = 0;
}
walker.setScene(this);

walker.fenced = this.fencePoints.lenght == 0? false: Intersection.inside(this.fencePoints, walker.p);
this.walkers.push(walker);
this.registerPoint(walker.p);
}
registerFence(point, threshold = (config.repulsion / 2)**2) {
if(this.registered > this.fencePoints.length) {
throw new Error('Cannot add fence points after normal point has been registered');
}
this.fencePoints.push(point);
this.registerPoint(point, threshold);
}
registerPoint(point, threshold = config.repulsion**2) {
this.registered++;
const xBin = (point[0] / this.binSize) | 0;
const yBin = (point[1] / this.binSize) | 0;
this.bins[xBin - 1][yBin - 1].push([point.map(v => v), threshold]);
this.bins[xBin - 1][yBin    ].push([point.map(v => v), threshold]);
this.bins[xBin - 1][yBin + 1].push([point.map(v => v), threshold]);
this.bins[xBin    ][yBin - 1].push([point.map(v => v), threshold]);
this.bins[xBin    ][yBin    ].push([point.map(v => v), threshold]);
this.bins[xBin    ][yBin + 1].push([point.map(v => v), threshold]);
this.bins[xBin + 1][yBin - 1].push([point.map(v => v), threshold]);
this.bins[xBin + 1][yBin    ].push([point.map(v => v), threshold]);
this.bins[xBin + 1][yBin + 1].push([point.map(v => v), threshold]);
}
proximityToRegistered(p, excludings = []) {
if(p[0] < -this.s || p[0] > this.s || p[1] < -this.s || p[1] > this.s) return true;

const xBin = (p[0] / this.binSize) | 0;
const yBin = (p[1] / this.binSize) | 0;

for(let i = 0; i < this.bins[xBin][yBin].length; i++) {
if(excludings.some(excluding => V.equals(this.bins[xBin][yBin][i][0], excluding))) continue;
if(V.lenSq(V.sub(this.bins[xBin][yBin][i][0], p)) < this.bins[xBin][yBin][i][1]) return true;
}
return false;
}
step() {
this.walkers.forEach(walker => walker.step(this));
}
hasActive() {
return this.walkers.some(w => w.mode !== MODE_INACTIVE);
}
}

const fences = [
(scene) => { //circle
const r = config.fenceRadius * config.size;
const stepSize = config.walkerDirectionLength / (4 * Math.PI * r);
let rad = 0;
while(rad < 2 * Math.PI) {
scene.registerFence([
], config.fenceRepulsion);
}
},
(scene) => { //polygon
const r = config.fenceRadius * config.size;
const pts = Array.from({length: config.fence}).map((e, i, a, f=2*Math.PI*i/config.fence) => [
r * Math.sin(f),
r * -Math.cos(f)
]);
const l = 2 * V.len(pts[0], pts[1]) / config.fenceRepulsion | 0;

pts.flatMap(
(pt, ptI) => Array.from({length: l}).map((e, i) => V.lerp(pt, pts[(ptI+1)%pts.length], i/l))
).forEach(pt => scene.registerFence(pt, config.fenceRepulsion));
}
];

const populators = [
(turtle) => { //random
return new Walker(
turtle,
[Math.random() * config.size * 2 - config.size, Math.random() * config.size * 2 - config.size],
V.scale(V.norm([Math.random()-.5, Math.random()-.5]), config.walkerDirectionLength)
)
},
(turtle) => { //circularWalker 1
const newPt = [Math.random() * config.size * 2 - config.size, Math.random() * config.size * 2 - config.size];
return new Walker(
turtle,
newPt,
V.scale(V.norm(newPt), V.len(newPt) > config.size?config.walkerDirectionLength: -config.walkerDirectionLength)
);
},
(turtle) => { //circularWalker 2
while(true) {
const newPt = [Math.random() * config.size * 2 - config.size, Math.random() * config.size * 2 - config.size];
const l = V.len(newPt);
if(config.size / 3 < l && 2 * config.size / 3 < l) continue;

return new Walker(
turtle,
newPt,
V.scale(V.norm(newPt), V.len(newPt) > config.size?config.walkerDirectionLength: -config.walkerDirectionLength)
);
}
},
(turtle) => { //circularWalker 3
while(true) {
const newPt = [Math.random() * config.size * 2 - config.size, Math.random() * config.size * 2 - config.size];
const l = V.len(newPt);
if(config.size / 3 < l && l < 2 * config.size / 3) continue;

return new Walker(
turtle,
newPt,
V.scale(V.norm(newPt), V.len(newPt) > config.size / 2?config.walkerDirectionLength: -config.walkerDirectionLength)
);
}
},
(turtle) => { //centrifuge
const newPt = [Math.random() * config.size * 2 - config.size, Math.random() * config.size * 2 - config.size];
return new Walker(
turtle,
newPt,
V.scale(V.norm(newPt), config.walkerDirectionLength)
);
},
(turtle) => { //Vortex
const newPt = [Math.random() * config.size * 2 - config.size, Math.random() * config.size * 2 - config.size];
return new Walker(
turtle,
newPt,
V.trans(V.rot2d(Math.PI/2), V.scale(V.norm(newPt), config.walkerDirectionLength))
);
},
(turtle) => { //Bi-Directional Vortex
const newPt = [Math.random() * config.size * 2 - config.size, Math.random() * config.size * 2 - config.size];
return new Walker(
turtle,
newPt,
V.trans(V.rot2d((Math.random() < .5? 1: -1) * Math.PI/2), V.scale(V.norm(newPt), config.walkerDirectionLength))
);
},
(turtle) => { //Squared
const newPt = [Math.random() * config.size * 2 - config.size, Math.random() * config.size * 2 - config.size];
return new Walker(
turtle,
newPt,
[[1,0],[0,1],[-1,0],[0,-1]][Math.random() * 4 | 0]
);
},
];

const ws = new WalkerScene(config.size, config.walkerDirectionLength * 2);
if(config.fence > 0) {
fences[config.fence == 1? 0: 1](ws);
}
for(let i = 0; i < config.populationMultiplier * config.size**2 / 10; i++) {
const walker = populators[populator](turtle);
if(ws.proximityToRegistered(walker.p)) continue;
}
let tries = 0;
let postDraw = -1;

function endTurtle() {
if(config.drawWalkersAsOne) {
postDraw = 0;
return true;
}
return false;
}

// The walk function will be called until it returns false.
function walk(i) {
if(postDraw > -1) {
if(postDraw >= ws.walkers.length) return false;
ws.walkers[postDraw].postPath.forEach((e, i) => turtle[i == 0?'jump':'goto'](e));
postDraw++;
return true;
}

if(config.maxIterations !== 0 && i > config.maxIterations) return endTurtle();

ws.step();

if(!ws.hasActive()) {
if(tries == config.repopulate) {
return endTurtle();
}

tries++;

for(let i = 0; i < config.populationMultiplier * config.size**2 / 10; i++) {
const walker = populators[repopulator](turtle);
if(ws.proximityToRegistered(walker.p)) continue;
}
}

return true;
}

function init() {
///////////////////////////////////////////////////////
// Vector functions - Created by Jurgen Westerhof 2024
///////////////////////////////////////////////////////
class Vector {
static add  (a,b) { return a.map((v,i)=>v+b[i]); }
static sub  (a,b) { return a.map((v,i)=>v-b[i]); }
static mul  (a,b) { return a.map((v,i)=>v*b[i]); }
static div  (a,b) { return a.map((v,i)=>v/b[i]); }
static scale(a,s) { return a.map(v=>v*s); }

static det(m)                { return m.length == 1? m[0][0]: m.length == 2 ? m[0][0]*m[1][1]-m[0][1]*m[1][0]: m[0].reduce((r,e,i) => r+(-1)**(i+2)*e*this.det(m.slice(1).map(c => c.filter((_,j) => i != j))),0); }
static angle(a)              { return Math.PI - Math.atan2(a[1], -a[0]); } //compatible with turtletoy heading
static rot2d(angle)          { return [[Math.cos(angle), -Math.sin(angle)], [Math.sin(angle), Math.cos(angle)]]; }
static rot3d(yaw,pitch,roll) { return [[Math.cos(yaw)*Math.cos(pitch), Math.cos(yaw)*Math.sin(pitch)*Math.sin(roll)-Math.sin(yaw)*Math.cos(roll), Math.cos(yaw)*Math.sin(pitch)*Math.cos(roll)+Math.sin(yaw)*Math.sin(roll)],[Math.sin(yaw)*Math.cos(pitch), Math.sin(yaw)*Math.sin(pitch)*Math.sin(roll)+Math.cos(yaw)*Math.cos(roll), Math.sin(yaw)*Math.sin(pitch)*Math.cos(roll)-Math.cos(yaw)*Math.sin(roll)],[-Math.sin(pitch), Math.cos(pitch)*Math.sin(roll), Math.cos(pitch)*Math.cos(roll)]]; }
static trans(matrix,a)       { return a.map((v,i) => a.reduce((acc, cur, ci) => acc + cur * matrix[ci][i], 0)); }
//Mirror vector a in a ray through [0,0] with direction mirror
static mirror2d(a,mirror)    { return [Math.atan2(...mirror)].map(angle => this.trans(this.rot2d(angle), this.mul([-1,1], this.trans(this.rot2d(-angle), a)))).pop(); }

static equals(a,b)   { return !a.some((e, i) => e != b[i]); }
static approx(a,b,p) { return this.len(this.sub(a,b)) < (p === undefined? .001: p); }
static norm  (a)     { return this.scale(a,1/this.len(a)); }
static len   (a)     { return Math.hypot(...a); }
static lenSq (a)     { return a.reduce((a,c)=>a+c**2,0); }
static lerp  (a,b,t) { return a.map((v, i) => v*(1-t) + b[i]*t); }
static dist  (a,b)   { return Math.hypot(...this.sub(a,b)); }

static dot  (a,b)   { return a.reduce((a,c,i) => a+c*b[i], 0); }
static cross(...ab) { return ab[0].map((e, i) => ab.map(v => v.filter((ee, ii) => ii != i))).map((m,i) => (i%2==0?-1:1)*this.det(m)); }
}
this.V = Vector;

class Intersection2D {
//a-start, a-direction, b-start, b-direction
//returns false on no intersection or [[intersection:x,y], scalar a-direction, scalar b-direction
static info(as, ad, bs, bd) { const d = V.sub(bs, as), det = -V.det([bd, ad]); if(det === 0) return false; const res = [V.det([d, bd]) / det, V.det([d, ad]) / det]; return [V.add(as, V.scale(ad, res[0])), ...res]; }
static ray(a, b, c, d) { return this.info(a, b, c, d); }
static segment(a,b,c,d, inclusiveStart = true, inclusiveEnd = true) { const i = this.info(a, V.sub(b, a), c, V.sub(d, c)); return i === false? false: ( (inclusiveStart? 0<=i[1] && 0<=i[2]: 0<i[1] && 0<i[2]) && (inclusiveEnd?   i[1]<=1 && i[2]<=1: i[1]<1 && i[2]<1) )?i[0]:false;}
static tour(tour, segmentStart, segmentDirection) { return tour.map((e, i, a) => [i, this.info(e, V.sub(a[(i+1)%a.length], e), segmentStart, segmentDirection)]).filter(e => e[1] !== false && 0 <= e[1][1] && e[1][1] <= 1).filter(e => 0 <= e[1][2]).map(e => ({position: e[1][0],tourIndex: e[0],tourSegmentPortion: e[1][1],segmentPortion: e[1][2],}));}
static inside(tour, pt) { return tour.map((e,i,a) => this.segment(e, a[(i+1)%a.length], pt, [Number.MAX_SAFE_INTEGER, 0], true, false)).filter(e => e !== false).length % 2 == 1; }
}
this.Intersection = Intersection2D;

class PathTools {
static bezier(p1, cp1, cp2, p2, steps = null) {steps = (steps === null? (V.len(V.sub(cp1, p1)) + V.len(V.sub(cp2, cp1)) + V.len(V.sub(p2, cp2))) | 0: steps) - 1;return Array.from({length: steps + 1}).map((v, i, a, f = i/steps) => [[V.lerp(p1, cp1, f),V.lerp(cp1, cp2, f),V.lerp(cp2, p2, f)]].map(v => V.lerp(V.lerp(v[0], v[1], f), V.lerp(v[1], v[2], f), f))[0]);}
// https://stackoverflow.com/questions/18655135/divide-bezier-curve-into-two-equal-halves#18681336
static splitBezier(p1, cp1, cp2, p2, t=.5) {const e = V.lerp(p1, cp1, t);const f = V.lerp(cp1, cp2, t);const g = V.lerp(cp2, p2, t);const h = V.lerp(e, f, t);const j = V.lerp(f, g, t);const k = V.lerp(h, j, t);return [[p1, e, h, k], [k, j, g, p2]];}
static circle(r){return this.circular(r,Math.max(12, r*2*Math.PI|0));}
static arc(radius, extend = 2 * Math.PI, clockWiseStart = 0, steps = null, includeLast = false) { return [steps == null? (radius*extend+1)|0: steps].map(steps => Array.from({length: steps}).map((v, i, a) => [radius * Math.cos(clockWiseStart + extend*i/(a.length-(includeLast?1:0))), radius * Math.sin(clockWiseStart + extend*i/(a.length-(includeLast?1:0)))])).pop(); }
static draw(turtle, path) {path.forEach((pt, i) => turtle[i==0?'jump':'goto'](pt));}
static drawTour(turtle, path) {this.draw(turtle, path.concat([path[0]]));}
static drawPoint(turtle, pt, r = .1) {this.drawTour(turtle, this.circle(r).map(e => V.add(e, pt)));}
}

this.PT = PathTools;

class Complex {
static sub(a,b)     { return V.sub(a,b); }
static scale(a,s)   { return V.scale(a,s); }
static mult(a,b)    { return [a[0]*b[0]-a[1]*b[1],a[0]*b[1]+a[1]*b[0]]; }
static sqrt(a)      { return [[Math.hypot(...a)**.5, Math.atan2(...a.reverse()) / 2]].map(ra => [ra[0]*Math.cos(ra[1]), ra[0]*Math.sin(ra[1])]).pop(); }
}
this.C = Complex;

class Numbers {
static approx(a,b,p)        { return Math.abs(a-b) < (p === undefined? .001: p); }
static clamp(a, min, max)   { return Math.min(Math.max(a, min), max); }
}
this.N = Numbers;

class Matrix {
static bayer(order) { return [...Array(1<<order)].map((_,y,a) => { const g = (k=order,x)=>k--&&4*g(k,x)|2*(x>>k)+3*(y>>k&1)&3; return a.map(g); }); }
static rotate(m) { return m[0].map((e, i) => m.map(r => r[i]).reverse()); }
static rotateCCW(m) { return m[0].map((e, i) => m.map(r => r[r.length-1-i])); }
static add(a,b) { return a.map((e, c) => e.map((e, r) => a[c][r] + b[c][r])); }
static sub(a,b) { return a.map((e, c) => e.map((e, r) => a[c][r] - b[c][r])); }
static multiply(a,b) { return Array.from({length: b.length}, (e,resCol) => Array.from({length: a[0].length}, (e,resRow) => b[resCol].reduce((acc, c, bRow) => acc + a[bRow][resRow] * b[resCol][bRow], 0)));}
static scale(a,s) { return a.map((e, c) => e.map((e, r) => a[c][r] * s)); }
static random(c,r,fillFn = Math.random) { return Array.from({length: c}, (e,i) => Array.from({length: r}, e => fillFn(c, r))); }
static identity(d) { return Array.from({length: d}, (e,c) => Array.from({length: d}, (e, r) => c==r?1:0 )); }
static log(m, name, logFn = console.log) { if(name != undefined) logFn(name); if(m === undefined || (typeof m == 'object' && (m[0] === undefined || m[0][0] === undefined))) { return logFn(`Failed to log matrix:`, m); } logFn(m[0].map((e,r) => m.map((e,c) => m[c][r]).join(', ')).join('\n')); }
static invert(m) { let _A = m.map(col => col.map(cell => cell));/*clone matrix*/let temp;const N = _A.length;const E = Array.from({length: N}, (e,i) => Array.from({length: _A[0].length}, (e,j) => i==j?1:0));for (let k = 0; k < N; k++) {temp = _A[k][k];for (let j = 0; j < N; j++) {_A[k][j] /= temp;E[k][j] /= temp;}for (let i = k + 1; i < N; i++) {temp = _A[i][k];for (let j = 0; j < N; j++) {_A[i][j] -= _A[k][j] * temp;E[i][j] -= E[k][j] * temp;}}}for (let k = N - 1; k > 0; k--) {for (let i = k - 1; i >= 0; i--) {temp = _A[i][k];for (let j = 0; j < N; j++) {_A[i][j] -= _A[k][j] * temp;E[i][j] -= E[k][j] * temp;}}}return E; }
static determinant(m) { return m.length == 1 ?m[0][0] :m.length == 2 ? m[0][0]*m[1][1]-m[0][1]*m[1][0] :m[0].reduce((r,e,i) => r+(-1)**(i+2)*e*this.determinant(m.slice(1).map(c => c.filter((_,j) => i != j))), 0)}
static flip(m) { return Array.from({length: m[0].length}, (_, r) => Array.from({length: m.length}, (e, c) => m[c][r])); }
static sum(m) { return m.reduce((a, c) => a + c.reduce((aa, cc) => aa + cc, 0), 0); }
}
this.M = Matrix;

class Algorithms {
static nthTriangular(n) { return ((n * n) + n) / 2; }
}
this.A = Algorithms;
}```