Advanced filter algorithm

Advanced algorithms

1, Palindrome checker

If the incoming string is a palindrome, it returns true; otherwise, it returns false.

Palindrome as like as two peas, which are ignored, punctuation, case and space, are exactly the same as those of reading correctly.

Look at the shit code I wrote.

function palindrome(str) {
  let s = /[A-Za-z0-9]/g
  // Regardless of the variable name, this is a regular match for all letters and numbers
  let st = str.match(s)
  // After matching, insert it into st, but it will behave like ["s", "v", "s"], which is harmless
  let flo = Math.floor((st.length / 2))
  // This is to divide the non-interference string or the array detected by regularization by 2 and round it down. In short, it is half the position
  let j = st.length - 1
  // This is the position of the last item
  for(let i=0;i<flo;i++) {
  // Start traversing until half the position
    if(st[i].toLowerCase() !== st[j].toLowerCase()) {
    // The first cycle, if the first term is different from the last term, what else is good to cycle
      return false
      // Return false to finish
    } else {
    // But if the first cycle, the head and tail are the same
      j--
      // Then move j forward and i back from for to start the next comparison
    }
  }
  return true;
  // If there is no false after traversal, it is true
}
palindrome("$_Atsfsta")

As for toLowerCase(), change the letters to lowercase.

Compare the head and tail. If they are the same, go to the middle of the array until they are all compared. If they are different, return directly.

It sucks.

2, Roman digital converter

Input numbers and output Roman numerals.

This algorithm is really awesome.

function convertToRoman(num) {
  let result = "";
  for(let key of ["IIII", "V", "XXXX", "L", "CCCC", "D", "MMMM"]) 
  // ES6 for for
    const length = key.length + 1;
    const remainder = num % length;
    // Current num remainder
    result = key.substr(0, remainder) + result;
    // The elements from 0 to the remainder in the current key are intercepted and added to the current result
    num = (num - remainder) / length;
    // Current num divided by current length whether added or not
  }

  result = result.replace(/DCCCC/g, "CM");
  result = result.replace(/CCCC/g, "CD");
  result = result.replace(/LXXXX/g, "XC");
  result = result.replace(/XXXX/g, "XL");
  result = result.replace(/VIIII/g, "IX");
  result = result.replace(/IIII/g, "IV");
  // Correct some of the writing when you're done
  return result;
}

I can only say that this algorithm cannot be evaluated.
I can't write out the degree of algorithm.

Although some logic is not understood, it is reasonable.

3, Caesar code ROT13

In Shift Cipher, the letters in plaintext are replaced with new letters by offsetting according to a fixed number.
Write a function that takes the string encoded by ROT13 as input and returns the decoded string.
In short, each letter is offset by 13 bits. The function should restore it and keep the symbol space.

function rot13(str) {
  let arr =[]
  for(let i=0;i<str.length;i++){
  // ergodic
    if(str.charCodeAt(i)<65 ||str.charCodeAt(i)>90){
      // Unicode code, 65 is A, 90 is Z
      arr.push(String.fromCharCode(str.charCodeAt(i)));
      // So what is outside this range is not capital letters, and the original path returns
    }
    else if(str.charCodeAt(i)>77){
      // 77 is m, 78 is N, and those greater than 77 are the letters after M
      arr.push(String.fromCharCode(str.charCodeAt(i)-13));
      // Those letters are the last half of the 26, so offset forward, Unicode encoding - 13
    }
    else{
      arr.push(String.fromCharCode(str.charCodeAt(i)+13));
      // The rest is the first half of the letter, offset back, + 13
    } 
  }
  return arr.join(''); 
  // Finally, connect all the elements in the array
}
rot13("SERR PBQR PNZC"); 

4, Telephone number checker

Returns true if the incoming string is a valid U.S. phone number format

As for the format of the U.S. number, it is not within the scope of management here.

function telephoneCheck(str) {
  if(str.match(/^1?\s?(\d{3}|\(\d{3}\))[-\s]?\d{3}[-\s]?\d{4}$/)){
    return true;
   }else{
    return false;
   }
}
telephoneCheck("555-555-5555");

Take it down.
^1? \s? (\d{3} | \( \d{3} \)) [-\s]? \d{3} [-\s]? \d{4}$

^1?, The first 1 is optional.
\s?, One space, optional.
(\ d{3} \ (\ d{3} \), \ d{3} on the left is three numbers,
The \ (\ d{3} \) in the right part is the left bracket, three numbers and the right bracket.
|Select only one of the left and right sides to match.
[-\s]? Is a character set, match - or space, optional.
\d{3}, three numbers.
[-\s]?, Also - or space, optional.
\d{4} $, four digits, must be at the end.

As the saying goes, regular expressions are very powerful, but may be difficult to read.

5, Calculation found 0

A function for cash register checkCashRegister():
The first parameter is the selling price, the second parameter is the payment amount cash, and the third parameter is the amount cid in the cash register.

cid is a two-dimensional array containing currency face values.
The function checkCashRegister() should return an object with the status attribute and the change attribute.

If the amount in the cash register is less than the change that should be recovered, or the exact amount cannot be returned, return {status: "inventory_funds", change: []}.
If the amount in the cash register is exactly equal to the amount of change that should be recovered, return {status: "CLOSED", change: [...]}, The attribute value of change is the amount in the cash register.
Otherwise, return {status: "OPEN", change: [...]}, The change key value is the amount of change to be recovered, and the face value of the change is sorted from high to low.

function checkCashRegister(price, cash, cid) {
  let change = cash * 100 - price * 100;  // Deduct the price from the charge to get the change
  let denoNum = [1, 5, 10, 25, 100, 500, 1000, 2000, 10000];// Face value array
  let denoStr = [];         // Face value name array, initially empty
  let total = 0;            // Total amount of change available
  let counterMap = {};      // Denomination name and available limit in the change counter
  let output = [];          // result
  let obj = {				// An object as the return value
    status: "INSUFFICIENT_FUNDS",
    change: []
  }

  for(let i=0;i < cid.length; i++) {
    // Traverse the zero cash cabinet cid
    let temp = cid[i][1] * 100;   // [1] It's the amount
    denoStr.push(cid[i][0])       // [0] is the name
    counterMap[cid[i][0]] = Math.round(temp);
    // Take the current name as the key name and the current amount as the key value after rounding
    total += Math.round(temp)     // Add the current amount to the total
  }

  if (change > total) {			  // If the change is not enough, you can go bankrupt
    return obj;
  }
  if (change === total) {		  // If there is just enough change in the change cabinet, return the whole change cabinet directly
    obj.status = "CLOSED";
    obj.change = cid;
    return obj;
  }

  for (let i = denoNum.length - 1; i >= 0;i--) {
    // Start traversing from the back. Change must give priority to those with large denominations
    if(denoNum[i] <= change) {
      let currentTotal = change - change % denoNum[i];
      // Total amount required for current denomination denoNum[i]
      if(counterMap[denoStr[i]] < currentTotal && counterMap[denoStr[i]] > 0) {
        // At present, the face value is still in the cabinet, but it is not enough
        output.push([denoStr[i], counterMap[denoStr[i]] / 100])
        // The name of the current face value and the total face value in the cabinet are inserted into the output as an array
        change -= counterMap[denoStr[i]];
        // The total amount of change, minus the current face value has tried its best to get the amount of change that needs to be changed
      } else if(counterMap[denoStr[i]] >= currentTotal) {
        // Current situation
        output.push([denoStr[i], currentTotal / 100]);
        // push the name of the current face value and the total amount used to output
        change -= currentTotal;
        // Less the amount processed by the current face value
      }
    }
    if(change === 0) {      // Until the amount to be found is 0, it is over
      obj.status = "OPEN";
      obj.change = output;
      return obj
    }
  }
  obj.status = "INSUFFICIENT_FUNDS";
  // It's been a long time. change is not 0. Don't play, or you can't afford it
  return obj;
}

Rearrange the change cabinet after each processing. The counterMap looks like {PENNY: 101, NICKEL: 205, DIME: 310, QUARTER: 425}.
Determine whether the total amount is enough before continuing.
Each change starts from the largest denomination to the smaller one. If the current denomination can be used, it is determined whether the denomination is enough. There are two cases.
If the current face value is processed, but the zero is still not found, then reduce the face value by one until the last penny. If it is still not found, it is a case.
In this process, change is 0 and the change is completed.

Added by goodgeneguo on Fri, 24 Dec 2021 11:53:01 +0200