Counting numbers in an random array - javascript

So I'm trying to find how many of each number from zero to ten is generated in a random array.
I created a random array list
i=0;
var ranList=[];
while (i<20){
i++;
ranList.push(Math.floor(10*Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
/*Then I made a function to count /elements from this array
*/
function ctnumber(array,elem){
var ct=0;
var j =0;
while(j<array.length)
{
j++;
if(array[j]==elem){
ct+=1;}
}
}
return ct;
}
alert(ctnumber(ranList,5));
The second function doesn't execute, any idea why?
Thank you!

First you should avoid using the name array for you variable:
http://www.w3schools.com/js/js_reserved.asp
Your brackets are also wrong. Change your function to this and it should work:
function ctnumber(arr,elem){
var ct=0;
var j =0;
while(j<arr.length)
{
j++;
if(arr[j]==elem){
ct+=1;}
}
return ct;
}

The problem with your code, as stated by Pardeep in his comment, is that you have an extra } after your ct+=1; in your second while loop.
The correct code would be: Fiddle
i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
function ctnumber(array, elem) {
var ct = 0;
var j = 0;
while (j < array.length) {
j++;
if (array[j] == elem) {
ct += 1; // NOTE NO } HERE NOW
}
}
return ct;
}
alert(ctnumber(ranList, 5));
I also suggest a bit of a code cleanup:
var i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random());
}
function countNumbers(list, elem) {
var count = 0;
// For loops are generally more readable for looping through existing lists
for (var i = 0; i < list.length; i++) {
if (list[i] == elem) {
count++;
}
}
return count;
}
alert(countNumber(ranList, 5));
Please note that console.log() is a much better debugging tool, it can be accessed by F12 in Firefox and Chrome/IE.

Related

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well.
cnt = 0;
for (let i = 0; i < this.fin.length; i++) {
for (let j = 0; j < this.fin.length; j++) {
if (this.fin[i] == this.fin[j]) {
cnt++;
if (cnt > 1) {
this.fin[j] = '';
}
}
if (j == this.fin.length - 1) {
cnt = 0;
}
}
}
this.ntmtg1 = true;
count = 0;
for (let j in this.fin) {
if (this.fin[j] == '') {
this.fin.splice(parseInt(j));
}
}
your logic is almost correct. The couple of mistakes you did are:-
In the for loop in the last part of your code, when you use for( let i in SomeCollection) 'i' will be the value and not index in the array. I think you want to access the index and not the value. I think you should use should use traditional for loop like for(int i =0; i<fin.length;i++).
You need to use splice with two arguments to delete some value from the array.
here is the link https://www.w3schools.com/jsref/jsref_splice.asp
You can do that in simply just one line of code with ES6 feature and Set :
var fin = ["Vivek","Vivek","Mak","Nik","Mak","Hir","Hari","Nur","Nik"];
var result = [...new Set(fin)];
console.log("Fin Total :" , fin.length , ", Result Total :" , result.length);
console.log(result);
Couple of fixes to your code
don't use for in if you're going to mutate the array
splice with only one argument splices from the index to the end of the array, so add a second argument, the length of the splice
in the code below, I omit this for simplicity
Also, I moved were cnt is defined, so no if condition gymnastics needed to reset it
const fin = [1,3,6,7,3,2,4,5,6,4,3,2,1,4,5];
for (let i = 0; i < fin.length; i++) {
let cnt = 0;
for (let j = 0; j < fin.length; j++) {
if (fin[i] == fin[j]) {
cnt++;
if (cnt > 1) {
fin[j] = '';
}
}
}
}
let count = 0;
for (let i = 0; i < fin.length; i++) {
if (fin[i] == '') {
fin.splice(i, 1);
--i; // we've removed an item
}
}
console.log(fin);
fin:any = ["OMAD","SVAC","SVCH","SVAD","LGAG","OMAM","OTBK","OTBH","LGAX","LGBL","SVAN","LGAD","SVAB","SKAP","LGRX","SVAA","SVAS","DNAS","EGEI","NCAT","SVBS","SVBL","SVFM","EPKG","OBBB","OBBS","OBKH","LTFD"
,"SVBC","SVBI","SVBM","SVBB","SVBO","TNCB","SVBZ","SKBU","SKBN","SVCI","SVCD","SVCL","SVCN","SVCC","SVCS","SVCO","SVCZ","SKGO","SVCP","NZCG","SVQM","SVCA","LGSA","MWCB","CYCK","SVCB","SVPI","MRCU","EKCN"
,"SVCR","SKCV","SVUR","SVCU","SVRB","TNCF","TNCC","LGTT","VRMD","OMDW","SVLL","SVED","SVRS","SVEM","SVJI","SVVG","LGEL","SVEZ","NZEV","EDTF","SVFT","VRMR","SKGB","SVGU","SVGD","SVGT","SVGI","SVQJ","EKHM"
,"SVQF","LSPK","SVQL"];

How to add a counter to this loop?

I'm a javascript newbie working on a hangman game, I had everything working properly until I realized that my method for comparing my guess to the answer was unable to handle words with multiple letters. I've written a new loop that takes care of this, but that's led to a new problem: I don't know how to work in a counter to keep track of wrong guesses.
This is the loop that I have:
function checkGuess(guess, array) {
for (let i = 0; i < array.length; i++) {
let found = false;
for (let j = 0; j < array.length; j++) {
if (array[i] === guess) {
found = true;
}
}
if (found) {
results += answer[i];
}
}
}
The game will end when the number of wrong guesses reaches a certain count or when results.length = answer.length but I can't figure out how to handle wrong guesses. Any tips would be appreciated.
try this, create a function that return the number of places that the guess exists
function checkGuess(guess, array) {
let found = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] === guess) {
found++;
}
}
return found;
}
then use 2 vars to hold the correct guess and the wrong guess
var correct = 0, wrong = 0
then every time the user is guessing, do the following:
var check = checkGuess(guess, question);
if (check > 0) {
correct += check;
} else {
wrong++;
}
to determine if win or lose
if (wrong >= 3) {
// set it to lose
}
if (correct == question.length) {
// set it to win
}
Is this maybe what you're looking for?
var wrongGuesses = 0;
function checkGuess(guess, array) {
for (let i = 0; i < array.length; i++) {
let found = false;
let go_time = false;
for (let j = 0; j < array.length; j++) {
if (array[i] === guess) {
found = true;
results += answer[i];
}
if(j===(array.length-1)){
go_time = true;
}
}
if (go_time===true&&found!==true) {
wrongGuesses++;
}
}
}

cannot detect error. Where is the infinite loop occurring?

// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count = 0;
var array = person.split(",");
var freq = [];
var words = [];
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i = 0, j = 0;
while (array.length > 0) {
var temp = array[0];
while (j < array.length) {
if (temp == array[j]) {
count = count + 1;
array.splice(j, 1);
//console.log(array);
j = 0;
}
else {
j = j + 1;
}
}
freq[freq.length] = count;
count = 0;
words[words.length] = temp;
}
window.alert(freq + "\n" + words);
The problem is that whenever I run it an infinite loop occurs and no output is shown, I cannot find the error please help if possible. This code is for finding the frequency of the words in a input string with words separated by commas. thank u.
You just need to put var i=0,j=0; inside the while !
while(array.length>0)
{var i=0,j=0;
Working fidddle
You're resetting your loop variable j to 0 on each iteration. This condition if(temp==array[j]) never fails so j is always reset to 0, so while(j<array.length) is always true.
After coming out of the inner While loop, you need to reset j to zero. As the incremental value of j is not allowing it to go again inside the inner loop So array.length is not reducing And we are getting an infinite loop.
// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count=0;
var array = person.split(",");
var freq = new Array();
var words = new Array();
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i=0,j=0;
while(array.length>0)
{
var temp=array[0];
while(j<array.length)
{
if(temp==array[j])
{
count=count+1;
array.splice(j,1);
//console.log(array);
j=0;
}
else
{
j=j+1;
}
}
freq[freq.length]=count;
count=j=0;
words[words.length]=temp;
}
window.alert(freq+"\n"+words);
It's where for is more useful for consistency. You can replace inner while loop by this for loop:
for(j=a.length-1; j>=0; j--)
if(temp==a[j]) {
count=count+1;
a.splice(j,1);
}
Nevertheless, overall complexity of your counting method can be reduced with data structure like map.
Essential part of your script can be reduced to this:
var counter = new Map();
for (i in array)
counter.set(array[i], (counter.get(array[i])||0)+1);
var freq = Array.from(counter.values());
var words = Array.from(counter.keys());

Speeding up simple math operations on numeric 2D array (matrix) in JavaScript

I have a numeric 2D array (an array of arrays, or a matrix) and I need to do simple matrix operations like adding a value to each row, or multiplying every value by a single number. I have little experience with math operations in JavaScript, so this may be a bone-headed code snippet. It is also very slow, and I need to use it when the number of columns is 10,000 - 30,000. By very slow I mean roughly 500 ms to process a row of 2,000 values. Bummer.
var ran2Darray = function(row, col){
var res = [];
for (var i = 0 ; i < row; i++) {
res[i] = [];
for (var j = 0; j < col; j++) {
res[i][j] = Math.random();
}
}
return res;
}
var myArray = ran2Darray(5, 100);
var offset = 2;
for (i = 0; i < myArray.length; i++) {
aRow = myArray[i];
st = Date.now();
aRow.map(function addNumber(offset) {myArray[i] + offset*i; })
end = Date.now();
document.write(end - st);
document.write("</br>");
myArray[i] = aRow;
}
I want to avoid any added libraries or frameworks, unless of course, that is my only option. Can this code be made faster, or is there another direction I can go, like passing the calculation to another language? I'm just not familiar with how people deal with this sort of problem. forEach performs roughly the same, by the way.
You don't have to rewrite array items several times. .map() returns a new array, so just assign it to the current index:
var myArray = ran2Darray(5, 100000);
var offset = 2;
var performOperation = function(value, idx) {
return value += offset * idx;
}
for (i = 0; i < myArray.length; i++) {
console.time(i);
myArray[i] = myArray[i].map(performOperation)
console.timeEnd(i);
}
It takes like ~20ms to process.
Fiddle demo (open console)
Ok, Just a little modification and a bug fix in what you have presented here.
function addNumber(offset) {myArray[i] + offset*i; }) is not good.
myArray[i] is the first dimention of a 2D array why to add something to it?
function ran2Darray (row, col) {
var res = [];
for (var i = 0 ; i < row; i++) {
res[i] = [];
for (var j = 0; j < col; j++) {
res[i][j] = Math.random();
}
}
return res;
}
var oneMillion = 1000000;
var myArray = ran2Darray(10, oneMillion);
var offset = 2;
var startTime, endTime;
for (i = 0; i < myArray.length; i++) {
startTime = Date.now();
myArray[i] = myArray[i].map(function (offset) {
return (offset + i) * offset;
});
endTime = Date.now();
document.write(endTime - startTime);
document.write("</br>");
}
try it. It's really fast
https://jsfiddle.net/itaymer/8ttvzyx7/

$.inArray() jQuery function

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]);
}
});

Categories