Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The example string(s) can look like that:
"3.0000+3"
"3.00+3.00"
"3.00+3.000"
I want to find the highest amount of decimal places out of the numbers inside 1 string
The most straight-forward way to do this is iterating over the string, checking for the occurence of a dot and from there on count the number of digits up to the next character that's NOT a number or the end of the string. Since your string contains multiple numbers you need to add a variable which holds the highest amount of decimal places.
e.g.
var str = "3.00+3.000";
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
console.log(str + " has " + getDecimalPlaces(str) + " decimal places");
This can be made a bit more elegant by using a regular expression in conjunction with the .match() method. This searches a string for a given pattern and returns an array of results.
var str = "3.00+3.000";
console.log(str.match(/(\.)([0-9]+)/g));
This will return an array like:
[".00", ".000"]
By comparing the length of it's elements - minus 1 since it includes the dot - we can get the number of decimal places using this nifty short function:
var str = "3.00+3.000";
var highest = str.match(/(\.)([0-9]+)/g).reduce(function(a, b) {
return Math.max(a.length - 1, b.length - 1);
});
console.log(str + " has " + highest + " decimal places");
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How to compare 2 text strings to see if they are similar, for example:
var a = "Hello Blue World";
var b = "Hello Blut World?";
if(a similar b)
{
console.log(true);
}
You could use string-similarity library.
Finds degree of similarity between strings, based on Dice's Coefficient, which is mostly better than Levenshtein distance.
var a = "Hello Blue World";
var b = "Hello Blut World?";
var stringSimilarity = require("string-similarity");
var similarityCoef = stringSimilarity.compareTwoStrings(a, b);
if (similarityCoef > 0.8) { console.log(true); }
Note that similarityCoef print true when the string matches at 80% (0.8). You can adjust this value to your needs.
That's tricky. Because you have somehow to tell in percent what similarity means for you. What about this approach?
You compare them string by string and count the matches. I know that this will fail as soon as there is one additional character very early in one of the strings. But for a start it should suffice.
var a = "Hello Blue World";
var b = "Hello Blut World?";
// only compare both strings with their mutual length, because of the loop we use
const mutualLength = (a.length > b.length) ? b.length : a.length;
const similarityAt = 90; // percent
let matchCount = 0;
// with each match increase matchCount by 1
for (let pointer = 0; pointer < mutualLength; pointer++) {
if (a.substring(pointer, 1) === (b.substring(pointer, 1) {
matchCount++;
}
}
// compute similarity in percent
const similarity = (matchCount * 100) / mutualLength;
console.log('Similarity given: ' + (similarity >= similarityAt));
B"H
Depends on degree of similarity, but if you want a percent amount to tell you what matches, you can simply loop through the shortest, and keep track of how many times each character matches with the subsequent index of the longest string (or add whitespace to the shortest string, but that might mess up some calculations), and then divide the total number of matches with the length of the (shortest) string to get the percent of equality
var str1 = "Hello blue world"
var str2 = "Hello blut world?!"
var shortest = str2.length >= str1.length?str1:str2
var longest = str2.length < str1.length?str1:str2
var matches= 0
shortest
.split("")
//Just check if index of shortest
//Matches index of longest, and if so (&& means do next
//Expression) add the total number of matches by one
.forEach (
(x,k)=>
((x==longest[k]) && (matches++) )
)
//Final result, divide matches by total length
var similarity = matches / shortest.length
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'am newbie in Python and i'am having a hard time trying to translate this Javascript arrow function into Python. I'am not able to make the part where i use substring in JS to get the next 3 values in my loop when i find '\x1D'. Any tips or suggestions ?
module.exports = edi => {
let decompressedEdi = ''
let lastCompressor = 0
for (let i = 0; i <= edi.length; i++) {
if (edi[i] === '\x1D') {
let decimal = parseInt(edi.substring(i + 1, i + 3), 16)
let repeater = edi[i + 3]
decompressedEdi +=
edi.substring(lastCompressor, i) + repeater.repeat(decimal)
lastCompressor = i + 4
}
}
decompressedEdi += edi.substring(lastCompressor, edi.length)
return decompressedEdi.replace(/(\r\n|\n|\r)/gm, '')
}
In python, strings can be sliced like arrays :
for i, c in enumerate(edi):
if c == '\x1D':
decimal = int(edi[i+1:i+3], 16)
The int function has the following signature: int(str, base)
from re import sub
def decompress(edi):
decompressed = ""
last_compressor = 0
for i, c in enumerate(edi):
if c == "\x1D":
repetitions = int(edi[i + 1: i + 3], 16)
repeating_char = edi[i + 3]
decompressed += edi[last_compressor:i] + repeating_char * repetitions
last_compressor = i + 4
decompressed += edi[last_compressor:-1]
return sub("\r\n|\n|\r", decompressed)
How I read the code
Feel free to ignore this bit, but it might help.
Given edi which has a len, for each edi that matches \x1D, get the substring of edi from the index + 1 to index + 3 as a hexadecimal integer as set as decimal. The repeater is the index + 3'th element of edi for each element and it is expected to be a str. It will be repeated the hexadecimal number of times defined in decimal, but only after the substring of edi from lastCompressor to the current index. On each iteration where \x1D is matched, the lastCompressor is increased by 4.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to add spaces to my input value while the user typing, it works for the constant digits like after 4 letters or after 5 letters. But I couldn't manage to add space after certain digits dynamically.
for example
if user types 1234567890
blocks: [3,3,4]
expected output: 123 456 7890
if user types 1234567890
blocks: [3,2,2,3]
expected output is: 123 45 67 890
Handling inputs as the user types can be tricky.
Although not perfect, one solution is to calculate what the expected result should be, and then compare with what it currently is. If they are different then update the actual input with the calculated one.
Below is a simple example,.. It will even handle were the user pastes in the numbers.
One issue with the below is the cursor position if say you inserted the number mid way, but this could be maybe handled with remembering the cursor position and restoring.
const splits = [3,3,4];
$('#a').on("input", function(){
let count = 0;
const breaks = splits.map(m => { const ret = m + count; count += m; return ret; });
const a = this.value.split("").filter(f => f !== ' ');
const s = a.map((m, ix) => {
if (breaks.includes(ix + 1)) return m + " "
else return m;
}).join("");
if (this.value.trim() !== s.trim()) this.value = s;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="a"/>
Try the below code
function splitValue(value, index) {
return value.substring(0, index) + " " + value.substring(index);
}
var test=[3,3,4];
var secondVar = '';
var firstVar = '1234567890';
for(let i = 0; i < test.length; i++){
var TestVar = splitValue(firstVar, test[i]);
secondVar = secondVar + " " + TestVar.split(" ")[0];
secondVar=secondVar.trim();
if(i == 0)
firstVar = firstVar.replace(secondVar.trim(),'');
else
firstVar = firstVar.replace(secondVar.split(' ')[i + 1],'');
}
console.log(secondVar);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm having a php json_encode object fetched by ajax. whet I want to do is to sum this array. Here's what I did so far:
var json = $.parseJSON(data);
var tot = new Array();
for (var i = 0; i < json.length; ++i) {
tot.push(json[i].final_total);
$('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
Now I want to sum this array. I tried this:
var sum = tot.reduce(function(pv, cv) { return pv + cv; }, 0);
$("#total").html( sum );
But the result is:
09.748.529.129.129.119.59.79.89.79.89.79.79.79.79.79.79719.248.59.79 ......
I also tried:
myFunction(tot);
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("total").innerHTML = item.reduce(getSum);
}
But I got the same result above (Numbers written next to each other).
I also tried this:
var tot = 0;
for (var i = 0; i < json.length; ++i) {
tot += json[i].final_total);
$('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
$("#total").html( tot );
But I got the same result above (Numbers written next to each other).
So what is the proper way to sum an array in javascript?
You have to use parseInt (if the numbers are Integers), parseFloat (if they are Floats) or Number (if not sure) to explicitly interpret them as numbers like:
sum = tot.reduce((a, n) => (a + Number(n)), 0);
Array elements are strings, in order to properly add them, they have to be casted to integer:
var sum = tot.reduce(function(a, b) {
return parseFloat(a) + parseFloat(b);
}, 0);
Taken from MDN:
the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
The is a common issue caused by + operator used for both string concatenation and addition. Issue is best described with following example:
var result = '1' + 3 + 3 + 7 //result is '1337'
Edit: #Pointy - Nice catch, thanks! :)
you will need to use a parse int because its concatenating the sting instead of adding integers
var sum = tot.reduce(function(pv, cv) { return parseInt(pv) + parseInt(cv); }, 0);
parseInt
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can somebody please explain how this code gets which number from array is the biggest?
var num = [];
for( var i = 0; i < 10; i++ ) {
num[i] = parseInt( prompt("Unesite broj " + (i+1) + "." ) );
}
var biggest = 0;
for(i=0; i < num.length; i++ ) {
if( num[i] > biggest ) {
biggest = num[i];
}
}
console.log("The biggest number is " + biggest );
To start, we've seen no numbers, and the code assumest the biggest is 0 or larger:
var biggest = 0;
We'll look at each number in the list:
for(i=0; i < num.length; i++ ) {
Is the current number bigger than the biggest we've seen?
if( num[i] > biggest ) {
If so, it's the new biggest number
biggest = num[i];
}
}
When the loop is done, biggest contains the largest number we saw along the way.
First for loop just prompts you to add numbers to an array.
The second loop just checks each number in the num array, if that number is bigger than the number in the biggest variable then it sets the biggest variable to that number.
It's as simple as that.
The if statement within the loop checks whether the number in the current element of the array is greater than the largest number found so far. If the current number is the greatest, the largest number found so far is updated to this new number.