I have one Question
Write a Javascript code to store a list of strings/sort it and print it in an unordered list
could you please tell me how to print unordered list in javascript ?
I do like this use Math.random function but it is not printing the value
var arr=['abc','pqr','mnc'];
for(var i=0;i<arr.length;i++){
console.log(arr[Math.floor((Math.random() * 3) + 1)]) ;
}
http://jsfiddle.net/3s4Lqr0o/1/
It is not printing the all values?
The first problem here is that Math.floor((Math.random() * 3) + 1) will return a number between 1 to 3. Your array only has elements at index 0, 1, and 2. So abc won't be printed at all.
The second problem is, there is no guarantee that your calculation will return every single number 0, 1 and 2 exactly once. You could be getting arr[1] three times in a row, resulting in pqr being printed 3 times.
I initially voted to mark this question as a duplicate of How to randomize (shuffle) a JavaScript array?. My thought was that you can simply shuffle the array, then print the shuffled array. However, since this question has been reopened, I will propose an alternate solution.
arr = ['abc','pqr','mnc'];
while (arr.length > 0) {
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]);
arr.splice(index, 1);
}
Randomly select one element in the array, print it and then remove it from the array. Repeat until there are no more elements.
Related
Problem: Write a function that takes in an int n and returns a double[] of length n where the starting element (value) is 1.0 and the other elements are the previous divided by 2. For example, halves(4) should return a double[] with numbers {1.0, 0.5, 0.25, 0.125}. (JAVASCRIPT)
Stuck on where to continue, currently just have setting the array to length.
Couldn't find any questions that already answered this.
void halves(int n){
arrhalves[] n;
}
If you are writing in JavaScript, define an array with only first element [1.0]. Then, define for-loop and loop over the array n times. Starting index should be 1 (because we already have one element in the array) and on each iteration push (arr[i - 1]) / 2 to the array.
Essentially, I have 2 datasets and a function. (The numbers after the name are stats, and are just placeholder but I need them to carry over exactly)
var randomIngredientsList = [["Bread", 1, 2], ["Water", 5, 2]]
var ingredients = [["Mustard", 2, 3]]
When I'm supposed to get a random ingredient, I want to carry over from randomIngredientsList, remove that specific part, and put it into ingredients.
There will also be different randomIngredientsLists with different tiers and stats so i need it to be able to differentiate them.
My function now looks something like this:
function generateRandomIngredient(nameOfArray){
var randomValue = Math.floor(Math.random() * nameOfArray.length) //grabs a random number from 0-the length of the dataset
console.log(randomValue)
if(nameOfArray.length = 0){ // if ingredient list is empty
exploreLogger.unshift("You seem to have picked clean all the ingredients in this tier. Good job!"); //explorelogger is a log at the end of the screen, which shows events
} else { //if it's not empty
ingredients.push(nameOfArray[randomValue]) // add it to the ingredients list
nameOfArray.splice(randomValue, 1) //remove the row from the dataset
}
}
When it run it with generateRandomIngredient(randomIngredientsList) it deletes all objects in randomIngredientsList and adds an undefined value to ingredients. I don't know what to do, I've spent 2 hours on this issue and found nothing about it online. Thanks to anyone who provides any help or answers.
You are assigning 0 to the array's length instead of comparing.
if(nameOfArray.length = 0){
should be changed to
if(nameOfArray.length === 0)
I have a master list with 8 items in, then a number of lists with the same items as the master list but where the items appear in a different order. How do I find a percentage similarity between each list with the master list?
For example, the master list might be:
[8,7,6,5,4,3,2,1];
One of the lists I want to compare it against could be:
[8,6,4,2,7,5,3,1];
I know I could just loop through the master list and check for matches, but is there an elegant way to work out how close each number is in the list to the same number in the master list?
For example:
position 0: '8' match in position 0; 0 positions difference (100%)
position 1: '7' match in position 4; 3 positions difference (57.1%)
position 2: '6' match in position 1; 2 positions difference (71.4%)
etc.
The end result would be a percentage similarity between the two lists.
You could use the Array map and reduce functions:
function getSimilaritry(a, b) {
return a.map(function(val, index) {
//calculate the position offset and divide by the length to get each
//values similarity score
var posOffset = Math.abs(b.indexOf(val) - index);
return posOffset/a.length
}).reduce(function(curr, prev) {
//divide the current value by the length and subtract from
//one to get the contribution to similarity
return (1 - curr/a.length) + prev;
});
}
If the lists aren't guaranteed to have the same values, you would need to add handling for that.
Also note that the order you pass the arguments a and b to the getSimilarity function will impact the result. Not clear if this is an issue for your application.
PS: I think your question was down-voted for not including the code you already had trying to solve this problem.
This question already has answers here:
Generate unique number within range (0 - X), keeping a history to prevent duplicates
(4 answers)
Closed 7 years ago.
I know how to sort through an array like this
var rand = myArray[Math.floor(Math.random() * myArray.length)];
but what I am trying to do is use this in a loop to pick values from my array that I haven't picked with this function before.
In other words, let's say my array contains apples, bananas, and oranges. i want to be able to pick all three of those out randomly, but I don't want to pick able to pick out the same one more than once.(I hope this made sense)
You can remove the item from the array, so it will not be selected again
var rand = myArray.length ? myArray.splice(Math.floor(Math.random() * myArray.length), 1)[0] : undefined;
Demo: Fiddle
Note: It will modify the original array, so if you want to keep the original array as it was you need to keep a different copy
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am writing a program that determines if a number is between two values in an array.
Here is an example of the array I am using.
var attackArray = new Array (2);
attackArray[0] = new Array("0","1","2","2","2","3","4");
attackArray[1] = new Array("2","3","2","3","2","3","4");
I am using the following code to compare the number against the first two values in the array. I then loop through the array until I find a line that meets the requirements. The number must be >= to the first number and <= the second number.
Here is the code that I am using.
function leveltest ( number)
{
var attack = attackArray.length;
for ( var count = 0 ; count < attack; count ++)
{
if ((number >= Number(attackArray [count][0])) && (number <= Number(attackArray [count][1])))
{
do something ;
}
}
}
If someone can look at my code and explain what I am doing wrong.
I believe you are trying to compare a number to each range of numbers defined by the item values with the same index in element 0 and element 1 of attackArray. If that is right, then the following applies.
The problems present in your code snippet were:
You have the index wrong on line 3. Your third line, attackArray[2] = new Array("1","3","2","3","2","3","4"); is creating a new third element in the attackArray created on the first line. Instead, I think you are wanting to populate the second element of attackArray which should be attackArray[1] = new Array("1","3","2","3","2","3","4"); Or you could use different array syntax as shown below.
In the function, you were using the length of attackArray var attack = attackArray.length;, to control the for loop following. Instead, you will want, var attack = attackArray[0].length; so long as attackArray[0] and attackArray[1] are the same length. You can think of it like this, you were getting your length along the wrong dimension of your array. You were getting the length "down" your array or list of objects, ran than "across" the horizontal dim of your array.
In the function, you are confused on how to loop through the array, and you have this attackArray [count][0] and attackArray [count][1] backwards. Instead they should be attackArray[0][count] and attackArray[1][count]. This will allow you to properly compare your number with each item in element 0 and the item of the same index in element 1.
The following code should be a concise, correct working piece of code to accomplish your goal. You can take and plug this in to jsfiddle.net and it should work in Chrome with the Javascript console used to view the results in the log. Here it is:
var attackArray = [];
attackArray[0] = ["0","0","2","2","2","3","4"];
attackArray[1] = ["1","3","2","3","2","3","4"];
function leveltest (number){
var attack = attackArray[0].length;
for (var count = 0;count < attack;count ++){
if ((number >= Number(attackArray [0][count])) &&
(number <= Number(attackArray [1][count]))) {
console.log(number + " matches at index " + count);
}
}
}
leveltest(2);
Looks like your second element in attackArray has the wrong index.
attackArray[2] = new Array("1","3","2","3","2","3","4");
attackArray.length == 2
you "count" can go up to 1, attackArray[1] is not defined by you.
The second comparation inside the if is wrong. At the second loop it will be attackArray[1][1] and you created an attackArray[0] and attackArray[2].