Sun lingzhi: a love of carbon water shandong big girl.

Calculate gender and age according to id number

National standard for id card number

1, scope,

Citizenship Number (GB11643-1999) This standard stipulates the code object of citizenship number, the structure of the number and the form of expression, so that each code object gets a unique and unchanged legal number.

2. Number structure

Citizenship number is a feature combination code, which consists of seventeen digit body code and one digit check code. From left to right: six-digit address code, eight-digit date of birth code, three-digit sequence code and one-digit check code.

2.1 Address Code

Represents the administrative division code of the county (city, flag, district) where the code object permanent residence is located

2.2 Date of birth code

Represents the year, month, and day the encoding object was born

2.3 Sequence code

Refers to the serial number of people born in the same year, month and day within the area identified by the same address code. The odd number of the sequence code is assigned to men and the even number to women.

2.4. Check code

According to the first 17-digit word code, according to the verification code calculation method in ISO 7064:1983.MOD 11-2

(1) Weighted Sum formula of 17-digit ontology code: S = Sum(Ai * Wi)

Id number 1 1 0 1 0 5 1 9 4 9 1 2 3 1 0 0 2
The weighting factor 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
Ai * Wi 7 9 0 5 0 20 2 9 24 27 7 18 30 5 0 0 4

S = 7 + 9 + 0 + 5 + 0 + 20 + 2 + 9 + 24 + 27 + 7 + 18 + 30 + 5 + 0 + 0 + 4 = 167 ​

(2) Calculation mode: Y = mod(S, 11) Y = 167% 11 => 2

(3) The corresponding verification code is obtained through the module

die 0 1 2 3 4 5 6 7 8 9 10
Check code 1 0 X 9 8 7 6 5 4 3 2

When the module is 2, the check code is X

Two, code implementation

1. Verify the correctness of id number

const WEIGHT = [7.9.10.5.8.4.2.1.6.3.7.9.10.5.8.4.2]
const MO = [1.0.'X'.9.8.7.6.5.4.3.2]

function isRightId(id){
  const arr = id.split(' ')
  const checkNumber = arr.pop() // Remove the checkNumber and assign the return value of pop to the checkNumber
  let sum = 0
  arr.forEach((ele, index) = > {
  	sum += ele * WEIGHT[index]
  })
  const m = sum % 11
  const result = MO[m]
  return result+' ' === checkNumber
}

console.log(isRightId('11010519491231002X')) // true
console.log(isRightId('110105194912310029')) // false
Copy the code

2. Age is calculated by id number

function getAge(id){
  // 1. Check the id number
  // 2
  const year = id.substr(6.4)
  const month = id.substr(10.2)
  const day = id.substr(12.2)
  
  const timeBrth = new Date(`${year}/${month}/${day}`).getTime()
  const timeNow = new Date().getTime()
  const longTime = timeNow - timeBrth
  const days = longTime / (1*24*60*60*1000)
  
  let result = ' '
  if(days<31){
		result = parseInt(days) + 'day'
  }else if(days<365){
  	result = `The ${parseInt(days/30)}monthThe ${parseInt(days%30)}Day `
  }else{
  	result = `The ${parseInt(days/ 365)}, ${parseInt (days % 365 /30)}monthThe ${parseInt(days%365%30)}Day `
  }
  return result 
}
console.log(getAge('11010519491231002X')) // 71 years old 8 months 16 days
console.log(getAge('11010520210820002X')) / / 6 days
console.log(getAge('11010520210720002X')) // 7 days in January
Copy the code

3. Determine gender by ID number

function getSex(id){
  // 1. Check the id number
  const sex = id.substr(16.1)
  return sex%2? 'male': 'woman'
}
console.log(getSex('11010519491231002X')) / / women
console.log(getSex('11010520210820001X')) / / male
Copy the code

Third, other

1. Is the ID number changed after the sex change operation?

  • After the gender change of the identity card for transgender people, the id card number will be changed according to the public announcement of the local police station.

2. Make sure you are alive before calculating your age

Iv. Reference materials

Citizenship Number (GB11643-1999)

Dynamic programming

1, define,

Dynamic Programming (DP) is a branch of operations research. It is a process to solve the optimization of decision process.

It can be simply understood as an optimization of traditional recursion. Important in DP practice are recursion relations and boundary conditions.

2. Easy: Take the stairs

The title

Suppose you’re climbing stairs. It takes n steps to get to the top.

You can climb one or two steps at a time. How many different ways can you climb to the top?

Notice that n is given to be a positive integer.

Example 1:

Input: 2 Output: 2 Explanation: There are two ways to climb to the top of the building. 1. 1 + 1 + 2. 2Copy the code

Example 2:

Input: 3 Output: 3 Explanation: There are three ways to climb to the top of the building. 1. 1 order + 1 order + 1 order 2. 1 order + 2 order 3Copy the code

Code:

// Cache the data in an array
var climbStairs = function(n) {
    let dp = []
    dp[0] =1;
    dp[1] =1;
    for(let i=2; i<=n; i++){ dp[i]=dp[i-1]+dp[i-2];
    }
    return dp[n];
};

// Use recursion
var climbStairs = function(n) {
    if(n===1) return 1
    if(n===2) return 2
    return climbStairs(n-1) + climbStairs(n-2)};Copy the code

Ideas:

F (x)= F (_X_ −1)+ F (x_−2) The number of solutions for climbing to step X is the sum of the number of solutions for climbing to step X-1 and the number of solutions for climbing to step X-2.

LeetCode results:

3. Medium: the longest substring of a text

The title

Given a string s, find the longest substring in s.

Example 1:

Input: s = "babad" Output: "bab" Explanation: "ABA" is also the answer to the question.Copy the code

Example 2:

Input: s = "CBBD" Output: "bb"Copy the code

Ideas:

S [I :j] is a palindrome string if s[I +1: J-1] is a palindrome string and if the ith and j of S are the same.

That is, P(I,j)=P(I +1,j−1) and (Si == Sj).

Boundary condition: The length of the substring is 1 or 2. For a substring of length 1, it’s obviously a palindrome string; A substring of length 2 is a palindrome string as long as its two letters are the same.

  • P(i, i) = true
  • P(i, i+1) = (Si == Si+1)

Code:

    function longestPalindrome (s) {
      // Determine the length of the string, if it is 1, return it directly
      let len = s.length
      if (len < 2) return s
      
      // Initialize variables
      let maxLen = 1
      let begin = 0
      
      // dp[I][j] indicates whether s[I..j] is a palindrome string
      let dp = []
      // Initialize: all substrings of length 1 are palindromes
      for (let i = 0; i < len; i++) {
        dp[i] = []
        dp[i][i] = true
      }
      
      // Cut a string into an array
      let charArray = s.split(' ')
      
      // Start the recursion
      for (let L = 2; L <= len; L++) { // enumerates the substring length
        // enumerate the left boundary. The upper bound of the left boundary can be looser
        for (let i = 0; i < len; i++) {
          J - I + 1 = L
          let j = L + i - 1;
          // If the right boundary is out of bounds, exit the loop
          if (j >= len) {
            break;
          }
          // Check whether it is palindrome
          if(charArray[i] ! == charArray[j]) { dp[i][j] =false
          } else {
            // For a substring, if it is a palindrome and its length is greater than 2, it is still a palindrome after removing the first and last two letters.
            let flag = j - i < 3
            dp[i][j] = flag ? true : dp[i + 1][j - 1]}// dp[I][L] == true; // dp[I][L] == true
          if (dp[i][j] && j - i + 1 > maxLen) {
            maxLen = j - i + 1; begin = i; }}}return s.substring(begin, begin + maxLen);
    }
    console.log(longestPalindrome('babad'), 'babad') // bab babad
    console.log(longestPalindrome('cbbd'), 'cbbd') // bb cbbd
Copy the code

LeetCode results:

4, difficulties: rain

Topic:

Given n non-negative integers to represent the height diagram of each column of width 1, calculate how much rain the columns in this order can catch after rain.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1,1] output: 6Copy the code

Example 2:

Height = [4,2,0,3,2,5Copy the code

Code:

function trap(height) {
    // If the condition is not met, return directly
    let len=height.length;
    if(len<=2) return 0;

    let maxLeft = []; // The height of the highest pillar to the left of the ith pillar
    let maxRight = []; // The height of the highest column to the right of the ith column

    maxLeft[0] = height[0];
    for(let i=1; i<len; i++){
            maxLeft[i] = Math.max(height[i], maxLeft[i-1]) // Dynamic transfer
    }

    maxRight[len-1] = height[len-1];
    for(let j=len-2; j>=0; j--){
            maxRight[j] = Math.max(height[j], maxRight[j+1]) // Dynamic transfer
    }

    let sum=0;
    for(let i=0; i<len; i++) sum+=Math.min(maxLeft[i],maxRight[i])-height[i];

    return sum;
}
Copy the code

Ideas:

The amount of rain received by each column is the minimum value of the tallest column on either side of the column minus the height of the column.

LeetCode results:

Attachment: two-pointer method

Code:

 function trap(height) {
    let ans=0;
    for(let i=1; i<height.length-1; i++){
    let l_hight = height[i];
    let r_hight = height[i];

                            // Find the highest column height on the right side of column I
    for(let r=i; r<height.length; r++){
     if(height[r]>r_hight) r_hight=height[r];
    }

    // Find the highest column height left of column I
    for(let l=i; l>=0; l--){
     if(height[l]>l_hight) l_hight=height[l];
    }

    ans+=Math.min(l_hight,r_hight)-height[i];
    }
    return ans;
 }
Copy the code

LeetCode results:

5. Reference materials

Source: LeetCode leetcode-cn.com/problems/cl…

Leetcode-cn.com/problems/lo…

Leetcode-cn.com/problems/tr…

Greedy algorithm

1, define,

Always do what seems best in the moment when solving a problem.

2. Divide the cookies

Let’s say you’re a great parent and you want to give your kids some cookies. However, no more than one cookie can be given to each child. For each child I, there is an appetite value g[I], which is the minimum size of a cookie to satisfy a child’s appetite; And every cookie J has a size S [J]. If s[j] >= g[I], we can assign this cookie J to child I, and the child will be satisfied. Your goal is to satisfy as many children as possible and output this maximum number.

Example 1: Input: g = [1,2,3], s = [1,1] Output: 1

Example 2: input: g = [1,2], s = [1,2,3] output: 2

function findContentChildren1(children, cookies){
  children = children.sort((a, b) = > a - b)
  cookies = cookies.sort((a, b) = > a - b)
  let childrenLength = children.length
  let cookiesLength = cookies.length
  let count = 0
  for(let i = 0, j = 0; i < childrenLength && j < cookiesLength; i++, j++){
    while(j < cookiesLength && children[i] > cookies[j]){
      j++
    }
    if(j < cookiesLength){
      count++
    }
  }
  return count
}


console.log(findContentChildren1([1.2.3], [1.1])) / / 1
console.log(findContentChildren1([1.2], [1.2.3])) / / 2
console.log(findContentChildren1([1.2.3], [1.1.3.4])) / / 3
Copy the code

Core ideas:

  1. Rank your child’s appetite and the size of the cookie from smallest to largest.
  2. For loop traverses, comparing the relationship between children[I] and the size of cookies[J]. When the current cookie does not satisfy the child’s appetite, select the next cookie for comparison.
  3. If the child’s appetite is satisfied and j is in range, count increases by 1.

Code interpretation:

  1. Define the function findContentChildren, which takes two parameters: children: the child’s appetite and the size of the cookies.
  2. Sort children and cookies from smallest to largest.
  3. Define count as the number that will satisfy your child’s appetite, and eventually return count.
  4. When children[I] > cookies[j] that is, the current cookie does not satisfy the child, J ++ selects the next cookie for comparison.
  5. If children[I] <= cookies[j] that is, cookies currently satisfy the child, and j is in range, count is increased by 1.
  6. Enter the next cycle (i.e. try to satisfy the next child).

3. Buy stocks

Given an array of integers prices, the ith element represents the stock price on the ith day; The round fee represents the processing fee for trading stocks. You can complete transactions as many times as you want, but you have to pay a fee for each transaction. If you have already bought a stock, you cannot continue to buy it until you have sold it. Returns the maximum profit earned. Note: a transaction refers to the entire process of buying, holding and selling a stock, and you only have to pay a fee for each transaction.

Example 1: Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 Output: 8 Explanation: Maximum profit that can be achieved: Total profit: ((8-1) -2) + ((9-4) -2) = 8 total profit: ((8-1) -2) + ((9-4) -2) = 8

Example 2: input: prices = [1,3,7,5,10,3], fee = 3 output: 6

function maxProfit(list, fee){
  const length = list.length
  let buy = list[0] + fee // Assume: buy time is day 1
  let profit = 0
  for(let i = 1; i < length; i++){
    if(list[i]+fee < buy){ // If the stock price falls, adjust the buying time
      buy = list[i]+fee
    }else if(list[i] > buy){ // If there is a profit, sell
      profit += list[i] - buy // Calculate the profit
      buy = list[i] // Adjust buying timing}}return profit
}

console.log(maxProfit([1.3.2.8.4.9].2)) / / 8
console.log(maxProfit([1.3.7.5.10.3].3)) / / 6
Copy the code

Code interpretation:

  1. Define the function maxProfit that takes two parameters, list for stock price trend and fee for fee
  2. Define profit and return profit at the end
  3. Assume: Buy time on day 1 (i.e. List [0])
  4. If the stock price falls, adjust the buying time for the next day
  5. If there is a profit, sell, calculate the profit, and adjust the buying time again (i.e. cycle steps 3, 4, 5)

Core ideas:

  1. Assumption: Buy time is day 1
  2. If the stock price falls, adjust the buying time for the next day
  3. If there is a profit, sell it and count the profit
  4. Again – Assumptions: Buying timing (Cycle steps 1-3)

Lovers hold hands

N couples are sitting in 2N consecutive seats, trying to hold each other’s hands. Count the minimum number of times you can switch seats so that each couple can sit side by side. Choose any two people at a time and have them stand up and switch seats. People and seats are represented by integers from 0 to 2n-1, and couples are numbered in order, with the first pair (0, 1), the second pair (2, 3), and so on, and the last pair (2N-2, 2N-1).

The couples’ initial seat row[I] is determined by the person who originally sat in the ith seat.

Example 1:

Input: row = [0, 2, 1, 3] Output: 1 Explanation: We simply swap the positions of row[1] and row[2].

Example 2:

Input: row = [3, 2, 0, 1] Output: 0 Explanation: All couples can already hold hands without switching seats.

/ * * *@param {number[]} row
 * @return {number}* /
var minSwapsCouples = function(row) {
    let hashMap = {}; // {person: position}
    for(let i=0; i<row.length; i++){
      hashMap[row[i]] = i
    }

    let ans = 0; // The number of swaps

    for(let i=0; i<row.length; i+=2) {// Follow a pair of traversals
        let lover=row[i]^1; // Row [I] lovers
        if(hashMap[lover] ! == i+1) {// If not, swap
            ans++;
            hashMap[row[i+1]] = hashMap[lover]; // row[I +1] uses the lover subscript
             // Switch places
            [row[i+1], row[hashMap[lover]]] = [row[hashMap[lover]], row[i+1]]
            hashMap[lover]=i+1; // The lover subscript is changed to I +1 to make it adjacent}}return ans;
};
Copy the code

Core ideas:

  1. Run through the pairs to see if the couples are next to each other, and if not, adjust one’s position so that they are next to each other.
  2. We try to move only one partner and not the other to keep the number of moves to a minimum.
  3. This exchange will not affect other couples.

Code interpretation:

  1. Define the function minSwapsCouples that takes an array of rows.
  2. Gets the object {person: position}.
  3. Define the swap number ANS and return it at the end.
  4. Walk over the couple on the left and check if the couple on the right is their partner. If not, find their partner and switch seats.

5. Reference materials

LeetCode (LeetCode)

Link: leetcode-cn.com

Go to the online diagnosis and treatment platform of Wedoctor Internet hospital, make a quick consultation, and find a top three doctor for you in 3 minutes.