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

}

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.







PHP: Reverse words

This program is going to read sentences from an archive and then reverse the order of the sentence written on it. Create an archive called input.txt where you will write different sentences and a PHP file index.php were you will write the following code:


<?php
$fh = fopen("input.txt", "r");
while (!feof($fh)) {
 
$test = trim(fgets($fh));
 echo (nl2br(reversed($test) . "\n"));
     if (empty($test) == true) {
            break;      
    }
}
function reversed($test) {

$words = explode(" ", $test);
$reversed = array_reverse($words);
return $testResult = implode(" ", $reversed);
}
fclose($fh);
?>

The above code is going to give you the following results:

Input
Hello world!

Output
world! Hello


Saturday, June 18, 2016

Java: Calculate if a number is divisible by another number

A number x is divisible by y if the remainder after the division is zero. Write
a program that tests whether one number is divisible by another number. Reads both numbers from the keyboard.

public static void divisible() {

            Scanner kb = new Scanner(System.in);
            System.out.println("Enter the value of x...");
            int x = kb.nextInt();
            System.out.println("Enter the value of y...");
            int y = kb.nextInt();

            if (x % y == 0) {

                  System.out.println(x + " is divisible by " + y);

            } else {

                  System.out.println(x + " is not divisible by " + y);
            }


      }


Code explanation:

public static void divisible(): Here the void we use void method because it won't return, but print a result. 
Scanner kb = new Scanner(System.in): In this program we're going to read two integers from the keyboard. Scanner is used with this objetive. Note: In order to utilize Scanner we need to import the Scanner library. We must include the following line of code:  import java.util.Scanner.

System.out.println("Entrar un numero x..."): System.out.println prints a message though the console. In this case to give instructions to the user. 

int x = kb.nextInt(): Here we declare the variable x as an int, which is equals to the variable kb that we declared in Scanner.  nextInt() means it is going to take the next Integer value the user enter through the keyboard and is going to be stored at the variable x.

Then we repeat the code for variable y.

if (x % y == 0): In order to get the remainder from the division between two numbers we use the Mod method. In Java it is represented by the percentage sign (%).

The rest of the code prints if either x is divisible by y or no.