Skip to main content

API Documentation Overview

 In this blog, we will explore an example of API documentation for one example function findNeedles().

findNeedles()

Overview

The purpose of the findNeedles() API takes two string parameters i.e. needles array and haystack and finds the total number of occurrences of each element in the needles array that are present in the haystack string.

This function searches for only five words or less from the needles array and logs an error if more words are available in the needles array.

The comparison is done by first splitting the haystack string using literals like backspace, tab space, single quote, and double quote etc into single elements and then looping over the needles array to find occurrences of these elements.

Parameters

This function takes following parameters:

Name

Type

Description

haystack

String

A string of any length

needles

String Array

An array of words  

 

Sample Code

public static void findNeedles(String haystack, String[] needles)

 {

      if (needles.length > 5)

     {

System.err.println("Too many words!");

      } else

     {

int[] countArray = new int[needles.length];

for (int i = 0; i < needles.length; i++)

          {

String[] words = haystack.split("[ \"\'\t\n\b\f\r]", 0);

              for (int j = 0; j < words.length; j++)

          {

if (words[j].compareTo (needles[i]) == 0)

{

countArray[i]++;

}

           }

        }

     for (int j = 0; j < needles.length; j++)

         {

System.out.println (needles[j] + ": " + countArray[j]);

         }

   }

}

Output

If the length of the needles array is less than or equal to five, then this function displays each word in needles array along with the total occurrences of it in haystack as shown below:

[needle_1]: number of occurrences

[needle_2]: number of occurrences

[needle_3]: number of occurrences

[needle_4]: number of occurrences

[needle_5]: number of occurrences

 

Error Message

If the needles array contains more than five words, the following error displays:

“Too many words!”

Calling the Function

This function takes in two parameters, a ‘haystack’ input string and a string array ‘needles’ containing words for which occurrences need to be found.

String haystack = “Quick Brown Fox Jumps Over The Wall”;

String[] needles = {“Quick”,“Jumps”,”Wall”,”Fox”, “Brown”}

findNeedles(haystack, needles);

Example Test Cases

Case 1:

String haystack = "Apple Orange Fruit";

String[] needles = {"Apple","Orange","Fruit"};

Result:

Apple: 1

Orange: 1

Fruit: 1

 

Case 2:

String haystack = "Apple Orange Fruit";

String[] needles = {"Apple","Orange","Fruit","Banana","Table","Mango"};

Result:

Too many words!

 

Case 3:

String[] needles = {};

String haystack =  ”Apple Orange Fruit”;

Result:


Case 4:

String haystack = "";

String[] needles = {};

Result:

 

Case 5:

String haystack = "A p p l e Orange Fruit";

String[] needles = {"A p p l e","Orange","Fruit"};

Result:

A p p l e: 0

Orange: 1

Fruit: 1

 

Limitations

·         The needles argument can accept only 5 search words. If this number exceeds, it shows an error.

·         This function can only search for single words in haystack string and cannot recognize words if space is there between letters. It also cannot recognize if phrases are provided.

·         The search words are case sensitive. “Apple” and “apple” are considered different.

 

Commented Code

class Main {

  public static void main(String[] args) {

    String haystack = "Apple Orange Fruit"// declaration of string haystack with some string value.

    String[] needles = {"apple","Orange","Fruit"}; // declaration of string array containing words to search in haystack.

    findNeedles(haystack, needles); // calling the findNeedles function with arguments haystack and needles. 

  }

  public static void findNeedles(String haystack, String[] needles) //this function searches for how many times each element in the needles array occurs in the haystack string.    

 {

    if (needles.length > 5

    {

        System.err.println("Too many words!"); //display an error if needles array contains more than 5 elements.

    } else //else case starts

    {

      int[] countArray = new int[needles.length];//creates a countArray of type integer with size equal to length of needles array.

      for (int i = 0; i < needles.length; i++) //initiates a loop to iterate over each element of needles array.   

          {

            String[] words = haystack.split("[ \"\'\t\n\b\f\r]"0);//create a new string array words that contains the result

                                                                    // after splitting the haystack by delimiters like tab, new line etc.

              for (int j = 0; j < words.length; j++)// initiate a loop to iterate over each element of words array

           {

                if (words[j].compareTo (needles[i]) == 0//compare each string in words array with each string in needles array 

                {

                    countArray[i]++; //if a particular string in words and needles matches, increment the countArray array by 1. 

                }

            }

        }

     for (int j = 0; j < needles.length; j++) //initiates a loop to iterate over each element in the needles array

         {

            System.out.println (needles[j] + ": " + countArray[j]); // display each element in needle array with its corresponding value in the countArray indicating total number

 of occurrences.

         }

   }

 }

}

 

Suggestions for Improvement of Code

·         Call the split function before the For Loop to improve performance and to reduce CPU and memory usage as split function will get called only once.

 

else {

          int[] countArray = new int[needles.length];

          String[] words = haystack.split("[ \"\'\t\n\b\f\r]", 0);

          for (int i = 0; i < needles.length; i++) {

              for (int j = 0; j < words.length; j++) {

                  if (words[j].compareTo(needles[i]) == 0) {

                      countArray[i]++;

                  }

              }

          }

 

·         Regex search can be utilized to compare words in ‘needles’ array with haystack string. This ensures reduction in memory usage. Moreover, using regex for search helps to overcome existing shortcomings like non-support of phrases, punctuation, case-sensitive text etc.

·         New enhancements can be brought in where user can be asked to search for desired word from the needle array.

 

 

Comments

Popular posts from this blog

Understanding Intents in Dialogflow

Dialogflow is a highly robust and dynamic natural language understanding platform that allows you to quickly build highly scalable conversational chatbots by leveraging the power of Artificial Intelligence (AI). You can easily create highly customizable chatbots for variety of channels like web applications, mobile applications, Facebook page, social media apps and much more. It provides seamless integration with variety of channels like Facebook, Viber, Telegram, Slack and much more. But in order to start working on building a chatbot yourself, lets connect the dots to get a clear picture of entire chatbot development process in Dialogflow. To create a chatbot, let us understand some of the nuances of the Dialogflow. What are Intents? Intents help Dialogflow ascertain the real intent or motive of the user messages. You can provide a set of certain training phrases that can help Dialogflow get trained to recognize similar such phrases and trigger a specific intent whenever such

Using Entities in Dialogflow to Extract Vital Information

Having learned about Intents in our previous blog , in this blog we will shed light on another interesting topic of Entities in Dialogflow . Entities provide an efficient way to capture and extract crucial information like name, country, location and any custom information from user inputs. Entities can be mainly categorized into three types: 1.  System Entities : These are build-in entities provided by Dialogflow through which you can identify and extract most common type of data like name, country, date, email address etc. 2. Custom Entities : These are user-defined entities that are useful to extract custom data from the user inputs. For example, you can define a Fruit entity type that can identify and map different fruit types like Mango, Apple etc.        3.  Session Entities : As the name suggests, these entities remain active only for the session for which they have been created. They provide additional capability through which we can update custom entity types with new

SOAP Vs REST – An Overview

Both SOAP and REST provides an efficient means of communication through exchange of data between two applications using web services. Although both are unique in their approach, they score over each other depending upon their suitability in various use cases. What is SOAP? SOAP (Simple Object Access Protocol) is a platform agnostic web communication protocol that uses only XML to exchange data. It adheres to strict message structure of Envelop, Header, Body and Fault (error) that enhances security and uses http to communicate between different applications. What is REST? REST (Representational State Transfer) is an architectural style to exchange data through efficient utilization of resources accessed using a unique URI. REST rides on HTTP/HTTPS to exchange data and supports XML, HTML, plain text and JSON data for API requests and responses. SOAP Vs REST – Which One to Select Both SOAP and REST have their own architectural styles that are flexible, scalable, and fulfil var