我正在研究一个问题,任务是编写一个程序,该程序可以从一组单词中重构每个句子并打印出原始句子。
INPUT SAMPLE:
2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2
And the answer is:
However, it was not implemented until 1998 and 2000
到目前为止,我已经将单词和数字提示组合为一个对象中的对值。我遇到的唯一问题是实际上缺少数字提示,因此其中一个单词的值不确定。
如何填写该值?
我尝试使用.HasOwnProperty()并进行循环遍历,以查看值之一是否等于undefined,但均无效。任何投入将不胜感激!
function encyrption(str){
var string = str.split(";");
var words = string[0].split(" ");
var hints = string[1].split(" ");
var object = {};
for(var i = 0; i < words.length; i++){
if(object[hints[i]] === undefined){
/////???
}else
object[hints[i]] = words[i];
}
return object;
}
console.info(encyrption("2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2"));
最佳答案
我会做这样的事情,只是猜测丢失的提示是最后一个字,而它永远是第六位。如果不是这种情况,我需要有关问题测试用例的更多信息来解决它。
function encyrption(str){
var string = str.split(";");
var words = string[0].split(" ");
var hints = string[1].split(" ");
var hints_sorted = hints.concat().sort();
var missing_hint;
var object = {};
for(var i = 0; i < words.length; i++) {
if(hints_sorted[i] != i+1) {
missing_hint = (i+1).toString();
break;
}
}
hints.push(missing_hint);
for(var i = 0; i < words.length; i++){
object[hints[i]] = words[i];
}
return object;
}
console.info(encyrption("2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2"));
//Result: However, it was not implemented until 1998 and 2000
那里有一个小解释:
我创建了hints_sorted数组,它是提示的一个副本,但是按照示例进行了排序:
hints = ['9','8','3','4','1','5','7','2'];
hints_sorted = ['1','2','3','4','5','7','8','9'];
然后,在for内,我将值与索引+ 1进行比较(因为循环内的索引从零开始):
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5
7 -> 6
在第六个元素上,我们的数组上有7个,我们期望6个,所以它在if里面,我们将6设置为缺少的提示,然后中断;循环,因此它不会继续检查值。