江苏省建设厅网站 杨洪海,站酷网素材图库排版,硬件开发一站式平台,老年大学网站建设#摘要#
一转眼过去6年多了#xff0c;没有更新过博客#xff0c;由于近期遇到了用代码解决数学上的问题#xff0c;比如今天说的排列组合。网上查了下#xff0c;有好多人都实现了#xff0c;方法各异#xff0c;但都没有按照面向对象的方式求解。我承认我今天写的这些没有更新过博客由于近期遇到了用代码解决数学上的问题比如今天说的排列组合。网上查了下有好多人都实现了方法各异但都没有按照面向对象的方式求解。我承认我今天写的这些可能小题大作但我是按照最简单逻辑思维方式拓展开的容易理解。
我们都知道排列和组合的区别一个有顺序一个没顺序。所以我用一个【全部的树】来表示排列结果用一个【向后的树】来表示组合结果。看代码您就知道了。
class PCNode {value 0index 0parent: PCNode | null nullchildren: ArrayPCNodelevel 1constructor() {this.children new ArrayPCNode()}get pathIndexList(): Arraynumber {const arr new Arraynumber()arr.push(this.index)if (this.parent) {let parent: PCNode | null this.parentwhile (parent) {arr.push(parent.index)parent parent.parent}}return arr}get pathValueList(): Arraynumber {const arr new Arraynumber()arr.push(this.value)if (this.parent) {let parent: PCNode | null this.parentwhile (parent) {arr.push(parent.value)parent parent.parent}}return arr}
}
class PermutationCombination {nodeInfo: ArrayPCNodeoriginArr: Arraynumberconstructor(isPermutation: boolean, originArray: Arraynumber) {this.nodeInfo new ArrayPCNode()this.originArr originArrayisPermutation ? this.initPermutation() : this.initCombination()}private initPermutation() {const generateChildren (parent: PCNode) {for (let index 0; index this.originArr.length; index) {if (parent.pathIndexList.indexOf(index) -1) {const child new PCNode()child.level parent.level 1child.index indexchild.value this.originArr[index]child.parent parentparent.children.push(child)generateChildren(child)}}}for (let index 0; index this.originArr.length; index) {const root new PCNode()root.value this.originArr[index]root.index indexthis.nodeInfo.push(root)generateChildren(root)}}private initCombination() {const generateChildren (parent: PCNode, startIndex: number) {for (let index startIndex; index this.originArr.length; index) {const child new PCNode()child.level parent.level 1child.value this.originArr[index]child.parent parentparent.children.push(child)generateChildren(child, index 1)}}for (let index 0; index this.originArr.length; index) {const root new PCNode()root.value this.originArr[index]root.index indexthis.nodeInfo.push(root)generateChildren(root, index 1)}}getResultByDeep(deep: number) {const allConditions new ArrayArraynumber()console.log(this.nodeInfo)const getChildByDeep (parent: PCNode) {if (parent.level deep) {allConditions.push(parent.pathValueList)} else if (parent.level deep) {parent.children.forEach(child getChildByDeep(child))}}this.nodeInfo.forEach((value: PCNode) getChildByDeep(value))return allConditions}
}
使用方法
const pc new PermutationCombination(false, [1,2,3,2,3])
console.log(pc.getResultByDeep(3))
解释下这里传的参数3也就是节点中的level值就是我们说的C53中的C符号上的数字。找到这一层的节点后按照自己的路径上找即可形成一个解。我这里代码的逻辑完全来源于手动演算的结果。
经简单测试没有发现问题。期待能有更多数学问题能用这种方式解决下次再见