From plain text to TEX - Javascript [closed] - node.js

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'm building a math application and I want to show math formulas written with a good design in javascript (nodejs). So I would transorm plain text to TEX format.
From formula like this:
(25*5)/6
To formula like this:
\frac{(25 \cdot 5)}{6}
To good design:
If there are other known methods you advise me.
Many thanks in advance!

I've rewritten this expression parser from java to javascript. not the most straightforward way. Note that this is not extensively tested.
function texFromExpression(str){
var pos = -1, ch;
function nextChar(){
ch = (++pos < str.length) ? str.charAt(pos) : -1;
}
function eat(charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
function parse(){
nextChar();
var x = parseExpression();
if (pos < str.length) throw `Unexpected: ${ch}`
return x;
}
function parseExpression() {
var x = parseTerm();
for (;;) {
if (eat('+')) x = `${x} + ${parseTerm()}` // addition
else if (eat('-')) x = `${x} - ${parseTerm()}` // subtraction
else return x;
}
}
function parseTerm() {
var x = parseFactor();
for (;;) {
if (eat('*')) x=`${x} \\cdot ${parseTerm()}`; // multiplication
else if (eat('/')) x= `\\frac{${x}}{${parseTerm()}}`; // division
else return x;
}
}
function parseFactor() {
if (eat('+')) return `${parseFactor()}`; // unary plus
if (eat('-')) return `-${parseFactor()}`; // unary minus
var x;
var startPos = pos;
if (eat('(')) { // parentheses
x = `{(${parseExpression()})}`
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = str.substring(startPos, pos);
} else if (ch >= 'a' && ch <= 'z') { // variables
while (ch >= 'a' && ch <= 'z') nextChar();
x= str.substring(startPos, pos);
if(x.length>1){
x = `\\${x} {${parseFactor()}}`;
}
} else {
throw `Unexpected: ${ch}`
}
if (eat('^')) x = `${x} ^ {${parseFactor()}}` //superscript
if(eat('_')) x = `${x}_{${parseFactor()}}`;
return x;
}
return `$${parse()}$`;
}

Related

Simple removeVowel function not changing input string

I'm trying to make a simple function in dart to test on which should remove all vowels from an input string but its seems my code never changes the from the original input. Could anyone help me with this? thanks
String removeVowel( str) {
var toReturn = "";
for (var i = 0; i < str.length; i++) {
var temp = str.substring(i,i+1);
if (temp != 'a' || temp != 'e' || temp != 'i' || temp != 'o' || temp!= 'u')
{
toReturn = toReturn + temp;
}
}
return toReturn;
}
and what my tests shows:
00:02 +0 -1: dog --> dg [E]
Expected: 'dg'
Actual: 'dog'
Which: is different.
Expected: dg
Actual: dog
^
Differ at offset 1
Good first try but there is a much easier way of doing this.
replaceAll should do the trick
String removeVolwels(String s){
return s.replaceAll(RegExp('[aeiou]'),'');
}
https://api.flutter.dev/flutter/dart-core/String/replaceAll.html
To make your code work you should change the || to &&
String removeVowel( str) {
var toReturn = "";
for (var i = 0; i < str.length; i++) {
var temp = str.substring(i,i+1);
if (temp != 'a' && temp != 'e' && temp != 'i' && temp != 'o' && temp!= 'u')
{
toReturn = toReturn + temp;
}
}
return toReturn;
}

Optimising A* pathfinding, runs very slow. Possible bugs(?) visual c++

Hi I'm having a few problems with my A* pathfinding algorithm. The algorithm does successfully execute, however in a debug environment it executes in about 10 seconds, in release it will still take 2-3 seconds. This speed is way too slow. I suspect this is either due to a bug in the code, or the fact it isn't well optimised.
The map that pathfinding is being used on is a 30*30 grid, with each square being 10 unites away from one another.
I have noticed when running the algorithm, that when the open and closed list are searched to see if a node already exists, the node already stored in one of the lists always has a lower cost, so there is no updating of nodes. Not sure if this is normal or not. Also, I am not sure if quicksort is a good sort to be using in this situation.
Here is the code:
The coords struture used as a node:
struct coords
{
int x;
int z;
coords* parent;
int cost;
int score;
};
The sort compare function:
bool decompare(coords* o1, coords* o2)
{
return (o1->score < o2->score);
}
The main pathfind loop:
while (!goalFound) //While goal has not been found
{
current = openList.front(); //Retrieve current state from the open list
openList.pop_front();
for (int count = 1; count < 5; count++)
{
if (!goalFound)
{
coords* possibleState = new (coords); //Allocate new possible state
found = false;
if (count == 1)
{
possibleState->x = current->x;
possibleState->z = current->z + 10; //North
}
else if (count == 2)
{
possibleState->x = current->x + 10; //East
possibleState->z = current->z;
}
else if (count == 3)
{
possibleState->x = current->x; //South
possibleState->z = current->z - 10;
}
else if (count == 4)
{
possibleState->x = current->x - 10; //West
possibleState->z = current->z;
}
if (possibleState->x >-1 && possibleState->x <291 && possibleState->z >-1 && possibleState->z < 291) //If possible state is in game boundary
{
possibleState->cost = current->cost + 10; //Add 10 to current state to get cost of new possible state
int a = (possibleState->x / 10) + (30 * (possibleState->z / 10)); //get index of map
if (map[a] != wallTest) //Test possible state is not inside a wall
{
p = openList.begin();
while (p != openList.end() && !found) //Search open list to see if possible state already exists
{
if (possibleState->x == (*p)->x && possibleState->z == (*p)->z) //Already exists
{
found = true;
if (!possibleState->cost >= (*p)->cost) //Test possible state has lower cost
{
(*p)->parent = current; //Update existing with attributes of possible state
a = abs((*p)->x - goalState->x);
b = abs((*p)->z - goalState->z);
(*p)->cost = possibleState->cost;
(*p)->score = (possibleState->cost) + ((a)+(b));
}
}
else
{
found = false; //Set not found
}
p++;
}
q = closedList.begin();
while (q != closedList.end())
{
if (possibleState->x == (*q)->x && possibleState->z == (*q)->z)
{
found = true;
int a = (*q)->cost;
if (possibleState->cost < a) //Test if on closed list
{
(*q)->parent = current;
a = abs((*q)->x - goalState->x);
b = abs((*q)->z - goalState->z);
(*q)->cost = possibleState->cost;
(*q)->score = (possibleState->cost) + ((a)+(b)); //If cost lower push onto open list
coords* newcoord;
newcoord->x = (*q)->x;
newcoord->z = (*q)->z;
newcoord->score = (*q)->score;
newcoord->cost = (*q)->cost;
openList.push_back(newcoord);
closedList.erase(q);
}
}
q++;
}
if (!found) //If not found on either list
{
possibleState->parent = current; //Push onto open list
a = abs((possibleState)->x / 10 - goalState->x / 10);
b = abs((possibleState)->z / 10 - goalState->z / 10);
(possibleState)->score = (possibleState->cost) + ((a)+(b));
openList.push_back(possibleState);
}
sort(openList.begin(), openList.end(), decompare); // Sort the open list by score
}
if (possibleState->x == goalState->x && possibleState->z == goalState->z) //if goal found
{
openList.push_back(possibleState);
node = possibleState;
goalFound = true;
while (node != 0)
{
wayPoints.push_back(*node);
node = node->parent;
wayCount = wayPoints.size() - 1;
}
}
}
}
}
closedList.push_back(current);
}
player->setWayPoints(wayPoints);
wayPoints.clear();
player->setMoved(2);
player->setPath(1);
openList.clear();
closedList.clear();
goalFound = false;
player->setNewPath(1);
return true;
}
else {
return false;
}
}
Are there any bugs that need to be sorted in this code that anyone can see? Or is it just important optimizations that need making? Thanks

Amazon puzzle asked in initial screening test [closed]

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 days ago.
Improve this question
Amazon can sell products in packs of 6,9 and 20. Given a number N, give the algorythm to find its possible or not.
Ex - 21 -- Not Possible
47 (9*3+20) -- Possible
A very simple, but recursive, solution would be
private bool isDiv(int n) {
if (n < 6) {
return false;
} else if (n == 6 || n == 9 || n == 20) {
Console.Write(n);
return true;
} else if (isDiv(n - 6)) {
Console.Write(" + " + 6);
return true;
} else if (isDiv(n - 9)) {
Console.Write(" + " + 9);
return true;
} else if (isDiv(n - 20)) {
Console.Write(" + " + 20);
return true;
}
return false;
}
But keep in mind that this is not the fastest solution - but it works good for small numbers like the ones in your example
Oh and 21 is quite possible:
2*6 + 9 = 21
A very simple logical solution using C
#include <stdio.h>
int main(){
int x = 6, y=9, z=20,n=26,t1,t2,i;
t1 = n%z;
for(i=0; i<2;i++)
{
if (t1 < y)
{
t2 = t1%x;
}
else
{
t2 = t1%y;
t1 = t2;
}
}
if (t2 == 0 || t1 == 0)
{
printf("Yes we can do it");
}
else
{
printf("we cannot do it");
}
}

removing a char from string in Unity3D

I am making a word game in unity3D game engine, I make a word if word spelling is wrong I want to remove a certain character from that word for making a correct spelling and then other character shift back... in my code I have an string and want to remove a char from string.... so that when the char is removed from the center of the string other char shift back.
static var nextPos = 200;
static var word: String;
var sel: String;
var isClicked : boolean=false;
var xpos: float = 200;
static var i:int=0;
function start()
{
word="";
}
function OnMouseDown()
{
if (!isClicked) {
isClicked = true;
xpos = nextPos;
sel=OnGUI();
word=word+sel;
nextPos += 8;
i++;
}
else if(isClicked)
{
isClicked = false;
xpos = nextPos;
nextPos -= 8;
}
}
function OnGUI()
{
if (gameObject.name == "Sphere(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "A");
return "A";
}
else if (gameObject.name == "Sphere 1(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "B");
return "B";
}
else if (gameObject.name == "Sphere 2(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "C");
return "C";
}
GUI.Label(new Rect(xpos,280,400,100), "Value" + i);
GUI.Label(new Rect(xpos,300,400,100), word);
}
Test this:
string value = "abcde";
string temp="";
temp = value.Substring(0, position - 1);
value = temp + value.Substring(position, value.Length);
you can check which key is pressed once your text is being displayed
this should work . you need just call it in your update function or OnGUI function
set "word" as a global variable if you use it in an Update function
I wrote this out of my head , It should work , sorry it it has any glitches.
if(Input.anyKey)
{
string letter = Input.inputString;
if (word.Contains(letter))
{
word.Replace(letter,"");
}
}

Substring algorithm

Can someone explain to me how to solve the substring problem iteratively?
The problem: given two strings S=S1S2S3…Sn and T=T1T2T3…Tm, with m is less than or equal to n, determine if T is a substring of S.
Here's a list of string searching algorithms
Depending on your needs, a different algorithm may be a better fit, but Boyer-Moore is a popular choice.
A naive algorithm would be to test at each position 0 < i ≤ n-m of S if Si+1Si+2…Si+m=T1T2…Tm. For n=7 and m=5:
i=0: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=1: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=2: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
The algorithm in pseudo-code:
// we just need to test if n ≤ m
IF n > m:
// for each offset on that T can start to be substring of S
FOR i FROM 0 TO n-m:
// compare every character of T with the corresponding character in S plus the offset
FOR j FROM 1 TO m:
// if characters are equal
IF S[i+j] == T[j]:
// if we’re at the end of T, T is a substring of S
IF j == m:
RETURN true;
ENDIF;
ELSE:
BREAK;
ENDIF;
ENDFOR;
ENDFOR;
ENDIF;
RETURN false;
Not sure what language you're working in, but here's an example in C#. It's a roughly n2 algorithm, but it will get the job done.
bool IsSubstring (string s, string t)
{
for (int i = 0; i <= (s.Length - t.Length); i++)
{
bool found = true;
for (int j = 0; found && j < t.Length; j++)
{
if (s[i + j] != t[j])
found = false;
}
if (found)
return true;
}
return false;
}
if (T == string.Empty) return true;
for (int i = 0; i <= S.Length - T.Length; i++) {
for (int j = 0; j < T.Length; j++) {
if (S[i + j] == T[j]) {
if (j == (T.Length - 1)) return true;
}
else break;
}
}
return false;
It would go something like this:
m==0? return true
cs=0
ct=0
loop
cs>n-m? break
char at cs+ct in S==char at ct in T?
yes:
ct=ct+1
ct==m? return true
no:
ct=0
cs=cs+1
end loop
return false
This may be redundant with the above list of substring algorithms, but I was always amused by KMP (http://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm)
// runs in best case O(n) where no match, worst case O(n2) where strings match
var s = "hippopotumus"
var t = "tum"
for(var i=0;i<s.length;i++)
if(s[i]==t[0])
for(var ii=i,iii=0; iii<t.length && i<s.length; ii++, iii++){
if(s[ii]!=t[iii]) break
else if (iii==t.length-1) console.log("yay found it at index: "+i)
}
Here is my PHP variation that includes a check to make sure the Needle does not exceed the Haystacks length during the search.
<?php
function substring($haystack,$needle) {
if("" == $needle) { return true; }
echo "Haystack:\n$haystack\n";
echo "Needle:\n$needle\n";
for($i=0,$len=strlen($haystack);$i<$len;$i++){
if($needle[0] == $haystack[$i]) {
$found = true;
for($j=0,$slen=strlen($needle);$j<$slen;$j++) {
if($j >= $len) { return false; }
if($needle[$j] != $haystack[$i+$j]) {
$found = false;
continue;
}
}
if($found) {
echo " . . . . . . SUCCESS!!!! startPos: $i\n";
return true;
}
}
}
echo " . . . . . . FAILURE!\n" ;
return false;
}
assert(substring("haystack","hay"));
assert(!substring("ack","hoy"));
assert(substring("hayhayhay","hayhay"));
assert(substring("mucho22","22"));
assert(!substring("str","string"));
?>
Left in some echo's. Remove if they offend you!
Is a O(n*m) algorithm, where n and m are the size of each string.
In C# it would be something similar to:
public static bool IsSubtring(char[] strBigger, char[] strSmall)
{
int startBigger = 0;
while (startBigger <= strBigger.Length - strSmall.Length)
{
int i = startBigger, j = 0;
while (j < strSmall.Length && strSmall[j] == strBigger[i])
{
i++;
j++;
}
if (j == strSmall.Length)
return true;
startBigger++;
}
return false;
}
I know I'm late to the game but here is my version of it (in C#):
bool isSubString(string subString, string supraString)
{
for (int x = 0; x <= supraString.Length; x++)
{
int counter = 0;
if (subString[0] == supraString[x]) //find initial match
{
for (int y = 0; y <= subString.Length; y++)
{
if (subString[y] == supraString[y+x])
{
counter++;
if (counter == subString.Length)
{
return true;
}
}
}
}
}
return false;
}
Though its pretty old post, I am trying to answer it. Kindly correct me if anything is wrong,
package com.amaze.substring;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CheckSubstring {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the main string");
String mainStr = br.readLine();
System.out.println("Enter the substring that has to be searched");
String subStr = br.readLine();
char[] mainArr = new char[mainStr.length()];
mainArr = mainStr.toCharArray();
char[] subArr = new char[subStr.length()];
subArr = subStr.toCharArray();
boolean tracing = false;
//System.out.println("Length of substring is "+subArr.length);
int j = 0;
for(int i=0; i<mainStr.length();i++){
if(!tracing){
if(mainArr[i] == subArr[j]){
tracing = true;
j++;
}
} else {
if (mainArr[i] == subArr[j]){
//System.out.println(mainArr[i]);
//System.out.println(subArr[j]);
j++;
System.out.println("Value of j is "+j);
if((j == subArr.length)){
System.out.println("SubString found");
return;
}
} else {
j=0;
tracing = false;
}
}
}
System.out.println("Substring not found");
}
}

Resources