Random pick items of an array in javascript - javascript

I have the following code in my index.html page
<body>
<script type="text/javascript" src="words.js"></script>
<script>
var words = [];
window.onload = function () {
words = getwords();
};
</script>
</body>
And in word.js file
function getwords() {
var block = [];
var keyword = ['HELLO', 'CYCLE', 'APPLE', 'albatross', 'platform', 'OPERA', 'COURT', 'HOUSE', 'NEWEST', 'AEROPLANE', 'SCIENTIST', 'CORRIDOR', 'BUTTERFLY'.
'MUSICAL', ' AUSTRALIA', 'XYLOPHONE', 'TAPESTRY', 'DREAM', 'NEEDLE', 'GIRAFFE'
];
var index = [];
for (var p = 0; p < keyword.length; p++) {
index[p] = 0;
}
for (var i = 0; i < 8; i++) {
var x = Math.floor(Math.random() * (keyword.length - 1));
for (var j = 0; j <= i; j++) {
if ((words[j] !== keyword[x]) && (index[x] !== 1)) {
block[i] = keyword[x];
index[x] = 1;
}
}
}
return block;
}
I want my getwords function to return any 8 words from keyword array everytime it is called in the onload and it should get stored in words array and those words shouldnt be repaeted next time. However my code doesn't work. May I know my mistake? Please help!
I tried
function getwords(){
var block = [], index =[];
var rem = keyword.length -1;
for(var p=0 ;p <(rem+1) ;p++)
{
index[p]=0;
}
for(var i = 0; i < rem; ++i) keys.push(i);
for(var i=0; i<8 ;i++) {
var x = Math.floor(Math.random() * rem);
while(index[x]===1)
{
x = parseInt(Math.random() * rem);
}
block.push(keyword[x]);
index[x]=1;
}
return block;
}
Still gives some same words on second call.

A small mistake has cost you this problem ...
While storing the indexes in the index array you are using index[p] = 0;
But which should be
for(var p = 0; p < keyword.length; p++) {
index[p] = p;
}
here is the Working Example

I can give you a nicer approach. Tested to be OK, have a try.
var keyword=[
'HELLO', 'CYCLE', 'APPLE', 'albatross', 'platform',
'OPERA', 'COURT', 'HOUSE', 'NEWEST', 'AEROPLANE',
'SCIENTIST', 'CORRIDOR', 'BUTTERFLY', 'MUSICAL',
'AUSTRALIA', 'XYLOPHONE', 'TAPESTRY', 'DREAM',
'NEEDLE', 'GIRAFFE'];
var keys = [];
for(var i = 0; i < keyword.length; ++i) keys.push(i);
function getwords(count){
var block = [];
// first.
// pick and remove [count] times. Becareful when keys goes empty.
while(count > 0 && keys.length > 0) {
var x = parseInt(Math.random() * keys.length);
block.push(keyword[keys[x]]);
keys[x] = keys[keys.length-1];
keys.pop();
--count;
}
return block;
}
console.log(getwords(8));
console.log(getwords(8));
console.log(getwords(8));

What you mean by "doesn't work"? What shows the console?
'BUTTERFLY'.'MUSICAL'. There's a dot instead of a comma.
Hope it helps.

Related

Having Issue On Pushing Array Into Two Dimension Array

Can you please take a look at this code and let me know why the storage.push(players) instead of adding new array/set of players into storage is merging them with previously added array?
Technically what I am expecting here is getting something like this
[
[2,52,35,16,18,46],
[18,44,66,25,78,26]
]
but what I am getting now is only one array in storage like
[
[2,52,35,16,18,46,18,44,66,25,78,26]
]
var storage = [];
var players = [];
function createplayers(arr) {
for (let i = 0; i < 8; i++) {
let a = true,
n;
while (a) {
n = Math.floor(Math.random() * 100) + 1;
a = arr.includes(n);
}
arr.push(n);
}
}
var x = 3;
var interval = 1000;
for (var i = 0; i < x; i++) {
setTimeout(function() {
createplayers(players);
storage.push(players)
console.log(players)
console.log(storage)
}, i * interval)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Your had only one players array all the time. Move the array creation to createplayers().
var storage = [];
function createplayers() {
var arr = [];
for (let i = 0; i < 8; i++) {
let a = true,
n;
while (a) {
n = Math.floor(Math.random() * 100) + 1;
a = arr.includes(n);
}
arr.push(n);
}
return arr;
}
var x = 3;
var interval = 1000;
for (var i = 0; i < x; i++) {
setTimeout(function() {
var players = createplayers();
storage.push(players)
console.log(players)
console.log(storage)
}, i * interval)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This Question has nothing to do with jQuery
You have to clear the players array everytime you add to storage.
Here is the solution
var storage = [];
var players = [];
function createplayers(arr) {
for (let i = 0; i < 8; i++) {
let a = true,
n;
while (a) {
n = Math.floor(Math.random() * 100) + 1;
a = arr.includes(n);
}
arr.push(n);
}
}
var x = 3;
var interval = 1000;
for (var i = 0; i < x; i++) {
setTimeout(function() {
createplayers(players);
storage.push(players)
console.log(players)
//Notice this line
players=[];
console.log(storage)
}, i * interval)
}

Reverse whole string while keeping the spaces at the same position

This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
for (var i = spaces.length - 1; i >=0; i = i - 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."
Then "array2" is an array of "array1" reversed.
Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.
Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".
I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.
You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
Here is my best crack at it.
const reverseStr = (input) => {
const revArr = input.replaceAll(' ', '').split('').reverse();
for (let i = 0; i < revArr.length; i++) {
if (input[i] === ' ') revArr.splice(i, 0, ' ');
}
return revArr.join('');
}
let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
// console.log(val.split('').reverse().join(''))
return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))

javascript array value is changing after it has been pushed

I am trying to debug the code below.
It is supposed to create a 2d-array, with all of the permutations of the input string.
It starts off great, and the initial string is pushed to the array, but after I run the reverse function in step 4, the value in strArr changes from having a length of 3 to a length of 2. basically like it is skipping the concat in the reverse function, but when I ran it in the debugger, z has a length of 3 after the concat, but then when the function returns it, the length becomes 2 again.
any help would be appreciated.
function permAlone(str) {
var perms = [];
var totalPerms = factorial(str.length);
var strCodes = converter(str);
var strArr = [];
strArr.push(strCodes);
// overall loop
for (var X = 0; X < totalPerms; X++) {
//step 1
var largestI = -1;
for (var i = 0; i < strCodes.length - 1; i++) {
if (strCodes[i] < strCodes[i + 1]) {
largestI = i;
}
}
//if none found break loop
if (largestI == -1) {
break;
}
//step 2
var largestJ = -1;
for (var j = 0; j < strCodes.length; j++) {
if (strCodes[largestI] < strCodes[j]) {
largestJ = j;
}
}
//step 3
swap(strCodes, largestI, largestJ);
//step 4
strCodes = reverse(strCodes, largestI);
//step 5 push to array
strArr.push(strCodes);
}
console.log(strArr);
return strArr;
}
function factorial(x) {
for (var i = x - 1; i > 0; i--) {
x *= i;
}
return x;
}
function converter(x) {
var temp = [];
for (var i = 0; i < x.length; i++) {
temp.push(x.charCodeAt(i));
}
return temp;
}
function swap(a, i, j) {
var temp = a[i];
a[i] = a[j];
a[j] = temp;
}
function reverse(z, a) {
var endArr = z.splice(a+1);
endArr.reverse();
z = z.concat(endArr);
return z;
}
debugger;
permAlone('abc');
The reverse function returns a new array and does not manipulate the existing. You need to change your code to the following:
endArr = endArr.reverse();
It looks like it was an issue with having a shallow copy of the array.
I added z = z.slice(); to the reverse function and it fixed the issue.

Return the index of largest sum within array

I'm a bit of a newbie when it comes to JavaScript. I'm working on a bit of a coding problem, and I'm running into a wall. Here's the code I'm having trouble with so far:
function creditCardTest (creditCardNumbers) {
var creditCardNumbers = [
'7629-1648-1623-7952',
'4962-1694-2293-7910',
'9999-9999-9999-9999', /*For test purposes*/
'4921-2090-4961-7308'
]
var sumArray = [ ]; //parallel to creditCardNumbers array
var largestValue = 0;
var locationOfLargest = 0;
var itemSum = 0;
for(var i = 0; i < creditCardNumbers.length; i++) {
var creditCardItem = creditCardNumbers [ i ];
/*console.log(creditCardItem); For test purposes*/
itemSum = 0; //required for functionality
for (var j = 0; j < creditCardItem.length; j++) {
var stringChar = creditCardItem.charAt( j );
/*console.log(stringChar); For test purposes*/
if ( stringChar >= '0' && stringChar <= '9' ) {
itemSum += parseInt(stringChar);
/*console.log(parseInt(stringChar)); For test purposes*/
}
}
sumArray[ i ] = itemSum;
console.log(sumArray[ i ]); /*required for functionality*/
}
if (!largestValue || sumArray[ i ] > largestValue) {
largestValue = sumArray[ i ];
locationOfLargest = i;
}
console.log(locationOfLargest);
}
creditCardTest( );
I'm looking to return the largest index in an array, but I'm only getting the 0th index as a result. Any input?
Here is a little fiddle
var largestValue = 0,
locationOfLargest = 0,
sumArray = [1, 100, 909, 8, 91098, 923823];
for (var i = 0; i < sumArray.length; i++) {
if (!largestValue || sumArray[i] > largestValue) {
largestValue = sumArray[i];
locationOfLargest = i;
}
}
console.log(locationOfLargest, largestValue);
or even a quicker solution:
var arr = [1, 100, 909, 8, 91098, 923823],
index = arr.indexOf(Math.max.apply(Math, arr));
console.log(index);
You could use a step by step approach
get first an array of digits
add the digits
get the index of max sum.
var data = ['7629-1648-1623-7952', '4962-1694-2293-7910', '9999-9999-9999-9999', '4921-2090-4961-7308'],
index = data.
map(a => a.match(/\d/g)).
map(a => a.reduce((a, b) => +a + +b)).
reduce((r, a, i, aa) => !i || aa[r] < a ? i : r, -1);
console.log(index);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Return Sorted Array Without Modifying Original Array

I'm having trouble with a function returning the original array as opposed to the sorted array. I tried to slice the array and return the sorted but it is not working. Any ideas on how to fix this?
function sortArr( comparator, array ){
var newArray = array.slice();
for(var i = 0; i < newArray.size; i++)
{
var min = i;
for(var x = i; x < newArray.size; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
min = x;
}
}
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
}
return newArray;
}
I fixed the function:
function sortArr( comparator, array ){
/*your code here*/
var i, x;
var min;
var newArray = array.slice();
for(i = 0; i < newArray.length - 1; i++)
{
min = i;
for(x = i + 1; x < newArray.length; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
min = x;
}
}
if(min != i){
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
}
}
return newArray;
}
Copy the array with slice and then use native sort:
function sortArr(comparator, array) {
return array.slice().sort(function(a,b) {
return comparator(a,b) * 2 - 1;
});
}
Your sorting algorithm doesn't look quite right. For a start the swapping of values should be inside the if statement. I would also advise to look at #Oriol's solution which is far more elegant.
function sortArr( comparator, array ){
var newArray = array.slice();
for(var i = 0; i < newArray.size; i++)
{
var min = i;
for(var x = i; x < newArray.size; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
min = x;
}
}
}
return newArray;
}
{"index.js":"var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
let newArr = globalArray.slice();\n let emptyArr = [];
return emptyArr.concat(newArr).sort();
}
nonMutatingSort(globalArray);"}

Categories