javascript 获取随机表达式生成器

8zzbczxx  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(162)

我有一个创建随机整数的函数,但我试图重构它来创建随机加法表达式。它目前只生成单个整数。然后,消费者需要记录生产者正在进行的随机表达式的总和。这是一个工作关闭这个老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');
monwx1rj

monwx1rj1#

这将产生一个字符串表达式的结果,其数字在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>
oaxa6hgo

oaxa6hgo2#

如果你需要一个像这样的字符串'X + Y',然后加上引号,这样js就不会把两个随机数相加

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

相关问题