How do I increase my number count by 1 in the array - javascript

Hello im new to javascript. My function is suppose to increase my count by 1 every-time i call it but when i run it in console it just repeats 1. Any suggestions?
var output = [];
var count = 1;
function bizzBuzz(){
output.push(count);
count++;
console.log(output);
}
bizzBuzz();

var count = 0;
var output = [];
function bizzBuzz() {
output.push(count += 1);
console.log(output);
}
bizzBuzz();
bizzBuzz();

Related

JavaScript infinity loop while generation numbers with minus?

I have JavaScript code that is used to make math problems(simple math questions). Everything is randomized.
With plus(+) everything works fine.
e.x.
1+3
2+4
8+9
The problem:
When the function that check if the first number for minus parameter is greater that the second(1-2 false;2-1 code executes) an infinity loop happens. I'm not good with the explanations hope will will get it when you see the code.
The structure of the output is:
the numbers from 1-10(random) with plus
the numbers from 1-10(random) with minus
the numbers from 1-100(random) with plus
the numbers from 1-10(random) with minus
<html>
<p id='plus10'></p>
<p id='minus10'></p>
<p id='plus100'></p>
<p id='minus100'></p>
<script>
arr2 = [];
var lastArr2 = [];
var num1,num2;
//FIRST ARRAY
while(lastArr2.length<121){
arr2.push('<br>'+Math.round(Math.random() * 10)+'+'+Math.round(Math.random() * 10)+'=');
lastArr2=removeDuplicates(arr2);
}
document.getElementById('plus10').innerHTML=(lastArr2.join(' '));
//SECOND ARRAY
arr1 = [];
var lastArr1 = [];
while (lastArr1.length < 121) {
arr1.push('<br>' + Math.round(Math.random() * 100) + '+' + Math.round(Math.random() * 100) + '=');
lastArr1 = removeDuplicates(arr1);
}
document.getElementById('plus100').innerHTML = (lastArr1.join(' '));
//THIRD ARRAY
arr3 = [];
var lastArr3 = [];
while (lastArr3.length < 121) {
gen();
}
function gen(){
//minus function
num1=Math.round(Math.random()*10);
num2=Math.round(Math.random()*10);
if(num1<num2){
gen();
}else{
lastArr3 = removeDuplicates(arr3);
arr1.push(num1+'-'+num2+'=');
}
}
document.getElementById('minus10').innerHTML = (lastArr3.join(' '));
function removeDuplicates(arr){
let unique_array = []
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}
</script>
</html>
EDIT:
I was wrong about
arr1.push(num1+'-'+num2+'=');
It should be
arr3.push(num1+'-'+num2+'=');
But this doesn't fix the infinity loop
I am not sure what you are trying to do here, but your
while (lastArr3.length < 121) {
gen();
}
while here (for the third array) definitely seems like a infinite loop to me. You should make some changes to your lastArr3 inside gen() to make your condition lastArr3.length < 121 unmet, which will finally break you out of the while.
Inside your gen() function, arr1.push() should probably be arr3.push(), otherwise the looping condition will never change and it will stay in infinite loop.

"Look and say sequence" in javascript

1
11
12
1121
122111
112213
122211
....
I was trying to solve this problem. It goes like this.
I need to check the former line and write: the number and how many time it was repeated.
ex. 1 -> 1(number)1(time)
var antsArr = [[1]];
var n = 10;
for (var row = 1; row < n; row++) {
var lastCheckedNumber = 0;
var count = 1;
antsArr[row] = [];
for (var col = 0; col < antsArr[row-1].length; col++) {
if (lastCheckedNumber == 0) {
lastCheckedNumber = 1;
antsArr[row].push(lastCheckedNumber);
} else {
if (antsArr[row-1][col] == lastCheckedNumber) {
count++;
} else {
lastCheckedNumber = antsArr[row-1][col];
}
}
}
antsArr[row].push(count);
antsArr[row].push(lastCheckedNumber);
}
for (var i = 0; i < antsArr.length; i++) {
console.log(antsArr[i]);
}
I have been on this since 2 days ago.
It it so hard to solve by myself. I know it is really basic code to you guys.
But still if someone who has a really warm heart help me out, I will be so happy! :>
Try this:
JSFiddle Sample
function lookAndSay(seq){
var prev = seq[0];
var freq = 0;
var output = [];
seq.forEach(function(s){
if (s==prev){
freq++;
}
else{
output.push(prev);
output.push(freq);
prev = s;
freq = 1;
}
});
output.push(prev);
output.push(freq);
console.log(output);
return output;
}
// Sample: try on the first 11 sequences
var seq = [1];
for (var n=0; n<11; n++){
seq = lookAndSay(seq);
}
Quick explanation
The input sequence is a simple array containing all numbers in the sequence. The function iterates through the element in the sequence, count the frequency of the current occurring number. When it encounters a new number, it pushes the previously occurring number along with the frequency to the output.
Keep the iteration goes until it reaches the end, make sure the last occurring number and the frequency are added to the output and that's it.
I am not sure if this is right,as i didnt know about this sequence before.Please check and let me know if it works.
var hh=0;
function ls(j,j1)
{
var l1=j.length;
var fer=j.split('');
var str='';
var counter=1;
for(var t=0;t<fer.length;t++)
{
if(fer[t]==fer[t+1])
{
counter++;
}
else
{
str=str+""+""+fer[t]+counter;
counter=1;
}
}
console.log(str);
while(hh<5) //REPLACE THE NUMBER HERE TO CHANGE NUMBER OF COUNTS!
{
hh++;
//console.log(hh);
ls(str);
}
}
ls("1");
You can check out the working solution for in this fiddle here
You can solve this by splitting your logic into different modules.
So primarily you have 2 tasks -
For a give sequence of numbers(say [1,1,2]), you need to find the frequency distribution - something like - [1,2,2,1] which is the main logic.
Keep generating new distribution lists until a given number(say n).
So split them into 2 different functions and test them independently.
For task 1, code would look something like this -
/*
This takes an input [1,1,2] and return is freq - [1,2,2,1]
*/
function find_num_freq(arr){
var freq_list = [];
var val = arr[0];
var freq = 1;
for(i=1; i<arr.length; i++){
var curr_val = arr[i];
if(curr_val === val){
freq += 1;
}else{
//Add the values to the freq_list
freq_list.push([val, freq]);
val = curr_val;
freq = 1;
}
}
freq_list.push([val, freq]);
return freq_list;
}
For task 2, it keeps calling the above function for each line of results.
It's code would look something like this -
function look_n_say(n){
//Starting number
var seed = 1;
var antsArr = [[seed]];
for(var i = 0; i < n; i++){
var content = antsArr[i];
var freq_list = find_num_freq(content);
//freq_list give an array of [[ele, freq],[ele,freq]...]
//Flatten so that it's of the form - [ele,freq,ele,freq]
var freq_list_flat = flatten_list(freq_list);
antsArr.push(freq_list_flat);
}
return antsArr;
}
/**
This is used for flattening a list.
Eg - [[1],[1,1],[1,2]] => [1,1,1,1,2]
basically removes only first level nesting
**/
function flatten_list(li){
var flat_li = [];
li.forEach(
function(val){
for(ind in val){
flat_li.push(val[ind]);
}
}
);
return flat_li;
}
The output of this for the first 10 n values -
OUTPUT
n = 1:
[[1],[1,1]]
n = 2:
[[1],[1,1],[1,2]]
n = 3:
[[1],[1,1],[1,2],[1,1,2,1]]
n = 4:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1]]
n = 5:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3]]
n = 6:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1]]
n = 7:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1]]
n = 8:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3]]
n = 9:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3],[1,1,2,2,1,1,3,1,1,3,2,1,1,1,3,1,1,2,3,1]]

How to add a tick mark based on a counter in Javascript

I'm making a simple game in HTML/Javascript where everytime a button or hyperlink gets pressed it adds 1 to a counter
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count + 1;
document.getElementById("p2").innerHTML = count;
}
</script>
My question is is there a way to also add a tick (Ascii #10004) equal to the number in the counter. I'm sure this is an easy solve but I've never really used Javascript and this seems the easiest language to do this all in. I appreciate any help given
You can use the HTML decimal: ☑
Just replace the code:
document.getElementById("p2").innerHTML = count;
with the following code:
document.getElementById("p2").innerHTML = "&#9745 "+count;
Or you can use:
document.getElementById("p2").innerHTML = "&#10004 "+count;
The result will be like this:
✔ 5
here 5 is your count.
Yes you can. You even don't need a loop to concatenate ticks.
see jsfiddle demo
var count = 5; // count is already 5 for demo purpose
function countClicks() {
count = count + 1;
var ticks = Array(count+1).join("✔");
document.getElementById("p2").innerHTML = count+' '+ticks;
}
countClicks(); # 6 ✔✔✔✔✔✔
Yes, you can use the String.fromCharCode to convert ascii code to character.
Example to display continuos ticks equal to number of count:
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count + 1;
var res = String.fromCharCode(10004);
var output = "";
for (var i = 0; i < count; i++) {
output += res+" ";
}
document.getElementById("p2").innerHTML = output;
}
</script>
This will do :
http://jsfiddle.net/oL83m567/1/
var count = 0;
function countClicks() {
count = count + 1;
var tick='';
for(var i=0;i<count;i++)
tick+= '&#x2714';
document.getElementById("p2").innerHTML = count + tick;
}
It sounds like you want to ADD another tick every time the thing is pressed? I would do it like this:
var count = 0;
function countClicks() {
count = count + 1;
document.getElementById("p2").innerHTML = document.getElementById("p2").innerHTML + '&#10004';
}
Or, slightly more efficiently:
var p2, count = 0;
function countClicks() {
count = count + 1;
p2 = document.getElementById("p2");
p2.innerHTML = p2.innerHTML + '&#10004';
}
In that case, count becomes unnecessary, unless you need it for something else.
I'd go for doing it with an array. Advantage of this is that you have the ticks stored as elements in the array and can manipulate them later e.g. change a chosen tick to a cross or have a button which removes a tick. Something like:
<script type="text/javascript">
var ticks=new Array();
function countClicks() {
ticks[ticks.length]="✔";
document.getElementById("p2").innerHTML = ticks.join("");
}
</script>

Javascript: reducing down to one number

So I need to take a date and convert it into one single number by adding up each digit, and when the sum exceeds 10, I need to add up the two digits. For the code below, I have 12/5/2000, which is 12+5+2000 = 2017. So 2+0+1+7 = 10 & 1+0 = 1. I get it down to one number and it works in Firebug (output of 1). However, it is not working in a coding test environment I am trying to use, so I suspect something is wrong. I know the code below is sloppy, so any ideas or help reformatting the code would be helpful! (Note: I am thinking it has to be a function embedded in a function, but haven't been able to get it to work yet.)
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
solution("2000, December 5");
You can just use a recursive function call
function numReduce(numArr){
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend","Reducing: "+numArr.join(","));
//Using the array's reduce method to add up each number
var total = numArr.reduce(function(a,b){return (+a)+(+b);});
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend",": Total: "+total+"<br>");
if(total >= 10){
//Recursive call to numReduce if needed,
//convert the number to a string and then split so
//we will have an array of numbers
return numReduce((""+total).split(""));
}
return total;
}
function reduceDate(dateStr){
var arrayDate = new Date(dateStr);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
return numReduce([d,m+1,y]);
}
alert( reduceDate("2000, December 5") );
<div id="log"></div>
If this is your final code your function is not outputting anything. Try this:
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
alert(solution("2000, December 5"));
It will alert the result in a dialog.

probability in javascript help?

Sorry, I'm new to JS and can't seem to figure this out: how would I do probability?
I have absolutely no idea, but I'd like to do something: out of 100% chance, maybe 0.7% chance to execute function e(); and 30% chance to execute function d(); and so on - they will add up to 100% exactly with a different function for each, but I haven't figured out exactly how to do this in any form.
What I found is mostly strange high school math tutorials "powered by" Javascriptkit or something.
For instance we define a number of functions
function a () { return 0; }
function b () { return 1; }
function c () { return 2; }
var probas = [ 20, 70, 10 ]; // 20%, 70% and 10%
var funcs = [ a, b, c ]; // the functions array
That generic function works for any number of functions, it executes it and return the result:
function randexec()
{
var ar = [];
var i,sum = 0;
// that following initialization loop could be done only once above that
// randexec() function, we let it here for clarity
for (i=0 ; i<probas.length-1 ; i++) // notice the '-1'
{
sum += (probas[i] / 100.0);
ar[i] = sum;
}
// Then we get a random number and finds where it sits inside the probabilities
// defined earlier
var r = Math.random(); // returns [0,1]
for (i=0 ; i<ar.length && r>=ar[i] ; i++) ;
// Finally execute the function and return its result
return (funcs[i])();
}
For instance, let's try with our 3 functions, 100000 tries:
var count = [ 0, 0, 0 ];
for (var i=0 ; i<100000 ; i++)
{
count[randexec()]++;
}
var s = '';
var f = [ "a", "b", "c" ];
for (var i=0 ; i<3 ; i++)
s += (s ? ', ':'') + f[i] + ' = ' + count[i];
alert(s);
The result on my Firefox
a = 20039, b = 70055, c = 9906
So a run about 20%, b ~ 70% and c ~ 10%.
Edit following comments.
If your browser has a cough with return (funcs[i])();, just replace the funcs array
var funcs = [ a, b, c ]; // the old functions array
with this new one (strings)
var funcs = [ "a", "b", "c" ]; // the new functions array
then replace the final line of the function randexec()
return (funcs[i])(); // old
with that new one
return eval(funcs[i]+'()');
Something like this should help:
var threshhold1 = 30.5;
var threshhold2 = 70.5;
var randomNumber = random() * 100;
if (randomNumber < threshhold1) {
func1()
}
else if (randomNumber < threshhold2) {
func2()
}
else {
func3()
}
This will execute func1() with 30.5% probability, func2() with 40%, and func3() with 29.5%.
You could probably do it more elegantly using a dictionary of threshholds to function pointers, and a loop that finds the first dictionary entry with a threshhold greater than randomNumber.
// generate cumulative distribution function from weights
function cdf(weights) {
// calculate total
var total = 0;
for(var i=0; i<weights.length; i++) {
total += weights[i];
}
// generate CDF, normalizing with total
var cumul = [];
cumul[0] = weights[0]/total;
for(var i=1; i<weights.length; i++) {
cumul[i] = cumul[i-1] + (weights[i]/total);
}
return cumul;
}
// pick the index using the random value
function selectInd(cumul,rand) {
for(var i=0; (i < cumul.length) && (rand > cumul[i]); ++i) {};
return i;
}
Code block to use the above
// setup (do this once)
var weights = [70,20,10];
var cumul = cdf(weights)
// get the index and pick the function
var ran = Math.random(); // 0 : 1
var func = funcs[selectInd(cumul,ran)];
// call the function
var someArgVal = 5;
var myResult = func(someArgVal);
// do it in one line
var myResult = (funcs[selectInd(cumul,Math.random())])(someArgVal);
Simplify calling code with a reusable object
function CumulDistributor(cumul,funcs) {
var funcArr = funcs;
var cumulArr = cumul;
function execRandomFunc(someArg) {
var func = funcArr[selectInd(cumulArr,Math.random())];
return func(someArg);
}
}
// example usage
var cdistor = new CumulDistributor(cumul,funcs);
var myResult = cdistor.execRandomFunc(someArgValue);
var decide = function(){
var num = parseInt(Math.random() * 10) + 1; // assigns num randomly (1-10)
num > 7 ? d() : e(); // if num > 7 call d(), else call e()
};
Look up how to get random numbers in JavaScript, and then depending on where that number falls, call each function.
Sounds like what you really want is the Javascript random() function.

Categories

Resources