【问题标题】:Scramble String According to Array Values - Javascript根据数组值加扰字符串 - Javascript
【发布时间】:2019-06-03 21:43:13
【问题描述】:

试图解决 Codewars 上的this question

我见过other articles 处理随机洗牌/加扰字符串。

但是根据给定数组中的值对字符串进行加扰呢?

abcd 给定数组 [0, 3, 2, 1] 将变为 acdb 因为:

  • a 移动到索引 0
  • b 移动到索引 3
  • c 移动到索引 2
  • d 移动到索引 1

我的猜测是从将字符串拆分为数组开始。然后我们想要获取传递给scramble 函数的数组的索引值,并将索引值处的字符从该数组推送到新数组中。最后加入数组:

function scramble(str, arr) {

  let newArray = str.split("");
  let finalArray = [];

  for (let i = 0; i < str.length; i++) {
    console.log(newArray);
    finalArray.push(newArray.splice(arr[i], 1));
  }
  return finalArray;
}

console.log(scramble("abcd", [0, 3, 1, 2]));

但是这个逻辑的问题是.splice()每次都会从newArray中删除字符。

是否有另一种方法可以在不修改原始数组的情况下删除指定索引处的字符?

我认为 slice 也不会起作用。

【问题讨论】:

  • 你的问题不一致;你问如何从影响数组的数组中删除一些东西。答案是“你不能”——这就是“移除”的定义。如果您只想获取特定索引处的字符,这就是 slice 的用途...
  • 如果您提供的数组长度与字符串不同,会发生什么情况?或者这永远不会发生?
  • @zfrisch 根据编码挑战,这不会发生。

标签: javascript arrays string


【解决方案1】:

你可以创建一个单独的数组来存储字母。

var str = "abcd";
var arr = [0, 3, 2, 1];
function scramble(s, a) {
    var ar = Array(a.length);
    a.forEach((e, i) => {
        ar[e] = s[i];
    });
    return ar.join('');
}
console.log(scramble(str, arr));

【讨论】:

  • 我不知道你可以创建一个指定长度的“空白”数组。和其他答案一样,将字符串索引值分配到 newArray 值要高效得多。谢谢!
【解决方案2】:

回答

在数组上使用reduce,当数组被迭代时,将字符串(s)中迭代器索引(i)的字符分配给新数组的值索引(v)( ra)。 reduce 完成后,使用join 将返回的数组(ra)转回字符串。

let scramble = (s, a) => a.reduce((ra,v,i)=> (ra[v] = s[i], ra), []).join("");

示例:

let scramble = (s, a) => a.reduce((ra,v,i)=> (ra[v] = s[i], ra), []).join("");

console.log( scramble("abcd", [0,3,2,1]) );

说明代码:

我意识到上面的代码可能难以理解。让我为您提供完全相同的功能,但在标准功能中。请记住,这正是上面代码中发生的事情,但如果你不习惯 ES6 的简洁性,它可能更容易理解:

function scramble(my_string, my_array) { 
   // create an array to return
   let returnable_array = [];

   // loop through the provided array. 
   // string index is the array key: 0,1,2,3
   // array_index is the value of the array keys: 0,3,2,1

   for(let [string_index, array_index] of my_array.entries()) {

   // we assign the character at string index 
   // to the value index inside the returnable array

    returnable_array[array_index] = my_string[string_index];
   } 

   // we turn the array into a string
   let returnable_string = returnable_array.join("");

   // we return the string
   return returnable_string
}

示例:

    function scramble(my_string, my_array) { 
       let returnable_array = [];
       for(let [string_index, array_index] of my_array.entries()) {
        returnable_array[array_index] = my_string[string_index];
       } 
       returnable_string = returnable_array.join("");
       return returnable_string
    }


console.log(scramble("abcd", [0,3,1,2]));

【讨论】:

    【解决方案3】:

    您可以循环输入字符串,使用 string.charAt(position) 获取当前位置的字符,并将其放入从位置数组检索到的新数组中。

    function scramble (str, arr) {
    let newArray = [];
    for (let i = 0; i < str.length; i++) {
        newArray[arr[i]]=str.charAt(i);
      }
      return newArray.join();
    }
    
    console.log(scramble("abcd", [0, 3, 1, 2]));

    【讨论】:

    • 也可以直接使用str[i],不需要调用函数。
    • 我没有意识到您可以像这样简单地将字符串值分配newArray。这比尝试推入新数组要简单得多。最后加上return newArray.join(),这行得通。
    • @Barmar - 酷!很高兴知道 - 虽然我不确定如果我对字符串使用数组访问,幕后会发生什么。
    • @HappyHands31 - 很高兴我能帮上忙! =)
    • 没有什么特别的事情发生。 EcmaScript 5 只是将其添加为等效功能。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    【解决方案4】:

    我认为最好的方法是将字符串放入一个新数组中:

        function scramble(str, arr) {
            //validate if the array has elements
            if (arr && arr.length) {
                //create a new array
                const strArr = []
                arr.forEach(index => {
                    //push each character by index
                    //As noted by Barmar you could either use
                    //str.charAt(index) or str[index]
                    //as both will return the character at the specified index
                    strArr.push(str.charAt(index))
                })
                //return a new string
                return strArr.join('');
            }
        }
    

    【讨论】:

    • 也可以直接使用str[i],不需要调用函数。
    • 你是对的 Barmar,因为字符串的行为也像数组。
    猜你喜欢
    • 2013-06-27
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多