1

I'm replacing all characters in an array with random letters/numbers. However, duplicate letters do not get the same values which is what I want.

var rWords = ["all","ball","balloon"];
var word = rWords[Math.floor(Math.random() * rWords.length)];

var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var getPos = function(arr) {
    return Math.floor(Math.random() * arr.length);
}

var arr = word.split('');
for (var i = 0; i < word.length; i++) {
    arr.splice(getPos(arr), 1, letters[getPos(letters)]);
}
word = arr.join('');

I want the output to be something like:
all = 4xx, ball = Y4xx, balloon = Y4xxRR1

1
  • It was this "duplicate letters do not get the same values" property which helped lead to the downfall of the Enigma machine. Commented Dec 4, 2017 at 21:37

1 Answer 1

2

create a map function that return unique char for same input (for each character we want to replace we check if we already have a replacement for it stored in _map, if not then we find one and use it and store it in _map for future use)

var rWords = ["all","ball","balloon"];

var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

var _map = {}
function map(char) {
    if (_map[char] === undefined) {
        _map[char] = letters[Math.floor(Math.random() * letters.length)]
    }
    return _map[char]
}
var result = rWords.map(function(word) {
    var arr = word.split('');
    for (var i = 0; i < word.length; i++) {
        arr.splice(i, 1, map(arr[i]));
    }
    return arr.join('');
})

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.