Skip to content

Instantly share code, notes, and snippets.

@razorthink-com
Last active October 25, 2015 17:03
Show Gist options
  • Save razorthink-com/f3d403b3a6c02c5e2725 to your computer and use it in GitHub Desktop.
Save razorthink-com/f3d403b3a6c02c5e2725 to your computer and use it in GitHub Desktop.
function flatten( arr ) { return [].concat.apply( [], arr ) }
function arrayOfSize( size, n ) {
n = n || 0;
return ( new Array( size + 1 ) ).join( '0' ).split( '' )
.map( function ( _ ) { return n } );
}
function createMatrix( size ) {
return arrayOfSize( size ).map( function ( row, rowIndex ) {
return arrayOfSize( size ).map( function ( col, colIndex ) {
return {
x: rowIndex,
y: colIndex,
name: ( [ rowIndex, colIndex ].join( '-' ) )
}
} )
} )
}
function distanceBetweenPoints( p1, p2 ) {
return Math.sqrt( Math.pow( p1.x - p2.x, 2 ) + Math.pow( p1.y - p2.y, 2 ) )
}
function isPointInCircle( radius, center, point ) {
return (
Math.pow( ( point.x - center.x ), 2 )
+ Math.pow( ( point.y - center.y ), 2 )
< Math.pow( radius, 2 )
)
}
function stringifyPoint( pt ) { return '(' + pt.x + ',' + pt.y + ')' }
function printMatrix( matrix ) {
return matrix
.map( function( row ) {
return row.map( stringifyPoint )
}).join( '\n\n' );
}
/* - - - - - - - - - - */
var m = createMatrix( 5 );
var force = 2;
var center = { x: 2, y: 2 };
var appliedForcePoints = flatten( m )
.filter( function ( pt ) {
return isPointInCircle( force, center, pt );
})
.map( function ( pt ) {
return {
name: pt.name,
displacement: force - distanceBetweenPoints( pt, center )
}
});
@razorthink-com
Copy link
Author

ES6 Version

const flatten = arr => [].concat(...arr);

const arrayOfSize = size => n => Array.from(new Array(size + 1), _ => n);

const createMatrix = size => arrayOfSize(size)(0)
    .map((_, rowIndex) => arrayOfSize(size)(0)
    .map((_, colIndex) => ({
        x: rowIndex,
        y: colIndex,
        name: `${rowIndex}-${colIndex}`
    })));

const distanceBetweenPoints = p1 => p2 => Math.sqrt( Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2), 2 );

const isPointInCircle = (radius, center, point) => 
    Math.pow(point.x - center.x, 2) + Math.pow(point.y - center.y, 2) < Math.pow(radius, 2);

let m = createMatrix(5);
let force = 2;
let center = {x: 2, y: 2};

let appliedForcePoints = flatten(m)
    .filter( pt => isPointInCircle(force, center, pt) )
    .map( pt => ({ name: pt.name, displacement: force - distanceBetweenPoints(pt)(center) }) );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment