如何重复 123 1231 直到长度目标

Posted

技术标签:

【中文标题】如何重复 123 1231 直到长度目标【英文标题】:how to repeat the 123 1231 till the length target 【发布时间】:2019-05-24 02:13:22 【问题描述】:

如何打印 str 中的数字并重复它直到长度目标, 示例:

如果我们有num = 4 并且我们打印的str target123

所以newStr = 应该是1231,如果num = 6newStr = 123123

newStr.length 应该类似于 num

function repeatIt(num) 
  var arr = [],
    markIt = true,
    add = true,
    hastag = true;
  while (arr.length < num) 
    var pushThis = "";
    if (markIt) 
      pushThis = "!";
       markIt = false;
     else if (add) 
      pushThis = "@";
       add = false;
       hastag = true;
     else if (hastag) 
      pushThis = "#";
       hastag = false;
       markIt = true;
       add = true;
    ;
    arr.push(pushThis)
  ;
  return num > 0 ? arr : "invalid input"
;

console.log(repeatIt(3))
// output : ['!','@','#'] 123 

console.log(repeatIt(6));
// output : ['!','@','#','!','@','#'] 123 123

console.log(repeatIt(4))
// output : ['!','@','#','!'] 123 1

console.log(repeatIt(0)) // invalid input

上面是我的例子,那是我的代码,我检查并更改了参数,它与我想要的输出匹配,但是我的代码似乎不干净而且太长,有什么方法可以更好地编写代码上面的例子,??

【问题讨论】:

【参考方案1】:

您可以使用字符数组,然后使用Array.from 构造数组,并检查i % chars.length 以获得正确的字符:

function repeatIt(length) 
  if (length === 0) return "invalid input";
  const chars = ['!', '@', '#'];
  return Array.from(
     length ,
    (_, i) => chars[i % chars.length]
  )


console.log(repeatIt(3))
// output : ['!','@','#'] 123 

console.log(repeatIt(6));
// output : ['!','@','#','!','@','#'] 123 123

console.log(repeatIt(4))
// output : ['!','@','#','!'] 123 1

console.log(repeatIt(0)) // invalid input

【讨论】:

【参考方案2】:

您的函数实际上应该有两个参数:原始字符串和目标长度。

它可能看起来像这样:

function repeatIt(str, num) 
    while (str.length < num) 
        str += str; // double the length
    
    return str.slice(0, num); // chop off 


console.log(repeatIt("!@#", 8));

如果允许使用内置的.repeat()方法,那么:

function repeatIt(str, num) 
    return str.repeat(Math.ceil(num / str.length)).slice(0, num);


console.log(repeatIt("!@#", 8));

如果输入和/或输出需要是一个字符数组,您只需应用.split("") 将字符串转换为数组,然后应用.join("") 将数组转换为字符串。

【讨论】:

【参考方案3】:

如果我正确理解了您的问题,那么可以通过使用% 模运算符来简化如下:

function repeatIt(num) 
  
  if(num <= 0) return;

  // The dictionary and result arrays used to generate result
  const dict = ['!','@','#'];
  const result = [];      
 
  // Iterate over the number range provide
  for(var i = 0; i < num; i++) 
    
    // For each iteration, add item from dict
    // that is current iteration, modulo the length
    // of characters in the dictionary
    result.push( dict[i % dict.length] );
  
  
  return result;


console.log(repeatIt(0));
console.log(repeatIt(3));
console.log(repeatIt(4));
console.log(repeatIt(5));
console.log(repeatIt(10));

【讨论】:

以上是关于如何重复 123 1231 直到长度目标的主要内容,如果未能解决你的问题,请参考以下文章

text 重复向上滑动直到找到目标图像的过程。 #SenseTalk

text 重复向上滑动直到找到目标图像的过程。 #SenseTalk

算法初步:二分查找

检查我视图中的所有文本字段是不是为空目标c [重复]

POJ 3087 Shuffle'm Up

从字符串中删除格式:目标 c 中的“(123) 456-7890” => “1234567890”