main
90e35a3 ยท 1 year ago 22 commits
 1const input = document.getElementById("n");
 2const steps = document.getElementById("steps");
 3let graph;
 4function CollatzConjecture(n) {
 5    let numberofSteps = 0
 6    let result = [];
 7    result.push({ step: numberofSteps, value: n })
 8    while (n != 1) {
 9        if (n % 2 == 0) {
10            n = n / 2
11        } else {
12            n = (n * 3) + 1
13        }
14        numberofSteps += 1
15        result.push({ step: numberofSteps, value: n })
16    }
17    return result;
18}
19
20function ConstructGraph(n) {
21    const data = CollatzConjecture(n);
22    if (graph) {
23        graph.destroy();
24    }
25    graph = new Chart("chart", {
26        type: "line",
27        data: {
28            labels: data.map(row => row.step),
29            datasets: [
30                {
31                    label: "Value",
32                    data: data.map(row => row.value),
33                    fill: false,
34                    borderColor: '#d4af37',
35                    backgroundColor: '#d4af37',
36                    color: 'white',
37                }
38            ]
39        },
40        options: {
41            plugins: {
42                tooltip: {
43                    callbacks: {
44                        title: function(context) {
45                            const Step = context[0].label == "0" ? "Initial Step" : "Step: " + context[0].label;
46                            const Value = `Value: ${context[0].parsed.y}`;
47                            return `${Step}\n${Value}`;
48                        },
49                        label: function(context) {
50                            return "";
51                        },
52                    }
53                },
54                legend: {
55                    display: false,
56                },
57            },
58            scales: {
59                y: {
60                  grid: {
61                    color: 'rgba(200, 200, 200, 0.1)',
62                  }
63                },
64                x: {
65                  grid: {
66                    color: 'rgba(200, 200, 200, 0.1)',
67                  }
68                }
69              }
70        },
71    });
72    steps.innerHTML = `${data.length}`;
73}
74
75input.addEventListener("input", function (e) {
76    if(e.target.value == '' || e.target.value == 0) {
77        graph.destroy();
78        steps.innerHTML = '0';
79    }
80    if (e.target.value == 1) {
81        return;
82    }
83    if (e.target.value < 1) {
84        e.target.value = '';
85        return;
86    }
87    const n = parseInt(e.target.value);
88    ConstructGraph(n);
89});
90
91ConstructGraph(50);