javascript - Using Math.random flexibly -


i create 4 letter long string, randomly containing of letters string: "roygbv".

what i've done this:

function generatesolution(){     var colors = "roygbv";     var str = "";     (var i=0; i<4; i++) {         var loc = math.ceil( math.random()*colors.length );         str += colors.charat(loc);     }      return str; } 

but doesn't seem right, why this?

also, exercise's solution:

str += colors.charat((math.random() * 6) | 0); 

i used math.ceil in solution prevent randoming floats 4.333123 , on. how solution work, without rounding randomed numbers?

also, | operator mean? , how randomization in second solution work?

the | bitwise or operator. since bitwise operations in javascript work 32-bit integers, that's shorthand way of rounding a number towards 0. in case it's equivalent this:

colors.charat(math.floor((math.random() * 6))); 

the number needs floored instead of rounded up, doing ceil, or miss first element of array (which @ index 0).

here's full details of conversion integer the spec:

the production : @ b, @ 1 of bitwise operators in productions above, evaluated follows:

  1. let lref result of evaluating a.
  2. let lval getvalue(lref).
  3. let rref result of evaluating b.
  4. let rval getvalue(rref).
  5. let lnum toint32(lval).
  6. let rnum toint32(rval).
  7. return result of applying bitwise operator @ lnum , rnum. result signed 32 bit integer.

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -