for loop not executing properly Javascript - javascript

i m trying to calculate weight of a string using the following function
function weight(w)
{
Cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
small = 'abcdefghijklmnopqrstuvwxyz'
spcl = "~!##$%^&*()_+[]\{}|;':,./<>?"
num = '0123456789'
var p = []
for(i=0;i<w.length;i++)
{
if(Cap.contains(w[i])==true)
p[i] = Cap.indexOf(w[i]) + 2
else if(small.contains(w[i])==true)
p[i] = small.indexOf(w[i]) + 1
else if(num.contains(w[i]))
p[i] = num.indexOf(w[i])
else if(spcl.contains(w[i]))
p[i] = 1
}
return _.reduce(p,function(memo, num){ return memo + num; }, 0);
}
where w is a string. this properly calculates weight of the string.
But whn i try to to calculate weight of strings given in a an array, it jst calculates the weight of the first element, ie. it does not run the full for loop. can anyone explain to me why is that so??
the for loop is as given below
function weightList(l)
{
weigh = []
for(i=0;i<l.length;i++)
weigh.push(weight(l[i]));
return weigh;
}
input and output:
>>> q = ['abad','rewfd']
["abad", "rewfd"]
>>> weightList(q)
[8]
whereas the output array should have had 2 entries.
[8,56]
i do not want to use Jquery. i want to use Vanilla only.

Because i is a global variable. So when it goes into the function weight it sets the value of i greater than the lenght of l. Use var, it is not optional.
for(var i=0;i<l.length;i++)
and
for(var i=0;i<w.length;i++)
You should be using var with the other variables in the function and you should be using semicolons.

I think your issue is just malformed JavaScript. Keep in mind that JavaScript sucks, and is not as forgiving as some other languages are.
Just by adding a few "var" and semicolons, I was able to get it to work with what you had.
http://jsfiddle.net/3D5Br/
function weight(w) {
var Cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
small = 'abcdefghijklmnopqrstuvwxyz',
spcl = "~!##$%^&*()_+[]\{}|;':,./<>?",
num = '0123456789',
p = [];
for(var i=0;i<w.length;i++){
if(Cap.contains(w[i])==true)
p[i] = Cap.indexOf(w[i]) + 2
else if(small.contains(w[i])==true)
p[i] = small.indexOf(w[i]) + 1
else if(num.contains(w[i]))
p[i] = num.indexOf(w[i])
else if(spcl.contains(w[i]))
p[i] = 1
}
return _.reduce(p,function(memo, num){ return memo + num; }, 0);
}
function weightList(l) {
var weigh = [];
for(var i=0;i<l.length;i++)
weigh.push(weight(l[i]));
return weigh;
}
q = ['abad','rewfd'];
results = weightList(q);
Hope that helps

Related

Fastest way to generate a lot of unique small random numbers in JavaScript

Wondering how to quickly generate lots of unique, small random numbers. When I implemented it like this it slows down exponentially it seems like, to the point where it never finishes, or will take hours to complete. Probably because it creates tons of duplicates toward the end.
var intsmap = {}
var intsarray = []
var i = 100000
while (i--) {
var int = randominteger(6)
if (intsmap[int]) i++
else {
intsmap[int] = true
intsarray.push(int)
}
}
// return intsarray
function randominteger(exp) {
var string = rand(exp)
return pad(string, exp)
}
function pad(num, size) {
var s = rand(9) + num
return s.substr(s.length - size)
}
function rand(exp) {
var integer = Math.random() * Math.pow(10, exp) << 0
var string = toString(integer, '0123456789')
return string
}
function toString(value, code) {
var digit
var radix = code.length
var result = ''
do {
digit = value % radix
result = code[digit] + result
value = Math.floor(value / radix)
} while (value)
return result
}
Wondering how to accomplish that but the code works within a few seconds if possible.
Update
I would like for the set of numbers to be distributed evenly over an arbitrary range (in this example 1000000 strings, not necessarily from 0-1000000, eg maybe 5050000 is in there).
I would like for the numbers to not necessarily be valid numbers, just a string of integers. So for example they can include 01010101 as a valid string, even though that's not a valid number.
You can use an object as a look up and only insert unique random number
var intsmap = {};
var i = 100000;
while (i--) {
var int = Math.random() * Math.pow(10, 6) << 0;
if(intsmap[int])
continue;
else
intsmap[int] = true;
}
console.log(Object.keys(intsmap));
You can use also use Durstenfeld shuffle after generating number in the given range.
var arr = Array.from({length:1000000}, (_,i) => (i+1));
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
shuffleArray(arr);
console.log(arr);
Just try to shuffle the array of numbers 1 to maxNum
First create an array
var maxNum = 1000000;
var arr = Array(maxNum).fill().map((e,i)=>i+1);
Now shuffle the array
arr.sort(function() {
return .5 - Math.random();
});
Now you have the array of unique random numbers
Demo
var startTime = new Date().getTime();
var maxNum = 1000000;
var arr = Array(maxNum).fill().map((e, i) => i + 1);
arr.sort(function() {
return .5 - Math.random();
});
var endTime = new Date().getTime();
console.log( "Time taken to get " + maxNum + " size random unique number is " + ( endTime - startTime ) + " ms");
I can propose this approach:
generate a random number
cast it to a string (0.1234567812345678)
and extract 6 substrings of length of 10
Code:
var res = {},
s = "";
for (let i=0; i<1000000; ++i) {
s = Math.random().toString();
for (let j=0; j<6; ++j) {
res[s.substring(2+j, 12+j)] = true; // extract 10 digits
}
}
After 1,000,000 iterations, you have computed 6,000,000 numbers with very little collisions (1,800 in average). So you have your 1,000,000 numbers and more in few seconds.
If you need unique big array try to think in other way. Just create range 0 ... 100000 and shuffle it and apply you function that you need for this array.
var acc = 0;
const result = [];
for(var i = 0; i < 100000; i++)
result.push(acc += Math.floor(Math.random() * 10) + 1);
I think the most expensive operation is the hashtable lookup/insertion, so simply do it without it.
One place where you might loose performances is in the Math.random call.
It's a quite expensive call, and you are calling it a huge number of times to generate your strings.
One solution to leverage it is to grab the whole string from a single result of Math.random().
var intsmap = {}
var intsarray = []
var i = 100000
while (i--) {
var int = randominteger(6)
if (intsmap[int]) {
i++
} else {
intsmap[int] = true
intsarray.push(int)
}
}
console.log(intsarray);
// It takes the whole string from a single call to 'random'.
// The maximum length is 16.
function randominteger(length){
return (Math.random() + '').substr(2,length);
}

JavaScript Dynamically created object undefined

I am doing the freecodecamp algorithmic challenge "Caesars Cipher". I have a problem with my code. I try to generate a lookup table as a dynamic object and for some reason it doesn't register. When doing console.log it is says "lookup table is undefined". It is the same with the Acode variable. If I comment out the console.logs then it will work but it will not encrypt anything because of the below part which checks if the char from strArr exists in the lookupTable, if not, it should assign the same value to the encryptedArr (this was done to not encrypt commas, spaces etc):
strArr.forEach(function(thisArg) {
var newValue;
if(lookupTable[thisArg] !== undefined ) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
Ofcourse lookupTable[thisArg] is always undefined.
Here is the whole function with the above part as well:
function rot13(str) { // LBH QVQ VG!
var strArr;
var encryptedArr = [];
var Acode;
var lookupTable = {}; //this object will contain the mapping of letters
var encryptedString;
//check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic
Acode = 'A'.charCodeAt(0);
console.log(Acode);
//generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time)
//this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works
for (i = 0; i < 26; i++) {
lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((Acode + i) - 13) % 26);
console.log(lookupTable[String.fromCharCode(Acode + i)]);
}
//save the string into the array
strArr = str.split("");
//change letters into numbers and save into the code array
strArr.forEach(function(thisArg) {
var newValue;
if (lookupTable[thisArg] !== undefined) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
encryptedString = encryptedArr.join("");
return encryptedString;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
console.log(Acode);
What am I doing wrong with the lookupTable object creation AND with the below?
Acode = 'A'.charCodeAt(0);
There's no undefined variable. The problem with your code is in how you calculate the lookup table entries. Your code is mapping every character to itself, not shifting by 13. The correct formula is
Acode + ((i + 13) % 26)
Acode is the ASCII code for the letter, and you shouldn't be including that when performing the modular shift. You just want to apply the modulus to the offset from the beginning of the alphabet after shifting it by 13.
function rot13(str) { // LBH QVQ VG!
var strArr;
var encryptedArr = [];
var Acode;
var lookupTable = {}; //this object will contain the mapping of letters
var encryptedString;
//check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic
Acode = 'A'.charCodeAt(0);
// console.log(Acode);
//generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time)
//this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works
for (i = 0; i < 26; i++) {
lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((i + 13) % 26));
// console.log(lookupTable[String.fromCharCode(Acode + i)]);
}
//save the string into the array
strArr = str.split("");
//change letters into numbers and save into the code array
strArr.forEach(function(thisArg) {
var newValue;
if (lookupTable[thisArg] !== undefined) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
encryptedString = encryptedArr.join("");
return encryptedString;
}
// Change the inputs below to test
var result = rot13("SERR PBQR PNZC");
console.log(result);

Get max value of similar items in array with Javascript

I have an array like this:
["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"]
and I want to get a final array that will group similar values that changes from each other only by the last numbers of the string ("13rq8", "13rq6", "13rq4", "13rq2", "13rq12", "13rq10"), and return only the biggest values like the example below:
["13dl", "12dl", "13rq12"]
Can you help me please resolve this in Javascript?
Thank You!
Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:
var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};
l.forEach(function(x) {
var m = x.match(/^(.*?)(\d*)$/);
var tag = m[1];
var num = parseInt("0" + m[2]);
if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});
var l2 = [];
for (var tag in tagNum) {
var num = tagNum[tag];
if (num) l2.push(tag + num);
else l2.push(tag);
}
console.log(l2);

Javascript: Example of recursive function using for loops and substring - can't figure out where I'm going wrong

I'm currently working on coderbyte's medium challenge entitled "Permutation Step."
The goal is to take user input, num, and to return the next number greater than num using the same digits So, for example, if user input is 123, then the number 132 should be returned. If user input is 12453, then 12534 should be returned...
Anywho, I have a correct model answer created by someone (probably a genius, cuz this stuff is pretty hard) and I'm trying to figure out how the answer works, line for line by having an example play out (I'm keeping it simple and playing out the function with user input 123).
The answer has 2 functions, but the 1st function used is what I'm currently trying to work out...
The relevant code is:
var PermutationStep1 = function(num) {
var num1 = num.toString();
var ar = [];
//return num1;
if (num1.length < 2) {
return num;
} else {
for(var i = 0; i < num1.length; i++) {
var num2 = num1[i];
var num3 = num1.substr(0,i) + num1.substr(i+1, num1.length -1);
var numAr = PermutationStep1(num3);
for(var j = 0; j < numAr.length; j++) {
ar.push(numAr[j] + num2);
}
}
ar.sort(function(a,b) {return a-b});
return ar;
}
}
Again, I'm trying to work thru this function with the inputted num as 123 (num = 123).
I'm pretty sure that this function should output an array with multiple elements, because the 2nd function merely compares those array elements with the original user input (in our case, 123), and returns the next greatest value.
So in our case, we should probably get an array, named 'ar', returned with a host of 3 digit values. But for some reason, I'm getting an array of 2 digit values. I can't seem to isolate my mistake and where I'm going wrong. Any help with where, specifically, I'm going wrong (whether it be the recursion, the use of substring-method, or the concating of strings together, whatever my problem may be) would be appreciated...
Here's some of my work so far:
PS1(123) / num1 = 123
i = 0;
num2 = (num1[i]) = '1';
num3 = (num1.substr(0, 0) + num1.substr(1, 2)) = ('0' + '23') = '23'
PS1(23)
i = 0;
num2 = '2';
num3 = '3'
PS1(3) -> numAr = 3 (since num1 is less than 2 digits, which is the recursion base case?)
(So take 3 into the 2nd for loop)...
ar.push(numAr[j] + num2) = ar.push('3' + '1') = 31
ar = [31] at this point
And then I go through the initial for-loop a couple more times, where i = 1 and then i = 2, and I eventually get....
ar = [31, 32, 33]...
But I'm thinking I should have something like ar = [131, 132, 133]? I'm not sure where I'm going wrong so please help. Because the answer is correctly spit out by this function, the correct answer being 132.
Note: if you need the 2nd part of the model answer (i.e. the 2nd function), here it is:
var arr = [];
function PermutationStep(num1) {
arr.push(PermutationStep1(num1));
var arrStr = arr.toString();
var arrStrSpl = arrStr.split(",");
//return arrStrSpl;
for(var p = 0; p < arrStrSpl.length; p++) {
if(arrStrSpl[p] > num1) {
return arrStrSpl[p];
}
}
return -1;
}
I'm sorry the first function i posted was under a mathematical logical mistake and i was to overhasty
I thought about it again and now i have the following function which definitley works
function getNextNumber (num)
{
var numberStr=num.toString (), l=numberStr.length, i;
var digits=new Array (), lighterDigits, digitAtWeight;
var weight,lightWeight, lighterDigits_l, value=0;
for (i=l-1;i>-1;i--)
digits.push (parseInt(numberStr.charAt(i)));
lighterDigits=new Array ();
lighterDigits.push (digits[0]);
for (weight=1;weight<l;weight++)
{
digitAtWeight=digits[weight];
lighterDigits_l=lighterDigits.length;
for (lightWeight=0;lightWeight<lighterDigits_l;lightWeight++)
{
if (digitAtWeight<lighterDigits[lightWeight])
{
lighterDigits.unshift (lighterDigits.splice (lightWeight,1,digitAtWeight)[0]);
lighterDigits.reverse ();
digits=lighterDigits.concat (digits.slice (weight+1,l));
for (weight=0;weight>l;weight++)
value+=Math.pow (10,weight)*digits[weight];
return value;
}
}
lighterDigits.push (digitAtWeight);
}
return NaN;
}
okay here is my solution i found it in 20 minutes ;)
//---- num should be a Number Object and not a String
function getNextNumber (num)
{
var numberStr=num.toString (), l=numberStr.length, i;
var digits=new Array (), digitA, digitB;
var weight,lightWeight;
var valueDifference,biggerValue;
for (i=l-1;i>-1;i--)
digits.push (parseInt(numberStr.charAt(i))); // 345 becomes a0=5 a1=4 a2=3 and we can say that num= a0*10^0+ a1*10^1+ a2*10^2, so the index becomes the decimal weight
for (weight=1;weight<l;weight++)
{
digitA=digits[weight];
biggerValue=new Array ();
for (lightWeight=weight-1;lightWeight>-1;lightWeight--)
{
digitB=digits[lightWeight];
if (digitB==digitA) continue;
valueDifference=(digitA-digitB)*(-Math.pow(10,weight)+Math.pow (10,lightWeight));
if (valueDifference>0) biggerValue.push(valueDifference);
}
if (biggerValue.length>0)
{
biggerValue.sort();
return (biggerValue[0]+num);
}
}
}
this is the solution I figured out for the problem without using a recursive function. It's passed all the tests on coderbyte. I am still new to this so using recursion is not the first thing I look for. hope this can help anyone else looking for a solution.
function PermutationStep(num) {
var numArr = (num + '').split('').sort().reverse();
var numJoin = numArr.join('');
for (var i = (num + 1); i <= parseInt(numJoin); i++){
var aaa = (i + '').split('').sort().reverse();
if (aaa.join('') == numJoin){
return i;
}
}
return -1;
}

Adding Pronumerals together in javascript

I want javascript to be able to interpret the following (a and b are always going to be different, so these are just an example)
a=(3x)+y
b=x+(4y)
and return the following
a+b=(4x)+(5y)
all variables are strings and not integers so math can not be applied to a,b,x or y
I have not started on this particular instance, due to the fact that i don't know where to start.
P.S. I have not had any experience with jQuery, so if possible, try and avoid it
EDIT: The program is designed to help find raw materials in the game minecraft. For example if you want a diamond sword (a) and a diamond pickaxe (b), a requires 1 wood (x) and 2 diamonds (y), and b requires 1 wood (x) and 3 diamonds (y). Once i run it through this program, i would like a response saying that it requires 2 wood and 5 diamonds. Sorry for any prior confusion...
First, let's program three little helper functions:
// exprToDict("3x + y") -> {x:3, y:1}
function exprToDict(e) {
var d = {};
e.replace(/(\d+)\s*(\w+)|(\w+)/g, function($0, $1, $2, $3) {
d[$2 || $3] = parseInt($1 || 1);
});
return d;
}
// addDicts({x:1, y:2}, {x:100, y:3}) -> {x:101, y:5}
function addDicts(a, b) {
var d = {};
for(var x in a) d[x] = a[x];
for(var x in b) d[x] = (d[x] || 0) + b[x];
return d;
}
// dictToExpr({x:1, y:2}) -> x + (2 y)
function dictToExpr(d) {
var e = [];
for(var x in d)
if(d[x] == 1)
e.push(x);
else
e.push("(" + d[x] + " " + x + ")");
return e.join(" + ")
}
Once we've got that, we're ready to code the main function:
function addThings(a, b) {
return dictToExpr(
addDicts(
exprToDict(a),
exprToDict(b)
))
}
Let's test it:
sword = "(3 wood) + diamond"
pickaxe = "wood + (2 diamond)"
console.log(addThings(sword, pickaxe))
Result:
(4 wood) + (3 diamond)
In order to process more than two things, modify addDicts to accept arrays:
function addDicts(dicts) {
var sum = {};
dicts.forEach(function(d) {
for(var x in d)
sum[x] = (sum[x] || 0) + d[x];
});
return sum;
}
and rewrite addThings to be:
function addThings(things) {
return dictToExpr(
addDicts(
things.map(exprToDict)));
}
Example:
sword = "(3 wood) + diamond"
pickaxe = "wood + (2 diamond)"
house = "10 wood + iron"
console.log(addThings([sword, pickaxe, house]))
First, parse the input string - according to your grammar - to an object to work with:
function parseLine(input) { // pass a string like "a=(3x)+y"
var parts = input.split("=");
if (parts.length != 2) return alert("Invalid equation");
for (var i=0; i<2; i++) {
var summands = parts[i].split("+");
parts[i] = {};
for (var j=0; j<summands.length; j++) {
summands[j] = summands[j].replace(/^\s*\(?|\)?\s*$/g, "");
var match = summands[j].match(/^(-?\d*\.?\d+)?\s*([a-z]+)$/);
if (!match) return alert("Parse error: "+summands[i]);
var mul = parseFloat(match[1] || 1);
if (match[2] in parts[i])
parts[i][match[2]] += mul;
else
parts[i][match[2]] = mul;
}
}
return parts;
}
// example:
parseLine("a=(3x)+y")
// [{"a":1},{"x":3,"y":1}]
Then, apply an algorithm for solving linear equation systems on it. I leave the implementation of that to you :-)
Wow, you're question has so radically changed that I'll write a completely new answer:
You can just use objects for that. Store the materials needed for the tools in key-value-maps:
var diamondSword = {
diamond: 2,
stick: 1
};
var diamondPickaxe = {
diamond: 3,
stick: 2
};
An addition function is very simple then:
function add() {
var result = {};
for (var i=0; i<arguments.length; i++)
for (var item in arguments[i])
result[item] = (result[item] || 0) + arguments[i][item];
return result;
}
// usage:
add(diamondSword, diamondPickaxe)
// {"diamond":5, "stick":3}

Categories

Resources