Selaa lähdekoodia

Add more toggles

Kirk Trombley 3 vuotta sitten
vanhempi
commit
3d646fbc32
2 muutettua tiedostoa jossa 21 lisäystä ja 6 poistoa
  1. 6 0
      nearest.html
  2. 15 6
      nearest.js

+ 6 - 0
nearest.html

@@ -14,6 +14,12 @@
             <input id="color-input" onchange="onColorChange()" />
             <img src="https://img.pokemondb.net/sprites/sword-shield/icon/bulbasaur.png" />
             <br/>
+            <span>Include X:</span>
+            <input type="checkbox" checked oninput="onColorChange()" id="include-x">
+            <br/>
+            <span>Normalize q and Y:</span>
+            <input type="checkbox" oninput="onColorChange()" id="norm-q-y">
+            <br/>
             <span>Number to find:</span>
             <input type="range" min="1" max="100" value="20" oninput="onColorChange()" id="num-poke">
             <span id="num-poke-display">20</span>

+ 15 - 6
nearest.js

@@ -1,5 +1,7 @@
 const getSprite = pokemon => `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`
 
+const vectorMag = v => Math.sqrt(v.map(x => x * x).reduce((x, y) => x + y));
+
 const onColorChange = () => {
   const numPoke = document.getElementById("num-poke")?.value;
   document.getElementById("num-poke-display").innerHTML = numPoke;
@@ -7,6 +9,9 @@ const onColorChange = () => {
   const closeCoeff = document.getElementById("close-coeff")?.value;
   document.getElementById("close-coeff-display").innerHTML = closeCoeff;
 
+  const includeX = document.getElementById("include-x")?.checked ?? false;
+  const normQY = document.getElementById("norm-q-y")?.checked ?? false;
+
   const bestList = document.getElementById("best-list");
   bestList.innerHTML = ''; // do the lazy thing
 
@@ -20,13 +25,17 @@ const onColorChange = () => {
     Number.parseInt(color.substring(2, 4), 16),
     Number.parseInt(color.substring(4, 6), 16),
   ];
+  const colorMag = vectorMag(colorValues);
 
-  database.map(([name, x, ...y]) => ({
-    name,
-    score: x - closeCoeff * y.map((yc, i) => yc * colorValues[i]).reduce((x, y) => x + y),
-    avgColor: y,
-  }))
-    .sort((a, b) => a.score - b.score)
+  database.map(([name, x, ...y]) => {
+    const xComp = includeX ? x : 0;
+    const norm = normQY ? vectorMag(y) * colorMag : 1;
+    return {
+      name,
+      score: xComp - closeCoeff * y.map((yc, i) => yc * colorValues[i] / norm).reduce((x, y) => x + y),
+      avgColor: y,
+    };
+  }).sort((a, b) => a.score - b.score)
     .slice(0, numPoke)
     .forEach(({ name, avgColor}) => {
       const li = document.createElement("li");