我有一个创建随机整数的函数,但我试图重构它来创建随机的加法表达式。它目前仍然只生成单个整数。然后,消费者需要记录生产者正在进行的随机表达式的总和。这是这个老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');
答案 0 :(得分:1)
如果您需要这样的字符串' X + Y'然后添加引号,以便js不会添加2个随机数
function getRandomExpression(from, to) {
return from + ' + ' + Math.floor(Math.random()*(to-from));
}
答案 1 :(得分:1)
这将产生一个结果作为字符串表达式,其数字介于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>