如何在Javascript保留空间位置的句子中加扰?

时间:2018-10-21 06:44:10

标签: javascript shuffle masking scramble

found an script会随机播放字符串:

val_in_lakhs

使用此脚本,后接单词:

SELECT q.id, 
       q.`date`, 
       q.volume, 
       q.symbol_id, 
       o1.expiry_date, 
       o1.val_in_lakhs 
FROM control_quotedaily AS q 
JOIN (SELECT o2.`date`, 
             o2.symbol_id
             MIN(o2.expiry_date) as closest_expiry_date              
      FROM control_oidaily AS o2
      GROUP by o2.`date`, o2.symbol_id                 
     ) AS dt 
  ON dt.`date` = q.`date` 
     AND dt.symbol_id = q.symbol_id
JOIN control_oidaily AS o1 
  ON dt.`date` = o1.`date`
     AND dt.symbol_id = o1.symbol_id 
     AND dt.closest_expiry_date = o1.expiry_date 

将随机将这个单词改头换面:

import numpy as np
import keras

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, X, labels, batch_size=32, dim=(32,32,32), n_channels=1,
                 n_classes=10, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.X = X
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.X) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch to make sure samples dont repeat
        list_IDs_temp = ... your code

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.X))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = self.X[ID,]

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

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

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("");
}

2 个答案:

答案 0 :(得分: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\'?'))

答案 1 :(得分: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()
);

还要注意,对String.prototype之类的内置对象进行突变通常被认为是很差的做法,并且会破坏事物。除非您要正式填充某些东西,否则最好使用独立功能:

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'?`
));