简体   繁体   English

Google Code Jam 2016:如何优化代码?

[英]Google Code Jam 2016 : How Can I optimize the Code?

Problem: 问题:
Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. 绵羊布莱特里克斯·特罗特(Bleatrix Trotter)制定了一项策略,可以帮助她更快入睡。
First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on. 首先,她选择一个数字N。然后,她开始命名N,2×N,3×N,依此类推。 Whenever she names a number, she thinks about all of the digits in that number. 每当她命名一个数字时,她都会考虑该数字中的所有数字。
She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as part of any number she has named. 她一直跟踪她至少看见过一次的数字(0、1、2、3、4、5、6、7、8和9),作为她所命名的任何数字的一部分。
Once she has seen each of the ten digits at least once, she will fall asleep. 一旦她至少看到十个数字中的每个数字,她就会入睡。 Bleatrix must start with N and must always name (i + 1) × N directly after i × N. For example, suppose that Bleatrix picks N = 1692. She would count as follows: N = 1692. Now she has seen the digits 1, 2, 6, and 9. 2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9. 3N = 5076. Now she has seen all ten digits, and falls asleep. Bleatrix必须以N开头,并且必须始终在i×N之后直接命名(i + 1)×N。例如,假设Bleatrix选择N =1692。她的计数如下:N =1692。现在她已经看到数字1 ,2、6和9。2N=3384。现在她已经看到数字1、2、3、4、6、8和9。3N=5076。现在她已经看到所有十个数字,并且入睡。
What is the last number that she will name before falling asleep? 她入睡前要说的最后一个号码是什么? If she will count forever, print INSOMNIA instead. 如果她将永远计数,请打印INSOMNIA。

https://code.google.com/codejam/contest/6254486/dashboard https://code.google.com/codejam/contest/6254486/dashboard

Array.prototype.unique = function () {
    return this.filter(function (value, index, self) {
        return self.indexOf(value) === index;
    });
}

var uniqueArr = [];
var Number = 1692;//Any number 


for (i = 1; ; i++) {
    var x = Number * i;
    while (x > 0) {
        uniqueArr.push(x % 10); //Converting number to Digits and pushing them into an array.
        x = Math.floor(x / 10);
    }
    var ar = uniqueArr.unique();
    if (ar.length == 10) {
        console.log(uniqueArr.unique(), Number * i);
        break;
    }
}

As long as x is always a positive number* (which is the case here) you could use 只要x始终为正数*(在这种情况下),就可以使用

x = ~~(x / 10)

instead of 代替

x = Math.floor(x / 10)

Which does the same job but is ~5 times faster. 可以完成相同的工作,但速度快约5倍。 Its more an obvious improvement but it optimize the code anyway. 它是一个明显的改进,但是无论如何它都会优化代码。

* ~~ is a bitwise operator, which just cuts off everything after the comma. * ~~是按位运算符,它将逗号后的所有内容都切掉。 So ~~-6.6 will result -6, but Math.floor(-6.6) gives you a -7. 因此~~ -6.6的结果为-6,但Math.floor(-6.6)的结果为-7。 Be carefull here. 小心点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM