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:
- let lref result of evaluating a.
- let lval getvalue(lref).
- let rref result of evaluating b.
- let rval getvalue(rref).
- let lnum toint32(lval).
- let rnum toint32(rval).
- return result of applying bitwise operator @ lnum , rnum. result signed 32 bit integer.
Comments
Post a Comment