Processing of string - javascript

I have following input for instance as a string:
(-4-1+255*4)^4
I also have some functions:
modulo(a, mod) => counts basic modulo
divideModulo (a, b, n) => divide operation for modulo
exponenatation(base, exp, mod) => exp operation for modulo etc.
I need to transform this string to:
exponenation(modulo(modulo(-4, mod) - modulo(-1, mod) + modulo(255, mod) * modulo(4, mod), mod), 2, mod)
Also string can contain / and square root and priority of signs must be preserved.
Right now, I am trying to do something like this:
var counter = 0;
var res = getNumbers(string); // return only numbers from string
var x = retezec.match(/\d+|\D/g); ( // returns array with numbers and string divided. Problem is // that "- digit" at the beginning is not added right now
for(var i = 0; i < x.length; i++){
if(!isNaN(x[i])){
x[i] = " modulo(" + res[counter] + ", " + mod + ") ";
counter++;
}
}
But it does not work as I need.
Thanks for help

Related

What is the minimum number of push operation in reversing A B C D in stack?

I Have coded to reverse the ABCD string with using push and pop operation in Javascript
var count = 0;
function reverse(str) {
let stack = [];
// push letter into stack
for (let i = 0; i < str.length; i++) {
stack.push(str[i]);
count++
}
// pop letter from the stack
let reverseStr = '';
while (stack.length > 0) {
reverseStr += stack.pop();
}
return reverseStr;
}
console.log(reverse("ABCD") + count);
What is the minimum number of push operation in reversing ABCD?
The maximum number should be either 3 or 4 depending on how you do it. Firstly, you should be using unshift() rather than push() as you really only need to push a character into the front of the array. So:
let count;
function reverse(str) {
count = 0;
let stack = [];
// push letter into stack
for (let i = 0; i < str.length; i++) {
stack.unshift(str[i]);
count++
}
return stack.join("");
}
let stringA = "ABCD";
console.log(stringA + " => " + reverse(stringA) + ": " + count);
However, as others have suggested, you could just move letters, going backwards from the one before the final character, and shifting them to the end:
let count;
function reverse2(str) {
count = 0;
let str2 = str.split("");
let sLength = str2.length;
for (let i = (sLength - 2); i >= 0; i--) {
let s = str2.splice(i, 1).toString();
str2.push(s);
count++
}
return str2.join("");
}
let stringB = "ABCD";
console.log(stringB + " => " + reverse2(stringB) + ": " + count);
In both cases, you could check for matching consecutive characters - eg, in good, you have two o's. But that would complicate things as you would be continually checking for this.
you don't even need the push operations if you are using JS str.split('').reverse().join('') and by the way it only takes 3 push operations.
Minimum number of Push Operation is equal to length of string as stack follows Last In First Out Order.

Converting from infix to prefix notation in JavaScript

Please help me in JavaScript: The program that I am coding is one that takes in an expression in prefix notation and outputs the same expression in infix notation. The idea behind this program is as follows:
if the user enters 1 + 2 the expected output is + 1 2. All valid symbols are +, -, *, /, and %. The amount of numbers that the user can enter should be limitless (so for example, if I enter 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, the program should return + 1 2 3 4 5 6 7 8 9 10).
Could someone please help me fill in the comment out portion of the loop, and if you think there's a better approach to the problem entirely, I am open to that!
function infix(input) {
var x = input.split(''); // splits each variable and stores it in an array
var output = [];
var final = " "; // will be used to store our infix expression
for (var i = 0; i < x.length; i++) {
//if x[i] is any of the following : "+, -, *, /, or %" , store it in array output at index 0
//else if x[i] is a number : store it in an index of array output that is >= 1
}
for (var j = 0; j < output.length; j++) {
var final = x[0] + x[j];
}
console.log(final);
}
infix("1 + 2 + 3")
Here's a snippet:
function infix(input){
const specialCharacters = ['+', '-', '*', '/', '%'];
const allCharacters = input.split('');
const prefixes = [];
const numbers = [];
// go through all chars of input
for (let i = 0; i < allCharacters.length; i++) {
const thisCharacter = allCharacters[i];
// If the char is contained within the list of 'special chars', add it to list of prefixes.
if (specialCharacters.includes(thisCharacter))
prefixes.push(thisCharacter);
// In case this is a whit space, just do nothing and skip to next iteration
else if (thisCharacter === ' ')
continue;
// If it's a number, just add it to the array of numbers
else
numbers.push(thisCharacter);
}
// Merge both arrays
const final = [...prefixes, ...numbers];
// Back to string
const finalString = final.join(' ');
console.log(final);
console.log('String format: ' + finalString);
}
infix('1 + 2 - 3');
Notice:
I replaced var by the new ES6 specification, const and let. (Use const always, use let if you have to re-write)
I am not sure if you want to keep all the symbols if you have them, so I made an array. If you want only one symbol, instead of keeping an array, just keep a single variable
Add an extra case for white spaces

JS - summing elements of arrays

I'm trying to make operations with numbers that are stored in arrays, unfortunately they seem to be considered as "text" rather than numbers, so when I do like array1[i] + array2[i], instead of doing 2+3=5 I would get 2+3=23 ...
The values of these arrays come from fields (html)
No idea how to deal with that ;D
Thanks for your help
If you wanna look at my code, here's what it looks like :
var polynome = [];
for (var i=0; i<=degree; ++i) {
polynome[i] = document.getElementById(i).value;
}
var a = document.getElementById("a").value;
var tempArray = [];
var quotient = [];
quotient[degree+1] = 0;
for (var i=degree; i>=0; --i) {
tempArray[i] = a * quotient[i+1];
quotient[i] = polynome[i] + tempArray[i];
}
document.getElementById("result").innerHTML = polynome + "<br>" + tempArray + "<br>" + quotient;
array1[i] contains string and not int so when you are trying both elements with + operator it is concatenating both the values rather of adding them
you need to cast both elements in arrays to integer
try this
parseInt( array1[i] ) + parseInt( array2[i] )
The + punctuator is overloaded an can mean addition, concatenation and conversion to number. To ensure it's interpreted as addition, the operands must be numbers. There are a number of methods to convert strings to numbers, so given:
var a = '2';
var b = '3';
the unary + operator will convert integers and floats, but it's a bit obscure:
+a + +b
parseInt will convert to integers:
parseInt(a, 10) + parseInt(b, 10);
parseFloat will convert integers and floats:
parseFloat(a) + parseFloat(b);
The Number constructor called as a function will convert integers and floats and is semantic:
Number(a) + Number(b);
Finally there is the unary - operator, but it's rarely used since subtraction (like multiplication and division) converts the operands to numbers anyway and it reverses the sign, so to add do:
a - -b

How to add a space in a specific index of a string? [duplicate]

How can I insert a string at a specific index of another string?
var txt1 = "foo baz"
Suppose I want to insert "bar " after the "foo" how can I achieve that?
I thought of substring(), but there must be a simpler more straight forward way.
Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:
var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
You could prototype your own splice() into String.
Polyfill
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* #this {String}
* #param {number} start Index at which to start changing the string.
* #param {number} delCount An integer indicating the number of old chars to remove.
* #param {string} newSubStr The String that is spliced in.
* #return {string} A new string with the spliced substring.
*/
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
Example
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
var result = "foo baz".splice(4, 0, "bar ");
document.body.innerHTML = result; // "foo bar baz"
EDIT: Modified it to ensure that rem is an absolute value.
Here is a method I wrote that behaves like all other programming languages:
String.prototype.insert = function(index, string) {
if (index > 0)
{
return this.substring(0, index) + string + this.substring(index, this.length);
}
return string + this;
};
//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)
Reference:
http://coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/
Just make the following function:
function insert(str, index, value) {
return str.substr(0, index) + value + str.substr(index);
}
and then use it like that:
alert(insert("foo baz", 4, "bar "));
Output: foo bar baz
It behaves exactly, like the C# (Sharp) String.Insert(int startIndex, string value).
NOTE: This insert function inserts the string value (third parameter) before the specified integer index (second parameter) in the string str (first parameter), and then returns the new string without changing str!
UPDATE 2016: Here is another just-for-fun (but more serious!) prototype function based on one-liner RegExp approach (with prepend support on undefined or negative index):
/**
* Insert `what` to string at position `index`.
*/
String.prototype.insert = function(what, index) {
return index > 0
? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
: what + this;
};
console.log( 'foo baz'.insert('bar ', 4) ); // "foo bar baz"
console.log( 'foo baz'.insert('bar ') ); // "bar foo baz"
Previous (back to 2012) just-for-fun solution:
var index = 4,
what = 'bar ';
'foo baz'.replace(/./g, function(v, i) {
return i === index - 1 ? v + what : v;
}); // "foo bar baz"
This is basically doing what #Base33 is doing except I'm also giving the option of using a negative index to count from the end. Kind of like the substr method allows.
// use a negative index to insert relative to the end of the string.
String.prototype.insert = function (index, string) {
var ind = index < 0 ? this.length + index : index;
return this.substring(0, ind) + string + this.substr(ind);
};
Example:
Let's say you have full size images using a naming convention but can't update the data to also provide thumbnail urls.
var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');
// result: '/images/myimage_thm.jpg'
If anyone is looking for a way to insert text at multiple indices in a string, try this out:
String.prototype.insertTextAtIndices = function(text) {
return this.replace(/./g, function(character, index) {
return text[index] ? text[index] + character : character;
});
};
For example, you can use this to insert <span> tags at certain offsets in a string:
var text = {
6: "<span>",
11: "</span>"
};
"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
Instantiate an array from the string
Use Array#splice
Stringify again using Array#join
The benefits of this approach are two-fold:
Simple
Unicode code point compliant
const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))
Given your current example you could achieve the result by either
var txt2 = txt1.split(' ').join(' bar ')
or
var txt2 = txt1.replace(' ', ' bar ');
but given that you can make such assumptions, you might as well skip directly to Gullen's example.
In a situation where you really can't make any assumptions other than character index-based, then I really would go for a substring solution.
my_string = "hello world";
my_insert = " dear";
my_insert_location = 5;
my_string = my_string.split('');
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');
https://jsfiddle.net/gaby_de_wilde/wz69nw9k/
I know this is an old thread, however, here is a really effective approach.
var tn = document.createTextNode("I am just to help")
t.insertData(10, "trying");
What's great about this is that it coerces the node content. So if this node were already on the DOM, you wouldn't need to use any query selectors or update the innerText. The changes would reflect due to its binding.
Were you to need a string, simply access the node's text content property.
tn.textContent
#=> "I am just trying to help"
You can do it easily with regexp in one line of code
const str = 'Hello RegExp!';
const index = 6;
const insert = 'Lovely ';
//'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
const res = str.replace(new RegExp(`^(.{${index}})(.)`), `$1${insert}$2`);
console.log(res);
"Hello Lovely RegExp!"
Well, we can use both the substring and slice method.
String.prototype.customSplice = function (index, absIndex, string) {
return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};
String.prototype.replaceString = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substr(index);
return string + this;
};
console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers
The only problem of a substring method is that it won't work with a negative index. It's always take string index from 0th position.
You can use Regular Expressions with a dynamic pattern.
var text = "something";
var output = " ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);
outputs:
"something "
This replaces text.length of whitespace characters at the beginning of the string output.
The RegExp means ^\ - beginning of a line \s any white space character, repeated {n} times, in this case text.length. Use \\ to \ escape backslashes when building this kind of patterns out of strings.
another solution, cut the string in 2 and put a string in between.
var str = jQuery('#selector').text();
var strlength = str.length;
strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);
jQuery('#selector').html(strf + 'inserted' + strb);
Using slice
You can use slice(0,index) + str + slice(index). Or you can create a method for it.
String.prototype.insertAt = function(index,str){
return this.slice(0,index) + str + this.slice(index)
}
console.log("foo bar".insertAt(4,'baz ')) //foo baz bar
Splice method for Strings
You can split() the main string and add then use normal splice()
String.prototype.splice = function(index,del,...newStrs){
let str = this.split('');
str.splice(index,del,newStrs.join('') || '');
return str.join('');
}
var txt1 = "foo baz"
//inserting single string.
console.log(txt1.splice(4,0,"bar ")); //foo bar baz
//inserting multiple strings
console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz
//removing letters
console.log(txt1.splice(1,2)) //f baz
//remving and inseting atm
console.log(txt1.splice(1,2," bar")) //f bar baz
Applying splice() at multiple indexes
The method takes an array of arrays each element of array representing a single splice().
String.prototype.splice = function(index,del,...newStrs){
let str = this.split('');
str.splice(index,del,newStrs.join('') || '');
return str.join('');
}
String.prototype.mulSplice = function(arr){
str = this
let dif = 0;
arr.forEach(x => {
x[2] === x[2] || [];
x[1] === x[1] || 0;
str = str.splice(x[0] + dif,x[1],...x[2]);
dif += x[2].join('').length - x[1];
})
return str;
}
let txt = "foo bar baz"
//Replacing the 'foo' and 'bar' with 'something1' ,'another'
console.log(txt.splice(0,3,'something'))
console.log(txt.mulSplice(
[
[0,3,["something1"]],
[4,3,["another"]]
]
))
I wanted to compare the method using substring and the method using slice from Base33 and user113716 respectively, to do that I wrote some code
also have a look at this performance comparison, substring, slice
The code I used creates huge strings and inserts the string "bar " multiple times into the huge string
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* #this {String}
* #param {number} start Index at which to start changing the string.
* #param {number} delCount An integer indicating the number of old chars to remove.
* #param {string} newSubStr The String that is spliced in.
* #return {string} A new string with the spliced substring.
*/
String.prototype.splice = function (start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
String.prototype.splice = function (idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
return string + this;
};
function createString(size) {
var s = ""
for (var i = 0; i < size; i++) {
s += "Some String "
}
return s
}
function testSubStringPerformance(str, times) {
for (var i = 0; i < times; i++)
str.insert(4, "bar ")
}
function testSpliceStringPerformance(str, times) {
for (var i = 0; i < times; i++)
str.splice(4, 0, "bar ")
}
function doTests(repeatMax, sSizeMax) {
n = 1000
sSize = 1000
for (var i = 1; i <= repeatMax; i++) {
var repeatTimes = n * (10 * i)
for (var j = 1; j <= sSizeMax; j++) {
var actualStringSize = sSize * (10 * j)
var s1 = createString(actualStringSize)
var s2 = createString(actualStringSize)
var start = performance.now()
testSubStringPerformance(s1, repeatTimes)
var end = performance.now()
var subStrPerf = end - start
start = performance.now()
testSpliceStringPerformance(s2, repeatTimes)
end = performance.now()
var splicePerf = end - start
console.log(
"string size =", "Some String ".length * actualStringSize, "\n",
"repeat count = ", repeatTimes, "\n",
"splice performance = ", splicePerf, "\n",
"substring performance = ", subStrPerf, "\n",
"difference = ", splicePerf - subStrPerf // + = splice is faster, - = subStr is faster
)
}
}
}
doTests(1, 100)
The general difference in performance is marginal at best and both methods work just fine (even on strings of length ~~ 12000000)
Take the solution. I have written this code in an easy format:
const insertWord = (sentence,word,index) => {
var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
for (var i = 0; i < sliceSentence.length; i++)
{
if (i === index)
{ // checking if index of array === input index
for (var j = 0; j < word.length; j++)
{ // if yes we'll insert the word
output.push(sliceWord[j]); // Condition is true we are inserting the word
}
output.push(" "); // providing a single space at the end of the word
}
output.push(sliceSentence[i]); // pushing the remaining elements present in an array
}
join = output.join(""); // converting an array to string
console.log(join)
return join;
}
Prototype should be the best approach as many mentioned. Make sure that prototype comes earlier than where it is used.
String.prototype.insert = function (x, str) {
return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};

How can I parse a string in Javascript?

I have string looking like this:
01
02
03
99
I'd like to parse these to make them into strings like:
1. 2. 3. 99. etc.
The numbers are a maximum of 2 characters. Also I have to parse some more numbers later in the source string so I would like to learn the substring equivalent in javascript. Can someone give me advice on how I can do. Previously I had been doing it in C# with the following:
int.Parse(RowKey.Substring(0, 2)).ToString() + "."
Thanks
Why, parseInt of course.
// Add 2 until end of string
var originalA = "01020399";
for (var i = 0; i < originalA.length; i += 2)
{
document.write(parseInt(originalA.substr(i, 2), 10) + ". ");
}
// Split on carriage returns
var originalB = "01\n02\n03\n99";
var strArrayB = originalB.split("\n");
for (var i = 0; i < strArrayB.length; i++)
{
document.write(parseInt(strArrayB[i], 10) + ". ");
}
// Replace the leading zero with regular expressions
var originalC = "01\n02\n03\n99";
var strArrayC = originalC.split("\n");
var regExpC = /^0/;
for (var i = 0; i < strArrayC.length; i++)
{
document.write(strArrayC[i].replace(regExpC, "") + ". ");
}
The other notes are that JavaScript is weakly typed, so "a" + 1 returns "a1". Additionally, for substrings you can choose between substring(start, end) and substr(start, length). If you're just trying to pull a single character, "abcdefg"[2] will return "c" (zero-based index, so 2 means the third character). You usually won't have to worry about type-casting when it comes to simple numbers or letters.
http://jsfiddle.net/mbwt4/3/
use parseInt function.
parseInt(09) //this will give you 9
var myString = parseInt("09").toString()+". "+parseInt("08").toString();
string = '01\n02\n03\n99';
array = string.split('\n');
string2 = '';
for (i = 0; i < array.length; i++) {
array[i] = parseInt(array[i]);
string2 += array[i] + '. ';
}
document.write(string2);
var number = parseFloat('0099');
Demo
Substring in JavaScript works like this:
string.substring(from, to);
where from is inclusive and to is exclusive. You can also use slice:
string.slice(from, to)
where from is inclusive and to is exclusive. The difference between slice and substring is with slice you can specify negative numbers. For example, from = -1 indicates the last character. from(-1, -3) would give you the last 2 characters of the string.
With both methods if you don't specify end then you will get all the characters to the end.
Paul
Ii they are always 2 digits how about;
var s = "01020399";
var result = []
for (var i = 0; i < s.length; i+=2)
result.push(parseInt(s.substr(i, 2), 10) + ".")
alert( result[2] ) // 3.
alert( result.join(" ") ) // 1. 2. 3. 99.

Categories

Resources