javascript - 无法正确存储数据以在应用程序中实现广度优先搜索,如培根的预言机(对象通信)
问题描述
我有 .JSON 文件,其中包含代表电影的对象,如下所示。我正在尝试将该文件中的数据存储在一个结构中,这样我就可以使用它来实现广度优先搜索来构建一个应用程序,比如(培根的预言)。我有节点对象和图形对象来存储所有节点。我需要为每部电影和每个演员制作一个节点。我的问题是 hasNode(node) -i 如果我在图形的节点中不存在,我只添加演员 - 总是返回 false。
#sample JSON object:
{
"title": "Diner",
"cast": [
"Steve Guttenberg",
"Daniel Stern",
"Mickey Rourke",
"Kevin Bacon",
"Tim Daly",
"Ellen Barkin",
"Paul Reiser",
"Kathryn Dowling",
"Michael Tucker",
"Jessica James",
"Colette Blonigan",
"Kelle Kipp",
"Clement Fowler",
"Claudia Cron"
]}
function Graph() {
this.nodes = [];
this.graph = {};
}
Graph.prototype.addNode = function (node) {
this.nodes.push(node);
}
Graph.prototype.hasNode = function (node) {
for (var i = 0; i < this.nodes.length; i++) {
if (this.nodes[i].name == node.name) {
return true;
} else {
return false;
}
}
}
function Node(name) {
this.name = name;
this.edges = [];
this.searched = false;
this.parent = null;
}
#My setup function:
var data;
var graph;
function preload() {
data = loadJSON('kevinbacon.json');
}
function setup() {
noCanvas();
graph = new Graph();
var movies = data.movies;
for (var i = 0; i < movies.length; i++) {
var movie = new Node(movies[i].title);
graph.addNode(movie);
var cast = movies[i].cast;
for (var j = 0; j < cast.length; j++) {
var actor = new Node(cast[j]);
if (!(graph.hasNode(actor))){
graph.addNode(actor);
}
}
}
console.log(graph);
}
我期望输出是所有演员(不重复)和电影的图形对象,但我得到的演员是重复的。
解决方案
问题是即使名称在第一个检查元素中不相等,您也会立即返回。相反,您应该只在找到名称时中止,否则它不会检查其余名称
//sample JSON object:
var example=JSON.parse('{ "title": "Diner", "cast": [ "Steve Guttenberg", "Daniel Stern", "Mickey Rourke", "Kevin Bacon", "Tim Daly", "Ellen Barkin", "Paul Reiser", "Kathryn Dowling", "Michael Tucker", "Jessica James", "Colette Blonigan", "Kelle Kipp", "Clement Fowler", "Claudia Cron" ]}');
function Graph() {
this.nodes = [];
this.graph = {};
}
Graph.prototype.addNode = function (node) {
this.nodes.push(node);
}
Graph.prototype.hasNode = function (node) {
for (var i = 0; i < this.nodes.length; i++) {
if (this.nodes[i].name == node.name) {
return true;
}
}
return false
}
function Node(name) {
this.name = name;
this.edges = [];
this.searched = false;
this.parent = null;
}
//My setup function:
var data;
var graph;
(function setup() {
graph = new Graph();
var movies = [example ];
for (var i = 0; i < movies.length; i++) {
var movie = new Node(movies[i].title);
graph.addNode(movie);
var cast = movies[i].cast;
for (var j = 0; j < cast.length; j++) {
var actor = new Node(cast[j]);
if (!(graph.hasNode(actor))){
console.log("adding node",actor)
graph.addNode(actor);
}
}
}
console.log(graph);
})();
推荐阅读
- mysql - 如何选择第一次出现列值的行?
- javascript - 如何在javascript中生成一个波动1的随机数数组?
- javascript - 光滑的滑块在 Chrome 上完全不同的位置与字体混淆
- python - 在python中绘制列出的值
- c++ - 如何使用 std::chrono 或其他任何东西来减慢我的 for 循环?
- c# - 如何在画布中的图像上获取绘制矩形的位置
- vue.js - 使用 Vue3 组合 API 打开/关闭模式无法按预期工作
- linux - 验证 .sh 文件头
- python - Kivy 动态替换 kv 文件并添加 .widget
- sql - 在Oracle SQL中将标签合并到由换行符分隔的值