How to pass a integer into a javascript function? - javascript

I am getting a response from ajax request(done by jquery).
I have a method that displays errors to the users. Sometimes though I have some other information coming along with the json request.
So I don't want this info shown(where the rest of the errors are). So I figured since I always know the length of the json coming back I can just shorten the length since the error method just uses a while loop so if it is one less then it won't display that json part.
So I did this
var length = result.length -1;
ErrorsMethod(result, length); // call function.
function ErrorsMethod(result, length)
{
while( i < length)
{
// do stuff.
}
}
length is always undefined when it gets passed in though. I don't understand why.
I then tried
length.length
ParseInt(length);
None seems to work. I don't even know what I am working with. When I do an alert of "length" var before it goes into the function it spits out a number.

Were you correctly calling parseInt?
var length = parseInt(result.length) - 1;
ErrorsMethod(result, length);
ErrorsMethod(result, length); // call function.
function ErrorsMethod(result, length)
{
while( i < length)
{
// do stuff.
}
}

ErrorsMethod(result); // call function.
function ErrorsMethod(result)
{
if (result && result.length)
for ( var i = 0 ; i < result.length ; ++i )
{
// do stuff.
}
}

nor result or i are defined variables so thats probably why the script stops executing. try something like this:
<script type="text/javascript">
var result = [10, 2];
var length = result.length;
ErrorsMethod(result, length); // call function.
function ErrorsMethod(result, length)
{
var i=0;
while( i < length)
{
// do stuff.
alert(i);
i++;
}
}
</script>

Related

recursion on returning vectors c++

Hey guys I am trying trying to right this javascript code into c++. I am doing quick sort and everything is straight forward minus the last step.
function quickSort(arr)
{
//base case if the arr is 1 or 0 then return the array
if(arr.length === 1 || arr.length === 0)
{
return arr;
}
var pivotIndex = Math.floor(arr.length/2);
var pivotValue = arr[pivotIndex];
var before = [];
var after = [];
for(var counter = 0; counter < arr.length; counter++)
{
if(counter === pivotIndex)
continue;
if(pivotValue <= arr[counter])
{
before.push(arr[counter])
}
else
{
after.push(arr[counter])
}
}
//this step I am having trouble rewriting in c++
return quickSort(after).concat(pivotValue).concat(quickSort(before));
}
I am having a hard time rewriting the recursive step in c++. I am not sure how concat 2 vector. I tried using the insert method but I keep getting an error about invalid use of void expression.
vector<int> quickSort(vector<int> arr)
{
if(arr.size() == 1 || arr.size() == 0)
{
return arr;
}
int pivotIndex = arr.size()/2;
int pivotValue = arr[pivotIndex];
vector<int> before;
vector<int> after;
//put values in before or after the piv
for(size_t counter = 0; counter < arr.size(); counter++)
{
if(counter == pivotIndex)
continue;
if(pivotValue <= arr[counter])
before.push_back( arr[counter]);
else
after.push_back( arr[counter]);
}
return //????? not sure how to do this
}
So, you realized that your core question was "how to concatenate two vectors", and you found a right answer: using insert. Now your question is about why you were getting "an error about invalid use of void expression." (That's the assumption my answer is for, at least.)
That's because you were likely trying to do something like the following:
return quickSort(after).insert( /* stuff */ );
which is wrong. In JavaScript, array.concat returns the concatenated array. It's return type is effectively Array, and so doing return arr.concat(arr2) returns an Array because arr.concat would return an Array. Further, in JavaScript, array.concat doesn't modify the array it was called on, but rather returns a new array.
In C++, however, vector.insert (#4 in the reference) returns void. That means it returns nothing. So when you try to return the result of insert, you get that error about invalid use of a void expression. Further, in C++, vector.insert does modify the vector it was called on.
So how do you use insert in this case?
vector<int> quickSort(vector<int> arr)
{
// ...
// Sort `before` and `after`
before = quickSort(before);
after = quickSort(after);
// Modify `after` and return it.
after.push_back(pivotValue);
after.insert(after.end(), before.begin(), before.end());
return after;
}
Note: My code isn't optimal and the idea of rewriting JS in C++ is also oddly specific. My answer is to simply outline the problem asked in the question, not to give a good C++ implementation of quick sort.
To concat two vector , you can use std::merge
like:std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dst));

Recursive function that generates the permutations of a string

//====================================================
function getPermutations(str){
//Enclosed data to be used by the internal recursive function permutate():
var permutations = [], //generated permutations stored here
nextWord = [], //next word builds up in here
chars = [] //collection for each recursion level
;
//---------------------
//split words or numbers into an array of characters
if (typeof str === 'string') chars = str.split('');
else if (typeof str === 'number') {
str = str + ""; //convert number to string
chars = str.split('');//convert string into char array
}
//============TWO Declaratives========
permutate(chars);
return permutations;
//===========UNDER THE HOOD===========
function permutate(chars){ //recursive: generates the permutations
if(chars.length === 0)permutations.push(nextWord.join(''));
for (var i=0; i < chars.length; i++){
chars.push(chars.shift()); //rotate the characters
nextWord.push(chars[0]); //use the first char in the array
permutate(chars.slice(1)); //Recurse: array-less-one-char
nextWord.pop(); //clear for nextWord (multiple pops)
}
}
//--------------------------------
}//==============END of getPermutations(str)=============
How is nextWord.pop() getting called multiple times?
Won't permutate(chars.slice(1)); not let nextWord.pop() execute since it will take you back to the top of the permutate function?
Also, when chars becomes empty from calling slice on it permutate(chars.slice(1)); who is populating chars once again? Is chars being populated by nextWord.pop(); since pop is returning the value to the permutate function?
Stepping through this code in chrome debugger it wasnt clear.
Recursive call permutate is inside a loop and each time it is executed it is put on the call stack. The nextWord.pop is called multiple times to finish executing each of the recursive calls on the stack. You can visualize the recursion with this tool http://visualgo.net/recursion.html. If you have a tool such as Webstorm, you can run it in the debugger to see that there are three permutate() calls in the stack when the first time nextWord.pop is called.
It would execute after premutate() returns. But I guess that's obvious from looking at the code. I think your question is how can premutate ever reutrn? The answer to that is to look at the for loop.
Since we're calling premutate() with one fewer character every time. It makes sense that at some point one of our calls to premutate() will be called with an empty array:
premutate([]); // happens when chars.slice(1) gives us an empty array
Now, let's see what happens when that happens:
function permutate(chars){
// The following gets executed:
if(chars.length === 0)permutations.push(nextWord.join(''));
// This for loop is skipped because 0 < 0 is false
for (var i=0; i < chars.length; i++){/*...*/}
// we return because we skipped the for loop
}
Now that the base-case have returned, all the other calls to premutate() also returns:
function permutate(chars){
if(chars.length === 0)permutations.push(nextWord.join(''));
for (var i=0; i < chars.length; i++){
chars.push(chars.shift());
nextWord.push(chars[0]);
permutate(chars.slice(1)); // This have returned..
nextWord.pop(); // so execute this line
}
// and return so that other calls to us can also execute pop()
}
chars.slice(1) is the character array chars starting at position 1, i.e. the second character, so calling permutate(chars.slice(1)); recurses with 1 fewer characters.
Eventually, chars.slice(1) will return zero characters, at which point permutations.push(nextWord.join('')); is executed and for (var i=0; i < chars.length; i++) will not execute the loop block inside because its terminating condition i < chars.length will already be false when the initial value of i is 0 and chars.length is also zero.
So the terminating condition of this recursive function is when it runs out of characters in the current word.
When the the permutate function finally returns, nextWord.pop() is called once for each time permutate was called.
Calling permutate will not reset you at the top of permutate. (as was mentioned by joe) It will simply wait for this child call to complete and then continue executing the method.
I think your recursive permutate could be simplified:
// suppose input = "abc"
permutate(chars) {
if(chars.length === 2) return [chars, chars[0] + chars[1]};
var arr = permutate(chars.slice(1)) // returns ["bc", "cb"]
var out = []
for (var i=0; i < arr.length; i++) {
for (var j = 0; j < chars.length - 1; ++j) {
out.push(arr[i].split(0,j) + chars[0] + arr[i].split(j)) // "a" gets inserted at every possible position in each string
}
}
// result here is ["abc", "bac", "bca", "acb", "cab", "cba"]
return out
}
function permutate(left, used, result) {
// If there are no more characters left to permute
if (0 == left.length) {
result.push(used);
}
// Iterate over all characters in the 'left' string
for (var i = 0; i < left.length; ++i) {
// Read the character we are going to work with in this iteration
var iObject = left[i];
// Create a new_left string that contains all the characters
// of the 'left' string without the one we are going to use now
var new_left = '';
for (j = 0; j < left.length; ++j) {
if (j != so.i) new_left += so.left[j];
}
// Create a new_used string that has all the characters of 'used'
// plus the one we are going to use now
var new_used = so.used + iObject;
// Call permute with new_left and new_used strings
permutate(new_left, new_used, result);
}
}
To run the function on some string you need to call it like this:
permutate('abcd', '', []);
For those who doesn't get this because of the recursion involved I found a page that illustrates the algorithm flow using interactive animations.
http://learntocode.guru/code/generate-permutations-recursively-string
Just click play and observe the variables change while the permutation function keeps calling itself. Also observe when a new permutation has been found and when it's added to the resulting permutations array.

Simple Looping In Java Script

I made a simple loop and would like to know how to carry this out.
The variable's name is Math, and it is equal to 4. I am trying to write a simple looping statement that says: "While Math is not equal to 4, await your number"
Here is the code I have so far:
var math = 2+2;
var loop = function(){
for(var i=0; i < 5; i++)
{
while (math[i] != 4)
{
console.log ("Await until you reach 4");
}
}
};
loop();
The following code will do what you presumably want:
var math = 2+2;
var loop = function(){
var i = 0;
while (i !== math) {
i++;
console.log ("Await until you reach 4");
}
}
loop();
Note that technically, the for loop in javascript (as well as in many other languages) actually is not that much different from a while loop, as the code for initialization, increment and termination is rather unrestricted. You are not even forced to have an iteration variable in you for loop.
The difference is in someone else's ease of understanding of your code (or your's after you haven't looked into you code for some time). for suggests a counted iteration of a list, while some operations to be performed while (sic!) a condition is fulfilled without which the operation make no sense or produce the wrong result.
This concept will create an endless loop, that waits for something to edit the variable.
As javascript occupies the thread its running in, all events will be waiting for this endless loop to end.
If it's part of the main GUI thread, (normal javascript) this means that your page will hang. Only use this method for webworkers, or extensions.
Instead redesign as eventhandlers, instead of a main loop
edit: having read your comments, and found out what you are trying to do:
var math = 2+2;
for(var i = 0; i < 5; i++){
if(i != math){
console.log ("Await until you reach 4");
continue
}
alert("yay")
}
or with a while loop
var math = 2+2;
var i = 0;
while(math != i){
if(i != math){
console.log ("Await until you reach 4");
}
i++;
}
alert("yay")
Maybe this is what you are trying to do:
var math = 2+2;
var loop = function(){
for(var i=0; i < 5; i++){
if(i != math){
console.log ("Await until you reach 4");
}else{
console.log("You have reached 4");
}
};
loop();
Using while
var math = 2+2;
var loop = function(){
var i=0;
while(i != math){
console.log ("Await until you reach 4");
i++;
}
};
loop();
var loop = function(math){
var i = 0;
while(i!==math){
console.log ("Await until you reach 4");
i++;
}
}
loop(2+2);

Javascript : How can I add X elements to an array

I need to create an array including the first 100 prime numbers, here is my code:
var premier= [];
var nombre= premier.length;
function isPrime(n)
{
if(n < 2)
{
return false;
}
for(i=2; i<Math.sqrt(n); i++)
{
if(n%i===0)
{
return false;
}
}
return true
};
while(nombre<100)
{
var j=2
if(isPrime(j)==true)
{
premier.push(j);
}
j=j+1
}
I am a beginner in Javascript, but I have tested the isPrime function and it works fine even forlarge numbers.
but when I run the program I have:
FATAL ERROR: JS Allocation failed - process out of memory
I think this part is wrong:
while(nombre<100)
{
var j=2
if(isPrime(j)=true)
{
premier.push(j);
}
j=j+1
}
console.log(premier)
But I can't tell why
You are repeatedly setting j=2 every time the loop runs, and you never change nombre so the loop will never end. Note that JavaScript sets literal vaues by value, not by reference, so nombre = premier.length won't magically update.
Additionally, statements of the form if( x = true) will set x to true, and then pass the condition automatically. In this case, since x is a function call, it is invalid syntax.
Did you mean this?
var j = 2;
while(premier.length < 100) {
if( isPrime(j)) premier.push(j);
j++;
}

How do I correctly use an iteration value in JavaScript?

I am creating a 'simple' javaScript function which basically displays new information on the page when a user clicks next or previous.
The information is taken from an array and I want to use either i++ or i-- to call an element of the array.
Heres my JavaScript:
var titles = ["Dundalk", "Navan", "Drogheda", "Dublin"];
var i = 0;
function next()
{
i++;
if (i == titles.length)
{
i = 0;
}
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
function prev()
{
if (i == 0)
{
i = titles.length;
}
i--;
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
The problem is, when I run this code in my HTML page, I get an 'UNDEFINED' result. The JavaScript is not recognizing that i has been initialized as 0 in the beginning.
If i change titles[i] to titles[2], for example, the correct text is displayed in HTML.
What am I forgetting or how can I overcome this?
Thanks
The fact that you're seeing undefined indicates that you're accessing an array index which hasn't been set. Your code looks fine at a glance, so I would guess that there's some more code you're not showing which also uses i as a loop variable and leaves it set to a value > titles.length after the code above has run.

Categories