Reputation: 119
I want to split a word into letters put it into in array and display the letters randomly. i am having trouble. with words that have double of the same letter. and also the correct amount of letter is being shown but not all the letters are being displayed.
Here is my code I'm a noob:
window.onload = init;
function init() {
//var name=prompt("what is your name ? ","");
//character(name) ;
words();
}
function character(name) {
var name = name;
document.getElementById("words").innerHTML = "hey " + name + " my name is koala could you help me put these words back in order?";
}
function words() {
var lastlet = "";
var words = ["joe", "suzy", "terry", "fox", "lopez"];
var rand = Math.floor(Math.random() * words.length) + 0;
//for one word and seperation with letters
var ranwor = words[rand].split("");
for (var i = 0; i < ranwor.length; i++) {
var inn = ranwor[Math.floor(Math.random() * ranwor.length)].split().shift();
if (true) {
var di = document.getElementById("wor").innerHTML += inn;
}
lastlet = inn;
}
}
#char {
height: 65px;
width: 65px;
}
#words {
height: 100px;
width: 200px;
}
<img id="char" src="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" />
<p id="words"></p>
<br>
<p id="wor"></p>
<p id="wo"></p>
<br>
<textarea id="inp"></textarea>
<br>
<button>
I think this is right :)
</button>
Upvotes: 0
Views: 103
Reputation: 207501
Just sort the array using a random number and use join() so you do not need to loop.
var words = ["joe", "suzy", "terry", "fox", "lopez"];
var rand = words[Math.floor(Math.random() * words.length)];
function scramble (word, rescrambled) {
var scrambled = word.split("").sort(function(){ return Math.random() > .5 ? 1 : -1; }).join("");
if (word===scrambled && !rescrambled) { //if it matches the original, retry once
return scramble (word, true);
}
return scrambled;
}
console.log("Random word: ", scramble(rand));
console.group("loop them");
while(words.length){
var x = words.pop();
console.log(x,":", scramble(x));
}
console.groupEnd("loop them");
Upvotes: 1