My question is similar to THIS question that hasn't been answered yet.
How can I make my code (or any javascript code that might be suggested?) find all possible solutions of a known string length with multiple missing characters in variation with repetition?
I'm trying to take a string of known character lengths and find missing characters from that string. For example:
var missing_string = "ov!rf!ow"; //where "!" are the missing characters
I'm hoping to run a script with a specific array such as:
var r = new Array("A","B","C","D","E","F","G","H","I","J","K",
"L","M","N","O","P","Q","R","S","T","U","V",
"W","X","Y","Z",0,1,2,3,4,5,6,7,8,9);
To find all the possible variations with repetition of those missing characters to get a result of:
ovArfAow
ovBrfAow
ovCrfAow
...
ovBrfBow
ovBrfCow
...
etc //ignore the case insensitive, just to emphasize the example
and of course, eventually find ovErfLow within all the variations with repetition.
I've been able to make it work with 1 (single) missing character. However, when I put 2 missing characters with my code it obviously repeats the same array character for both missing characters which is GREAT for repition but I also need to find without repetition as well and might need to have 3-4 missing characters as well which may or may not be repeated. Here's what I have so far:
var r = new Array("A","B","C","D","E","F","G","H","I","J","K",
"L","M","N","O","P","Q","R","S","T","U","V",
"W","X","Y","Z",0,1,2,3,4,5,6,7,8,9);
var missing_string = "he!!ow!r!d";
var bt_lng = missing_string.length;
var bruted="";
for (z=0; z<r.length; z++) {
for(var x=0;x<bt_lng;x++){
for(var y=0;y<r.length;y++){
if(missing_string.charAt(x) == "!"){
bruted += r[z];
break;
}
else if(missing_string.charAt(x) == r[y]){
bruted += r[y];
}
}
}
console.log("br: " + bruted);
bruted="";
}
This works GREAT with just ONE "!":
helloworAd
helloworBd
helloworCd
...
helloworLd
However with 2 or more "!", I get:
heAAowArAd
heBBowBrBd
heCCowCrCd
...
heLLowLrLd
which is good for the repetition part but I also need to test all possible array M characters in each missing character spot.
Maybe the following function in pure javascript is a possible solution for you. It uses Array.prototype.reduce to create the cartesian product c of the given alphabet x, whereby its power n depends on the count of the exclamation marks in your word w.
function combinations(w) {
var x = new Array(
"A","B","C","D","E","F","G","H","I","J","K",
"L","M","N","O","P","Q","R","S","T","U","V",
"W","X","Y","Z",0,1,2,3,4,5,6,7,8,9
),
n = w.match(/\!/g).length,
x_n = new Array(),
r = new Array(),
c = null;
for (var i = n; i > 0; i--) {
x_n.push(x);
}
c = x_n.reduce(function(a, b) {
var c = [];
a.forEach(function(a) {
b.forEach(function(b) {
c.push(a.concat([b]));
});
});
return c;
}, [[]]);
for (var i = 0, j = 0; i < c.length; i++, j = 0) {
r.push(w.replace(/\!/g, function(s, k) {
return c[i][j++];
}));
}
return r;
}
Call it like this console.log(combinations("ov!rf!ow")) in your browser console.
Related
TL:DR
According to the google docs, getResponseText() should return a string... but I get a message that claims it is an object when I try to sort it.. huh?
TypeError: Cannot find function sort in object
I was under the impression that a javascript string sort of works like an array, and it seems to behave like one because string[0] returns the first letter of a string..
DETAILS:
here is the sheet I am working
Hello everyone, I have a very unique situation where I need to update dirty strings (courtesy of an undesirable OCR import).
I have created a function that does the job but needs additional functionality.
Currently, the process goes like this:
enter your desired string
each cell (in your selection) is checked for that string
cells are updating with desired string if the match is over 50% alike
the check works like this:
compare the first letter of desired string (txtT[0])
against the first letter of target cell (valT[0])
compare additional letters [x] up to the length of the longest string
for example:
desired string = "testing"
target cell = "t3st1ng"
the loop goes like this:
create a point system do to math
(total points = length of longest string)
compare t and t ... if matching, add one point (+1 in this case because it matches)
compare e and 3 ... if matching, add one point (+0 in this case because it does not match)
compare s and s ... if matching, add one point (+1 in this case because it matches)
compare t and t ... if matching, add one point (+1 in this case because it matches)
compare i and 1 ... if matching, add one point (+0 in this case because it does not match)
compare n and n ... if matching, add one point (+1 in this case because it matches)
compare g and g ... if matching, add one point (+1 in this case because it matches)
points earned/total points = % of alike
The problem with this system is that if is based on the position of the letters in each string.
This causes problems when comparing strings like "testing" and "t est ing"
I tried to update it so that the first thing it does is SORT the string alphabetically, ignoring all special characters and non alphabetical characters.
That's when I came across an error:
TypeError: Cannot find function sort in object testing.
This does not make sense because my desired string is a string. See code where it says "this is where i get my error":
According to the google docs, getResponseText() should return a string... but I cannot call the sort method on the string.. which makes no sense!
function sandboxFunction() {
try {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var as = ss.getActiveSheet();
var ar = as.getActiveRange();
var sv = ui.prompt('enter desired string');
var txt = sv.getResponseText();
var txtT = txt.trim();
txtT = txtT.replace(/ /g, ''); //this is the trimmed comparison string
txtT = txtT.sort(); //***this is where I get my error***
ui.alert(txtT);
var vals = ar.getValues();
for (var r = 0; r < vals.length; r++) {
var row = vals[r];
for (var c = 0; c < row.length; c++) {
var val = row[c];
var valT = val.trim();
valT = valT.replace(/ /g, ''); // this is the trimmed comparison cell
ui.alert(valT);
//this is where we test the two
//test length
var tl = txtT.length;
var vl = valT.length;
if (vl < tl) {
ui.alert("different lengths.. applying fix");
for (vl; vl < tl; vl++) {
valT = valT.concat("x");
ui.alert(valT);
}
}
else if (tl < vl) {
ui.alert("different lengths.. applying fix");
for (tl; tl < vl; tl++) {
txtT = txtT.concat("x");
ui.alert(txtT);
}
}
if (valT.toUpperCase() == txtT.toUpperCase()) {
ui.alert("your strings match");
}
else {
var total = txtT.length;
var pts = 0;
for (var x = 0; x < total; x++) {
if (valT[x] == txtT[x]) {
pts++;
}
}
if (pts / total >= 0.5) {
ui.alert("at least 50% match, fixing text");
vals[r][c] = txt;
}
}
}
}
ar.setValues(vals);
}
catch (err) {
ui.alert(err);
}
}
You can't sort a string in that way, sort is a method of arrays.
You can convert your string to an array, later you can sort
var txtT = "This is a string".trim();
txtT = txtT.replace(/ /g, ''); //this is the trimmed comparison string
var txtArray = txtT.split(''); // Convert to array
var txtSorted = txtArray.sort(); // Use sort method
console.log(txtSorted);
See sort() docs
I'm trying to write a twitter bot that replies to people with a random haiku, but I'm having trouble creating the structure for it in javascript. In the code I've attached you'll see that using p5.js I've loaded two text files, one with a bunch of nouns and the other with a bunch of adjectives. I then split them by syllable using some code I found, but I can't figure out how to re-organize my list into separate arrays per syllable amount.
like "oneSyllable = []", "twoSyllable = []" etc.
Any help would be greatly appreciated- even just an explanation of what the regex function does would help. This one- (/(?=[^laeiouy]es|ed|[^laeiouy]e)$/, '')
Also, is there an easier way to do this within javascript? Using p5 means I'll have to run it to the twitter bot using the command line, something which I still have to learn. If you have any additional information on making a haiku twitter bot please let me know! I've done a bunch of research but I can't find any source code for the several that are out there.
This is for a code final due soon and I'm way out of my depth!! Hope someone can help.
function setup() {
createCanvas(600, 6000);
fill(0);
loadStrings("./nouns.txt", doText);
loadStrings("./adjectives.txt", doText2);
}
function doText(data) {
for (var i=0; i<data.length; i++) {
text("Nouns list:", 5, 20);
text(data[i]+ ": " + (new_count(data[i])), 5, 20*i+50);
}
}
function doText2(data) {
for (var j=0; j<data.length; j++) {
text("Adjectives list:", 100, 20);
text(data[j]+ ": " + (new_count(data[j])), 100, 20*j+50);
}
}
function new_count(word) {
word = word.toLowerCase();
if(word.length <= 3) { return 1; }
word = word.replace(/(?=[^laeiouy]es|ed|[^laeiouy]e)$/, '');
word = word.replace(/^y/, '');
return word.match(/[aeiouy]{1,2}/g).length;
}
I suggest to store words organized by syllable count in a dictionary with keys being syllable count and values being lists of words having the respective syllable count.
Provided any object in JavaScript is an associative array, which is just another term for "dictionary", you may end up with the following function to re-organize your lists:
function groupBySyllableCount(wordList) {
var wordsBySyllableCount = {};
for (var i = 0, len = wordList.length; i < len; i++) {
var slblCount = new_count(wordList[i]);
if (wordsBySyllableCount[slblCount] === undefined) {
wordsBySyllableCount[slblCount] = [wordList[i]];
} else {
wordsBySyllableCount[slblCount].push(wordList[i]);
}
}
return wordsBySyllableCount;
}
// TEST & DEMO:
var nouns = ['air', 'time', 'community', 'year', 'people', 'woman', 'house', 'research'];
var nounsBySyllableCount = groupBySyllableCount(nouns);
console.log(nounsBySyllableCount);
function new_count(word) {
word = word.toLowerCase();
if(word.length <= 3) { return 1; }
word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');
word = word.replace(/^y/, '');
return word.match(/[aeiouy]{1,2}/g).length;
}
As of the (?=[^laeiouy]es|ed|[^laeiouy]e)$ regex, it matches
either es not preceded by l, a, e, i, o, u, or y,
or ed
or e not preceded by l, a, e, i, o, u, or y
but only if they are go just before end of string (a word in your case), which is denoted by the $ anchor. The (?=...) is a positive look-ahead and used here merely to group the [^laeiouy]es, ed and [^laeiouy]e patterns to state that each of them should be followed by end of string.
In fact using a positive look-ahead is an overkill here. Grouping with a capturing ((...)) or a non-capturing ((?:...)) group construct would be enough. See the amended regex in my demo above.
Recently, I've been attempting to emulate a small language in jQuery and JavaScript, yet I've come across what I believe is an issue. I think that I may be parsing everything completely wrong.
In the code:
#name Testing
#inputs
#outputs
#persist
#trigger
print("Test")
The current way I am separating and parsing the string is by splitting all of the code into lines, and then reading through this lines array using searches and splits. For example, I would find the name using something like:
if(typeof lines[line] === 'undefined')
{
}
else
{
if(lines[line].search('#name') == 0)
{
name = lines[line].split(' ')[1];
}
}
But I think that I may be largely wrong on how I am handling parsing.
While reading through examples on how other people are handling parsing of code blocks like this, it appeared that people parsed the entire block, instead of splitting it into lines as I do. I suppose the question of the matter is, what is the proper and conventional way of parsing things like this, and how do you suggest I use it to parse something such as this?
In simple cases like this regular expressions is your tool of choice:
matches = code.match(/#name\s+(\w+)/)
name = matches[1]
To parse "real" programming languages regexps are not powerful enough, you'll need a parser, either hand-written or automatically generated with a tool like PEG.
A general approach to parsing, that I like to take often is the following:
loop through the complete block of text, character by character.
if you find a character that signalizes the start of one unit, call a specialized subfunction to parse the next characters.
within each subfunction, call additional subfunctions if you find certain characters
return from every subfunction when a character is found, that signalizes, that the unit has ended.
Here is a small example:
var text = "#func(arg1,arg2)"
function parse(text) {
var i, max_i, ch, funcRes;
for (i = 0, max_i = text.length; i < max_i; i++) {
ch = text.charAt(i);
if (ch === "#") {
funcRes = parseFunction(text, i + 1);
i = funcRes.index;
}
}
console.log(funcRes);
}
function parseFunction(text, i) {
var max_i, ch, name, argsRes;
name = [];
for (max_i = text.length; i < max_i; i++) {
ch = text.charAt(i);
if (ch === "(") {
argsRes = parseArguments(text, i + 1);
return {
name: name.join(""),
args: argsRes.arr,
index: argsRes.index
};
}
name.push(ch);
}
}
function parseArguments(text, i) {
var max_i, ch, args, arg;
arg = [];
args = [];
for (max_i = text.length; i < max_i; i++) {
ch = text.charAt(i);
if (ch === ",") {
args.push(arg.join(""));
arg = [];
continue;
} else if (ch === ")") {
args.push(arg.join(""));
return {
arr: args,
index: i
};
}
arg.push(ch);
}
}
FIDDLE
this example just parses function expressions, that follow the syntax "#functionName(argumentName1, argumentName2, ...)". The general idea is to visit every character exactly once without the need to save current states like "hasSeenAtCharacter" or "hasSeenOpeningParentheses", which can get pretty messy when you parse large structures.
Please note that this is a very simplified example and it misses all the error handling and stuff like that, but I hope the general idea can be seen. Note also that I'm not saying that you should use this approach all the time. It's a very general approach, that can be used in many scenerios. But that doesn't mean that it can't be combined with regular expressions for instance, if it, at some part of your text, makes more sense than parsing each individual character.
And one last remark: you can save yourself the trouble if you put the specialized parsing function inside the main parsing function, so that all functions have access to the same variable i.
)
I have searched high and low, but i can´t find what i need. Or i´m to stupid to get it right ;-)
I need a page with several input boxes where i can type some text, and then an output area below each input, that shows the text converted to some predefined numbers.
example:
input: abcde fghi æøå (i need all kinds of characters like .,/: etc.)
output: 064 065 066 067 068 032
So it needs to convert like this:
"a"="064 "
"b"="065 "
"space"="032 "
(and yes, each number in output needs to be separated, or a space added after each number)
I have tried some different cipher guides in both php and javascript, but can´t get it to work. I did do an Excel document that could do some of it, but it had a limited amount of characters it could convert, then it started behaving weird. So i thought maybe PHP was the answer!
Any help is very appreciated
/Rasmus
In the spirit of elclanrs deleted answer, and for posterity:
<script>
// Using standard for loop
function stringToCharcodes(s) {
var result = [];
function pad(n){ return (n<10? '00' : n<100? '0' : 0) + n;}
for (var i=0, iLen=s.length; i<iLen; i++) {
result.push(pad(s.charCodeAt(i)));
}
return result.join(' ');
}
// Using ES5 forEach
function stringToCharcodes2(s) {
var result = [];
function pad(n){ return (n<10? '00' : n<100? '0' : 0) + n;}
s.split('').forEach(function(a){result.push(pad(a.charCodeAt(0)))});
return result.join(' ');
}
</script>
<input onkeyup="document.getElementById('s0').innerHTML = stringToCharcodes(this.value);"><br>
<span id="s0"></span>
Edit
If you want a custom mapping, use an object (I've only included 2 characters, you can add as many as you want):
var mapChars = (function() {
var mapping = {'198':'019', '230':'018'};
return function (s) {
var c, result = [];
for (var i=0, iLen=s.length; i<iLen; i++) {
c = s.charCodeAt(i);
result.push(c in mapping? mapping[c] : c);
}
return result.join(' ');
}
}());
alert(mapChars('Ææ')); //
Using the character code for mapping seems to be a reasonable solution, using the actual character may be subject to different page character encoding.
I have a hidden field on my page that stores space separated list of emails.
I can have maximum 500 emails in that field.
What will be the fastest way to search if a given email already exists in that list?
I need to search multiple emails in a loop
use RegEx to find a match
use indexOf()
convert the list to a
javascript dictionary and then
search
If this is an exact duplicate, please let me know the other question.
Thanks
EDIT:
Thanks everyone for your valuable comments and answers.
Basically my user has a list of emails(0-500) in db.
User is presented with his own contact list.
User can then choose one\more emails from his contact list to add to the list.
I want to ensure at client side that he is not adding duplicate emails.
Whole operation is driven by ajax, so jsvascript is required.
The answer is: It depends.
It depends on what you actually want to measure.
It depends on the relationship between how many you're searching for vs. how many you're searching.
It depends on the JavaScript implementation. Different implementations usually have radically different performance characteristics. This is one of the many reasons why the rule "Don't optimize prematurely" applies especially to cross-implementation JavaScript.
...but provided you're looking for a lot fewer than you have in total, it's probably String#indexOf unless you can create the dictionary once and reuse it (not just this one loop of looking for X entries, but every loop looking for X entries, which I tend to doubt is your use-case), in which case that's hands-down faster to build the 500-key dictionary and use that.
I put together a test case on jsperf comparing the results of looking for five strings buried in a string containing 500 space-delimited, unique entries. Note that that jsperf page compares some apples and oranges (cases where we can ignore setup and what kind of setup we're ignoring), but jsperf was being a pain about splitting it and I decided to leave that as an exercise for the reader.
In my tests of what I actually think you're doing, Chrome, Firefox, IE6, IE7 and IE9 did String#indexOf fastest. Opera did RegExp alternation fastest. (Note that IE6 and IE7 don't have Array#indexOf; the others do.) If you can ignore dictionary setup time, then using a dictionary is the hands-down winner.
Here's the prep code:
// ==== Main Setup
var toFind = ["aaaaa100#zzzzz", "aaaaa200#zzzzz", "aaaaa300#zzzzz", "aaaaa400#zzzzz", "aaaaa500#zzzzz"];
var theString = (function() {
var m, n;
m = [];
for (n = 1; n <= 500; ++n) {
m.push("aaaaa" + n + "#zzzzz");
}
return m.join(" ");
})();
// ==== String#indexOf (and RegExp) setup for when we can ignore setup
var preppedString = " " + theString + " ";
// ==== RegExp setup for test case ignoring RegExp setup time
var theRegExp = new RegExp(" (?:" + toFind.join("|") + ") ", "g");
// ==== Dictionary setup for test case ignoring Dictionary setup time
var theDictionary = (function() {
var dict = {};
var index;
var values = theString.split(" ");
for (index = 0; index < values.length; ++index) {
dict[values[index]] = true;
}
return dict;
})();
// ==== Array setup time for test cases where we ignore array setup time
var theArray = theString.split(" ");
The String#indexOf test:
var index;
for (index = 0; index < toFind.length; ++index) {
if (theString.indexOf(toFind[index]) < 0) {
throw "Error";
}
}
The String#indexOf (ignore setup) test, in which we ignore the (small) overhead of putting spaces at either end of the big string:
var index;
for (index = 0; index < toFind.length; ++index) {
if (preppedString.indexOf(toFind[index]) < 0) {
throw "Error";
}
}
The RegExp alternation test:
// Note: In real life, you'd have to escape the values from toFind
// to make sure they didn't have special regexp chars in them
var regexp = new RegExp(" (?:" + toFind.join("|") + ") ", "g");
var match, counter = 0;
var str = " " + theString + " ";
for (match = regexp.exec(str); match; match = regexp.exec(str)) {
++counter;
}
if (counter != 5) {
throw "Error";
}
The RegExp alternation (ignore setup) test, where we ignore the time it takes to set up the RegExp object and putting spaces at either end of the big string (I don't think this applies to your situation, the addresses you're looking for would be static):
var match, counter = 0;
for (match = theRegExp.exec(preppedString); match; match = theRegExp.exec(preppedString)) {
++counter;
}
if (counter != 5) {
throw "Error";
}
The Dictionary test:
var dict = {};
var index;
var values = theString.split(" ");
for (index = 0; index < values.length; ++index) {
dict[values[index]] = true;
}
for (index = 0; index < toFind.length; ++index) {
if (!(toFind[index] in dict)) {
throw "Error";
}
}
The Dictionary (ignore setup) test, where we don't worry about the setup time for the dictionary; note that this is different than the RegExp alternation (ignore setup) test because it assumes the overall list is invariant:
var index;
for (index = 0; index < toFind.length; ++index) {
if (!(toFind[index] in theDictionary)) {
throw "Error";
}
}
The Array#indexOf test (note that some very old implementations of JavaScript may not have Array#indexOf):
var values = theString.split(" ");
var index;
for (index = 0; index < toFind.length; ++index) {
if (values.indexOf(toFind[index]) < 0) {
throw "Error";
}
}
The Array#indexOf (ignore setup) test, which like Dictionary (ignore setup) assumes the overall list is invariant:
var index;
for (index = 0; index < toFind.length; ++index) {
if (theArray.indexOf(toFind[index]) < 0) {
throw "Error";
}
}
Instead of looking for the fastest solution, you first need to make sure that you’re actually having a correct solution. Because there are four cases an e-mail address can appear and a naive search can fail:
Alone: user#example.com
At the begin: user#example.com ...
At the end: ... user#example.com
In between: ... user#example.com ...
Now let’s analyze each variant:
To allow arbitrary input, you will need to escape the input properly. You can use the following method to do so:
RegExp.quote = function(str) {
return str.toString().replace(/(?=[.?*+^$[\]\\(){}-])/g, "\\");
};
To match all four cases, you can use the following pattern:
/(?:^|\ )user#example\.com(?![^\ ])/
Thus:
var inList = new RegExp("(?:^| )" + RegExp.quote(needle) + "(?![^ ])").test(haystack);
Using indexOf is a little more complex as you need to check the boundaries manually:
var pos = haystack.indexOf(needle);
if (pos != -1 && (pos != 0 && haystack.charAt(pos-1) !== " " || haystack.length < (pos+needle.length) && haystack.charAt(pos+needle.length) !== " ")) {
pos = -1;
}
var inList = pos != -1;
This one is rather quite simple:
var dict = {};
haystack.match(/[^\ ]+/g).map(function(match) { dict[match] = true; });
var inList = dict.hasOwnProperty(haystack);
Now to test what variant is the fastest, you can do that at jsPerf.
indexOf() is most probably the fastest just keep in mind you need to search for two possible cases:
var existingEmails = "email1, email2, ...";
var newEmail = "somethingHere#email.com";
var exists = (existingEmails.indexOf(newEmail + " ") >= 0) || (existingEmails.indexOf(" " + newEmail ) > 0);
You're asking a question with too many unstated variables for us to answer. For example, how many times do you expect to perform this search? only once? A hundred times? Is this a fixed list of emails, or does it change every time? Are you loading the emails with the page, or by AJAX?
IF you are performing more than one search, or the emails are loaded with the page, then you are probably best off creating a dictionary of the names, and using the Javascript in operator.
If you get the string from some off-page source, and you only search it once, then indexOf may well be better.
In all cases, if you really care about the speed, you're best off making a test.
But then I'd ask "Why do you care about the speed?" This is a web page, where loading the page happens at network speeds; the search happens at more or less local-processor speed. It's very unlikely that this one search will make a perceptible difference in the behavior of the page.
Here is a little explanation:
Performing a dictionary lookup is relatively complicated - very fast compared with (say) a linear lookup by key when there are lots of keys, but much more complicated than a straight array lookup. It has to calculate the hash of the key, then work out which bucket that should be in, possibly deal with duplicate hashes (or duplicate buckets) and then check for equality.
As always, choose the right data structure for the job - and if you really can get away with just indexing into an array (or List) then yes, that will be blindingly fast.
The above has been taken from one of the blog posts of #Jon Skeet.
I know this is an old question, but here goes an answer for those who might need in the future.
I made some tests and the indexOf() method is impossibly fast!
Tested the case on Opera 12.16 and it took 216µs to search and possibly find something.
Here is the code used:
console.time('a');
var a=((Math.random()*1e8)>>0).toString(16);
for(var i=0;i<1000;++i)a=a+' '+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16)+((Math.random()*1e8)>>0).toString(16);
console.timeEnd('a');
console.time('b');
var b=(' '+a).indexOf(((Math.random()*1e8)>>0).toString(16));
console.timeEnd('b');
console.log([a,b]);
In the console you will see a huge output.
The timer 'a' counts the time taken to make the "garbage", and the timer 'b' is the time to search for the string.
Just adding 2 spaces, one before and one after, on the email list and adding 1 space before and after the email, you are set to go.
I use it to search for a class in an element without jQuery and it works pretty fast and fine.