best result i could gather has been "The toFixed() Method" - javascript

OS: CentOS7
I run "OpenWebSpider v0.3.0" on my local server (for searching/indexing). ~its working as it should. when i receive the "results", it shows "Relevancy XX.XXXXXXXXXXXXXX".I would like to shorten that to only 3 Decimal places; "XX.XXX"..
enter image description here
I am new here, and to some of this javascript. i think i have found what i need to embed? The toFixed()Method, but i cannot determine where exactly, or for that matter If that is the best way to accomplish this seemingly simple task.?:)
this is (what i am thinking) is the relevant "code" area.
enter image description here
Being a newbie at this i have tried various areas to edit or just add this: for (var i = 0; i.toFixed(2); i < results.length; i++)
to the "code area" that is pictured above (pic 2); (with a lot of variations) all results are none though. so far.
Sorry if my "Question" is Not compliant, i will work on it, i absolutely have the highest respect for stackoverflow, and what it is.. Thank you very much.

Well if you just want to print out the number with reduced decimals toFixed() wil do fine. But notice that it will change your number to a string. One other way to do it would be to use Math.round (). In your case to get 3 decimals it would be
Math.round(your_number * 1000) / 1000.
And for your loop. for (var i = 0, i.toFixed(2); i < results.length; i++) (assuming the first ; should be a ,) won't work because i.toFixed(2) will not only get executed once at the beginning of your loop, it also gets applied to i which is just your loop-counter. You need to apply it like this inside your loop:
results[i]['relevancy'].toFixed(3).

Related

Random Array Picker - Javascript

i was coding for a small project but my random array picker doesnt work
var btnarray = [xfn.left, xn.left, xnln.left, xln.left, xnn.left];
(this is the array)
var rand = btnarray[Math.floor(Math.random() * 4)];
(this is the random picker var)
Well, when i start, the rand value results equal to btnarray[0]
anyone can help me please?
Oh i perfectly know that the variables are all different.
Thanks
Since your array's length is 5, you need to multiply the value of the random function by that number. Better yet, use the length property.
var rand = btnarray[Math.floor(Math.random() * btnarray.length)];
You shouldn't use Math.floor since it will make very hard to get the last element in your btnarray array, you'll need to get exactly the number btnarray.length in order to get at that element. Also, floor tends to flatten probability outcomes and looks like you're stuck on some value(s) since it's threshold is forcing you to have the greatest integer smaller than or equal to some number.
You should use round instead, this will even the probability for every array element and will give you more apparently random indexes. Try this, it's already tested with a dummy btnarray array variable and works fine.
var rand = btnarray[Math.round(Math.random() * btnarray.length)];
if you toss this in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
you can just do this:
var randomValue = rando(btnarray).value
I usually go with randojs.com because it can handle pretty much any random functionality you need, and it's all short and easy to read.

Looping to a specific index within a string

I'm currently doing a puzzle and am having trouble formulating my thoughts on how to do the following. Heres some code for some context on my thoughts (this isn't working yet)
const words = ['this', 'is', 'my', 'dog', 'bit', 'bite', 'every'];
const strings = ['thisis', 'thisisacat', 'thisisaduck', 'thisismy', 'thisismydog', 'bitevery'];
var count;
for (var i = 0 ; i < strings.length ; i++)
{
for (var j = 0; j <words.length; j++)
{
if(strings[i].indexOf(words[j]) !== -1)
{
count+=words[j].length;
}
}
}
Basically I want to first go to the word this check if it is in strings[j]. If it is then get the length of words[i], and go to the words[i]'th position inside strings[j] meaning I want the 'is' part of the 'thisis'. Basically I just want to test whether each element in strings can be represented by any amount of combos in words. This of course can be done with regular expressions, but I would like to use the current thought process that I have.
TLDR
With my current way, how can I check whether words in the words array exist within each element of strings(I am attempting this with indexOf), and if it is, go to the length of that words position meaning go to the position where i is in thisis. I realize that the way I am phrasing it it might be a bit verbose, but I'm not sure how else to phrase it. Any help is appreciated.
Example Run
We are at strings[i], now we check if any element in words is in strings[i]. Now this is in 'thisis', so add an index of four, since this has a length of four, to get to the 4th position and beyond of thisis, now we have isso loop again through the rest of words, now is is inside is, that means we have succesfully created a word from using some amount of words in the words array. Note, I actually don't want to delete the this from thisis, as I know modifying strings altogether is very costly in memory.
Another Run
Take thisismydog in strings. Let us iterate through words. this is inside thisismydog, so now go to the 4th onwards of thisismydog ( since this has a length of 4) namely now we consider ismydog. Now iterate again looking at the elements in words. We see is is there, so we go to the second element in ismydog, namely mydog. Since we reach the end of the word we can successfully conclude that thisismydog can indeed be represented by a combination of those elements within words.

Custom function for Google Spreadsheet - handling the array passed from the spreadsheet

I am trying to build a simple script to work with a Google Spreadsheet. The spreadsheet takes input from a Google Form, so there is a series of values in the spreadsheet like this:
My goal is to write a script that would strip the number from each form input in a user-specified range, then add all the numbers to provide a single score. So, for example, the user could type =sumColumns(H2:K2) in a cell, and it would return the sum of the scores (for the sample screenshot I posted, it would return the result of 3+3+0+3, 9).
Here is the code that I wrote to do this:
function sumColumns(values) {
var sum = 0;
for(var i = 0; i <= values.length; i++){
var input = values[0][i];
var x = input.toString();
var y = x.charAt(0);
var num = parseInt(y);
sum += num;
}
return sum;
}
The problem is that it only ever seems to add two values together. So, when I put =sumColumns(H2:K2) in a cell in the spreadsheet, it only returns 6. Also, on line 3, if I change it from i <= values.length to i < values.length it only adds one number, so that I get 3 as a result. My guess is that I am misunderstanding the way that the Google Spreadsheet values are passed to the function, but I have been completely unable to make it work. I'd really appreciate any help!
Oops - edited & saved the question, wrote an answer - and forgot to save it. I let Serge beat me to it! And, as usual, Serge's answer works well (with integer values). But you did ask about how things worked, so here you go.
When you give a Custom Function a range as a parameter, H2:K2 in this case, the function receives a two-dimensional array, equivalent to the return value of Range.getValues(). You can test this easily, by (temporarily) changing your function to return a JSON representation of the parameter:
function sumColumns(values) {
return JSON.stringify(values); // For debugging, just return string showing values
...
Here's what you'll see in the cell that contains =sumColumns(H2:K2):
[["3 (Rarely)","3 (Frequently)","0 (Never)","3 (Frequently)"]]
That's showing an Array enclosed by [ .. ], with another Array inside, also enclosed by square brackets, and that array has four elements. If we change the range to be H2:K3 instead, we get this (with whitespace added for clarity):
[
["3 (Rarely)","3 (Frequently)","0 (Never)","3 (Frequently)"],
["","","",""]
]
Now that you know that, it's easy to see why your function was giving the results it did.
First, for(var i = 0; i <= values.length; i++) is using the wrong array bounds to loop over, since values.length will tell us how many rows are in values. In H2:K2, that length is 1. Instead, we need to be looping over the columns in the first row (values[0]), with its 4 cells.
You were wondering about < vs <= for this loop - we do need to use < since it's a 0-based index, and .length returns a count of elements. So we end up with:
for (var i=0; i < values[0].length; i++){ ... }
Using parseInt() is a good choice, and works well for the values in your spreadsheet. It can be improved, though, by ensuring that any String values have leading non-numeric values stripped first - parseInt() can then find an Integer inside a string.
function sumColumns(values) {
return JSON.stringify(values); // For debugging, just return string showing values
var sum = 0;
for(var i = 0; i < values[0].length; i++){
var input = new String(values[0][i])
.replace( /^\D+/g, ''); // Strip any leading non-digits
sum += parseInt(input);
}
return sum;
}
I'm not good with custom function because I never use them but it seems that values is not really an array...
Comments in italic :
Hmmm embarrassing ... my first though was that it had to be a 2D array but I logged val[0] in my test and it returned an 'undefined' error... I must have mistyped something at that moment... Anyway, that's why I looked for a way around handling data as a string and using split and regex.
As usual with Mogsdad's answers you have an answer and all the explanations that go with it ;-) and, as often with him too, you get a better answer than mine.
(one restriction though (#Mogsdad) your comment about non integer values could be applied to your code as well... you simply strip out any decimal value with parseInt()...:-)
That said, your use case was well described and in the limits of this example both code should work as expected, Mogsdad's one being more 'academic' and programmatically correct.
end of comment.
Using this trick below it works as expected for any input range (1 or more row and columns):
function sumCol(val) { // returns the sum of all numeric values in range
var values = val.toString().split(',');
var sum = 0;
for(var n=0;n<values.length;++n){
sum+=Number(values[n].replace(/[^0-9+.]/ig,''));
}
return sum;
}
I changed also the number extraction mode to make it more universal.

Index or size is negative or greater than allowed amount (non-negative indices)

While using Firefox, I keep getting the error described in the subject line for this block of code:
for(var i = 0; i < tables.length; i++)
{
var j = rows.length - 1;
while(j--)
{
if(hideDP && tables[i].innerHTML.indexOf(">D<") != -1)
{
if(!platTag && !soulSilverTag && pearlTag)
{
tables[i].deleteRow(j);//ERROR IS ON THIS LINE
}
}
}//end while loop (rows)
}//end for loop (tables)
I suspect that this error is because I'm somewhat new to making reverse loops, but I specifically made a reverse loop in this instance because it made deleting rows from a table easier. Note also that j is something like 24 and i is 0, so they're non-negative. Could someone shed some light on this for me?
EDIT : The full code can be found here.
Strictly working off of the currently posted code, here are the issues I see:
The posted code looks incomplete. Where is rows being initialized? This could cause the stated error.
Given while(j--);   The var j = rows.length - 1; line is incorrect. That is, unless you know that the last row will never need deleting. But if that is the case, then comment the code to make it clear.
For example, if there were 4 rows, the current code initializes j to 3, but because of the location of the -- operator, the inside of the loop sees: 2, 1, 0.   For the code as shown, use var j = rows.length; or add a comment to show that the logic is deliberate.
The 2 if() statements do not depend on j at all! (At least as the code is posted here.) If this is true, then move the conditionals outside of the j loop.
Consider posting the full, unedited, code. Or linking to it on a site like Pastebin.
Update for full script, now that it's been linked to:
Scanning the complete code, it looks like tables[i].deleteRow(j); can be called multiple times for the same row.
The easy solution, that should be done anyway, is to add a continue statement after each row delete.
For extra credit, reanalyze and simplify the flag and if logic too. :)
Update for target page, now that it's been linked to:
Examining the target page, the tables being looped by this script contain nested tables.
That throws off the row count in this line:
var rows = tables[i].getElementsByTagName("tr");
Sometimes making it seem like table[i] has more rows than it really directly owns.
Solution, use the built in rows array; so the line becomes:
var rows = tables[i].rows;
~~~~
While examining the script relative to the target page, a few other issues seemed apparent:
It's not best to loop through all tables. Target just the ones you need. So this:
tables = document.getElementsByTagName("table");
Should be changed to:
var tables = document.querySelectorAll ("div.KonaBody > table.roundy");
...which will select just the 4 payload tables, and not their subtables or the other tables scattered about.
By fine-tuning the initial table selection, the following, problamatic, test is not needed:
if(tables[i].getAttribute("style").indexOf("border: 3px solid") != -1)
Missing var in front of the majorSections initialization.
That error will also be generated if j is >= to the amount of rows in the table, but I'm not seeing the exact problem.

is there any JavaScript interpretor that can handle very large numbers? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Is there a bignum library for JavaScript?
Strange syntax of Number methods in JavaScript
I just wrote some code to figure out a Project Euler question.
I kept getting...
Uncaught SyntaxError: Unexpected token ILLEGAL
I couldn't see the syntax error in my code...
The number I'm using is 1000 digits long. I ran in Chrome's console
Number.MAX_VALUE > 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
And got false. Bummer.
Is there a interpreter that can run my code?
Here is the code if needed...
var num = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450.toString();
var max = 0,
  length = num.length;
for (var i = 0; i < length; i++) {
 
 var consecTotal = 1,
limit = i + 5;
  
  for (var j = i; j < limit; j++) {
    consecTotal *= parseInt(num.substr(j, 1), 10);
  }
  
  max = Math.max(max, consecTotal);
  
}
console.log(max);
The question is to find the largest number that is the product of 5 consecutive numbers. I won't type it word for word, as I think Project Euler frowns upon answers being posted online (I'm not even sure mine may work yet).
I turned to JavaScript because I wasn't sure how to set up an int to handle the number in C.
To actually explain the Uncaught SyntaxError: Unexpected token ILLEGAL.
The cause of this is actually that...
...20752963450.toString();
^-------- ...the dot after a number is treated as a decimal point
Therefore this doesn't make sense.
But if you add a space in front of the dot, then it will work because
now JavaScript uses it to access the toString() method.
12323 .toString() // this will work as you'd expect it to if you come from Ruby or the like
Still, if you add the space num will be infinity. So you'll have to look at awoodland's answer for a BigNum implementation.
Sounds like you're looking for a big num class. It seems there's one for Javascript and if you want to do it in C you could use gmp.
First, your num variable should be a proper string literal if you want to use it as a string. Which is what you appear to be doing. I've never seen the notation you are trying to use there and I can't get it to work in Chrome or IE. Just use:
var num = '73167176531330....';
Second, your inner loop is never going to terminate. j will always be less than j + 5. Did you perhaps mean j < i + 5?
Third, you'll need to make your outer loop only go to i < length - 4. Otherwise you are going to overrun then end of your "num" string in your inner loop when i gets close to the end length.
If I make those changes I get an answer. I don't know if it is the answer you are seeking.

Categories

Resources