7

I was playing on this site, and I got stuck at the random4 problem.

So, basically, the problem is the following.

var random4 = new function() {
  var rand = Math.random();

  this.test = function(x) {
    return rand === x;
  }
};

What value of x should be passed to random4.test in order to have it return true?

Note that the code here is slightly different from the linked page. This is because we do not have access to the rand variable and I want to make this explicitly clear.

Just a student
  • 10,560
  • 2
  • 41
  • 69
stackoverflow
  • 1,303
  • 2
  • 21
  • 36

3 Answers3

4

Math.random() can be predictable, which can be exploited. In theory. The ES6 spec says

Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.

(Emphasis mine.)

In practice, most modern browsers use xorshift128+ (Chrome, Firefox, Safari). Its implementation is rather brief and can be understood relatively easily. See this related question.

Can we attack this implementation and predict values in the sequence, or try to figure out previous values? According to Security.SX, we can. We really can. It is definitely not easy, but possible.

I don't know if this can really be used to solve the linked exercise. In theory, it could.


An alternative could be to pass in something that will always be equal to any number compared to it. That is, overload the strict equality === operator. Unfortunately, JavaScript does not support operator overloading, as far as I know. You can cheat and use post processing (cannot be used on the linked page), or fake it in some cases, but this challenge is not one of them as we have primitives that are compared using the strict equality operator - that one does not do casting or valueOf.

Community
  • 1
  • 1
Just a student
  • 10,560
  • 2
  • 41
  • 69
0

You simply pass the rand variable that you've already declared in:

random4(rand);

rand is equal to x which is equal to rand.

var rand = Math.random();
function random4(x) {
    return rand === x;
}

console.log(random4(rand));
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • the problem is that rand is defined in another context, therefore it is not accessible, you can try it there and you'll get "rand is undefined" – stackoverflow Mar 17 '17 at 08:46
0

Still trying this but it could be similar to

random4(
    Math.random = function(){return true}
)

Though this needs the function itself to be equal to its return value, thats the part Im not sure about

https://stackoverflow.com/a/6959642/1281385

Doesnt help here

Community
  • 1
  • 1
exussum
  • 18,275
  • 8
  • 32
  • 65
  • 1
    rand is set to Math.random() prior to random4 being called, so no matter how you define Math.random, it's not going to make a difference. – dav Mar 22 '17 at 20:32