给定A-Z生成A-Z的良好算法 [英] Good algorithm for generating A-Z by given A-Z

查看:99
本文介绍了给定A-Z生成A-Z的良好算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何最好地称呼我的问题,这是问题所在:

I don't know how to best title my problem, here is the problem:

有一个函数y = f(x)

There is a function y = f(x)

x的域是一组在[AZ]组合处的字符串。

Domain for x is a set of string at combination of [A-Z]

输出y是x的一个字母。

Output y is one letter up of x.

例如:

x = A-> y = B

x = A -> y = B

x = Z-> y = AA

x = Z -> y = AA

x = AB-> y = AC

x = AB -> y = AC

x = ZZ-> y = AAA

x = ZZ -> y = AAA

x = ZZA-> y = ZZB

x = ZZA -> y = ZZB

任何人都有好的

我现在所拥有的条件检查非常完整,如果Z到A,一次输入一个字符。

What I have now is very completed condition check, if Z then A, one char a time.

推荐答案

一种方法是查看流中的最后一个字母,然后尝试通过将其转换为字符代码来将其增加一个。如果已经是Z,请将最后一个字母重设为A,然后对第二个字母至最后一个字母重复该过程。重复直到结束。

One way of doing this is look at the last letter in the stream and attempt to increase it by one by converting it to a character code. If it's already a Z, reset the last one to A and repeat the process on the second to the last letter. Repeat until you get to the end.

function increment(x) {
  if (!x) {
    return '';
  }

  // Convert the string into an array of characters
  let chars = x.split('');
  
  let i = chars.length - 1;
  for (; i >= 0; i--) {
    let oldChar = chars[i];
    if (oldChar === 'Z') {
      // If it's a Z, reset to A and process
      // the previous letter in the sequence
      chars[i] = 'A';
    } else {
      // Convert the character to a character code
      let code = chars[i].charCodeAt(0);
      // Increment that code and convert it back to a character
      let newChar = String.fromCharCode(code + 1);
      
      // Replace the existing letter
      chars[i] = newChar;
      break;
    }
  }

  // If we got all the way to the end, that means that all
  // of the letters were Z's that have now been converted
  // to A's. Append one more A to finish the incrementing
  if (i === -1) {
    chars.push('A');
  }

  // Join the array of characters together to form a string
  return chars.join('');
}

console.log(increment('A'));   // B
console.log(increment('Z'));   // AA
console.log(increment('AB'));  // AC
console.log(increment('ZZ'));  // AAA
console.log(increment('ZZA')); // ZZB

这篇关于给定A-Z生成A-Z的良好算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆