Pages

Sunday, December 26, 2021

How to find Max Consecutive Ones?


We are given an array with binary values named nums, this will return the max consecutive ones.  

In order to solve this problem I am going to be using JavaScript.

As an example, the first array to be executed will be:

nums: [1,1,0,1,1,1] which will return the value: 3. 

 

The following is the code to solve this problem: 

var findMaxConsecutiveOnes = function(nums) {
    let c = 0;
    let l1 = 0;
    let l2 = 0;
    let largest = 0;

    for (let i=0; i<nums.length; i++) {
        
        if (nums[i] === 1) {
            c++;
        }  
        
        if (nums[i] === 0 || i === (nums.length - 1)) {
            
            if (l1 !== 0 && l2 < l1) {
                l2 = l1;
            }
            
            l1 = c;
            c = 0;  
 
            if (l1 > l2) {
                largest = l1;
            } else {
                largest = l2;
            }
        }
        
    }

    console.log(largest);
    return largest;
    
};


Now, I am going to explain the code:

var findMaxConsecutiveOnes = function(nums) {
    let c = 0;
    let l1 = 0;
    let l2 = 0;
    let largest = 0;

};

First, we declare the function "findMaxConsecutiveOnes" e ititialize the variables c, l1, l2, and largest equal to 0. 

 

var findMaxConsecutiveOnes = function(nums) {
    let c = 0;
    let l1 = 0;
    let l2 = 0;
    let largest = 0;

    for (let i=0; i<nums.length; i++) {
        
        if (nums[i] === 1) {
            c++;
        }  

};

Then we need to iterate through each element on the array nums. In orde to do this we utilize a for loop. At the same time, every time the index "i" is equal to 1 we'll increment the value of variable "c" by one.

 

var findMaxConsecutiveOnes = function(nums) {
    let c = 0;
    let l1 = 0;
    let l2 = 0;
    let largest = 0;

    for (let i=0; i<nums.length; i++) {
        
        if (nums[i] === 1) {
            c++;
        }  
        
        if (nums[i] === 0 || i === (nums.length - 1)) {
           
l1 = c;
            c = 0;

        }
};

Now we ask: if index "i" is equal to 0, or index "i" indicates the end of the array then we should set the value of "l1" equal to the value of the accumulator variable "c". Then we reset the variable "c" to 0. 

 

var findMaxConsecutiveOnes = function(nums) {
    let c = 0;
    let l1 = 0;
    let l2 = 0;
    let largest = 0;

    for (let i=0; i<nums.length; i++) {
        
        if (nums[i] === 1) {
            c++;
        }  
        
        if (nums[i] === 0 || i === (nums.length - 1)) {
            
            if (l1 !== 0 && l2 < l1) {
                l2 = l1;
            }
            
            l1 = c;
            c = 0; 
        } 
    }

};

Let's say the max consecutive ones in the array id equal to 2 and then we find that there is a new value, higher of consecutibe ones, then we should replace this value as the new max. In order to do this we inquiere whether the variable "l1" is not equal to 0 and also if "l1" is greater that "l2", then "l2" would be the value of "l1". 

 

var findMaxConsecutiveOnes = function(nums) {
    let c = 0;
    let l1 = 0;
    let l2 = 0;
    let largest = 0;

    for (let i=0; i<nums.length; i++) {
        
        if (nums[i] === 1) {
            c++;
        }  
        
        if (nums[i] === 0 || i === (nums.length - 1)) {
            
            if (l1 !== 0 && l2 < l1) {
                l2 = l1;
            }
            
            l1 = c;
            c = 0;  
 
            if (l1 > l2) {
                largest = l1;
            } else {
                largest = l2;
            }
        }
        
    }

    console.log(largest);
    return largest;
    
};

Finally, we figure out if the max consecutive ones of the newest found value "l1" is greater than the previous max value "l2". Then, we assign "l1" to "largest"; otherwise, "largest" will be equal to "l2". We the proceed to return the value of "largest", which will give us the final answer.

 

 

 


Sunday, December 19, 2021

Comparing JavaScript with CSS-based Web Animations

 

Web applications are sometimes equipped with animations. Some animations are
event driven, such as when the user hovers over a button and this progressively
expands its size, or they can simply happen without any user interaction, as an example
a flickering square figure on the screen. Animations provide visual effects to web
applications to make them more engaging and visually appealing. Some applications
are more suited for certain elements to be animated than others, as in the case of
interactive games.


There are different ways on which these visual effects can be achieved on the web. I am going to analyze the JavaScript and CSS web animation approaches.
Which method is more efficient, and under which circumstances? Which one is easier to
write and maintain?


In the past Flash was very popular for creating animated applications; however, as
demand became more targeted toward mobile devices, animation performance became
highly important and Flash did not offer the best capabilities, which ultimately made it
obsolete. Some JavaScript libraries came out, such as jQuery which offers easy to write
JavaScript animations. Nevertheless, as convenient as jQuery was for developers it
also felt short on achieving high animation performance [3]. As CSS3 came out there
was a better solution for animations that did not imply installing any external library to
our project, and therefore was a promise for more efficient animations.


There are two different ways in which CSS can be used to create animations. These are
CSS transitions and animations properties:


CSS transitions: display animations between two states. These could be for example,
animating a button between its resting state and a hover. The button could display a
fading effect while the user tries to select this button. CSS transitions have different
properties that define the targeted animation property, the animation duration, easing
effect, and delay. Both duration and delay are measured in seconds.
CSS animations: assigns animations between a set of start and end properties. This
consists of keyframes for the progression of the animations and styling for the
appearance of it [2].


Both are programmed in different ways but also share similar shortcomings. CSS
animations do not allow great interaction between the programmer/user and the
animation. For example, there is no way to find a particular keyframe on a CSS
animation, also once the animation has started it can not be reversed at any or to any
particular point. Aside from this, only some browsers allow the user to pause and
resume a CSS animation. When it comes to relative values CSS animations do not offer
great flexibility either, meaning that if the programmer would like to instruct the animated
element to move 50px to the right of where the animations starts, it would not be
possible to do merely utilizing CSS animations [3].


Another popular alternative to animate web application elements is by using
JavaScript. As previously mentioned, there are certain JavaScript libraries that can be
used to produce animations by simplifying the task for developers. jQuery made an
attempt to achieve this but felt short in performance. Another library alternative would be
GSAP (GreenSock Animation Platform) which was built specifically to create animations
for the web, taking optimization and efficiency into account for these tasks [3].
However, there is a more standard approach to creating JavaScript animations, and this
is the Web Animations API which works by targeting DOM elements [6].
JavaScript provides certain functionalities not possible utilizing CSS animations such
as the possibility to pause, resume, stop, slow down, and reverse an animation. The
ability for the user to have certain control over the animation is what makes an
application truly interactive, a feature not possible using CSS [3]. JavaScript animations
can also make use of objects, which makes it possible to integrate Object Oriented
Programming to our animations, allowing more complex designs to be developed.
Another advantage of JavaScript over CSS animations is being able to animate other
objects other than DOM elements [2].


Aside from interactivity and ease of development there is another, more important
aspect when comparing two programming methods. This is performance. First we are
going to discuss which properties and components are least and most expensive to
animate. The cheapest properties for browsers to animate are: position, scale, rotation,
and opacity [4]. Now, the most expensive properties to animate are those that change
the entire layout of the page along with them, as well as painting on the screen. For
example, if we have a web page element with width and height measured in percentage
next to other elements, changing these properties constantly will cause the surrounding
elements to also recalculate their values, making this a highly expensive task. These
performance issues can be attributed to both types of JavaScript and CSS of
animations.


When it comes to threading CSS animations, as well as JavaScript Web Animations
are run in a thread called “compositor thread”. This thread is different from the thread
where the browser makes most of the work regarding styling, layout, painting, and
JavaScript execution. The name of this thread is “main thread”. The fact that there is a
separate thread for CSS and Web Animations to execute means that they will run
independently from the workload the browser is carrying from other highly consuming
tasks. This makes CSS and JavaScript based animations perform equally well in that
sense [2]. Another advantage that makes CSS and JavaScript animations run smoothly
is the advantage both take of hardware. GPU layering allows the isolation of animated
elements which in turns makes it easy for the GPU to move those layers around and
compose them later on. However, in order for JavaScript to take advantage of this GPU
layering advantage it needs to make use of 3D transformations and matrices. The only
downside of GPU layering would be a small delay when starting out both applications
because of the browser layer’s calculation and uploading to GPU time [3].

In conclusion, both JavaScript and CSS-based animations perform relatively and
almost equally well when JavaScript is well optimized. The decision to choose one over
the other has more to do with flexibility and the complexity of the animation that wants to
be achieved. For smaller, simpler projects it recommended to use CSS animations.
They come with the advantage of being easier to write. For more complex animations
that require pause, stop, resume, and slow down JavaScript animations are necessary.
The Web Animations API is the go-to for JavaScript animations development; however,
there are other high performing animation libraries such as GSAP.


References:
[1] https://developers.google.com/web/fundamentals/design-and-ux/animations/css-vs-javascript
Updated 2019
[2]https://developers.google.com/web/fundamentals/design-and-ux/animations/animations-andperformance#
css-vs-javascript-performance Updated 2019
[3] https://css-tricks.com/myth-busting-css-animations-vs-javascript/ 2014 - Updated 2017
[4] https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/

Sunday, May 3, 2020

Reverse a String using Recursion



First of all. What is recursion?

Recursion is the process where a function calls itself. The solution of recursion problems depend on the solution of smaller instances of the same problem.

Steps for recursion

Step 1. Have a precise spec.
Step 2. Check that the method works in the base case(s).
Step 3. Look at the recursive case(s).  In your mind replace each recursive call by what it does according to the spec and verify correctness.
Step 4. No recursion problem should be infinite. Make sure that the arguments of recursive calls are in some sense smaller than the parts of the method.

I am now going to discuss how to solve the problem of inverting a String using recursion. This same problem could easily be solve using a loop. However, on this case I am going to do the same thing but with the method of recursion.

1. First we create a function called: "reverseString", which is going to have "str" as an argument.

function reverseString(str) {
}

2. We need to know the length of the String and assign it to a variable.

function reverseString(str) {
    let sLen = str.length;
}


3. The logic of the recursive functions requires that we call the function "reverseString()" as many times as necessary, knowing that everytime we call the function the argument: "str" is going to smaller and smaller.

If every time we call the function "reverseString()" we want that the input becomes smaller then the base case would be when the String's length be less or equal to 0. Therefore:

function reverseString(str) {
    let sLen = str.length;
    if (sLen <= 0) {
        return '';
    }
}

When we have call the function multiple times until exhaust the Strings's length we then should return an empty String.

4. The most important part of recursive functions is calling themselves. On this case, to revert a String we should first use the "chatAt()" method to get the last character of our input String and concatenate it with the result of our invoked recursive function. Because we want the String to be deleting the character that we will be adding from the back to the beginning, the input is going to be decreasing. We use the method "substring" to achieve this. This way our final code will look something like:


function reverseString(str) {
    let sLen = str.length;
    if (sLen <= 0) {
        return '';
    } else {
        console.log(str.length - 1);
        return str.charAt(sLen - 1) + reverseString(str.substring(0, sLen -1));
    }
}


Saturday, May 2, 2020

How to find the second largest element in an array



In order to solve this problem I am going to use JavaScript. This problem is going to find the second largest element inside an array.

First we declare a variable named: "arr" which is going to contain the values we are going to compare.

let arr = [ 8, 6, 4, 12, 10, 2 ];

Then we declare the function "secondLargest" passing the array "arr" as a paramether.


let arr = [ 8, 6, 4, 12, 10, 2 ];

function secondLargest(arr) {
}

We can start off by declaring two variables largest and seclargest, and  initialize then to zero.


let arr = [ 8, 6, 4, 12, 10, 2 ];

function secondLargest(arr) {

    let largest = 0;
    let seclargest = 0;
}


Now we should compare all the elements within the array to figure out the second largest. In order to do that we need to first find out the largest element. We are going to use a for loop to iterate through the array and compare the values with a if statement.

let arr = [ 8, 6, 4, 12, 10, 2 ];

function secondLargest(arr) {
    let largest = 0;
    let seclargest = 0;

    for (let i = 0; i < arr.length; i++) {  
        if (arr[i] > largest) {
            largest = arr[i];
        }
    }
}


In the code above, "if (arr[i] > largest)" is going to compare whether the value of "arr[i]"is greater than the value of the "largest" variable. When the for loop compares the value "8" for the first time "8" is larger than "0" which would be the current value of the "largest" variable; therefore, the value of the variable "largest" now is going to be equals to "8".

When the for loop compares the second value of "6" then it would ask: 6 > 8, being the result false, then we should say that 8 is still the largest value and 6 will become the second largest value. In order to accomplish this we add an else statement and utilize the variable "seclargest".


let arr = [ 8, 6, 4, 12, 10, 2 ];

function secondLargest(arr) {
    let largest = 0;
    let seclargest = 0;

    for (let i = 0; i < arr.length; i++) {  
        if (arr[i] > largest) {
            largest = arr[i];
        } else {
             if (arr[i] > seclargest) {
                seclargest= arr[i];
             }
         }

    }
}


Now, when the for loop compares the value of "4" then it would ask: 4 > 8, (8 still is the greatest value) this would also be false, therefore the code will jump to the else statement and ask again: 4 > 6, (6 still being the second largest value), this will also be false; therefore, the value of both variable will continue to be the same.


When comparing 12 > 8, this will be true, now the value of the "largest" variable is equals to 12. What would happen if the value 8 which now would be the second largest number? We can solve this simply by making the "secLargest" variable equals to the former "largest" value.



let arr = [ 8, 6, 4, 12, 10, 2 ];

function secondLargest(arr) {
    let largest = 0;
    let seclargest = 0;

    for (let i = 0; i < arr.length; i++) {  
        if (arr[i] > largest) {
            seclargest = largest;
            largest = arr[i];
        } else {
             if (arr[i] > seclargest) {
                seclargest= arr[i];
             }
         }

    }
}


Finally we print the final value of the "secLargest" variable and call the function.


let arr = [ 8, 6, 4, 12, 10, 2 ];
function secondLargest(arr) {
    let largest = 0;
    let seclargest = 0;

    for (let i = 0; i < arr.length; i++) {
    
        if (arr[i] > largest) {
            seclargest = largest;
            largest = arr[i];
        }
         else {

             if (arr[i] > seclargest) {
                seclargest = arr[i];
             }
         }
    }
     console.log(largest);
     console.log(seclargest);
}

secondLargest(arr);



The second largest value here would be 10. 

Sunday, January 26, 2020

Java: Count the number of blank characters in a given string

The following code is going to print a message with the number of white spaces in a given sentence.



First, we need to write the name of the procedure: countWhiteSpaces


public static void countWhiteSpaces() {

}


The above procedure is static because only one copy of the object is needed.

Then, we need Scanner, in order for the user to be able to write the sentence on the screen. We will also print indications for the user.

Scanner kb = new Scanner(System.in);
System.out.println("Enter a sentence...");

The kb variable will hold the sentence the user is going to type. We store this information into the String called sentence.

String sentence = kb.nextLine();

We need to count the figure out the length of the sentence, for that we user the .lenght() property.

int senLen = sentence.length();

Also, a variable needs to be initialized for counting the number of white spaces.

int blankSpaces = 0;

In order to check and count the number of white spaces in a sentence we will use a for loop. This is going to start in 0 and will iterate until the length of the sentence. The if statement is going to check whether each character is an empty space or not, and then increase the blankSpace variable.

for (int i = 0; i < senLen; i++) {
     if (sentence.charAt(i) == ' ') {
            blankSpaces++;
     }
}


Finally, we are going to print the result

System.out.println("The number of white spaces in your sentence is: " + blankSpaces);




The final code is going to look like this:


import java.util.Scanner;

public class couSpaces {

public static void main(String[] args) {
// TODO Auto-generated method stub
countWhiteSpaces();
}

public static void countWhiteSpaces() {

Scanner kb = new Scanner(System.in);
System.out.println("Enter a sentence...");

String sentence = kb.nextLine();
int senLen = sentence.length();
int blankSpaces = 0;

for (int i = 0; i <  senLen; i++) {

if (sentence.charAt(i) == ' ') {
blankSpaces++;
}

}

System.out.println("The number of white spaces in your sentence is: " + blankSpaces);
}

}

Saturday, June 3, 2017

Python: Determine whether a graph has an Euler circuit, Euler path or neither

Given the set of vertices and vertex pairs associated to the edges of a directed graph, find the in-degree and out-degree of each vertex, and state whether the graph has Euler circuit, Euler path, or not.

Example of an input (from keyboard):
Set of vertices: a,b,c
Edges: (a,b), (a,c), (b,a),(b,c)

We are giving the solution using Python:

def EulerCPN():
    print("Enter every input separated by comma (,) \n")
    print("Ex: \nSet of vertices: a,b,c \nEdges: (a,b),(a,c),(b,a),(b,c) \n")

    sov = input("Set of vertices: ")  # Get vertices letter from input
    Ssov = sov.split(",")       # Splitting vertices from input delimited from commas and putting them into array

    edg = input("Edges: ")
    edg1 = edg.replace(",", "")     # Deleting all commas (,) from the input edges
    edg2 = edg1.replace("(", "")    # Deleting all open parenthesis from the input edges
    edg3 = edg2.replace(")", "")    # Deleting all closing parenthesis from the input edges
 
    outdeg = []     # Creating empty out-degree list
    indeg = []      # Creating empty in-degree list

    odCounter = 0   # Declaring out-degree counter equal to 0
    idCounter = 0   # Declaring in-degree counter equal to 0

    equalDegrees = 0     # Variable to accumulate whenever degrees in and out are equal
    notEqualDegrees = 0

    EPEequalDegrees = 0  # Variable to accumulate every even vertex
    EPOequalDegrees = 0

    ECreason = 0        # Variable for the reason of not having an Euler Circuit reason
    EPreason = 0        # Variable for the reason of not having an Euler Path reason


    eulerPath = False
    ep1 = 0
    ep2 = 0

    eulerCircuit = False
    ec = 0

    forCounter = 0

    for j in Ssov:  ## Iterate through each vertex

        ## See if vertex if equal to out-degree

        ## Out-degree
        for i in range(0, len(edg3), 2):
            op, code = edg3[i:i+2]  ## Get edges 2 by 2 from the edges list and assigning the first letter to op and the second to code
                                    ## op will compare out-degree. code will compare in-degree

            if j == op:  ## If the current vertex is equal to the first out-degree occurrence ads to the counter
                odCounter = odCounter + 1  ## Add an out-degree to a vertex

        outdeg.append(odCounter)  ## Add the amount of out-degree occurrences for a vertex into outdeg list
        odCounter = 0; ## Set odCounter equals to 0

        ## In-degree
        ## Repeat all steps from Out-degree into in-degree
        for i in range(0, len(edg3), 2):
            op, code = edg3[i:i+2]

         
            if j == code:
                odCounter = odCounter + 1

        indeg.append(odCounter)
        odCounter = 0;

    for j,o,i in zip(Ssov,outdeg,indeg):
        print(str('deg-('),j,str(')= '),o, str(', deg+('),j,str(')= '),i,  str('\n')) # Printing the values for every vertex letter and corresponding in and out degrees


    ## Check for Euler circuit
     
        if (o == i):
            equalDegrees = equalDegrees + 1 ## Everytime an out-degree and in-degree vertex are equal add to the counter
        else:
            notEqualDegrees = notEqualDegrees + 1   ## Everytime an out-degree and in-degree vertex are not equal add to the counter
         
        if (notEqualDegrees == 0): ## If the vertices where never not equal then we have an Euler Circuit
            eulerCircuit = True
        else:
            eulerCircuit = False
            ECreason = 2
         

    ## Check for Euler Path
        if ((o-i) == 1):
            ep1 = ep1 + 1

        if ((i-o) == 1):
            ep2 = ep2 + 1
     

        ## Check that every other vertex have in-degree = to out-degree
        ## When even
        if ((forCounter%2) == 0):
            if (o == i):
                EPEequalDegrees = EPEequalDegrees + 1
        else:
            if (o == i):
                EPOequalDegrees = EPOequalDegrees + 1
        forCounter = forCounter +1

    ## End for


 
    if (EPEequalDegrees >= 1 or EPOequalDegrees >= 1):
        if (ep1 == 1 and ep2 == 1):
            eulerPath = True
        else:
            eulerPath = False
            EPreason = 1
    else:
        EPreason = 2

 
    print(str('Euler Circuit: '),eulerCircuit)
    print(str('Euler Path: '),eulerPath)

    if (eulerCircuit == True):
        print("The graph has an Euler Circuit")
    else:
        if (ECreason == 2):
            print("The graph doesn't have an Euler circuit because the In-degree and out-degree of every vertex is not the same")

    if (eulerPath == True):
        print("The graph has an Euler Path")
    else:
        if (EPreason == 1):
            print("The graph doesn't have an Euler path because neither at most one vertex has (out-degree) − (in-degree) = 1, nor it has at most one vertex has (in-degree) − (out-degree) = 1")
        elif(EPreason == 2):
            print("The graph doesn't have an Euler path because every other vertex doesn't have in-degree = out-degree")


EulerCPN()






Thursday, August 18, 2016

Java: sum of the first N positive odd integer numbers

Write a fragment of code that will compute the sum of the first n positive
odd integers. For example, if n is 5, you should compute 1 +3 + 5 +7 + 9.

For doing so write the following code:


public static void sumNPositiveOddIntegers() {
 System.out.println("Escriba un numero entero...");
 Scanner kb = new Scanner(System.in);
 int n = kb.nextInt();

 int x = 1;
 int sum = 0;
 for (int i = 0; i < n; i++)
 {
  sum += x;
  x += 2;
  System.out.println(x);
 }
 System.out.println("The sum of first " + n + " positive odd integers is: " + sum);

}


Code explanation:

public static void sumNPositiveOddIntegers(): As we are printing the result we use void.

Scanner kb = new Scanner(System.in): Here we declare the variable kb with the method Scanner in order to read from the keyboard.

int n = kb.nextInt(): Assign to the variable n the integer value from the keyboard.

 int x = 1, sum = 0: Initialize the variables x and sum.

 for(int i = 0; i < n; i++): This loop initializes the variable I with value 0. Then it states: while i is less than n, then the i's variable value will be increasing.

sum += x: the variable sum will be storing the value of x during the loop.

x += 2: x will be increasing in pairs in order to sort the odd numbers. That's way we initialize it with value 1.

System.out.println(x): Prints out the x's value that will be the positive odd integer numbers.

Finally, the last line of code will print the sum of the previous numbers.