I am using javascript function, where the loop should run 10 times, during these 10 times, it should throw a random question based on ,+ and - operations, in that too there should be 4 "+" questions, 3 "-" questions and 3 "" questions. And the loop should not run more than 10 times, someone please frame a logic for this...
My code so far:
<script type="text/javascript">
var op=new Array();
var addCount=0;
var subCount=0;
var mulCount=0;
var counter=0;
var no;
op[0]="+";
op[1]="-";
op[2]="x";
Array.prototype.chooseRandom = function()
{
return this[Math.floor(Math.random() * this.length)];
};
var a = [1, 2];
var b = [0, 2];
var c = [0, 1];
no=Math.floor((Math.random()*3));
while(addCount < 4|| subCount < 3 || mulCount < 3)
{
no=Math.floor((Math.random()*3));
if(no==0)
{
if(addCount<4)
{
addCount++;
var op1=Math.floor(Math.random() * (99 - 10+1)) + 10;
var op2=Math.floor(Math.random() * (99 - 10+1)) + 10;
}
else
{
no=a.chooseRandom();
}
}
else if(no==1)
{
if(subCount<3)
{
subCount++;
var no1=Math.floor(Math.random() * (99 - 10+1)) + 10;
var no2=Math.floor(Math.random() * (99 - 10+1)) + 10;
if(no1>no2)
{
var op1=no1;
var op2=no2;
}
else
{
var op1=no2;
var op2=no1;
}
}
else
{
no=b.chooseRandom();
}
}
else if(no==2)
{
if(mulCount<3)
{
mulCount++;
var op1=Math.floor(Math.random() * (99 - 10+1)) + 10;
var op2=Math.floor(Math.random() * (9 - 1+1)) + 1;
}
else
{
no=c.choseRandom();
}
}
counter++;
}
</script>
Make an array containing required number of +, - and * then random sort that aray using function below:
arr.sort(function() {return 0.5 - Math.random()})
Hoping it will help -
<script type="text/javascript">
function shuffle(o) {
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
function getQuestions(){
var operators = shuffle(["+", "+", "+", "+", "-", "-", "-", "x", "x", "x"]);
var a = [1, 2, 3, 4, 5, 6];
var counter = 0;
Array.prototype.chooseRandom = function () {
return this[Math.floor(Math.random() * this.length)];
};
while (counter < 10) {
var op1 = a.chooseRandom();
var op2 = a.chooseRandom();
alert(op1 + operators[counter] + op2 + "?")
counter++;
}
}
getQuestions();
</script>
Related
This is my code
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join();
}
basicIO.write(convertToCurr(input));
context.log.INFO("log data");
}
These are my outputs
{"output":"R 1,000,000,.00","log":["log data"]}
{"output":"R 1,000,.00","log":["log data"]}
I need to exctract the last "," so that the amounts make sense
The most straightforward solution is to perform a String.prototype.replace() on the final join().
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join().replace(',.', '.');
}
console.log(convertToCurr(10000.75));
console.log(convertToCurr(10.01));
console.log(convertToCurr(1000));
console.log(convertToCurr(7002344));
It should be noted that replace() only replaces a single instance of the substring you provide it in the input string, but this doesn't matter here since ,. only appears in your output string one time.
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
var combinedString; // holds string value after join
if (z == 0) {
a = x / 3 - 1;
} else {
a = x / 3;
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
combinedString = vals.join(); // join array into string
return combinedString.replace(",.", "."); // replace ,. with .
}
console.log(convertToCurr(50000000.15));
why when i paste my code in playcode.io it works like this
function Nums(args) {
let n = Number(args[0]);
let p1 = 0;
let p2 = 0;
let p3 = 0;
let p4 = 0;
let p5 = 0;
for (let i = 1; i < n; i++) {
let currentNum = Number(args[i])
if (currentNum < 200) {
p1++;
} else if (currentNum < 400) {
p2++;
} else if (currentNum < 600) {
p3++;
} else if (currentNum < 800) {
p4++;
} else if (currentNum <= 1000) {
p5++;
}
}
console.log(p1);
console.log(p2);
console.log(p3);
console.log(p4);
console.log(p5);
}
Nums(["4", "1", "3", "999"]);
I want to sort some numbers but aren't arrays starting from 0,why when i type 4 as first number calcs it correct? if i type 2 it places my 1 and 3 if fist variable and the last varibale is empty
You could take an array for counting the number in a certain slot.
function nums(values) {
let counts = [0, 0, 0, 0, 0];
values.forEach(v => counts[Math.min(Math.floor(v / 200), 4)]++);
return counts;
}
console.log(...nums([4, 1, 3, 999, 1000]));
Hello friends i got it working the way i wanna. I don't explain clear enough in the first place sorry.Here is the correction :
function Histogram(args) {
let n = Number(arguments[0]);
let v1 = 0.0;
let v2 = 0.0;
let v3 = 0.0;
let v4 = 0.0;
let v5 = 0.0;
for (let i = 1; i <= n; i++) {
let currentNum = Number(arguments[i])
if (currentNum < 200) {
v1++;
}
else if (currentNum < 400) {
v2++;
}
else if (currentNum < 600) {
v3++;
}
else if (currentNum < 800) {
v4++;
}
else if (currentNum < 1000) {
v5++;
}
}
console.log(v1);
console.log(v2);
console.log(v3);
console.log(v4);
console.log(v5);
}
Histogram('3','1', '2', '999');
Now i'm wondering why when i insert more code it breaks again...
let p1Percantage = 0;
let p2Percantage = 0;
let p3Percantage = 0;
let p4Percantage = 0;
let p5Percantage = 0;
p1Percantage = (v1 / n * 100);
p1Percantage = (v2 / n * 100);
p1Percantage = (v3 / n * 100);
p1Percantage = (v4 / n * 100);
p1Percantage = (v5 / n * 100);
console.log(p1Percantage.toFixed(2) + "%");
console.log(p2Percantage.toFixed(2) + "%");
console.log(p3Percantage.toFixed(2) + "%");
console.log(p4Percantage.toFixed(2) + "%");
console.log(p5Percantage.toFixed(2) + "%");
The variable that is suppost to show the last it shows as first...
Expected output
66.67%
0.00%
0.00%
0.00%
33.33%
Main:
33.33%
0.00%
0.00%
0.00%
00.00%
The whole program supposed to sort the histogram array in the correct variables by their values and show the percentage of each variables p1Percantage = (v1 / n * 100); .
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
}
return fib.filter(function(a) {
return (a % 2 != 0);
})
.reduce(function(a, z) {
return a + z;
})
}
console.log(sumFibs(10));
Expected output 10, but getting 99
Add a < num to your filter callback test, so you get a % 2 && a < num
function sumFibs(num) {
var fib = [0, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
}
return fib.filter(function (a) {
return a % 2 && a < num;
}).reduce(function (a, z) {
return a + z;
}, 0);
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))
You don't need to use array at all if you need only sum of those numbers
function sumFibs(num) {
if(num <= 1) return 0;
var a = 0, b = 1, sum = a + b;
while(true) {
var next = a + b;
if(next >= num) {
break;
}
if(next % 2) {
sum += next;
}
a = b;
b = next;
}
return sum
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))
You need to change the loop condition. Loop till the last value of fib is less than num
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; fib[fib.length - 1] < num; i++) {
var next = fib[i - 1] + fib[i - 2];
fib.push(next);
}
return fib
.filter(x => !(x % 2))
.reduce((ac,a) => ac + a,0)
}
console.log(sumFibs(10));
If you want to retain your code for the most part, you can add an if statement that breaks the loop once your next number goes beyond your num:
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
if ( next > num ) { // not >= assuming you want to include your num
break;
}
fib.push(next);
}
console.log({fib});
return fib.filter(function(a) {
return (a % 2 != 0);
})
.reduce(function(a, z) {
return a + z;
})
}
console.log(sumFibs(10));
Your code is summing the first N Fibonacci numbers that are odd. You seem to be looking for the first odd Fibonacci numbers that sum to N:
function oddFibsThatAddTo(target)
{
let currentFib = 1;
let lastFib = 1;
let sum = 2;
const outs = [1,1];
while(sum < target)
{
let nextFib = currentFib + lastFib;
if(nextFib % 2 == 1)
{
sum += nextFib;
outs.push(nextFib);
}
lastFib = currentFib;
currentFib = nextFib;
}
if(sum > target)
{
throw 'can\'t find perfect sequence';
}
return outs;
}
console.log(oddFibsThatAddTo(10))
function sumFibs(num) {
var fib=[1,1];
for(var i=2; i<num; i++){
var next=fib[i-1]+fib[i-2];
var fibi=fib.push(next);
}
return fib.filter(function(a){
return(a%2!=0 && a<=num);
})
.reduce(function(a,z){
return a+z;
})
}
console.log(sumFibs(10));
I want to do this math game that generates numbers and operators randomly.
This is hint - x = Math.floor(Math.random()*101); will generate a random number between 0 and 100. Select operators randomly (+,*,-) for each equation. Please any one can help me.
var arr = []
while(arr.length < 8){
var r = Math.floor(Math.random()*100) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
document.write(arr);
Here's an ES6 implementation of that, I used console.log instead of document.write
let questionsCount = 10;
function generateQuestions() {
let questions = [];
for(let i = 0;i < questionsCount;i++) {
let n1 = Math.floor(Math.random() * 101);
let n2 = Math.floor(Math.random() * 101);
let operatorObj = randomOperator(n1,n2)
questions.push({
question: `${n1} ${operatorObj.operator} ${n2} ?`,
answer: operatorObj.answer
});
}
return questions;
}
function randomOperator(n1,n2) {
let n = Math.floor(Math.random() * 4);
switch (n) {
case 0:
return {operator: '+', answer: n1 + n2};
case 1:
return {operator: '-', answer: n1 - n2}
case 2:
return {operator: '*', answer: n1 * n2}
case 3:
return {operator: '/', answer: n1 / n2}
}
}
let questions = generateQuestions();
let answers = questions.map((question) =>
prompt(question.question));
answers.forEach((answer,i) => {
console.log(`${questions[i].question} ${answer} ${(answer ==
questions[i].answer) ? 'Correct': `Wrong should be
${questions[i].answer}`}`)
});
You can use switch-case statement to select the operator and use Math.random() to randomize it
var arr = []
while(arr.length < 8){
var r = Math.floor(Math.random()*100) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
for (var i=0; i<4; i++) {
operator = Math.floor(Math.random() * 3);
switch(operator) {
case 0:
eval(prompt(arr[i*2] + " + " + arr[i*2+1]));
break;
case 1:
eval(prompt(arr[i*2] + " - " + arr[i*2+1]));
break;
case 2:
eval(prompt(arr[i*2] + " * " + arr[i*2+1]));
break;
}
}
Better solution: While it doesn't use prompts I'm sure you can figure that part out.
works best on codepen, and not very well inside the awkward snippet
feature that stack-overflow provides (due to the reset button triggering reload)
here's the code in case your interested:
//Solve the equation - math problem game
//change * 4 if you want more operators then add the
//operator as a string inside the operator array...
//you may also add duplicate operators to increase odds
//higher odds of harder operator = harder mode
var a = location;
function start() {
document.body.innerHTML = null;
var operators = ["/", "*", "-", "+"],
arr = [],
arrCompiled,
i = 0, a = location;
while (arr.length < 8) {
var r = Math.floor(Math.random() * 100) + 1;
if (arr.indexOf(r) === -1) arr.push(r);
}
while(i < arr.length) {
var oper = ' '+operators[Math.floor(Math.random() * 4)]+' ';
if (i === 0) {
arrCompiled = arr.toString()
.replace(/,/, oper);
}
arrCompiled = arrCompiled.replace(/,/, oper);
i++;
}
document.write('<div id="questions">'+arrCompiled+' = ???</div>');
document.getElementById("questions").insertAdjacentHTML('afterend', '<button id="solve">Solve</button>');
}
start();
document.getElementById('solve').addEventListener('click', function() {
if (document.getElementById('solve')) {
var x = document.getElementById('questions').innerText.replace(/\?/g, "");
var y = x.replace(/[^0-9*/+-.()]+/g, "");
var z = Math.round(eval(y) * 100) / 100;
document.write(x + z + ' - solved <button>New Problem</button>');
document.getElementById('questions').remove();
}
});
var arr = []
while(arr.length < 8){
var r = Math.floor(Math.random()*100) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
document.write(arr);
I wrote a JavaScript function to find the number of odd integers, number of negative integers, average, and median value.
The code is accomplishing everything that I wanted it to, however, I am wondering if I can rewrite it to get the function to return an object rather than just the console log values. I've also included a link to my JS Bin (https://jsbin.com/digagozuru/edit?html,css,js,console,output)
Any advice or suggestions would be appreciated! Thanks.
var arrayAnalyzer = function(myArray) {
var odds = 0;
var negatives = 0;
var avg;
var median;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 2 !== 0) {
odds += 1;
}
if (myArray[i] < 0) {
negatives += 1;
}
}
console.log("There are " + odds + " odd numbers.");
console.log("There are " + negatives + " negative numbers.");
var sum = myArray.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
avg = sum / myArray.length;
console.log("The average is " + avg.toFixed(2));
var orderedArray = myArray.sort(function(a, b) {
return a - b;
});
if (orderedArray.length % 2 === 0) {
var position1 = orderedArray.length / 2;
var position2 = position1 - 1;
median = (orderedArray[position1] + orderedArray[position2]) / 2;
} else {
var position = Math.floor(orderedArray.length / 2);
median = orderedArray[position];
}
console.log("The median is " + median);
};
arrayAnalyzer([7, -3, 0, 12, 44, -5, 3]);
var arrayAnalyzer = function(myArray) {
var odds = 0;
var negatives = 0;
var avg;
var median;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 2 !== 0) {
odds += 1;
}
if (myArray[i] < 0) {
negatives += 1;
}
}
console.log("There are " + odds + " odd numbers.");
console.log("There are " + negatives + " negative numbers.");
var sum = myArray.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
avg = sum / myArray.length;
console.log("The average is " + avg.toFixed(2));
var orderedArray = myArray.sort(function(a, b) {
return a - b;
});
if (orderedArray.length % 2 === 0) {
var position1 = orderedArray.length / 2;
var position2 = position1 - 1;
median = (orderedArray[position1] + orderedArray[position2]) / 2;
} else {
var position = Math.floor(orderedArray.length / 2);
median = orderedArray[position];
}
console.log("The median is " + median);
// Returns an object with named attributes
return {
odds:odds,
negatives:negatives,
avg:avg,
median:median
};
};
var myArray = arrayAnalyzer([7, -3, 0, 12, 44, -5, 3]);
console.log("Odds: " + myArray.odds +
"\nNegatives: " + myArray.negatives +
"\nAverage:" + myArray.avg +
"\nMedian: " + myArray.median);
I'm not sure if I get your question right, but why dont create an object at the beginning of your method and then write the values in the object as soon as you calculated them?
var arrayAnalyzer = function(myArray) {
var odds = 0;
var negatives = 0;
var avg;
var median;
var result = {};
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 2 !== 0) {
odds += 1;
}
if (myArray[i] < 0) {
negatives += 1;
}
}
result.negatives = negatives;
result.odds = odds;
var sum = myArray.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
avg = sum / myArray.length;
result.avg = avg;
var orderedArray = myArray.sort(function(a, b) {
return a - b;
});
if (orderedArray.length % 2 === 0) {
var position1 = orderedArray.length / 2;
var position2 = position1 - 1;
median = (orderedArray[position1] + orderedArray[position2]) / 2;
} else {
var position = Math.floor(orderedArray.length / 2);
median = orderedArray[position];
}
result.median = median;
return result;
};
console.log(arrayAnalyzer([7, -3, 0, 12, 44, -5, 3]));