javascript - 降低 forEach 循环中的时间复杂度
问题描述
我正在使用 Javascript 构建一个简单的刽子手游戏,并且想知道优化我的代码的最佳方法是什么。
const Hangman = function (word, remainingGuesses) {
this.word = word.toLowerCase().split("");
this.remainingGuesses = remainingGuesses;
this.guessedLetters = [];
};
Hangman.prototype.getPuzzle = function () {
let puzzle = "";
this.word.forEach((char) => {
this.guessedLetters.includes(char) || char === " "
? (puzzle += char)
: (puzzle += "*");
});
return puzzle;
};
目前,从上面的代码中可以看出,我正在执行一个forEach
循环 forthis.word
然后在forEach
我.includes()
用来查找是否已猜到单词的循环内,如果没有,则将 char 设置为*
.
目前我相信O(n2)
由于includes()
内部的时间复杂度,重写函数forEach
的更好方法是什么?getPuzzle()
解决方案
使用Set
forguessedLetters
进行恒定时间查找:
const Hangman = function (word, remainingGuesses) {
this.word = word.toLowerCase().split("");
this.remainingGuesses = remainingGuesses;
this.guessedLetters = new Set(); // this is a Set now
};
Hangman.prototype.getPuzzle = function () {
let puzzle = "";
this.word.forEach((char) => {
// use Set.has instead of Array.includes
this.guessedLetters.has(char) || char === " "
? (puzzle += char)
: (puzzle += "*");
});
return puzzle;
};
您可以添加一个新的猜测字母this.guessedLetters.add(char)
。
推荐阅读
- swift - (SwiftUI) 将 Slider 和 TextField 绑定到同一个变量?
- laravel - Laravel + Nuxt - 如何在 VDS 中组合它们?
- cplex - 使用 PYOMO 在 CPLEX 日志上获取约束标签(非索引)
- python - 使用连续行作为 Y 轴的小提琴图
- algorithm - 更快的算法与更快的计算机
- c++ - 根据加载的图像调整 QGraphicsView 的大小并始终保持纵横比
- php - 使用 PHP 从新闻站点访问 XML 元素和命名空间(已编辑)
- android - nativescript - 提取 tns-android 时验证失败
- javascript - 需要哪些 javascript 包含文件才能使布局扩展在 cytoscape 中工作?
- python - 熊猫数据框在排序后未保存