I have this JavaScript below that add different fields. It works but does not round up the sum:
function Field2Value(aFields) {
var aValues = new Array(aFields.length);
for(i = 0; i < aFields.length; i++) {
aValues[i] = this.getField(aFields[i]).value;
}
return aValues;
} // end Field2Value
function SumArray(aValues) {
var sum = 0;
for(i = 0; i < aValues.length; i++) {
if(isNaN(aValues[i])) aValues[i] = 0;
sum += Number(aValues[i]);
}
return sum;
} // end SumArray
var myFields = new Array("AverageDiv", "AverageDiv1", "AverageDiv2",
"AverageDiv3", "AverageDiv4", "AverageDiv5", "AverageDiv6", "AverageDiv7",
"AverageDiv8", "AverageDiv9", "AverageDiv10", "AverageDiv11",
"AverageDiv12", "AverageDiv13");
event.value = SumArray( Field2Value(myFields) );
function Round(nValue, nDec) {
return Number(util.printf( "%,0 ." + Number(nDec) + "f", Number(nValue))) ;
}
I also have a script I want to use that will round up the sum of the average dividends but I do not know where to place this script in the script above.
Here is the rounding script:
function Round(nValue, nDec) {
return Number(util.printf( "%,0 ." + Number(nDec) + "f", Number(nValue))) ;
}
Please help.
The easiest way to round a number using Javascript is to use Math.round():
http://www.w3schools.com/jsref/jsref_round.asp
Edit - looking more closely, it looks like you're round to a set number of decimal places. You're using 'util.printf' - is that a library call? Does that function exist? That could be why your function is failing.
Put your code in a code block and it would be a lot easier to read.
Related
Background
I'm new to JavaScript and am solving various formulations of the Josephus Problem to better understand the syntax. Using a circularLinkedList implementation*, I've solved the classic formulation: Wikipedia||Numberphile. I've also solved the problem for any fixed number of fighters and a fixed number of skips between eliminations (e.g., if skipping two fighters between eliminations, 1 eliminates 4, 5 eliminates 8, etc). I am now trying to solve the problem given any function that indicates the number of skips at a given moment.
Problem
I can't access the return value of my skip function. I understand from 1, 2, 3 that my issue involves asynchronicity, but am having trouble isolating takeaways from the long responses involving AJAX and jQuery, which I'm unfamiliar with. Could I get an ELI5 solution? I apologize for my lack of understanding.
Code
function winnerStepFunc(num, func) {
let cll = new circularLinkedList(); //Initializing list with participants
for (let a = 0; a < num; a++) {
cll.append(a);
}
function next(funcSteps) { //Generating string indicating #steps from function's output
let toEvaluate = "start";
for (let i = 0; i < funcSteps; i++) {
toEvaluate += ".next"
}
return toEvaluate;
}
let start = cll.getHead(); //Selecting first eliminator
while (cll.size() > 1) {
let toCheck = func(); // PROBLEM LINE
console.log("toCheck = " + toCheck); //toCheck = undefined
let str = next(toCheck);
while (eval(str) !== start && cll.size() > 1) { //
let locCurrent = cll.indexOf(start.element);
start = eval(str).next;
cll.removeAt(((locCurrent + toCheck)% cll.size()));
}
cll.delete(eval(str).next.element);
start = start.next;
}
console.log(start.element + 1);
}
function callFunction(name, args) { // builds function string to be evaluated
let result = name + "(";
for (let i = 0; i < args.length -1; i++) {
result += args[i] + ", ";
}
result += args[args.length-1] + ")";
return result;
}
function callFunction(name) {
let result = `${name}()`;
return result;
}
function addOne() { //<--The first basic example I'm trying:
return ++globalTimes; //Make the step increase by one for each elimination
}
var globalTimes = 0;
winnerStepFunc(12, function(){eval(callFunction("addOne"))});
*CLL Implementation
You don't return in your function. I would remove all the eval stuff and just call the function directly.
winnerStepFunc(12, addOne);
I am trying to write a code in javascript/jquery and html which I thought would be fairly simple, but turns out to be quite challenging (to me). I have a program which computes the first x numbers of the fibonacci sequence, and stores it in an array. What I am trying to do is make two buttons that will display the next or previous number in the sequence. This is what I have so far.
Javascript:
var all = new Array();
fib = function (numMax) {
for (i = 0, j = 1, k = 0; k < numMax; i = j, j = x, k++) {
x = i + j;
//window.document.write(x + " ");
all[k] = x;
}
};
fib(1000);
fibon = function () {
getElementById("mynum").innerHTML = "all[+1]";
};
HTML:
<input type="text" id="mynum">
<button onclick="fibon();">Next</button>
You need a variable that contains the current index, and then increment it each time you click.
fibindex = 0;
function fibon() {
if (fibindex >= all.count) {
document.getElementById("mynum").value = "We've run out of Fibonacci numbers";
} else {
document.getElementById("mynum").value = all[fibindex];
fibindex++;
}
}
Also, notice that you should not put quotes around a use of a variable. Add you use .value to fill in an input, not .innerHTML.
DEMO
I have no idea why this code doesn't work, could anyone help:
toDecimal: function () {
var counter = 0;
var decimalValue = 0;
for (var i = 7; i > 0; i--){
var binaryValue = self.binaryArray[i];
decimalValue += binaryValue * Math.pow(2, counter);
counter++;
}
return decimalValue;
}
the code self.binaryArray is just an array of numbers (contains only 8, a byte, that's all i need to work with) something like this [0,0,0,0,1,1,1,1]
2nd'ly
Can you provide a slicker way of doing the counter, for the life of me I can't figure out how to calculate the counter from the i value, which shouldn't be too difficult, simple maths really.
Thanks
Your original loop never processes binaryArray[0]. As to a "slicker" way of doing things, assuming that binaryArray[0] is the most significant bit, I'd write your loop like this:
toDecimal: function () {
var decimalValue = 0;
for (var i = 0; i < 8; i++){
decimalValue = (decimalValue << 1) + self.binaryArray[i];
}
return decimalValue;
}
(The left shift is just a quick way of multiplying by 2.)
However, I like StephenH's suggestion:
toDecimal: function () {
return parseInt(self.binaryArray.join(''), 2);
}
Why not just use JavaScript's built in parseInt function?
Syntax: parseInt(string, radix);
var n = parseInt("10001",2);
n = 17
function averageCalculator (numvalues) {
for(i=0, i <= numvalues, i++>) {
var score = prompt("input the score")
result1 += score;
}
alert(result1 / 3);
}
this function is later triggered by a button with onclick="averageCalculator (2)
<input type="button" value="Click for the average" onclick="averageCalculator (2)">
any ideas why its not working? it should prompt you for 2 values and then alert you with the average. not sure whats wrong.
Your code has multiple issues. The for loop is not well formatted and you need to terminate statements with a semi-colon. Also you need to declare variables. And your loop will run numvalues+1 times which is why i removed the = in your loop. Also if you want to calculate an average you want to divide by numvalues.
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += score;
}
alert(result1 / numvalues);
}
On top of the invalid syntax you will run into a common "problem" with javascript here. The inputs are treated as strings and instead of being added they will be concatenated. Providing 2 and 2 as scores will result in 11. 2 concatenated with 2 = 22 / 2 = 11. You need to cast the value to a number explicitly before adding them together:
function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {
var score = prompt("input the score");
result1 += Number(score);
}
alert(result1 / numvalues);
}
Above code will correctly return 2
The syntax of your for-loop is wrong:
for(i=0, i <= numvalues, i++>) {
should be
for(i=0; i <= numvalues; i++) {
Tip: Also, it's better to use
for(var i=0; i <= numvalues; i++) {
since then i will be a local variable instead of a global one.
Try like this
for(var i=0; i <= numvalues; i++){}
An alternative solution (using a functional programming libary, like Underscore.js):
function averageCalculator(numValues) {
var numbers = _.map(_.range(numValues), function(element) {
return +prompt('input the score');
});
var result = _.reduce(numbers, function(memo, number) {
return memo + number;
}, memo);
alert(result / 3);
}
While a little bit more complicated (and less efficient), you'll get rid of loops altogether.
EDIT
The +prompt('input the score') does effectivly the same as Number(prompt('input the score')).
I have a problem with this script, something is going wrong.
Rnumer stays undefined.This script should return and write all uneven digits from the random number list. Can someone tell me what I do wrong. Thanks in advance
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
// document.write(Rnumber[i] + "<br/>");
}
function unevenAndDivisible(Rnumber)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder = parseInt(Rnumber[i])%2;
}
return remainder;
}
document.write(unevenAndDivisible());
Changed to
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
// document.write(Rnumber[i] + "<br/>");
}
function unevenAndDivisible(Rnumber)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder[i] = Rnumber[i]%2;
}
return remainder;
}
document.write(unevenAndDivisible(Rnumber));
but now i get the result :
0,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,1....
I simply want maybe I asked it wrong the first time, to write al uneven numbers from the random list of Rnumbers
Then I need to divide that through 7 and return that.
EDIT
Allmost all problems are clear , thanks everyone for that.
Their is still one question left:
In this code below it only take the first uneven value from remainder and I want that it takes all values that are uneven to the next if statement to check %7.
Maybe you see the problem better if you run it for youreself
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
}
function unevenAndDivisible()
{
var remainder = [];
var answer = [];
for (i = 0; i<= 100; i++)
{
if (Rnumber[i]%2 !== 0)
{
remainder.push(Rnumber[i]);
for (c = 0; c <= remainder.length;c++)
{
if (remainder[c]%7 == 0)
{
answer.push(remainder[c]);
}
}
}
}
return answer;
}
answer = unevenAndDivisible();
document.write(answer);
Problem solved , Thanks everyone
You don't need to pass Rnumber to the function, as it's already available in scope:
function unevenAndDivisible()
{
var remainder = [];
for (i = 0; i<= 100; i++)
{
if (Rnumber[i]%2 !== 0) {
remainder.push(Rnumber[i]);
}
}
return remainder;
}
remainder = unevenAndDivisible();
console.log(remainder);
JS Fiddle demo.
Edited in response to question from OP (in comments to question, above):
...can someone explain what this mean: var remainder = [];
Sure, it's array-literal notation, which is equal to: var remainder = new Array();, it's just a little more concise, and I prefer to save myself the typing. I get the impression, from JS Lint, whenever I use var x = new Array(); therein that the above version is generally preferred (since it complains otherwise), but I don't know why.
Either pass Rnumber to the function unevenAndDivisible or omit it from the argument list. Since it is an argument, it has more local scope than the initial declaration of Rnumber.
Your problem is the line
function unevenAndDivisible(Rnumber)
You are passing in Rnumber in as an argument, but when you call unevenAndDivisible()
you are not passing it it.
Consequently for the body of the function Rnumber is undefined (cause you passed nothing in)
The following snippet is equivalent to what you wrote nad might explain better
function unevenAndDivisible(xyz)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder = parseInt(xyz[i])%2;
}
return remainder;
}
then called as
unevenAndDivisible(undefined)
to fix it remove the argument from the call definition
i.e. define it as
function unevenAndDivisible()
1 - you is not defining the Rnumber value that's function argument.
2 - in loop, you're defining remainder to divised value of ranumber and is not saving in array; try:
change:
remainder = parseInt(Rnumber[i])%2;
to
remainder[i] = parseInt(Rnumber[i])%2;
var array = [],
i = 100;
while (i--) {
var random = Math.random()*i|0;
if(random % 2)
array.unshift(random);
}
alert(array);