龙空技术网

30秒就能理解的JavaScript短代码片段,K最近邻、快速排序等算法

维度小屋 357

前言:

眼前姐妹们对“数据结构及算法js”大约比较看重,咱们都需要学习一些“数据结构及算法js”的相关资讯。那么小编也在网络上收集了一些关于“数据结构及算法js””的相关知识,希望姐妹们能喜欢,看官们快快来学习一下吧!

30 seconds of code是创建于2017年、适用于所有技能水平的开发者的开源高质量知识库。在社区贡献者的帮助下,该项目已经创建了数百个短代码片段和编程文章。目标是使得软件开发更易获得,并通过帮助人们学习代码促进开源社区的发展。

该项目非常火热,在GitHub上已经积累了96.6k的Star,并曾被评为2018年度十大开源项目之一

项目地址:开源协议:CC-BY-4.0 license

项目创建者是来自希腊雅典的web开发者、JavaScript工程师Angelos Chalaris。

具体地,30 seconds of code精心挑选收集了满足所有开发需求的短代码片段,涵盖的主题从简单的代码问题到理论概念和开发技术,应有尽有。比如JavaCript、CSS、React Hooks、Python、JavaScript算法、Git、JavaScript面试问题、Node.js、JavaScript数据结构、JavaScript承诺、React渲染、技巧和经验、CSS Centering等。

我们以JavaScript Snippets为例进行展示,它收集了各种各样的ES6辅助函数,用来处理基元(primitives)、数组和对象、算法、DOM操作函数和Node.js实用工具等。

JavaScript Snippets中包含的部分算法如下图所示,比如K-均值聚类、K-最近邻、Luhn算法检查、堆排序、子字符串索引、桶式排序、数组阵列、凯撒密码、快速排序、选择排序、算数数列等

比如K-均值聚类算法

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;};

K-最近邻算法

const kNearestNeighbors = (data, labels, point, k = 3) => {  const kNearest = data    .map((el, i) => ({      dist: Math.hypot(...Object.keys(el).map(key => point[key] - el[key])),      label: labels[i]    }))    .sort((a, b) => a.dist - b.dist)    .slice(0, k);  return kNearest.reduce(    (acc, { label }, i) => {      acc.classCounts[label] =        Object.keys(acc.classCounts).indexOf(label) !== -1          ? acc.classCounts[label] + 1          : 1;      if (acc.classCounts[label] > acc.topClassCount) {        acc.topClassCount = acc.classCounts[label];        acc.topClass = label;      }      return acc;    },    {      classCounts: {},      topClass: kNearest[0].label,      topClassCount: 0    }  ).topClass;};

子字符串索引算法

const indexOfSubstrings = function* (str, searchValue) {  let i = 0;  while (true) {    const r = str.indexOf(searchValue, i);    if (r !== -1) {      yield r;      i = r + 1;    } else return;  }};

快速排序算法

const quickSort = arr => {  const a = [...arr];  if (a.length < 2) return a;  const pivotIndex = Math.floor(arr.length / 2);  const pivot = a[pivotIndex];  const [lo, hi] = a.reduce(    (acc, val, i) => {      if (val < pivot || (val === pivot && i != pivotIndex)) {        acc[0].push(val);      } else if (val > pivot) {        acc[1].push(val);      }      return acc;    },    [[], []]  );  return [...quickSort(lo), pivot, ...quickSort(hi)];};

更多其他算法请参阅原项目。

标签: #数据结构及算法js