Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
Comprobación recursiva de datos que contienen otros datos en Javascript

Tengo que resolver un problema. Tengo un conjunto de datos con la siguiente estructura y tengo que crear una matriz de todas las bolsas que contienen una bolsa dorada brillante (incluidas las bolsas que contienen bolsas que contienen la bolsa dorada brillante)

Implementé algo como lo siguiente, que funciona para el conjunto de datos anterior pero no para el más grande (casi 600 líneas). Mi pregunta es: -por qué el código funciona para ese pequeño conjunto de datos pero no para el más grande -Sé que la mía no es la forma más elegante de resolverlo, entonces, ¿hay alguna técnica para resolverlo de manera más eficiente?

este es mi codigo

 const input = `light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags.` .split("\n") .map((row) => Array(row)) .map((row) => row[0].replace("contain", ",").split(",")); function checkColors(arr, str) { for (let i = 1; i < arr.length; i++) { if (arr[i].includes(str)) return arr[0]; } } let colors = input .map((entry) => checkColors(entry, "shiny gold")) .filter((entry) => entry != undefined) .map((entry) => entry.replace("bags", "").trim()); let colorsMain = colors; let tempCol = []; do { for (let j = 0; j < colors.length; j++) { tempCol = input.map((entry) => checkColors(entry, colors[j])); } tempCol = tempCol .filter((entry) => entry != undefined) .map((entry) => entry.replace("bags", "").trim()); colorsMain = colorsMain.concat(tempCol); colors = tempCol; console.log(colorsMain); } while (tempCol.length > 0); console.log(colorsMain.length);

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Podría construir un objeto con todas las relaciones y luego recopilar los valores deseados.

 const addToSet = (s, v) => (relations[v] || []).reduce(addToSet, s.add(v)), data = `light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags.`, relations = data .split(/[\r\n]+/) .reduce((r, s) => { const [value, key] = s.split(' bags contain '), keys = key === 'no other bags.' ? [] : key .split(/[,.]\s*/) .filter(Boolean) .map(s => s.match(/\d+\s(.*)\sbag/)[1]); keys.forEach(k => (r[k] ??= []).push(value)); return r; }, {}), result = [...relations['shiny gold'].reduce(addToSet, new Set)]; console.log(result); console.log(relations);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

¿Que tal este?

 const input = `light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags.` function buildColorDict(input) { const colorDict = {} input.split("\n").map((line) => { return line.match(/([a-zA-Z]+\s+[a-zA-Z]+)+(?=\s+bags?)/g) }).forEach((arr) => { arr.slice(1).forEach((color) => { colorDict[color] ? colorDict[color].push(arr[0]) : colorDict[color] = [arr[0]] }) }) return colorDict } function lookUp(colorDict, color) { const _lookUp = (_color) => { if (colorDict[_color]) { return colorDict[_color].concat(colorDict[_color].map((_color1)=> _lookUp(_color1)).flat()) } else { return [] } } return new Set(_lookUp(color)) } const colorDict = buildColorDict(input) const result = lookUp(colorDict, "shiny gold") console.log(Array.from(result))

Básicamente, extraiga el color de la input usando regex y cree un diccionario de búsqueda inversa. Dado un color, digamos shiny gold . Busca qué bolsa lo contiene y, utilizando los colores encontrados, busca de forma recursiva qué bolsas contienen las bolsas de colores encontradas.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!