2

找到了一个可以对字符串进行洗牌的脚本

String.prototype.shuffle = function () {
    var a = this.split(""),
        n = a.length;

    for (var i = n - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
    return a.join("");
}

使用此脚本,以下单词:

What is the difference in between 'Apache Environment', 'Environment' and 'PHP Variables'?

将随机改组为这个词:

ftewE'eim rasent  VhiEAn'oeded ta ' mb one'ennfva'nbcr?n elcttpnP iaWePh'irH rshv ieinena,

但是,我想知道如何保留每个空间的原始位置:

ftew E' eim rasentVhiE An 'oededt a'mbone 'ennfva'nbcr? nelcttpnPiaWe Ph' irHr shvieinena,
4

2 回答 2

3

a[i]如果&a[j]是空格,您也可以简单地检查您的函数:

const shuffleMeSoftly = function(str, breaker = ' ') {
  var a = str.split(""),
      n = a.length;

  for (var i = n - 1; i > 0; i--) {
    if (a[i] != breaker) {
      var j = Math.floor(Math.random() * (i + 1));
      if (a[j] != breaker) {
        var tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
      }
    }
  }
  return a.join("");
}

console.log(shuffleMeSoftly('What is the difference in between \'Apache Environment\', \'Environment\' and \'PHP Variables\'?'))

于 2018-10-21T07:03:06.847 回答
1

一种选择是创建一个随机字符数组(无空格),然后使用正则表达式调用replace原始字符串,该正则表达式将非空格字符替换为数组中相关索引处的项目,在此过程中递增索引:

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

String.prototype.shuffle = function () {
  // pass to shuffleArray an array of all non-whitespace characters:
  const randomChars = shuffleArray([...this.replace(/\s+/g, '')]);
  let index = 0;
  // `\S` matches any non-whitespace character:
  return this.replace(/\S/g, () => randomChars[index++]);
}

console.log(
  `What is the difference in between 'Apache Environment', 'Environment' and 'PHP Variables'?`
  .shuffle()
);

另请注意,改变内置对象 likeString.prototype通常被认为是非常糟糕的做法,并且可能会破坏事物;除非你正在 polyfill 一些官方的东西,否则最好使用一个独立的函数:

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

function shuffle(str) {
  const randomChars = shuffleArray([...str.replace(/\s+/g, '')]);
  let index = 0;
  return str.replace(/\S/g, () => randomChars[index++]);
}

console.log(shuffle(
  `What is the difference in between 'Apache Environment', 'Environment' and 'PHP Variables'?`
));

于 2018-10-21T06:51:49.800 回答