js算法:克拉茨猜想(二)

上一篇是根据某一个数字画出当前数字所在的分支。本篇将介绍输入一个层级,输出该层级的所有分支。

实现思路

因为一个数字它只能从奇数或者偶数过来,是逆推过程。比如8只能从偶数过来是16,因为(8-1)/3不是自然数,所以不能从奇数过来。
仍然使用echart做展示

export interface EchartTree {
  name: number;
  children: EchartTree[];
}

将最后一层的节点存到数组里,方便计算下一层

type tailListTotal = EchartTree[][]

实现生成树形结构的方法,传入当前最后一层的节点数组,并为最后一层节点的children添加下一层节点,同时把下一层节点存到数组中

type getSequence = (tailList: EchartTree[]) => void

具体实现

export interface EchartTree {
  name: number;
  children: EchartTree[];
}

export default class Service {

  // 初始化数据
  constructor(deep?: number) {
    this.deep = deep || 10
    this.getSequence([this.root])
  }

  // 要计算的深度
  protected deep: number;

  // 初始节点设置到8,因为1和4会不断循环
  protected root: EchartTree = {
    name: 8,
    children: [],
  };

  // 每一层的所有节点
  protected tailListTotal: EchartTree[][] = []

  getRoot(): EchartTree {
    return this.root;
  }

  getTailList(): EchartTree[][] {
    return this.tailListTotal;
  }

  // 根据某一层节点,生成下一层
  protected getSequence(tailList: EchartTree[]): void {
    const tmpList: EchartTree[] = [];
    for (const v of tailList) {
      const tmp: EchartTree = {
        name: v.name * 2,
        children: [],
      };
      tmpList.push(tmp);
      v.children.push(tmp);
      const oddNum = (v.name - 1) / 3;
      if (oddNum % 2 === 1) {
        const tmp2: EchartTree = {
          name: oddNum,
          children: [],
        };
        tmpList.push(tmp2);
        v.children.push(tmp2);
      }
    }
    this.tailListTotal.push(tmpList);
    this.deep--;
    if (this.deep > 0) {
      this.getSequence(tmpList);
    }
  }
}

实现效果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值