How to get String output as in single quote in javascript - javascript

Advance thanks, Question looks like simple but i could not able to find the solution.
function sumStrings(a, b)
{
return +a + +b;
}
sumStrings('1','2') //=>3
Expected output
sumStrings('1','2') // => '3'

After addition, add ' to beginning and end.
function sumStrings(a, b){
return "'" + (Number(a) + Number(b)) + "'";
}
console.log(sumStrings('1','2'));

function sumStrings(a, b) {
// Separate decimal part here
var pointa = a.indexOf(".");
var pointb = b.indexOf(".");
var deca = pointa != -1 ? a.substring(pointa + 1) : "0";
var decb = pointb != -1 ? b.substring(pointb + 1) : "0";
if (deca.length < decb.length)
deca += (Math.pow(10, decb.length - deca.length)).toString().substring(1);
else
decb += (Math.pow(10, deca.length - decb.length)).toString().substring(1);
var inta = pointa != -1 ? a.substring(0, pointa) : a;
var intb = pointb != -1 ? b.substring(0, pointb) : b;
// console.log(deca + " " + decb);
var decc = addBigInt(deca, decb);
var intc = addBigInt(inta, intb);
if (decc.length > deca.length) {
intc = addBigInt(intc, "1");
decc = decc.substring(1);
}
var lastZero = decc.length - 1;
while (lastZero >= 0 && decc[lastZero] == "0") {
lastZero--;
}
if (lastZero >= 0)
return intc + "." + decc.substring(0, lastZero + 1);
else
return intc;
}
function addBigInt(a, b) {
var inda = a.length - 1;
var indb = b.length - 1;
var c = [];
const zero = "0".charCodeAt(0);
var carry = 0;
var sum = 0;
while (inda >= 0 && indb >= 0) {
var d1 = a.charCodeAt(inda--) - zero;
var d2 = b.charCodeAt(indb--) - zero;
sum = (d1 + d2 + carry);
carry = Math.floor(sum / 10);
sum %= 10;
c.unshift(sum);
}
if (inda >= 0) {
while (carry && inda >= 0) {
sum = a.charCodeAt(inda--) - zero + carry;
c.unshift(sum % 10);
carry = Math.floor(sum / 10);
}
c.unshift(a.substring(0, inda + !carry));
} else {
while (carry && indb >= 0) {
sum = b.charCodeAt(indb--) - zero + carry;
c.unshift(sum % 10);
carry = Math.floor(sum / 10);
}
c.unshift(b.substring(0, indb + !carry));
}
if (carry)
c.unshift(carry);
return c.join("");
}
console.log(sumStrings("1","2"));
console.log(sumStrings("800","9567"));
console.log(sumStrings("99.1","1"));
console.log(sumStrings("00103","08567"));
console.log(sumStrings("50095301248058391139327916261.5","81055900096023504197206408605"));

If you want to escape the single quote, you can try to add a backslash before the single quote.
i.e.
var x = '\'5\'';

With the new template literal you can try this:
a=`'5'`;
console.log(a);

Related

using Damerau-Levenshtein distance to compare sets of text in code.org

Not very knowledgeable with coding, I usually use block coding and not typing.
I've used many different Levenshtein distance codes I've found online and most of them didn't work for one reason or another
var levDist = function (s, t) {
var d = []; //2d matrix
// Step 1
var n = s.length;
var m = t.length;
if (n == 0) return m;
if (m == 0) return n;
//Create an array of arrays in javascript (a descending loop is quicker)
for (var i = n; i >= 0; i--) d[i] = [];
// Step 2
for (i = n; i >= 0; i--) d[i][0] = i;
for (var j = m; j >= 0; j--) d[0][j] = j;
// Step 3
for (i = 1; i <= n; i++) {
var s_i = s.charAt(i - 1);
// Step 4
for (j = 1; j <= m; j++) {
//Check the jagged ld total so far
if (i == j && d[i][j] > 4) return n;
var t_j = t.charAt(j - 1);
var cost = (s_i == t_j) ? 0 : 1; // Step 5
//Calculate the minimum
var mi = d[i - 1][j] + 1;
var b = d[i][j - 1] + 1;
var c = d[i - 1][j - 1] + cost;
if (b < mi) mi = b;
if (c < mi) mi = c;
d[i][j] = mi; // Step 6
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
};
This is all the code I’ve written (including the most recent attempt of getting the levenshtein distance)
var levDist = function (s, t) {
var d = []; //2d matrix
// Step 1
var n = s.length;
var m = t.length;
if (n == 0) return m;
if (m == 0) return n;
//Create an array of arrays in javascript (a descending loop is quicker)
for (var i = n; i >= 0; i--) d[i] = [];
// Step 2
for (i = n; i >= 0; i--) d[i][0] = i;
for (var j = m; j >= 0; j--) d[0][j] = j;
// Step 3
for (i = 1; i <= n; i++) {
var s_i = s.charAt(i - 1);
// Step 4
for (j = 1; j <= m; j++) {
//Check the jagged ld total so far
if (i == j && d[i][j] > 4) return n;
var t_j = t.charAt(j - 1);
var cost = (s_i == t_j) ? 0 : 1; // Step 5
//Calculate the minimum
var mi = d[i - 1][j] + 1;
var b = d[i][j - 1] + 1;
var c = d[i - 1][j - 1] + cost;
if (b < mi) mi = b;
if (c < mi) mi = c;
d[i][j] = mi; // Step 6
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
};
var S = "Hello World";
var grossWPM;
var Transparency = 1;
var Timer = 60;
var InitialTime = Timer;
var Texts = getColumn("Texts", "Texts");
var TextLength = getColumn("Texts", "Number of Characters");
var Title = getColumn("Texts", "Titles");
var Author = getColumn("Texts", "Authors");
var TextSelector = randomNumber(0, 19);
console.log("Article #" + (TextSelector + 1));
console.log(TextLength[TextSelector] + " Characters in total");
console.log(Title[TextSelector]);
console.log("By: " + Author[TextSelector]);
var Countdown;
var Countdown = 6;
//Texts are obtained from
//https://data.typeracer.com/pit/texts
onEvent("button1", "click", function( ) {
timedLoop(1000, function() {
Countdown = Countdown - 1;
setText("button1", Countdown - 0);
timedLoop(100, function() {
setText("text_area2", "");
});
if (Countdown <= 1) {
stopTimedLoop();
setTimeout(function() {
setText("button1", "GO!");
setText("text_area1", Texts[TextSelector]);
if (getText("button1") == "GO!") {
var TransparentLoop = timedLoop(100, function() {
Transparency = Transparency - 0.1;
setProperty("Warning", "text-color", rgb(77,87,95, Transparency));
if (Transparency <= 0) {
deleteElement("Warning");
showElement("label2");
stopTimedLoop(TransparentLoop);
}
});
var TimerLoop = timedLoop(1000, function() {
Timer = Timer - 1;
setText("label2", Timer);
if (Timer <= 0) {
grossWPM = (TextLength[TextSelector] / 5) / ((InitialTime - Timer) / 60);
console.log(grossWPM);
setScreen("screen2");
if (Timer == 1) {
S = " second";
} else {
S = " seconds";
}
setText("label1", "Your typing speed was approximately " + (Math.round(grossWPM) + (" WPM* with " + (Timer + (S + " left")))));
stopTimedLoop(TimerLoop);
}
});
console.log("Timer Started");
timedLoop(10, function() {
var str = getText("text_area2");
if (str.length == TextLength[TextSelector]) {
stopTimedLoop(TimerLoop);
grossWPM = (TextLength[TextSelector] / 5) / ((InitialTime - Timer) / 60);
setScreen("screen2");
levDist(str, Texts[TextSelector]);
if (Timer == 1) {
S = " second";
} else {
S = " seconds";
}
setText("label1", "Your typing speed was approximately " + (Math.round(grossWPM) + (" WPM* with " + (Timer + (S + " left")))));
if (grossWPM == 69) {
setText("label4", "Nice");
}
stopTimedLoop();
}
});
}
}, 1000);
}
});
});
Obviously not that good at this so can anyone help?
I want to compare two sets of text
Something the user types in.
Paragraph that the user was supposed to type.
This is for a WPM test and I want a way to get a measurement for WPM that includes errors the user makes while typing.
If there is a way to check this besides the Levenshtein distance please tell me, I just looked up a way to do that and Levenshtein distance seemed like the way to do so
The error given by code.org says:
ERROR: Line: 50: TypeError: d[n] is undefined
I fixed the issue, I used this code
function levenshtein(s1, s2) {
if (s1 == s2) {
return 0;
}
var s1_len = s1.length;
var s2_len = s2.length;
if (s1_len === 0) {
return s2_len;
}
if (s2_len === 0) {
return s1_len;
}
// BEGIN STATIC
var split = false;
try {
split = !('0')[0];
} catch (e) {
// Earlier IE may not support access by string index
split = true;
}
// END STATIC
if (split) {
s1 = s1.split('');
s2 = s2.split('');
}
var v0 = new Array(s1_len + 1);
var v1 = new Array(s1_len + 1);
var s1_idx = 0,
s2_idx = 0,
cost = 0;
for (s1_idx = 0; s1_idx < s1_len + 1; s1_idx++) {
v0[s1_idx] = s1_idx;
}
var char_s1 = '',
char_s2 = '';
for (s2_idx = 1; s2_idx <= s2_len; s2_idx++) {
v1[0] = s2_idx;
char_s2 = s2[s2_idx - 1];
for (s1_idx = 0; s1_idx < s1_len; s1_idx++) {
char_s1 = s1[s1_idx];
cost = (char_s1 == char_s2) ? 0 : 1;
var m_min = v0[s1_idx + 1] + 1;
var b = v1[s1_idx] + 1;
var c = v0[s1_idx] + cost;
if (b < m_min) {
m_min = b;
}
if (c < m_min) {
m_min = c;
}
v1[s1_idx + 1] = m_min;
}
var v_tmp = v0;
v0 = v1;
v1 = v_tmp;
}
return v0[s1_len];
}
and I got that code from this question
This is levenshtein distance NOT damerau-levenshtein distance

if a positive number is equal to its reverse

I'm making a program to receive a positive number and output "yes" if it's equal to its reverse;
otherwise, output "no".
What I've done so far:
HTML
<div class="column1">
<div class="input">
<button onclick="problem()"> Run the program </button>
</div>
<strong><p id="output"> </p></strong>
</div>
JS
function problem() {
var outputObj = document.getElementById("output");
var a = parseInt(prompt("Please enter a number: ", ""));
outputObj.innerHTML = "number: " + a + "<br><br>";
var reverse = 0;
while (a > 0){
num = a % 10; // the last digit
reverse = (reverse *10) + num; // calculating the reverse
a = Math.floor(a / 10); // go to next digit
}
if ( reverse == a){
outputObj.innerHTML = "yes";
}
else {
outputObj.innerHTML = "no";
}
outputObj.innerHTML = outputObj.innerHTML + "<br><br>" + "program ended";
document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}
function isPalindrome(number){
return +number.toString().split("").reverse().join("") === number
}
Art for art
function palindrom(x)
{
let len = Math.floor(Math.log(x)/Math.log(10) +1);
while(len > 0) {
let last = Math.abs(x - Math.floor(x/10)*10);
let first = Math.floor(x / Math.pow(10, len -1));
if(first != last){
return false;
}
x -= Math.pow(10, len-1) * first ;
x = Math.floor(x/10);
len -= 2;
}
return true;
}
You should search for plaindromic numbers. For example the following code:
const isPalindrome = x => {
if (x < 0) return false
let reversed = 0, y = x
while (y > 0) {
const lastDigit = y % 10
reversed = (reversed * 10) + lastDigit
y = (y / 10) | 0
}
return x === reversed
}
const isPalindrome = num => {
const len = Math.floor(Math.log10(num));
let sum = 0;
for(let k = 0; k <= len; k++) {
sum += (Math.floor(num / 10 ** k) % 10) * 10 ** (len - k);
}
return sum === num;
}
console.log(isPalindrome(12321));

Unique in generated random number (no duplicate)

I want only the generated random number will hava no duplicate, whenever i try to put the number, the generated random number has duplicate, any other idea. what should i change here?
See the fiddle
var arr = hello.toString(10).replace(/\D/g, '0').split('').map(Number);
for(i=0;i<arr.length;i++) arr[i] = +arr[i]|0;
//initialize variables
var z = arr[3];
var y = arr[2];
var x = arr[1];
var w = arr[0];
while((((a2 <= 0) || (a2 > 49)) || ((b <= 0) || (b > 49)) || ((c <= 0) || (c > 49)) || ((d <= 0) || (d > 49)) || ((e2 <= 0) || (e2 > 49)) || ((f <= 0) || (f > 49)) || ((g <= 0) || (g > 49) ))){
//loop ulit kapag hindi match yung random number sa value nung z
while( zRandomString != z){
zRandom = Math.floor(Math.random() * (109 - 100 + 1)) + 100;
zRandomRound = zRandom % 10;
zRandomString = zRandomRound.toString();
}
var zNew = zRandom; //new value ng z
document.getElementById("zebra").innerHTML = "Z = " + zNew + "<br />";// udsadsadsad
h = zNew;
while( yRandomString != y){
yRandom = Math.floor(Math.random() * (49 - 1 + 1)) + 1;
yRandomRound = yRandom % 10;
yRandomString = yRandomRound.toString();
}
var yNew = yRandom; //new value ng z
document.getElementById("yeah").innerHTML = "Y = " + yNew + "<br />";// udsadsadsad
h = h - yNew;
while( xRandomString != x){
xRandom = Math.floor(Math.random() * (h - 1 + 1)) + 1;
xRandomRound = xRandom % 10;
xRandomString = xRandomRound.toString();
}
var xNew = xRandom; //new value ng z
document.getElementById("ex").innerHTML = "X = " + xNew + "<br />";// udsadsadsad
h = h - xNew;
while( wRandomString != w){
wRandom = Math.floor(Math.random() * (h - 1 + 1)) + 1;
wRandomRound = wRandom % 10;
wRandomString = wRandomRound.toString();
}
var wNew = wRandom; //new value ng z
document.getElementById("weh").innerHTML = "W = " + wNew + "<br />";// udsadsadsad
//h = Math.abs(h - wNew); // new value of h
h = h - wNew;
a = Math.floor(Math.random() * (wNew - 1 + 1)) + 1;
a2 = wNew - a;
b = Math.floor(Math.random() * (a2 - 1 + 1)) + 1;
c = a - b;
d = yNew;
e = Math.floor(Math.random() * (xNew - 1 + 1)) + 1;
e2 = xNew - e;
f = Math.floor(Math.random() * (e2 - 1 + 1)) + 1;
g = e - f;
}
var combo = a2.toString() + ', ' + b.toString() + ', ' + c.toString() + ', ' + d.toString() + ', ' + e2.toString() + ', ' + f.toString() + ', ' + g.toString() + ', ' + h.toString();
document.getElementById("combo").innerHTML = combo;
Try to use this scheme:
var r;
do {
r = Math.floor(Math.random() * 10);
} while (r == 6);
It is not quite clear what you want, but one way to create a sequence on unique random numbers is to create a pool of numbers and sucessively pick and remove items from it:
function pick(pool) {
if (pool.length == 0) return undefined;
// pick an element from the pool
var k = (Math.random() * pool.length) | 0;
var res = pool[k];
// adjust array
pool[k] = pool[pool.length - 1];
pool.pop();
return res;
}
// example
var pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
while (pool.length) {
console.log(pick(pool));
}
Another method is to shoffle the pool first and then pop off elements:
function shuffle(arr) {
var n = arr.length;
while (n) {
// pick element
var k = (Math.random() * n--) | 0;
// swap last and picked elements
var swap = arr[k];
arr[k] = arr[n];
arr[n] = swap;
}
}
var pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
shuffle(pool);
while (pool.length) {
console.log(pool.pop());
}
These two methods aren't very different if you look at the pick and shuffle functions. Of course, eventually you will exhaust the pool. You can then decide to recreate or reshuffle the array. Also note that these methods will produce repeated elements if the pool has repeated entries.

Javascript autoincrement index

I need to create a function or use if is possible an already made library to auto increment an index. For example if it starts with 'A' it has to be incremented to 'Z' and after 'Z' it has to start from 'A1' and as soon as . . .'B1','C1', ... 'Z1', 'A2','B2',... . Does exist something like this already made ?
My idea is this, but start from 'A' and don't add number . . .
function nextChar(cont,letter) {
if (cont === 0){return letter;}
else {
letter=letter.charCodeAt(0) + 1;
return String.fromCharCode(letter);
}
}
One of many options:
function nextIndex(idx) {
var m = idx.match(/^([A-Z])(\d*)$/)
if(!m)
return 'A';
if(m[1] == 'Z')
return 'A' + (Number(m[2] || 0) + 1);
return String.fromCharCode(m[1].charCodeAt(0) + 1) + m[2];
}
var a = "";
for(i = 0; i < 100; i++) {
a = nextIndex(a)
document.write(a + ", ")
}
This one's less efficient than georg's but maybe easier to understand at first glance:
for (var count = 0, countlen = 5; count < countlen; count++) {
for (var i = 65, l = i + 26; i < l; i++) {
console.log(String.fromCharCode(i) + (count !== 0 ? count : ''));
}
}
DEMO
Allow me to propose a solution more object-oriented:
function Index(start_with) {
this.reset = function(reset_to) {
reset_to = reset_to || 'A';
this.i = reset_to.length > 1 ? reset_to[1] : 0; // needs more input checking
this.c = reset_to[0].toUpperCase(); // needs more input checking
return this;
};
this.inc = function(steps) {
steps = steps || 1;
while(steps--) {
if (this.c === 'Z') {
this.i++;
this.c = 'A';
} else {
this.c = String.fromCharCode(this.c.charCodeAt(0) + 1);
}
}
return this;
};
this.toString = function() {
if (this.i === 0) return this.c;
return this.c + '' + this.i;
};
this.reset(start_with);
}
var a = new Index(); // A
console.log('a = ' + a.inc(24).inc().inc()); // Y, Z, A1
var b = new Index('B8'); // B8
console.log('a = ' + a.reset('Y').inc()); // Y, Z
console.log('b = ' + b); // B8
Another way to think about this is that your "A1" index is just the custom rendering of an integer: 0='A',1='B',26='A1',etc.
So you can also overload the Number object to render your index. The big bonus is that all the math operations still work since your are always dealing with numbers:
Number.prototype.asIndex = function() {
var n = this;
var i = Math.floor(n / 26);
var c = String.fromCharCode('A'.charCodeAt(0) + n % 26);
return '' + c + (i ? i : '');
}
Number.parseIndex = function(index) {
var m;
if (!index) return 0;
m = index.toUpperCase().match(/^([A-Z])(\d*)$/);
if (!m || !m[1]) return 0;
return Number((m[1].charCodeAt(0) - 'A'.charCodeAt(0)) + 26 * (m[2] ? m[2] : 0));
};
var c = 52;
var ic = c.asIndex();
var nc = Number.parseIndex(ic);
console.log(c+' = '+ic+' = '+nc); // 52 = A2 = 52
If you go this way I would try to check if the new methods don't already exist first...

Converting/expressing double number in non-exponent/short form in Javascript

I have a double in Javascript whose value is, for example, 1.0883076389305e-311.
I want to express it in the following form, using as example the 'bc' utility to calculate the expanded/higher precision/scale form:
$ bc
scale=400
1.0883076389305000*10^-311
.0000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000010883076389305000000000000000\
0000000000000000000000000000000000000000000000000000000000000
I need a Javascript bigint library or code to produce the same output as a string with the expanded/higher precision form of the number.
Thanks!
This is horrible, but works with every test case I can think of:
Number.prototype.toFullFixed = function() {
var s = Math.abs(this).toExponential();
var a = s.split('e');
var f = a[0].replace('.', '');
var d = f.length;
var e = parseInt(a[1], 10);
var n = Math.abs(e);
if (e >= 0) {
n = n - d + 1;
}
var z = '';
for (var i = 0; i < n; ++i) {
z += '0';
}
if (e <= 0) {
f = z + f;
f = f.substring(0, 1) + '.' + f.substring(1);
} else {
f = f + z;
if (n < 0) {
f = f.substring(0, e + 1) + '.' + f.substring(e + 1);
}
}
if (this < 0) {
f = '-' + f;
}
return f;
};
If you find a number that doesn't parse back correctly, i.e. n !== parseFloat(n.toFullFixed()), please let me know what it is!
// So long as you are dealing with strings of digits and not numbers you can
use string methods to convert exponential magnitude and precision to zeroes
function longPrecision(n, p){
if(typeof n== 'string'){
n= n.replace('*10', '').replace('^', 'e');
}
p= p || 0;
var data= String(n), mag, str, sign, z= '';
if(!/[eE]/.test(data)){
return data;
if(data.indexOf('.')== -1 && data.length<p) data+= '.0';
while(data.length<p) data+= '0';
return data;
}
data= data.split(/[eE]/);
str= data[0];
sign= str.charAt(0)== "-"? "-": "";
str= str.replace(/(^[+-])|\./, "");
mag= Number(data[1])+ 1;
if(mag < 0){
z= sign + "0.";
while(mag++) z += "0";
str= z+str;
while(str.length<p) str+= '0';
return str;
}
mag -= str.length;
str= sign+str;
while(mag--) z += "0";
str += z;
if(str.indexOf('.')== -1 && str.length<p) str+= '.0';
while(str.length<p) str+= '0';
return str;
}
var n='1.0883076389305000*10^-311';
longPrecision(n, 400);
/* returned value: (String)
0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001088307638930500000000000000000000000000000000000000000000000000000000000000000000000000
*/

Categories

Resources