Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

每天一道算法题(简单版) #9

Closed
rottenpen opened this issue Aug 9, 2018 · 8 comments
Closed

每天一道算法题(简单版) #9

rottenpen opened this issue Aug 9, 2018 · 8 comments

Comments

@rottenpen
Copy link
Owner

rottenpen commented Aug 9, 2018

In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants?

At the end of the first year there will be: 
1000 + 1000 * 0.02 + 50 => 1070 inhabitants

At the end of the 2nd year there will be: 
1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)

At the end of the 3rd year there will be:
1141 + 1141 * 0.02 + 50 => 1213

It will need 3 entire years.

More generally given parameters:

p0, percent, aug (inhabitants coming or leaving each year), p (population to surpass)

the function nb_year should return n number of entire years needed to get a population greater or equal to p.

aug is an integer, percent a positive or null number, p0 and p are positive integers (> 0)

Examples:

nb_year(1500, 5, 100, 5000) -> 15
nb_year(1500000, 2.5, 10000, 2000000) -> 10

Note: Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02.

代码:

function nbYear(p0, percent, aug, p) {
    // your code
    var ny = 0
    var sum = p0
    while(sum < p){
      sum = sum + sum*percent/100 + aug
      ny = ny + 1
    }
    return ny
}
@rottenpen
Copy link
Owner Author

rottenpen commented Aug 11, 2018

动态规划

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。

1.  1 阶 + 1 阶
2.  2 阶

示例 2:

输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。

1.  1 阶 + 1 阶 + 1 阶
2.  1 阶 + 2 阶
3.  2 阶 + 1 阶

正确答案:

var climbStairs = function(n) {
    if(n >= 3){
        return climbStairs(n-1) + climbStairs(n-2)
    }
    if(n<3){
        return n
    }
};

@rottenpen
Copy link
Owner Author

In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.

Example:

highAndLow("1 2 3 4 5"); // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"
Notes:

All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space, and highest number is first.
我的答案

function highAndLow(numbers){
  // ...
  return Math.max(...numbers.split(' ')) + " " + Math.min(...numbers.split(' '))
}

@rottenpen
Copy link
Owner Author

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b.

array_diff([1,2],[1]) == [2]
If a value is present in b, all of its occurrences must be removed from the other:

array_diff([1,2,2,2,3],[2]) == [1,3]

我的答案:

function array_diff(a, b) {
  return a.filter(v=>b.indexOf(v)<0)
}

@rottenpen
Copy link
Owner Author

rottenpen commented Aug 15, 2018

"123456789876543212345678987654321..." 的第 n 位是什么?

答案:

function whichn(n){
    let arr = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2]
    return arr[n % 16 - 1]
}

function whichn(str, n){
    return str.charAt(n-1)
}

function whichn(str, n){
    str.split('')
    return str.split('')[n - 1]
}

@rottenpen
Copy link
Owner Author

rottenpen commented Aug 22, 2018

Friday 13th or Black Friday is considered as unlucky day. Calculate how many unlucky days are in the given year.

Find the number of Friday 13th in the given year.

Input: Year as an integer.

Output: Number of Black Fridays in the year as an integer.

Precondition: 1000 < |year| < 3000

Examples:

unluckyDays(2015) == 3
unluckyDays(1986) == 1

我的答案:

function unluckyDays(year){
  //your code here
  let months = [0,1,2,3,4,5,6,7,8,9,10,11]
  return months.reduce((num,v) => {
     if (new Date(year, v,13).getDay() == 5){
        num ++
      }
      return num
      }, 0
    )
}

@rottenpen
Copy link
Owner Author

Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.

Your task is to write a function maskify, which changes all but the last four characters into '#'.

Examples

maskify("4556364607935616") == "############5616"
maskify(     "64607935616") ==      "#######5616"
maskify(               "1") ==                "1"
maskify(                "") ==                 ""

// "What was the name of your first pet?"
maskify("Skippy")                                   == "##ippy"
maskify("Nananananananananananananananana Batman!") == "####################################man!"
function maskify(cc) {
  let arr = cc.split('')
  return arr.map((ele, i) => (i - arr.length) >= -4 ? ele : '#' ).join('')
}

@rottenpen
Copy link
Owner Author

判断是否为质数

function isPrime(num) {
  //TODO
    let ns = Math.sqrt(num)
    if ( num === 0 || num === 1 ) return false
    if ( num === 2 || num === 3 ) return true
    if ( num % 6 !== 1 && num % 6 !== 5 ) return false
    for (let i = 5; i <= ns ; i++) {
        if ( num % i === 0 || num % (i + 2) === 0 ) return false
    }
    return true
}

@rottenpen
Copy link
Owner Author

数组里独特的数字

There is an array with some numbers. All numbers are equal except for one. Try to find it!

findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55

It’s guaranteed that array contains more than 3 numbers.

我觉得我的解答方法是💩:

function findUniq(arr) {
    // do magic
    let obj={}
    for(let i=0; i<3; i++) {
        if(!obj[arr[i]]) {
            obj[arr[i]] = 1
        } else {
            obj[arr[i]] = obj[arr[i]] + 1
            if (obj[arr[i]] >= 2) return arr.filter(ele => (ele != arr[i]))[0]
        }
    }
}// 拿前3个数做比对 如果有数字的数量超过1 就在原数组过滤掉这个数
console.log( findUniq([ 1, 1, 1, 2, 1, 1 ]));

看看别人比较好的解法

// solution 1
function findUniq(arr) {
  arr.sort((a,b)=>a-b);
  return arr[0]==arr[1]?arr.pop():arr[0]
}// 排序[ 1, 1, 1, 2, 1, 1 ]->[ 1, 1, 1, 1, 1, 2 ]

// solution2:
function findUniq(arr) {
  return arr.find(n => arr.indexOf(n) === arr.lastIndexOf(n));
} // 这个性能应该是3个解法里最差的,但简洁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant