Samstag, 14. Mai 2016

Javascript Beginner's Array Exercises: Evaluate the existance of a specific element in an array

Now we search a specific array element an array of integers. The element we search for is stored in the variable V.
In Javascript, there is a function that provides just that functionality: indexOf. indexOf returns the index of the searched for element. If the array does not contain the element, indexOf would return -1. For more information, see: http://www.w3schools.com/jsref/jsref_indexof_array.asp

However, the task is to get used to traverse and work with arrays. So in this video we won't use indexOf, but we will search for the array element manually.



Here is the relevant source code:

var arNums = [76,42,2,3,5,6,2,56,777,9,0,5,2,56,1];
var V = 716;

var foundV = false;
for(let i = 0; i < arNums.length && foundV==false; i++) {
  if(arNums[i] == V) {
    foundV = true;
  }
}


You can also check for the existance of the element using indexOf like this:

if (arNums.indexOf(V) > -1) {
   foundV = true;
} else {
   foundV = false;
}

You can even abbreviate that 5 lines above like this:

foundV = (arNums.indexOf(V) > -1);

Why does this work? arNums.indexOf(V) > -1 is an expression that yields true or false, which is just what we want the variable foundV to contain. So we can write the result of that expression directly in our variable.

Donnerstag, 12. Mai 2016

Javascript Beginner's Array Exercises: Finding elements in an array

In this video about arrays in Javascript we find the number of integer elements in an array that are >= 10.




Here is the important part of the source code:

// 1: Given an integer array: The program must compute and write how many integers are greater than or equal to 10.

var arNums = [76,42,2,3,5,6,2,56,777,9,0,5,2,56,1];

var intsGTE10 = 0;
for(let i = 0; i < arNums.length; i++) {
  if(arNums[i] >= 10) {
    intsGTE10++;
  }
}

Find more of these exerciseson (with solutions in C++) in wikibooks: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Exercises/Static_arrays/Pages

Montag, 2. Mai 2016

Boost the performance of your JavaScript code using memoization

Memoization is a technique to cache function results in programming languages with certain functional features like JavaScript. It's known since the late 60s but you have to do a bunch of tricks to get memoization working in most of the popular languages in the last few decades. However, with the great popularity of languages like JavaScript or Python and with new features in the more "traditional" languages, memoization becomes available to a broad of computer programmers.

In this video I give an overview about writing a memoizer for a function that takes 1 argument. If you understand this basic principle, you can build even more powerful and versatile memoizers that can handle functions with one or more arguments. For an example, see this article on the Hexacta blog.