获取随机表达式生成器

Get random expression generator

我有一个创建随机整数的函数,但我正在尝试重构它以创建随机加法表达式。它目前仅仍在生成单个整数。然后消费者需要记录生产者所做的随机表达式的总和。这是旧 github 的作品。 https://github.com/ajlopez/SimpleQueue/blob/master/samples/ProducerConsumer/app.js

var sq = require('../..');

function getRandomInteger(from, to) {
    return from + Math.floor(Math.random()*(to-from));
}

function Producer(queue, name) {
    var n = 0;
    var self = this;

    this.process = function() {
        console.log(name + ' generates ' + n);
        var msg = n;
        n++;
        queue.putMessage(msg);
        setTimeout(self.process, getRandomInteger(500, 1000));
    }
}
//this should log 
//Producer generates 5 + 9
//Second Producer generates 12 + 8


 function Consumer(queue, name) {
    var n = 0;
    var self = this;

    this.process = function() {
        var msg = queue.getMessageSync();

        if (msg != null)
            console.log(name + ' process ' + msg);

        setTimeout(self.process, getRandomInteger(300, 600));
    }
}
//this should log the SUM of the 2 producers random expressions ie: 
//Consumer process 5 + 9 = 14
//Consumer process 12 + 8 = 20

var producer = new Producer(queue, 'Producer');
var producer2 = new Producer(queue, 'Second Producer');
var consumer = new Consumer(queue, 'Consumer');

如果您需要这样的字符串 'X + Y' 然后添加引号,这样 js 就不会添加 2 个随机数

function getRandomExpression(from, to) {
    return from + ' + ' + Math.floor(Math.random()*(to-from));
}

这将产生一个字符串表达式的结果,其数字在 500 到 1000 之间:

function rand(min, max){
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomExpression(from, to){
  var a = rand(from, to), b = to - a;
  return a + " + " + b
}

var expr = getRandomExpression(500, 1000);

//

document.querySelector("pre").innerHTML = JSON.stringify(expr);
<pre></pre>