Tia  Gottlieb

Tia Gottlieb

1596427800

KMP — Pattern Matching Algorithm

Finding a certain piece of text inside a document represents an important feature nowadays. This is widely used in many practical things that we regularly do in our everyday lives, such as searching for something on Google or even plagiarism. In small texts, the algorithm used for pattern matching doesn’t require a certain complexity to behave well. However, big processes like searching the word ‘cake’ in a 300 pages book can take a lot of time if a naive algorithm is used.

The naive algorithm

Before, talking about KMP, we should analyze the inefficient approach for finding a sequence of characters into a text. This algorithm slides over the text one by one to check for a match. The complexity provided by this solution is O (m * (n — m + 1)), where m is the length of the pattern and n the length of the text.

Find all the occurrences of string pat in string txt (naive algorithm).

#include <iostream>
	#include <string>
	#include <algorithm>
	using namespace std;

	string pat = "ABA"; // the pattern
	string txt = "CABBCABABAB"; // the text in which we are searching

	bool checkForPattern(int index, int patLength) {
	    int i;
	    // checks if characters from pat are different from those in txt
	    for(i = 0; i < patLength; i++) {
	        if(txt[index + i] != pat[i]) {
	            return false;
	        }
	    }
	    return true;
	}

	void findPattern() {
	    int patternLength = pat.size();
	    int textLength = txt.size();

	    for(int i = 0; i <= textLength - patternLength; i++) {
	        // check for every index if there is a match
	        if(checkForPattern(i,patternLength)) {
	            cout << "Pattern at index " << i << "\n";
	        }
	    }

	}

	int main() 
	{
	    findPattern();
	    return 0;
	}
view raw
main6.cpp hosted with ❤ by GitHub

KMP approach

This algorithm is based on a degenerating property that uses the fact that our pattern has some sub-patterns appearing more than once. This approach is significantly improving our complexity to linear time. The idea is when we find a mismatch, we already know some of the characters in the next searching window. This way we save time by skip matching the characters that we already know will surely match. To know when to skip, we need to pre-process an auxiliary array prePos in our pattern. prePos will hold integer values that will tell us the count of characters to be jumped. This supporting array can be described as the longest proper prefix that is also a suffix.

#programming #data-science #coding #kmp-algorithm #algorithms #algorithms

What is GEEK

Buddha Community

KMP — Pattern Matching Algorithm
Tia  Gottlieb

Tia Gottlieb

1596427800

KMP — Pattern Matching Algorithm

Finding a certain piece of text inside a document represents an important feature nowadays. This is widely used in many practical things that we regularly do in our everyday lives, such as searching for something on Google or even plagiarism. In small texts, the algorithm used for pattern matching doesn’t require a certain complexity to behave well. However, big processes like searching the word ‘cake’ in a 300 pages book can take a lot of time if a naive algorithm is used.

The naive algorithm

Before, talking about KMP, we should analyze the inefficient approach for finding a sequence of characters into a text. This algorithm slides over the text one by one to check for a match. The complexity provided by this solution is O (m * (n — m + 1)), where m is the length of the pattern and n the length of the text.

Find all the occurrences of string pat in string txt (naive algorithm).

#include <iostream>
	#include <string>
	#include <algorithm>
	using namespace std;

	string pat = "ABA"; // the pattern
	string txt = "CABBCABABAB"; // the text in which we are searching

	bool checkForPattern(int index, int patLength) {
	    int i;
	    // checks if characters from pat are different from those in txt
	    for(i = 0; i < patLength; i++) {
	        if(txt[index + i] != pat[i]) {
	            return false;
	        }
	    }
	    return true;
	}

	void findPattern() {
	    int patternLength = pat.size();
	    int textLength = txt.size();

	    for(int i = 0; i <= textLength - patternLength; i++) {
	        // check for every index if there is a match
	        if(checkForPattern(i,patternLength)) {
	            cout << "Pattern at index " << i << "\n";
	        }
	    }

	}

	int main() 
	{
	    findPattern();
	    return 0;
	}
view raw
main6.cpp hosted with ❤ by GitHub

KMP approach

This algorithm is based on a degenerating property that uses the fact that our pattern has some sub-patterns appearing more than once. This approach is significantly improving our complexity to linear time. The idea is when we find a mismatch, we already know some of the characters in the next searching window. This way we save time by skip matching the characters that we already know will surely match. To know when to skip, we need to pre-process an auxiliary array prePos in our pattern. prePos will hold integer values that will tell us the count of characters to be jumped. This supporting array can be described as the longest proper prefix that is also a suffix.

#programming #data-science #coding #kmp-algorithm #algorithms #algorithms

Samanta  Moore

Samanta Moore

1623835440

Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.

The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the** Creational Design Pattern**.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern

Gamedev Patterns and Algorithms with TypeScript.

Welcome back!

Last time we discussed the Entity Component system. We will use it as a fundamental building block in our game. Today we are about to prepare yet another crucial piece of almost any game: the Game Loop.

Feel free to switch to the _ecs_ branch of the repository. It contains the working result of the previous posts and is a great starting point for this one.


Table of contents

  1. Why do we need a Game Loop?
  2. What is a Game Loop?
  3. Updatable Entity and Component
  4. Let the Game Begin!
  5. Conclusion

Why do we need the Game Loop?

When we develop an application that should be executed in a browser, we rely on our users heavily. In fact, the almost entire data flow of an application depends on the user’s input: “click here,” “type in there,” “navigate to that page,” and so on.

Image for post

In a game, user input is essential as well. After all, the game makes zero sense if nobody plays it. But games as software have a whole lot going on regardless of user input.

The game we are building in this series is a turn-based game. It means that each player makes a move one after another, not simultaneously. AI controls one of the players. When the human player ends their move, the game doesn’t “stop.” Ships are still flying; AI makes its calculations, a timer is ticking, and so on. Plenty of processes are happening; some of them are visible to the player, like animations and timers. Some of them are hidden. In any case, they are independent of the user’s input. Contrary to the business applications, where almost everything freezes waiting for users to start interacting with it, games, in a sense, live their own lives.

Considering all this, we must have a way to keep the game moving even if a human player does nothing. And Game Loop exists precisely to help us with that.


What is a Game Loop?

Image for post

The idea is simple. We run an endless loop that notifies every piece of the game about the start of every iteration. The game loop itself does not apply any functionality or logic. It merely says, “yet another moment has passed.”

Every element of the game being notified deals with that information how it sees fit. Ship animation, for example, may slightly change the position of the space ship in the world. AI engine may consider starting a new cycle of calculations. Health or Mana of RPG character may restore a bit

It is vital to understand that this is an endless, always running loop. With regard to the performance, all operations of all elements must be as lightweight as possible.

What kind of elements should receive notification about a new iteration? The loop may not know in advance, and frankly, it does not care. In the previous chapter, we utilized a powerful architectural approach: Entity Component System. We can now extend it to cooperate with the Game Loop. This way, every element of the game that follows ECS will be updated by the loop. Space ships will fly; enemies will be able to think, mana will be restored!

#design-patterns #javascript #algorithms #typescript #game-development #algorithms

Vern  Greenholt

Vern Greenholt

1595536140

Gamedev Patterns and Algorithms in Action with TypeScript.

Chapter I of series of tutorials on how to build a game from scratch with TypeScript and native browser APIs

Image for post

Welcome to the first article in the series “Gamedev Patterns and Algorithms in Action with TypeScript”! We start our journey with one of the most widely used patterns: Entity Component System.


Table of Contents:

  1. What is ECS?
  2. Implementing Component
  3. Implementing Entity
  4. Testing
  5. Conclusion

What is ECS?

It’s one of the architectural patterns that allows us to combine and composite elements of the codebase without creating strong hierarchical interconnections. In a gist, it enables attaching/detaching functionality to elements of the system in a runtime.

Ok, but what does it mean, exactly? Consider the RPG game where the player can cast magic spells. Different ways of playing available depending on what character class Player chooses. For example, Mage can cast spells, and Paladin can slaughter enemies with the heavy sword. From a technical perspective, all these behaviors can be attached to the player when they choose the class. Even more, this can happen in real-time: when a player reached a new level, new behaviors can become available to them.

Image for post

In this example, the player is an Entity, while the abilities to cast the spell or fight with the sword are Components. We can assign different components to an entity to provide new functionality without changing the code of it.

An Entity can be anything: Player, grid, scene, bullets, even game itself. ECS does not apply any restrictions on the functionality of the Entity. There is only one rule: an Entity has to be able to handle Components.

A component can be anything as well as long as it can be attached to an Entity. Some components can be required by an Entity, which means: Entity cannot really exist without it.

In our game, we will have quite a few Entities and Components. One example is the Ship, which can flight, attack, take damage, etc.


Implementing Component

First, we should take a look at our project. The source code is located at the GitHub. Switch to the init branch and you should see a completely set up but empty project.

Take a look at the srcfolder. All it has is an empty main.ts file and a dummy test in main.spec.ts. Let’s killmain.spec.ts since we don’t need it anymore.

Image for post

In this post, we are creating helpers that put in place the Entity Component System. We are going to use ECS in later chapters for building game elements: Ships, Player, Grid, and Nodes.

These helpers, however, don’t depend on the game itself and can be potentially reused in other games. Let’s start by dedicating a folder that will hold all helpers like that in this project. I’ll call it utils.

#algorithms #typescript #design-patterns #javascript #gamedev #algorithms

Gamedev Patterns and Algorithms in Action with TypeScript.

Chapter II in the series of tutorials on how to build a game from scratch with TypeScript and native browser APIs

Image for post

Welcome back to the series “Gamedev Patterns and Algorithms in Action with TypeScript”! In this series, we learn the fundamentals of gamedev using a web browser’s API and TypeScript.

Last time we end up with the question: how can we start the Game Loop without overcomplicating the constructor. One of the approaches we could take is making it ‘awakable’’.

Feel free to switch to the _game-loop-1_ branch of the repository. It contains the working result of the previous posts and is a great starting point for this one.


Table of contents

  1. Into
  2. Entity Awakens
  3. Starting the Loop
  4. Nested Entity
  5. Testing Game Entity
  6. Conclusion

Into

If you recall, we made significant progress setting up the game entity. We even prepared its Update method that recursively updates all components of the Game. However, it is not much of a help since nobody makes an initial call to start the loop!

We also established that it is possible to start the loop with the help of constructor:

A better approach would be to provide a dedicated initialization method. This method can start the loop and do many other setups, while the constructor remains lean. We can call this method whatever we like, for example, Init or Awake. I will use the latest to mimic the Unity3d API.

Entity Awakens

Image for post

All Entities and Components will now become “awakeble”. That is: they will have the public Awake method.

Note that this lifecycle method doesn’t have a strong relationship with a constructor. An object can be constructed only ones, while it’s _Awake_ may be executed multiple times per the lifespan of an object. It can fall “asleep” and then being awaken again. One of the typical examples is reusing objects to avoid the cost of memory allocation of instantiating the object (read: executing constructor).

It is tempting to simply add a new method to abstract Entity and interface IComponent. But just as UpdateAwake can be part of other elements of our game, not only ECS. It is wiser to create a dedicated IAwake interface and then implement it.

#design-patterns #game-development #typescript #algorithms #javascript #algorithms