Pages

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);
}

}