Loading...
More JavaScript Posts
arr = [] // empty arrayconst isEmpty = arr => !Array.isArray(arr) || arr.length === 0;// ExamplesisEmpty([]); // trueisEmpty([1, 2, 3]); // false
export const Main = () => {const [title, setTitle] = useState('');return (<ChildComponenttitle={title}onChange={e => setTitle(e.target.value)}/>);};export const ChildComponent = ({ title, onChange }) => {return (<Box component="form" onSubmit={() => {}} noValidate mt={5}><TextFieldfullWidthid="title"label="Title"name="title"autoComplete="title"autoFocuscolor="primary"variant="filled"InputLabelProps={{ shrink: true }}value={title}onChange={onChange}/></Box>);};
const kMeans = (data, k = 1) => {const centroids = data.slice(0, k);const distances = Array.from({ length: data.length }, () =>Array.from({ length: k }, () => 0));const classes = Array.from({ length: data.length }, () => -1);let itr = true;while (itr) {itr = false;for (let d in data) {for (let c = 0; c < k; c++) {distances[d][c] = Math.hypot(...Object.keys(data[0]).map(key => data[d][key] - centroids[c][key]));}const m = distances[d].indexOf(Math.min(...distances[d]));if (classes[d] !== m) itr = true;classes[d] = m;}for (let c = 0; c < k; c++) {centroids[c] = Array.from({ length: data[0].length }, () => 0);const size = data.reduce((acc, _, d) => {if (classes[d] === c) {acc++;for (let i in data[0]) centroids[c][i] += data[d][i];}return acc;}, 0);for (let i in data[0]) {centroids[c][i] = parseFloat(Number(centroids[c][i] / size).toFixed(2));}}}return classes;};kMeans([[0, 0], [0, 1], [1, 3], [2, 0]], 2); // [0, 1, 1, 0]
const gcd = (...arr) => {const _gcd = (x, y) => (!y ? x : gcd(y, x % y));return [...arr].reduce((a, b) => _gcd(a, b));};gcd(8, 36); // 4gcd(...[12, 8, 32]); // 4
# Acronyms## Computer Numerical Control (CNC)- Typicalldfdfsdffdafdasgfdgfgfdfdafdasfdafda
// There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.// You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:// The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').// The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').// For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.// Return the number of rods that have all three colors of rings on them.let rings = "B0B6G0R6R0R6G9";var countPoints = function(rings) {let sum = 0;// Always 10 Rodsfor (let i = 0; i < 10; i++) {if (rings.includes(`B${i}`) && rings.includes(`G${i}`) && rings.includes(`R${i}`)) {sum+=1;}}return sum;};console.log(countPoints(rings));