Okay, trying to put together a numeric array and arrange it in ascending order. The more I look, the more I confuse myself. The alerts come up as "undefined." What am I overlooking?
var random = new Array();
function main() {
generate();
original();
ascending(random);
}
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = document.write(Math.floor(Math.random() * 100) + ", ");
}
}
function original() {
var storage = "";
for (var i = 0; i < 25; i++) {
storage += random[i] + ", ";
}
alert(storage);
}
function ascending(random) {
var tempArray = random;
var storage = "";
random.sort(function (a, b) {
return a - b
});
for (i = 0; i < 25; i++) {
storage += tempArray[i] + ", ";
}
alert("ASCENDING- " + storage);
}
No need for document.write (not sure what were you trying to achieve with it), this is enough:
random[i] = Math.floor(Math.random() * 100);
Afterwards, if you need to convert it to a string for output, just join it:
random.join(",");
Here is your generate function:
var random = [];
function generate() {
document.write("Here are 25 Random Numbers:<br><br>");
for (var i = 0; i < 25; i++) {
random[i] = Math.floor(Math.random() * 100);
}
}
generate();
var str = random.join(', ');
document.write(str);
Note: try to avoid using document.write whenever you can.
Take out your document.write() call in generate(), that prints a number out to your HTML document, just assign it directly to your array. You're assigning the result of that print out to your array, which is definitely not what you want.
Related
I am currently working on some code to insert user inputted variables into an array at a specified point WITHOUT using the splice or the push command. I decided to try to use a while command as that is what makes the most sense to me as I am very new to javascript. When I do try to display nothing comes up.
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 100 to set array values
for (var i = 0; i < 100; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length - 1; i++) {
d += i + ' : ' + array[i] + "<br/>";
}
document.getElementById("output").innerHTML = d;
}
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
while (i < m) {
i++;
}
if (i == m) {
array[i] == n;
}
displayArray();
}
Possible solution is to create new array every time and overwrite old one. We create two counters one for old array, second for new array. While coping items from old array to new one, when we'r at desired index we'r adding desired value from input and increases only new array counter.
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var c = 0, o = 0, l = array.length + 1, new_array = [];
while (c < l) {
if (c === m) {
new_array[c] = n;
} else {
new_array[c] = array[o];
o++;
}
c++;
}
array = new_array;
clearDisplay();
displayArray();
}
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 10 to set array values
for (var i = 0; i < 10; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length; i++) {
d += i + " : " + array[i] + "<br/>";
}
document.getElementById("output").innerHTML = d;
}
fillArray();
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var c = 0, o = 0, l = array.length + 1, new_array = [];
while (c < l) {
if (c === m) {
new_array[c] = n;
} else {
new_array[c] = array[o];
o++;
}
c++;
}
array = new_array;
clearDisplay();
displayArray();
}
<p>Output: </p>
<input type="text" id="index">
<input type="text" id="value">
<button onClick="insertArray();">Insert</button>
<hr>
<div id="output">
</div>
You can use the following code to add elements to an array without using the splice or push command at the given index. See the implementation of insertArray function, I have commented out the wrong code and written a new line.
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 100 to set array values
for (var i = 0; i < 100; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
//displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length - 1; i++) {
d += i + ' : ' + array[i] + " ";
}
document.getElementById("output").innerHTML = d;
}
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var temp = array[m];
array[m] = n;
for (var i = m+1; i < 100; i++) {
array[i] = temp;
temp = array[i];
}
/*
while (i < m) {
i++;
}
if (i == m) {
array[i] = n;
}
*/
displayArray();
}
fillArray();
<p>Output: </p>
<input type="text" id="index">
<input type="text" id="value">
<button onClick="insertArray();">Insert</button>
<hr>
<div id="output">
</div>
Please let me know if this is what you wanted.
I am trying to create a score predictor based on a teams goal difference (football). I am new to JavaScript, and I have managed to get this far.
I want it to be like spinning a ten-sided dice 20 times + the team's goal difference. I have got this bit sorted I think. With my code now I have a list of random numbers logged in the console which is what I wanted. Now I would like to choose a number (e.g., 2) and see how many times this occurs in the list. I'd like to save this in a new variable called homeFinalScore (So if '2' occurs three times in the list of random numbers, the homeFinalScore variable should be 3). I've tried several things but have been unable to sort it yet!
Any help would be extremely helpful. Thank you in advance!
var homeFinalScore = 0;
function calculateScore(){
var homeTeam = document.getElementById("HomeTeam").value;
var awayTeam = document.getElementById("AwayTeam").value;
var homeGd = parseInt(document.getElementById("HomeGD").value);
var awayGd = parseInt(document.getElementById("AwayGD").value);
var homeGd = 20 + homeGd;
var awayGd = 15 + awayGd;
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
console.log(randNum);
}
}
You can create an array, use Array.prototype.push() to push randNum to the array, then use Array.prototype.filter(), .length to determine how many occurrences of a value are present within array.
var homeGd = 20 + 2;
var awayGd = 15 + 2;
var arr = [];
function countOccurrences(n, arr) {
return arr.filter(function(value) {
return value === n
}).length;
}
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
arr.push(randNum);
}
console.log(arr);
console.log(countOccurrences(2, arr));
Alternatively, you can increment a variable when randNum is equal to a value.
var homeGd = 20 + 2;
var awayGd = 15 + 2;
var n = 0;
var num = 2;
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
console.log(randNum);
if (randNum === num) {
++n
}
}
console.log("occurrences of 2:", n);
const homeGd = 10;
const randomNumbers = []; // array of random numbers
for (i = 0; i < homeGd; i++) {
randomNumbers.push(Math.floor(Math.random() * 11));
}
const countBy = randomNumbers.reduce((acc, current) => {
acc[current] = (acc[current] || 0) + 1;
return acc;
}, {});
console.log(countBy);
I have written a Javascript file of two algorithms. As shown in the code below, I am using a for loop to generate random values which are used by both algorithms as input.
At present, I am displaying output of the binarySearch and SearchSorted alternatively.
The problem I am facing is I have to pass the same array values generated by randomlyGenerateArray in the main program to both the algorithms for a meaningful comparison. But I don't know how to change the output format.
I have thought of adding them in different loops, but as I have explained above i need to use the same randomArray values for both the algorithms.
i.e., The below code produces output as shown below -
Binary Search Successful 1
Search Sorted Successful 5
Binary Search Successful 3
Search Sorted Successful 10
How do I display the output of Binary Search First and then display output of Search Sorted? it's something like this. Any help will be greatly appreciated.
Binary Search Successful 1
Binary Search Successful 3
Search Sorted Successful 5
Search Sorted Successful 10
// Binary Search Algorithm
function binarySearch(A,K)
{
var l = 0; // min
var r = A.length - 1; //max
var n = A.length;
var operations = 0;
while(l <= r)
{
var m = Math.floor((l + r)/2);
operations++;
if(K == A[m])
{
console.log('Binary Search Successful %d',operations);
return m;
}
else if(K < A[m])
{
r = m - 1;
}
else
{
l = m + 1;
}
}
operations++;
console.log('Binary Search Unsuccessful %d',operations);
return -1;
}
// Search Sorted Algorithm
function searchSorted(A, K)
{
var n = A.length;
var i = 0;
var operations = 0;
while (i < n)
{
operations++;
if (K < A[i])
{
return -1;
}
else if (K == A[i])
{
console.log('Search Sorted Successful %d', operations);
return i;
}
else
{
i = i + 1;
}
}
operations++;
console.log('Search Sorted Unsuccessful %d', operations);
return -1;
}
// Random Array generator
var randomlyGenerateArray = function(size)
{
var array = [];
for (var i = 0; i < size; i++)
{
var temp = Math.floor(Math.random() * maxArrayValue);
var final = array.splice(5, 0, 30);
array.push(final);
}
return array;
}
//Sort the Array
var sortNumber = function(a, b)
{
return a - b;
}
// Main Program
var program = function()
{
var incrementSize = largestArray / numberOfArrays;
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i);
var sort = randomArray.sort(sortNumber);
var randomKey = 30;
binarySearch(sort, randomKey);
searchSorted(sort, randomKey);
}
}
var smallestArray = 10;
var largestArray = 10000;
var numberOfArrays = 1000;
var minArrayValue = 1;
var maxArrayValue = 1000;
program();
You could store the sorted randomArrays in an array (which I've called sortedRandomArrays), then run a for loop for each search.
The Main Program would then look like:
// Main Program
var program = function()
{
var incrementSize = largestArray / numberOfArrays;
var sortedRandomArrays = [];
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i));
var sort = randomArray.sort(sortNumber);
sortedRandomArrays.push(sort);
var randomKey = 30;
}
for (var i = 0; i < sortedRandomArrays.length; i++)
{
binarySearch(sortedRandomArrays[i], randomKey);
}
for (var i = 0; i < sortedRandomArrays.length; i++)
{
searchSorted(sortedRandomArrays[i], randomKey);
}
}
Solution is simple: store the results and print with 2 separate loops (take out the printing from within the functions).
var program = function()
{
var binarySearchResults = [];
var sortedSearchResults = [];
var incrementSize = largestArray / numberOfArrays;
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i);
var sort = randomArray.sort(sortNumber);
var randomKey = 30;
binarySearchResults[i] = binarySearch(sort, randomKey);
sortedSearchResults[i] = searchSorted(sort, randomKey);
}
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
//print binary results
}
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
//print sorted results
}
}
Hallo by lotto generator code I got some numbers double in one "generate" cycle. This is the code:
function lottery() {
for (var i=0; i<=7; i++) {
var lottery = Math.floor(Math.random() * 49);
document.getElementById ("lotto" + i).innerHTML = lottery;
}
}
Who knows where is the problem? Thank You!
Just for fun: O(N) solution (other posted are O(N^2))
It uses the Fisher-Yates shuffle algorithm and then after the first 7 elements have been shuffled it takes them as is.
So, no need to check if any of the numbers have already been drawn:
const arr = Array(50).fill(0).map((_, i) => i);
const DRAW = 7;
const rand = (from, to) => Math.floor(Math.random() * (to - from + 1)) + from;
for (let i = 0; i < DRAW; ++i) {
const r = rand(i, arr.length - 1);
[arr[r], arr[i]] = [arr[i], arr[r]];
}
const selected = arr.slice(0, DRAW);
References:
Online demo
Like #JNK commented, you need to store used values to avoid using them again.
The easiest way to do this would be to store them in an array, and check if they've been used.
function lottery() {
var used = [];
for (var i=0; i<=7; i++) {
var lottery;
while(true) { // this loop keeps going until a new number is found
lottery = Math.floor(Math.random() * 49);
var newNum = true;
for(var j=0; j<used.length; j++) {
if(used[j] == lottery) {
newNum = false; // if already used, set newNum to false
break;
}
}
if(newNum) { // if not already used, then add num to used array
used.push(lottery);
break;
}
}
document.getElementById ("lotto" + i).innerHTML = lottery;
}
}
All credits to JNK for this one from his link. This isn't very intuitive (it's minimized, like in code golf), but it's an interesting solution.
Optimized random number generator (86 bytes):
var getRandomLottoNumbers = function () {
var n=[],i=0;
for(;++i<50;)
n.push(i);
for(;--i>6;)
n.splice(i*Math.random()|0,1);
return n
};
Full explanation here.
Similar approach as the others, however just using one loop.
function lottery() {
var winners = [];
while (winners.length < 7) {
var lottery = Math.floor(Math.random() * 49);
if (winners.indexOf(lottery) === -1) {
winners.push(lottery);
document.getElementById ("lotto" + winners.length).innerHTML = lottery;
}
}
}
I can not figure out why this is not working, should be returning an array with four distinct values, but it doesn't
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
while ($.inArray(randomNumbers[i], randomNumbers) !== -1) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
}
for (var i = 0; i < randomNumbers.length; i++) {
if ($('#output').html() !== '') {
var existingOutput = $('#output').html();
$('#output').html(existingOutput + randomNumbers[i]);
} else {
$('#output').html(randomNumbers[i]);
}
}
});
Can cut out the if and the second loop by appending the joined array
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
var ran =newNum();
/* unique check*/
while ( $.inArray( ran, randomNumbers) >-1){
ran=newNum();
}
randomNumbers.push(ran)
}
$('#output').append( randomNumbers.join(''))
});
function newNum(){
return Math.floor((Math.random() * 9) + 1);
}
Alternate solution using a shuffle method ( found in this post ):
var a=[1,2,3,4,5,6,7,8,9];
function Shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
$('#output').append( Shuffle(a).splice(0,4).join(''))
If you generate a number and put it in the array, don't you think that $.inArray() will tell you so?
Your while loop is guaranteed to hang. A member of the array (randomNumbers[i]) is always, of course, going to be in the array. In fact $.inArray() when called to see if randomNumbers[i] is in the array will return i (if it's nowhere else, which in this case it can't be). Your loop won't get past the first number, so it'll just be 0.
I don't understand the point of your while loop. inArray only returns -1 if the value isn't found, which it will always be found, so you're just creating an infinite loop for yourself that will keep resetting the random number generated.
If you're just trying to add four random numbers to a div, this worked for me:
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
for (var i = 0; i < randomNumbers.length; i++) {
if ($('#output').html() !== '') {
var existingOutput = $('#output').html();
$('#output').html(existingOutput + randomNumbers[i]);
} else {
$('#output').html(randomNumbers[i]);
}
}
});
Further refactored:
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
for (var i = 0; i < randomNumbers.length; i++) {
$('#output').append(randomNumbers[i]);
}
});