Sometimes **Artificial Intelligence** and **Machine Learning** are considered to be the same even if they have a difference between them

Imagine, there is a toy robot that can perform different tasks like singing a song, or solving puzzles. This robot is an example of Artificial Intelligence as it can do tasks that require human intelligence.

Now, let's say the robot learns to do a new task like catching a ball or writing a blog article by watching someone else do it a few times. That's what we call Machine Learning (ML). The robot learned how to catch a ball, and write blogs without being explicitly programmed to do so.

The example above gives a brief idea about the difference between Machine Learning and AI. The example is taken from ChatGPT, the modern powerful AI.

So, when I asked this question to ChatGPT, it found an answer which met the needs of my question and answered the question. It did a task that required human intelligence. So, that is why we call Chat GPT an AI

`## CHAT GPT PROMPTdifferentiate ai and ml such that it can be understood by a 6 years old boy`

Now, let's go back to the time when it was created. It was provided a sample set of data which contained a bunch of prompts and their answers. From that data, it learned to answer questions like this. An algorithm was used so that it can extract the data and find patterns between them. Thus, it learned how to answer these kinds of questions by finding similar patterns in data. This process by which the algorithm learned to answer these kinds of questions is a process of Machine Learning.

I have seen many roadmap videos on YouTube and some stuff is common in every Machine Learning Roadmap video. So, I'll give you a detailed roadmap of Machine Learning

It is the backbone of machine learning, providing the tools and concepts needed to understand and apply the algorithms and models used in the field. The topics of mathematics required for Machine Learning are:

Linear Algebra

Statistics and Probability

Calculus

Let's learn the importance of these topics

Linear Algebra helps in playing with numbers arranged in rows and columns (known as matrices). Imagine, you have a toy box with many toys in it. Each toy can be represented as a number. Linear Algebra helps to work with these kinds of matrices by performing operations like addition, subtraction, and multiplication and it can help to find patterns in the numbers.

So, imagine you have a toy robot that you want to teach to make decisions based on lots of data. You can use Linear Algebra to help the robot understand and analyze the data.

Imagine you want to teach a robot to predict the weather. Statistics and Probability can help the robot understand how likely it is to rain based on past weather data. The robot can then predict the weather.

We use Statistics and probability to help our toy robot guess what might happen in the future, based on what has happened in the past.

Calculus is like a GPS system for the robot that helps it find the best way to learn. Just like a GPS helps us find the quickest route to a destination, Calculus helps our robot find the quickest and easiest way to learn new things.

So, the work of optimizing ML algorithms (also called models) is done by Calculus

You don't need to learn everything about these. You can do a Ph.D. in these topics and spend most of your life learning about Maths and not ML also. But if you want the fast way, then learn these specific topics

Vectors and vector operations:

Definition and representation of vectors

Vector addition and subtraction

Scalar multiplication

Dot product and cross product

Length and normalization of vectors

Angle between vectors

Orthogonal and orthonormal sets of vectors

Matrix operations:

Definition and representation of matrices

Matrix addition and subtraction

Scalar multiplication

Matrix multiplication

Transpose of a matrix

Trace of a matrix

Determinant of a matrix

Inverse of a matrix

Determinants, inverses, and eigenvalues/eigenvectors:

Determinant of a matrix and its properties

Inverse of a matrix and its properties

Eigenvalues and eigenvectors of a matrix

Diagonalization of matrices

Characteristic polynomial of a matrix

Jordan form of a matrix

Linear systems of equations and Gaussian elimination:

Solving linear systems of equations using Gaussian elimination

Gauss-Jordan elimination

LU decomposition

QR decomposition

Singular value decomposition (SVD)

Orthogonality and projections:

Orthogonal and orthonormal sets of vectors

Projections and orthogonal projections

Orthogonal basis and orthonormal basis

Orthogonal matrices and orthonormal matrices

Gram-Schmidt process

Singular value decomposition (SVD):

Definition and properties of SVD

Computing SVD of a matrix

Applications of SVD in data compression and denoising

Low-rank approximations of matrices

Principal Component Analysis (PCA):

Definition and intuition behind PCA

Computing the principal components of a dataset

Dimensionality reduction using PCA

Applications of PCA in data visualization and feature extraction

Matrix factorization methods:

Non-Negative Matrix Factorization (NMF)

Latent Dirichlet Allocation (LDA)

Collaborative Filtering

Least squares optimization and gradient descent:

Least squares optimization

Gradient descent algorithm

Stochastic gradient descent (SGD)

Convergence analysis of gradient descent

Batch gradient descent vs. stochastic gradient descent

Probability:

Axioms of probability

Conditional probability

Bayes' Theorem

Joint and marginal distributions

Independence and dependence

Random variables and expected value

Variance and covariance

Probability Distributions:

Discrete distributions (Bernoulli, Binomial, Poisson, etc.)

Continuous distributions (Uniform, Normal, Exponential, etc.)

Characteristic functions and moment generating functions

Estimation of parameters (Maximum Likelihood, Moment Estimation, etc.)

Convergence in distribution

Hypothesis Testing:

Null and alternative hypotheses

p-values and significance levels

Type I and Type II errors

One-sample and two-sample tests

t-tests and ANOVA

Chi-square tests

Confidence Intervals:

Definition and properties of confidence intervals

Central Limit Theorem and normal approximation

t-intervals and proportion intervals

Regression Analysis:

Simple linear regression

Multiple linear regression

Logistic regression

Polynomial regression

Regularization (Ridge, Lasso, etc.)

Statistical Inference:

Point estimation

Interval estimation

Maximum Likelihood Estimation

Bayesian inference

Central Limit Theorem and Law of Large Numbers

Machine Learning specific topics:

Overfitting and underfitting

Bias-variance tradeoff

Cross-validation

Regularization

Maximum likelihood and maximum a posteriori (MAP) estimation

Differentiation:

Limits and derivatives

Rules for differentiation (power rule, sum rule, product rule, chain rule, etc.)

Partial derivatives and gradient

Jacobian matrix

Implicit differentiation

Integration:

Indefinite and definite integrals

Fundamental Theorem of Calculus

Techniques for integration (substitution, integration by parts, partial fractions, etc.)

Multivariate Calculus:

Partial derivatives and gradient

Hessian matrix and second partial derivatives

Laplacian and Laplace's equation

Extrema of multivariate functions

Constrained optimization and Lagrange multipliers

Differential Equations:

Ordinary Differential Equations (ODEs)

Separation of variables, Euler's method, and Runge-Kutta method

Partial Differential Equations (PDEs)

Heat equation and wave equation

Probability and Statistics:

Probability distributions (discrete and continuous)

Expectation and variance

Joint and marginal distributions

Conditional probability

Correlation and covariance

Optimization:

Unconstrained optimization and local minima/maxima

Constrained optimization and Lagrange multipliers

Gradient descent and stochastic gradient descent

Newton's method and quasi-Newton methods

Convex optimization

Programming with Python

Libraries:

Numpy

Pandas

Matplotlib

Now, you have a solid foundation in Mathematics and programming. So, the next step is to learn the basics of ML algorithms

Supervised Learning:

Linear Regression

Logistic Regression

Decision Trees

Random Forest

Support Vector Machines (SVM)

K-Nearest Neighbors (KNN)

Naive Bayes

Unsupervised Learning:

K-Means Clustering

Hierarchical Clustering

Density-Based Clustering

Principal Component Analysis (PCA)

Reinforcement Learning:

Markov Decision Processes (MDP)

Q-Learning

Monte Carlo Methods

Deep Learning:

Neural Networks

Convolutional Neural Networks (CNN)

Recurrent Neural Networks (RNN)

Long Short-Term Memory (LSTM)

Autoencoders

Model evaluation techniques:

Overfitting and underfitting

Bias-Variance tradeoff

Cross-Validation

Hyperparameter tuning

Now, you have become an intermediate in ML. Its time to upgrade your ML sword now. To sharpen your sword of ML, you must **Practice.** One great resource is Kaggle

In this article, you have seen the roadmap for learning Machine Learning. But there are some techniques I would like to tell you which will accelerate your learning process.

I have given you individual topics. So, you can search them in sequence one by one on **YouTube** and **Google** and you can gather the explanation from there.

I would like to tell you about one of the newest techniques for simplifying your understanding. If you are here, you might know about **ChatGPT**

You can use that as a tool to accelerate your learning process. Here's how you should learn for a simplified and better understanding:

Let's say you want to learn a specific topic from the list

Go to Chat GPT and write this prompt

`Write a basic article on [topic] so that a child can understand it`

Now, once you know the overview of the topic you are learning, you can search on YouTube or Google for a better understanding

**Exception:**Let's say you didn't understand a subtopic of the topic you are learning (read the sentence again) from YouTube after following my steps. Then repeat the 2nd step and just change`[topic]`

to your`[subtopic]`

And there you have it folks, everything you need to know about Machine Learning, and the way to learn it. Whether you're a toy robot trying to learn how to solve puzzles or a human trying to understand the complexities of AI, this article has got you covered.

So, dive into the world of ML. And let me tell you one little secret. I have used Chat GPT intensely to make this article also. It gave me an explanation of the robot which I used earlier. The subtopics are also generated by it. So, use ChatGPT and remember one thing that I learned from Kunal Kushwaha's Twitter handle:

]]>AI will not replace you. A person who is using AI will replace you.

**Machine Learning is the study of computer algorithms that improves themselves through data**

In normal programming problems, we provide the data and some set of rules on which the data is processed and we expect the answer as output. In ML problems, we provide the answers and data to the program and the program finds the rules which connect the data to the answers. These relations are generated during the training process

All problems are data and all solutions are relations/functions: In ML problems, we need our answers and data to give to our algorithm as input. The work of the algorithm is to find out the relation between the answers and the data we provided

We convert qualitative inputs into numbers which become the input data. We call these numbers

**INPUT VECTORS**Similarly, the answers or the output we need after training the ML algorithm has to be also converted into numbers which are called

**OUTPUT VECTORS**As written earlier, the goal of that algorithm is to find out the relation between the

**INPUT**and**OUTPUT VECTORS**

Gathering Data: We need to gather the data that is needed to train the machine

Preparing Data: We need to prepare the data to be used in that algorithm

Choosing a Model/ Algorithm that meets the needs

Training the model on the data

Testing Model

Hyperparameter Tuning: Tuning the model using parameters whose values are used to control the learning process

The above 6 steps are steps of Training/ Testing the model

- Prediction: After everything is done, you will deploy your model and then it can be used for the prediction of your needs

ML is about the mapping of INPUT VECTORS to their corresponding OUTPUT VECTORS. To map these vectors, we need to use matrix-based transformations

So, we need to know about **Matrices and Vectors** in Linear Algebra

There can be uncertainty in data, e.g if you want to make an algorithm, that predicts the prices of stocks, there can be uncertainty

So, we need to know about **PROBABILITY**

It is the science of collecting, analyzing, presenting and interpreting data. So, we need to use it in the process of Preparing data

Optimization of data is done using concepts of calculus

]]>Matrices are a vital part of machine learning, as they are used to represent data in a structured and organized way. In this article, we will discuss the basics of matrices and how they are used in machine learning. We will also discuss some of the different types of matrices and how they can be used in Machine Learning algorithms

A matrix is a two-dimensional array of numbers, symbols, or expressions. In machine learning, matrices are used to represent data sets and to make calculations on them. Each element in the matrix is called a matrix entry or an entry. Entries are arranged in rows and columns, which makes a matrix appear like a table.

Matrices are typically used to store and manipulate multi-dimensional data sets. For example, if you want to analyze the performance of a machine learning algorithm on a data set, you would use a matrix to store the data and then work with it to analyze the results.

Identity Matrix: An identity matrix is a square matrix with all diagonal entries equal to 1 and all other entries equal to 0. It is often used to represent a linear transformation

Square Matrix: A square matrix is a matrix with the same number of rows and columns

Diagonal Matrix: A diagonal matrix is a square matrix with all off-diagonal entries equal to zero. It is used to represent a linear transformation, such as an affine transformation

Symmetric Matrix: A symmetric matrix is a square matrix where all entries on both the upper and lower diagonals are equal. It is used to represent a linear transformation, such as a rotation

Matrices are used in many machine learning algorithms, such as linear regression and neural networks. In linear regression, matrices are used to represent the data points and the coefficients of the regression equation. In neural networks, matrices are used to represent the weights of the network and the data points.

Matrices are also used in other algorithms, such as support vector machines and decision trees. In these algorithms, matrices are used to represent the data points and the parameters of the algorithm.

Matrices are an important part of machine learning, as they are used to represent data in a structured and organized way. Several different types of matrices are used in machine learning algorithms, such as identity matrices, diagonal matrices, symmetric matrices, tridiagonal matrices, and orthogonal matrices. Matrices are used in many machine learning algorithms to represent the data points and the parameters of the algorithm. Understanding matrices and how they are used in machine learning algorithms is essential for any aspiring machine learning engineer.

]]>Mainly there are 2 types of Machine Learning named as:

Supervised Learning

Unsupervised Learning

Here, the model is trained on data of desired Input and output mappings. You give your algorithm the input and the desired output data at first and then train your model. After the model has learned from your data, you give a completely new value to the model and it tries to produce a new output.

Spam filtering and speech recognition are some of the most used applications of supervised learning.

But there are two subcategories to supervised learning too:

Regression

Classification

In regression, the algorithm gives output in numbers from many possible output numbers. Let's take an example of house price prediction.

You will need to have a sample dataset of houses with a certain number of rooms, washrooms, and floors and their price. Now, your data will be used to train your ML model

If you need to predict the price of a house with 10 rooms, 3 washrooms and 3 floors, then your ML model will tell you the price.

In classification, your algorithm will return a category (also called a class) as its output. One of the classic examples of classification is spam filtering

The algorithm is trained on a large dataset of sample emails with input as the sender, the subject line, and the content of the email and the output of a particular email (spam or not spam) is already present there

Then when a new email is sent to a user, the algorithm tries to classify it as spam or not depending on the parameters like the sender, the subject line, and the content of the email

In supervised learning, we used data that had input and the corresponding correct output pairs. But in unsupervised learning, that output is not present in that data. The algorithm often predicts patterns in data and the data gets categorized by the rules made by the algorithm itself.

It is commonly used for tasks such as customer segmentation or document classification. In customer classification, the algorithm tries to classify the customers based on certain parameters like "paying users", "members", "blog readers" etc. etc. When an algorithm does this kind of task of classifying, it is often known as **Clustering Algorithm**

It aims at identifying any unusual data points that don't fit in any similar pattern of data. It is used in detecting transaction fraud detection

It involves reducing parameters from data while having access to much information in the dataset. It is used in tasks like data compression

]]>In this tutorial, we will be showing you how to use Next.js and TailwindCSS to build a desktop app. We will be using Electron, which is a framework for building cross-platform desktop applications with web technologies, to package our Next.js app as a desktop app. Electron allows us to take our web app and wrap it in a native container, giving it the same functionality as a traditional desktop app.

By the end of this tutorial, you will have a basic understanding of how to use Next.js and Electron to build a desktop app. You will also have a working desktop app that you can run on your computer.

To begin, copy and paste the following code into your terminal to initialize a new project using Next.js, TailwindCSS and ElectronJs

`npx create-nextron-app my-app --example with-javascript-tailwindcss`

This will create the folders of the app, cd into that directory and install the packages using `npm install`

or `yarn`

.

After that you will be able to see a folder structure that looks like this:

You can see a similar folder structure to that of a bare next js app in the `renderer`

folder. And we will be working on that only

Write `npm run dev`

or `yarn dev`

in your terminal of vs code and you will be able to see your electron app pop out

In the pages folder, you will see that there is a file named `home.jsx`

, which is equivalent to `index.js`

file in normal Next js applications. Go ahead and rename the `home.jsx`

to `index.jsx`

. You will see the default 404 page of Next js in the window.

To make this thing correct, we will navigate to the `background.js`

file under the `main`

folder and change the following lines:

Now, the renderer folder looks exactly like that of a new Next Js app.

Let's start coding

We will be making a simple javascript code editor. Here's a preview

Paste this code in the `app.jsx`

file so that the layout looks pretty 💘

`import React from "react";import "../styles/globals.css";function MyApp({ Component, pageProps }) { return ( <div className="bg-gray-700 max-w-screen min-h-screen text-white"> <Component {...pageProps} /> </div> );}export default MyApp;`

Now go to the `global.css`

file in the styles folder and remove everything except these

`@tailwind base;@tailwind components;@tailwind utilities;`

Now you have your beautiful app layout. Head on to the `index.jsx`

file and remove everything. Then paste the code below

`import React from "react";import Head from "next/head";function Home() { return ( <div className="w-screen h-screen flex items-center justify-center relative"> <Head> <title>Code Editor</title> </Head> </div> );}export default Home;`

In this tutorial, we will be utilizing the `react-ace`

library to build a code editor component for our application. So, go ahead and install the `react-ace`

package.

Create a folder named `components`

inside the `renderer`

folder and then create a new file. In my case, it is `CodeEditor.js`

. Below is the given code of that file. To use any other language, you will need to import it using `import "ace-builds/src-noconflict/mode-<language>"`

. Where `<language>`

stands for the language you want to use. Now, for using any other theme, you have to import that using `import "ace-builds/src-noconflict/theme-<theme>"`

.

`import React, { useEffect, useState } from "react";import AceEditor from "react-ace";import "ace-builds/src-noconflict/mode-javascript";import "ace-builds/src-noconflict/theme-twilight";import "ace-builds/src-noconflict/ext-language_tools";const CodeEditor = () => { const [code, setCode] = useState(""); return ( <div className="w-[90%] md:w-[70%] flex h-max items-center justify-center shadow-xl"> <AceEditor mode="javascript" theme="twilight" onChange={(e) => setCode(e)} name="coding_area" editorProps={{ $blockScrolling: true }} value={code} /> </div> );};export default CodeEditor;`

Let's import this file into the `index.jsx`

file and see how it looks

`import React from "react";import Head from "next/head";import CodeEditor from "../components/CodeEditor";function Home() { return ( <div className="w-screen h-screen flex items-center justify-center relative"> <Head> <title>Code Editor</title> </Head> <CodeEditor /> </div> );}export default Home;`

If you stop the server and restart it, you will see this error

This is coming due to server-side rendering of Next Js. The `window`

object is only defined in the browser, so if you are trying to start the server on the server-side (e.g., using Node.js), the `window`

object will not be defined.

We have to dynamically import the component inside the directory

`import React from "react";import Head from "next/head";import Link from "next/link";import dynamic from "next/dynamic";// Dynamically importing the componentconst Editor = dynamic(import("../components/CodeEditor"), { ssr: false });function Home() { return ( <div className="w-screen h-screen flex items-center justify-center relative"> <Head> <title>Code Editor</title> </Head> <Editor /> </div> );}export default Home;`

Now, restart the server and you will see this beautiful screen

To customize the code editor, you may want to consider using various props provided by the react-ace library. For a complete list of available props, please see the documentation here: **https://github.com/securingsincity/react-ace/blob/master/docs/Ace.md#available-props**. Below, we have provided the code to beautify the editor using some of these props:

`// components/CodeEditor.jsximport React, { useEffect, useState } from "react";import AceEditor from "react-ace";import "ace-builds/src-noconflict/mode-javascript";import "ace-builds/src-noconflict/theme-twilight";import "ace-builds/src-noconflict/ext-language_tools";const CodeEditor = () => { const [code, setCode] = useState(""); return ( <div className="w-[90%] md:w-[70%] flex h-max items-center justify-center shadow-xl"> <AceEditor mode="javascript" theme="twilight" onChange={(e) => setCode(e)} name="coding_area" editorProps={{ $blockScrolling: true }} setOptions={{ enableBasicAutocompletion: true, enableLiveAutocompletion: true, enableSnippets: true, }} showGutter={false} className="rounded-lg" style={{ width: "100%" }} onLoad={(editor) => { editor.renderer.setPadding(20); editor.renderer.setScrollMargin(20); }} maxLines={100000} minLines={30} wrapEnabled value={code} /> </div> );};export default CodeEditor;`

Your app should look like this if you write the following stuff

Go ahead and paste `npm run build`

or `yarn build`

in your terminal to start the build

A new dist directory has been built at the root of the project. Since I am using windows, it has created a setup.exe file for me. Install it and your app is ready

In this article, we walked through the steps of creating a desktop app using Next.js. From setting up a new project and installing the necessary dependencies to customizing the user interface and adding features like syntax highlighting, we covered all the basics of building a desktop app with Next.js. By following these steps, you should now have a solid foundation for creating your desktop apps with Next.js. Whether you are looking to build a simple app for personal use or a more complex app for professional purposes, Next.js provides all the tools you need to get started

]]>Adversarial search is a type of search algorithm used in artificial intelligence and computer science to find the best move in a two-player game. In an adversarial search, one player (the maximizer) tries to maximize their score while the other player (the minimizer) tries to minimize the maximizer's score. This is in contrast to non-adversarial search algorithms, which are used to find a solution to a problem without considering the actions of any other player.

Adversarial search algorithms are commonly used in games such as chess, checkers, and Go, where players take turns making moves and the goal is to win the game. They are also used in other fields, such as finance and military strategy, where there is a need to make decisions in the face of an opposing player.

One of the key components of adversarial search algorithms is the evaluation function, which is used to evaluate the current state of the game and predict the outcome if the game were to continue from that state. The evaluation function takes into account factors such as the number of pieces each player has, their positions on the board, and any potential moves that could be made.

One popular adversarial search algorithm is the minimax algorithm, which is a recursive algorithm that explores all possible moves and countermoves in a game tree, evaluating the scores of each possible outcome. The minimax algorithm starts at the root of the game tree and works its way down to the leaf nodes, assigning a score to each node based on the evaluation function. The minimax algorithm then "minimizes" the score of the maximizer's moves and "maximizes" the score of the minimizer's moves, leading to an optimal move for the maximizer.

Another popular adversarial search algorithm is the alpha-beta pruning algorithm, which is a variant of the minimax algorithm that reduces the number of nodes that need to be evaluated by "pruning" the game tree. The alpha-beta pruning algorithm uses two values, alpha and beta, to keep track of the minimum and maximum scores that the maximizer and minimizer can achieve, respectively. If the alpha value becomes greater than the beta value, the algorithm can prune the remainder of the game tree, as it is no longer possible for the maximizer to achieve a better score.

Adversarial search algorithms are a powerful tool for finding the optimal move in two-player games, but they can be computationally expensive, as they require the evaluation of a large number of possible moves and countermoves. However, with advances in computer hardware and optimization techniques, adversarial search algorithms have become increasingly efficient and are now commonly used in a variety of applications.

]]>- You must know the fundamentals of programming i.e loops, functions, classes etc.

That's it. If you know that basic stuff, then its completely alright and you can follow along

5 points denoting 5 places are marked over here named A, B, C, D, E. The arrows represent the directions.

If you are at B, you can move to C only.

You can't move back to A. If you are at D, you can only move to E, not any other place.

Now, let's say you want to move from A to E. You have 2 paths to go from A to E: One via B (let's call it `Path 1`

) and other via D (let's call it `Path 2`

).

Considering that equal distances are present between any 2 points, it is clear that you would move using `Path 2`

cuz' it will take less energy.

There are some basic elements of AI that you need to know:

**Agent:** It is an entity that acts upon a given environment. In this case, since you are walking from A to E, so you are the `agent`

.

**State:** It is the environment in which the `agent`

is present. In this case, the network of the 5 places, is the `state`

.

**Initial State:** It is the initial environment from where the `agent`

starts. Here, if you are standing at point A, it is the `initial state`

.

**Actions:** It is the set of choices that can be made in a given state. If you are at B, the set of actions will contain just one action i.e `{move from B to C}`

. If you are at A, the set of actions will contain 2 actions i.e `{move from A to B, move from A to D}`

.

`ACTIONS(state) -> returns a set of actions that can be performed in a given state`

Now, after you perform an `action`

in a given state, your `state`

has changed. So, the computer must have something to determine the state change. Here's where a **Transition Model** comes into light.

The `Transition Model`

is a function that returns the result after a particular action is performed in a particular state. It takes in `state`

and `action`

as its arguments.

`RESULT(state, action) -> returns the resulting state`

In the picture, you are at point A and you perform an action `move from A to B`

. You will get this resulting state 👇

Now, let's say you have reached your goal. There must be a sort of test to determine that right? As a human, you know that you reached your goal but for a computer, the instruction must be given if it has reached its goal or not. That's why we do a **Goal Test** to determine if the AI has reached its goal or not.

There were 2 ways to go from A to E, right? But why did you choose the 2nd path? It is because it took less energy. A computer should take the 2nd path so that it takes less computing power. The numerical cost associated with a given path is known as **Path Cost**.

Now there were 2 `set of actions`

that leads you to the goal. This set of actions that lead the agent to the goal state is called **the Solution**

**The Optimal Solution** is the solution with the lowest path cost. In this case, `Path 2`

is the path with the lowest path cost so it is the Optimal Solution to this problem

So, **Search Problems** are the problems in which an `agent`

is present which starts from an `initial state`

and the AI finds the `Optimal Solution`

for that agent to reach its `goal`

In a search problem, data is stored in a node. It is a data structure that holds information that is important to the AI. A node contains:

A state

Its parent node: The node through which the current node was generated

The action: That was applied to the parent to get to the current node

The path cost from the initial state to this node

Start with a frontier containing the initial state and an empty set of explored items

REPEAT UNTIL THE GOAL IS REACHED

if the frontier is empty:

- return None as there are no solutions.

else:

Remove a node from the frontier. We will store this node in a variable (let's say the variable is

`checking_node`

) for checking.If the

`checking_node`

is the goal then return the`solution`

.else:

If the

`checking_node`

is not present in the explored set then find all the`nodes`

that can be reached through that node and add them to the frontier.Then add the current node to the explored set.

The Frontier is just a data structure where nodes get added and removed. But there are choices by which these nodes get removed.

We can either use Stack as the data structure for the Frontier or we can use Queue as a data structure for the frontier. If we are using stack, we will be using `breadth-first search`

on the other hand, if we are using a queue, we will be using `depth-first search`

.

For performing DFS, we treat the frontier as a `stack`

. We add nodes at the last and we remove the last added node from the frontier.

**The paragraph written below is taken form:** https://cs50.harvard.edu/ai/2020/notes/0/

Take a situation where you are looking for your keys. In a *depth-first* search approach, if you choose to start with searching in your pants, youd first go through every single pocket, emptying each pocket and going through the contents carefully. You will stop searching in your pants and start searching elsewhere only once you will have completely exhausted the search in every single pocket of your pants.

For using BFS, we treat the frontier as a `queue`

. We add nodes at the last and we remove the 1st node that was previously added.

**The paragraph written below is taken form:** https://cs50.harvard.edu/ai/2020/notes/0/

Suppose you are in a situation where you are looking for your keys. In this case, if you start with your pants, you will look in your right pocket. After this, instead of looking at your left pocket, you will take a look in one drawer. Then on the table. And so on, in every location, you can think of. Only after you will have exhausted all the locations will you go back to your pants and search in the next pocket.

There are more kinds of search algorithms like Greedy Breadth First Search and A* search. In the next article, we will look at **Adversarial Search**

The start of the year was pretty wonderful, I was in class 10th and I had seen hype in the crypto space. So, I started learning about web3. Learned solidity, made a few projects and then participated in Thirdweb hashnode hackathon. Learned new things **but never shared**.

To be very honest, I did it because of the prize. I had never participated in any hackathon before and didn't even earn a penny from programming. So, I thought that I will just participate, make a product and win the prize.

Life gave me a lemon, but I couldn't make lemonade out of it. When I couldn't win the prize, I just didn't feel like participating in any other hackathon

I worked very hard for my 10th CBSE board exam. After the board exam was over, I got a freelance client who paid $ 120 for an NFT project. That project was on the Solana Blockchain and I learned a lot again **but I never shared my learnings.**

I was very happy and thought that class 11th will be easy for me. But I never knew the other side of hard work. I never knew what a mental breakdown was and I never really knew what happens when no expectations get fulfilled.

I was getting bad grades despite working very hard. There was a huge rise in the syllabus and I couldn't handle it at first

I couldn't consistently post about my learnings on social media platforms. I started using Twitter but I don't even have 50 followers today. I just have 1 follower in my hashnode as of today.

I don't know why I didn't post and I don't want to waste my thinking of it too. I just know that in the coming year I have to be consistent so that I can break out of this valley of regret.

The only thing which kept me alive and gave me pleasure in this valley of regret is coding. I can code for hours without thinking of anything. I did get to hear a lot of taunts from my parents for this cuz' my school academics were not great like that of 10th but I really don't care about that now.

I learned solidity, did freelancing and did get a decent amount of money.

Then I started learning Rust for Solana blockchain. I found that Solana was faster than Ethereum and had very less gas fees. Found out that buildspace was the perfect place for learning that. But after a couple of months, I didn't feel like doing it anymore so I left it and started building apps with what I knew.

I started learning DSA from LearnCodeOnline didn't complete the full course but I learned a lot

DSA is like a fundamental building block. Once you know DSA, it will improve your logic-building skills immensely. I don't know everything about DSA but I have found immense progress in my logic-building skills after learning a few concepts of DSA.

I knew how to make web apps with MERN stack and mobile apps with React Native. But I thought why stop at that I learned NextJs and Prisma. As of today, I can make full-stack apps easily

I still am in a valley of disappointment. But I will implement my learnings from this year so that I can make myself better. I am currently learning about Artificial Intelligence parallelly to learning DSA. This blog will stay as a reminder to me. It will remind me about what to do next

I will share what I learn

I will stop putting expectations in everything

I am starting today

I will make a plan for the next day before every night (started this at the start of this month)

I will go out for a walk for 30 mins thinking about "how can I make this day better" every day (started this at the start of this month)

The best time to start a new thing was in the past

But the second best time is now

If you want to put up some suggestions, then please put them up. This year, I faced hard situations but I have learned from them. Now, I can successfully avoid these traps and make myself better. And yes, I don't expect to win prizes in Dev Retro 2022 😊

]]>Time complexity is basically the relation between input size and running time

You obviously have apps in your phone. You are most likely to prefer the ones which takes less time to load the data and consumes less space. The factor which is used to measure the time is related to time complexity. But what about the space? How do we measure the space used by a code?

The relation between the input size and memory consumed in your system.

If you want your code to be optimized, it should take less time and less space too. So, here's where space complexity comes in place cause this is the way to measure how much space your code will take

The space used by a code depends on how many variables are used. The more variables, the more space used.

How much memory consumed by a code is directly proportional to how many variables assigned

`sum = 0i = 0while (i < 24): sum += i i += 1print(sum)`

Here, there are 2 variables which we are assigning to the memory that is `i`

and `sum`

. Now, no matter the the value of sum increases the memory used by that one variable would be the same. So, the space complexity for this code will be O(1)

Now, let's take the example of arrays. It is basically a data structure which stores a list of elements. We will talk about arrays deeply later

`def create_array(n): a = [] for i in range(n): a.append(i) return a`

In this function, we take integer `n`

as an input. Then we create an array. Using the loop we store the numbers 0 to n-1 in the array. Then we return it. So, basically what we are doing is, we are generating a series of numbers and storing it in an array. Here, with the increasing size of input, the space used by the code also increases. So, the space complexity for this code is O(n)

You can check the size here:

`sys.getsizeof()`

gives out the size of a particular function, class, variable etc. in python

**I really hope you understood, if you didn't then feel free to criticize in the comment section. It's okay to criticize if I have wasted your valuable time. Also if you have any doubts, feel free to put it up in the comments section**

`calculateTime()function fancyName(){ do something}calculateTimeDifference()`

In this approach of judging code, before running a chunk of code, the initial time is taken and after running that code, the final time is taken. Then when the final time is subtracted from initial time, we get the how much time was required for processing of the code.

This method of calculating code performance is rated as average but still this approach is used hugely to judge code

- It is based on machine: Depends from processor to processor
- It is based on processing: Depends on the processing power of your PC

Counting the number of operations in a code. Technically, this literally means that we are going to count the number of operations in a code.

**Count Operation in the code below**`a = a + 1`

If you said there is one operation, you are wrong my friend. There are actually 2 operator: "=" and "+"

Now, count the operation in this code

`sum = 0winner = 1for (i = 1; i < n; i++){ sum = sum+1}`

Notice closely, that there are several operators. In total, there is 3 "="s, 1 "<", then in `i++`

, there are actually 2 operators which are responsible to increment the value of i, `i++`

can be written as `i = i+1`

, so in `i++`

there are 2 operators. Then inside the loop there are 2 operators: "=" and "+"

But, in this code, apart from `sum = 0`

, `winner = 1`

, `i=1`

, all the other operators are dependent on the variable `n`

. So, there are 3 constant operators, and 5 operators which varies with the value of `n`

. Thus there are 3+5n operators

The whole way of measuring code with number of operators is known as Big O.

**Code 1**

`sum = 0i = 0while (i < n): sum += i i += 1print(sum)`

In this given code, there are 5n+2 operators.

Now, coming to the complexity of the code: To measure the complexity of the code, the constants are to be ignored.

So O(n) [Said as O of n] is the complexity

**Code 2**

`for (------): --------- ---------for (------): --------- ---------`

You might think that the complexity of the above code is 2O(n) and that's completely correct. But since the constants are to be ignored, so the complexity will be O(n).

**Code 3**

`for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { sum+=j }}`

In the above code, O(n) is inside another O(n). Thus, the complexity of the code becomes O(n^2). If the nested loop would run on a constant and not on N, the complexity would not be O(n^2).

Code Complexity | Notation | Note |

O(10), O(1000) O(k), 3O(k) kO(k) | O(1) | "k" is some constant |

O(3n), O(4n+100000) | O(n) | Constants are to be ignored |

O(3n^2), O(4n^2+100000) | O(n^2) | Constants are to be ignored |

O(3n^2), O(4n^2 + 3n + 4) | O(n^2) | Since with increasing value of n, the value of n^2 will become much higher than theat of n, so n can be ignored, incase of cubic equations,the complexity will be O(n^3) and so on |

This graph shows the time for complexity of code with increasing input.

]]>The main moto to learn DSA is to know how to write optimized code. In this age of *Cloud Functions*, the optimized code requires less money as less computation and memory is used in the servers. On the other hand if you don't write optimized code, you will have to pay more money and also the results from the cloud servers would be very slow.

Now you know that writing optimized code would save your time. But how will you judge if a code is optimized or not? Many people say that the less number of lines means the more optimized code. But this is a true lie. Optimized code can't be judged by the number of lines but the parameters involved in the code. Judge this case:

**Problem Statement**: Generate a series of number from 1 to n and store it in a variable or function so that it can be accessed later

Code 1:

`def gen_series(): a = [] n = int(input("What's n? ")) for i in range(1, n+1): a.append(i) return adef print_series(): a = gen_series() for i in a: print(i)if __name__ == "__main__": print_series()`

Code 2:

`def gen_series(): n = int(input("What's n? ")) a = series(n) print(a) return adef print_series(): a = gen_series() for i in a: print(i)def series(n): d = 11 for i in range(1, n+1): yield i + d d += 11if __name__ == "__main__": print_series()`

If you count the number of lines, you would say Code 1 is more optimized but is it?

In both the cases the series is generated and stored inside the function named `gen_series()`

. If you know about the `sys.getsizeof()`

method in python, you will know that it gives out the memory used inside a variable, function. If you write this in your code editor, run the program, and enter 200 as the input of `What's n?`

`import sysdef gen_series(): a = [] n = int(input("What's n? ")) for i in range(1, n+1): a.append(i) return adef print_series(): a = gen_series() for i in a: print(i)if __name__ == "__main__": print(sys.getsizeof(gen_series()))`

You will get the memory used in bytes. And surprisingly, you will notice that the 2nd code consumes less memory.

So, we can come to a conclusion that less code always doesn't mean optimized code. For a code to be judged, the parameters are important.

DSA is mostly independent of programming language the main things which matter are the concepts. I'll be using python in the next articles regarding DSA

]]>Before reading this blog, I want to make a clear statement that this blog is written completely based on my understanding about how generators work in python. To move forward, you must be an intermediate in python.

An object that contains countable number of values. The next value can be accessed with the `next(object_name)`

parameter

You can know more about iterators here: Iterators by W3 Schools

Let's say you are working in a company and your company gives you a task to write a program to find a series of numbers. Each number having a difference of 12 from the previous. So the series is like: [12,24,36,48.....]

You have to find the series till a number given by the user and store the results somewhere so that others get those values using a loop.

So, if the user enters 10, the program will return a series like: **12,24,36,........,120**

You will be like: *Okay that's easy*

`def gen_series(): n = int(input("What's n? ")) a = [] d = 11 for i in range(1, n+1): a.append(i + d) d += 11 return aif __name__ == "__main__": print(gen_series())`

Now, your program works nicely if the user inputs numbers like 12, 23, 89, 74.

If you test this code yourself and you enter a number like 1000000000000000 then what happens?Your code starts to hang, the program doesn't work smoothly. So, this is not the best approach to get a series of numbers.

**Let's refactor this code a bit**

`def gen_series(): n = int(input("What's n? ")) a = series(n) print(a)def series(n): a = [] d = 11 for i in range(1, n+1): a.append(i + d) d += 11 return aif __name__ == "__main__": gen_series()`

Now, the program runs the same but our problem is not yet solved. We want to generate a series of numbers with each number having a difference of 12 from the previous and we want our program to generate as much numbers as we want.

Try to run this code:

`def gen_series(): n = int(input("What's n? ")) a = series(n) print(a)def series(n): d = 11 for i in range(1, n+1): yield i + d d += 11if __name__ == "__main__": gen_series()`

If you run this code and input a number as 20, you will see the output as `<generator object series at 0x0000020B20684350>`

. Now, if you run again, and input a big number such as 1000000000000000, you will notice that your program doesn't lag. It works perfectly fine and you get the output.

The `yield`

keyword is responsible to make this function a generator.

The `series`

function is now a generator function which generates an iterator. If you have read the article of W3 Schools, you will certainly know that we can easily access the values from an iterator using a loop.

So, here's the definition of generators

Generators are those kind of functions that return an iterator.

Now to print the values of the series we can use another function

`def print_series(): a = gen_series() for i in a: print(i)`

The complete code:

`def gen_series(): n = int(input("What's n? ")) a = series(n) print(a) return adef print_series(): a = gen_series() for i in a: print(i)def series(n): d = 11 for i in range(1, n+1): yield i + d d += 11if __name__ == "__main__": print_series()`

- Generators are functions that return an iterator
- We can turn a normal function to generator by using the
`yield`

keyword

**If you didn't understand then don't forget to criticize me in the comments. That will help me to come up with a better explanation. It is okay to criticize me if I have wasted your time. Also if you have any questions, please ask me in the comments**

HODL: "Hold on for dear life". This term is used by crypto enthusiasts denoting a long-term approach to cryptocurrency investing.

One of the major problem that people face while investing into crypto is that they cannot hold the crypto currencies for long. If someone is an early investor and invests in cryptocurrencies then the main problem for them would be to keep their mind stable to hold it for long aka keep their mind stable enough to **HODL** it.The instability of the crypto market is the main reason of people's panic due to which they widraw the crypos they bought. The most safe investment strategy for crypto is to *HODL* them. If cryptos can be hold for long time then only they give exponential returns. But since the panic comes into the path so, it becomes tuff to **HODL** the cryptos for long (specially for the early investors).

HodlBank is the solution to this problem. Here's how it works:

- Transfer your ETHEREUM (faucet from rinkeby testnet) to HODL in the Bank.
- Set the time upto which you want to HODL
- Do a successful HODL
- Come Back after that specified time and get your ETHEREUMs back

- NextJs
- Tailwind Css
- Moralis
- @thirdweb
- Solidity
- Hardhat

**Before you get started, make sure that your Metamask is connected to the rinkeby test network and you have some Rinkeby Faucets**

After your metamask is setup, it is extremely easy to authenticate a user. Click on the **Connect** or the **Get Started** button on the homepage and you will see a metamask popup, from there authentication is just a click.

Once you are authenticated, click on the **Get Started** button and you will get redirected to the **Create Hodl** page. Set an amount to HODL and set the date and time till you want to HODL your Ethereums. After you are done, click on the **Create Hodl** button and confirm your transaction by paying a small amount of gas fee.

When your time comes to widraw your HODL, you have to click on the **Get Hodls** card on the homescreen and you will get redirected to the screen where you can **get the records of your created HODLs**. From there itself, you can widraw your created HODL(s).

We also have a discord community for our application users. People can get an exclusive role in that server by purchasing the nft from Opensea Testnet. This NFT was hosted through the @thirdweb platform.

I do have future plans for this application. Maybe sometime I will deploy it on the ethereum mainnet and people can then HODL real ethereums. Currently, you can only HODL ethereums of the rinkeby testnet. Feel free to share your thoughts regarding this.

Solana is backed by one of the most popular crypto exchange platform named FTX. They have chosen only Solana out of all the cryptos because of its speed. Look at this comparison chart to see the stats of Solana.

One of the major problem is its high gas fees. And certainly gas fees are important in a decentralized system. Even in my previous blogs, I have discussed about how Ethereum works and it completely demonstrates why gas fees are important as well as requried. But the average gas fees as you can see in this chart of Ethereum is 10000x from that of Solana.

Ethereum has much faster transaction speed than bitcoin but is is enough for a dapp? The average transaction per second (TPS) for Bitcoin is about 3 where as it is 15-20 for Ethereum. Well that's fast but it is nothing compared to that of Solana. Right now, Solana can handle about 65,000 transactions per second.

Ethereum team is trying to solve their problems of TPS and gas fees by methods called sharding, proof of stak. But Solana uses completely different mothod for its usage. Its known as proof of history. To understand the tech behind Solana, we at first need to understand about the **Blockchain Scalability Trilema** which is also known as the **Blockchain Trilema**.

Actually the founder of Ethereum i.e Vitalik Buterin himself coined this term. Any blockchain is based on 3 qualities which are Decentralisation, Security, Scalability. The trilema claims that 2 of these qualities can only be maximised. Ethereum and Bitcoin maximises Decentralisation and Security but had to compromise in scalability. Maximum blockchains follow the Blockchain Trilema.

But Solana claims a total different thing. It is decentralised, highly secure and also highly scalable. But the question is how does Solana achieve this? It's by implementing a whole new mechanism named as Proof of history.

In *Proof of Work*, computers just fight with each other to create the next hash and make a new block. Bitcoin takes about 10 minutes to create a new block while ethereum takes about 15 seconds. This speed is good for transactions since web 2.0 banks also take fairly the same time. But it is worthless for a Dapp. Suppose you make a social media and it takes 15 seconds to post a video or picture. So, if you are a miner then the better computer you have and the more computers you have, the more is the chance of getting the reward for computatation.

Proof of stake is a type of consensus mechanism used to validate cryptocurrency transactions. With this system, owners of the cryptocurrency can stake their coins, which gives them the right to check new blocks of transactions and add them to the blockchain.

Proof of History is a sequence of computation that can provide a way to cryptographically verify passage of time between two events. It uses a cryptographically secure function written so that output cannot be predicted from the input, and must be completely executed to generate the output.Here's a video which best explains what proof of history is and its from the official channel of Solana itself.

]]>I will cover the roadmaps for those people who are totally new for this programming world. If you know some technologies then that's oviously a benefit for you and you can also skip to the parts of your interest from the table of contents.

If you want to be a developer, there are 2 parts (mainly):

- Frontend Developement: All the things you see i.e the visuals. If you go to facebook you can see the login form, the beautiful logo which is placed at the top corner. All of that falls under the frontend part.
- Backend Developement: Now, you want to login to facebook, you give your email, password in the form and click on the Login button. What happens after that is your credentials are saved in the facebook database. That's the work of backend parts.

Here are the List of technologies you need to learn for frontend developement.

- HTML
- CSS
- JavaScript
- React or other frameworks of Javascript (Highly Recommended)

- Solana

It's oviously not everything. There are a few things which you need to learn and that's not an option. You must learn. But you don't need to worry cause you will learn all of these in the flow.

- Node Js
- Truffle

I have gathered some of the free and good quality resources for you to get started. Remember to make some projects after you complete each trutorial:

**Wish you all the very best for your Ethereum Developement journey and if you have any queries from me, just leave a comment below. Have a great day .**

The full form is Non-Fungible Token. But what the heck does it mean. So there are 3 concepts by which we can understand NFTs better. After you read this blog, most of the questions regarding NFTs will be resolved.

- Subjective vs Objective Value
- Fungible vs Non-Fungible Assets
- What are Tokens

Objective value are those values which are 100% true, unibased and balanced. Objective values do not change with respect to the vision of people.

Subjective Values are the opposite of Objective values. These values are those which doesn't show clear picture and it changes with person's outlook.

Let's understand it with an example:Suppose you want to travel from Los Angeles to United Kingdom through aeroplane. Now going through that plane and sitting in a seat of the plane is an Objective Value. To go to UK, you have to go by an aeroplane and you have to take a seat in the plane. But here also, there can be some people who are willing to pay more just to get the seat beside the window. That might be due to personal satisfraction or some other reasons.

Another example is that, if you play fortnite, you might buy skins of guns. It is also a subjective value, you buy that to get clout or to look cool or due to some other reasons.

And this is the same reason due to which people buy NFTs when they can download the digital pictures of those NFTs.

Fungible assets are those assets which can be interchanged by the same same type. Money, Bitcoin are fungible assets. 1 Bitcoin can be interchanged with anouther Bitcoin.

Non-fungible assets as you have already guessed, are those assets which cannot be interchanges by that of the same type. If you sea NFT artworks on OpenSeas then you will notice that the artworks are unique.

Tokens are something which can be physical or digital which can be exchanged for a good servise or other form of value or utility.

NFT of a Non Fungible Token are those token which have a value and they cannot be traded for their same type.

The answer to this question is very simple. The "being cool" culture and the "clout" culture will increase if not decrease. Thus people will buy the NFTs to be cool in front of others or to get clout or that might be a sense of personal satisfraction. Another reason can be the incoming METAVERSE. One can buy NFTs and showcase them in their virtual house or museum. You can also generate an income by selling those NFTs at higher prices or just creating a membership ticket for your people.

I hope that all the basic questions regarding NFTs are resolved and if you have any questions, then you can just put it up in the comments section. I would love to answer them.

]]>Ethereum is one of the product of the bockchain technology just like Bitcoin. Bitcoin is used only for transactions and are actually non-programmable but Ethereum is actually programmable and applications can be built in top of that.

**But... Ethereum is a blockchain based software platform and it doesnot have any central authority. Then How does it opereate and how are the applications which are built on top of the ethereum netwok so scalable. You will understand the answer to this question in parts**

Often people use Ether and Ethereum inchangably where both of these are 2 different things. Now let's talk about Ether. Ether is the currency which is like Bitcoin and acts as a store of value or a form of payment.

*If BITCOIN corresponds to digital gold then ETHER is like digital oil.*

Since Ethereum network is divided; the dapps need to pay for the computing power to host and manage data. The amount of ether or network fees required is determined as gas fee.

GAS fees are determined according to the bandwidth, space and the computational difficulty.

GAS = Bandwidth + Space + Computational Difficulty

Ether gas prices are in GWEI.1 Ether = 10^(18) GWEI.

The higher the gas fees the faster the transaction. So, Gas fees are the fees that the people need to pay for the computing charges of a transaction in the Ethereum Network.

The base layer of this network consists of a vast network of computer called nodes. These computers have softwares installed on them and they are connected to each other to run the **ETHEREUM BLOCKCHAIN**.

In this base layer of nodes, the transacition data is processed, validated, broadcasted and stored. These nodes do the computational work and they are paid in ethers to process the data. These ethers are the gas fees which they recieve as a reward for handling the conmputaional charges. The transaction data contains *value in form of ethers and informatin in form of code*.

This code can transmit data and trigger action into the software layer. The software layer is the layer above the hadware or the base layer. This software layer supports programming lanuages like Solidity, Rust etc. Using these languages, developers can write Smart contracts.

Smart Contract are lines of code which dictate the terms of a contract and controls and executes the lines of the contract.

Between the hardware and the software layer lies the smart contract. It can authorise transactions and carry out terms of contract and create a trustworthy decentralised system which does not require a central authority.

The hardware layer and software layer of computers and the computers which are connected to each other over a vast network together forms a super computer named as EVM or the Ethereum Virtual Machine.

*Make sure to comment down for doubts*

This is the literal diagram of the blockchain and this diagram itself is enough to explain what blockchain is. Here you can see that there are blocks and all of these blocks are connected to each other. This connection creates a network. So, blockchain is a network of blocks.

Now, **What do these blocks contain and where are these blocks stored?** These blocks contain data and these blocks are stored in computers.

*To sum up, we can say that the chain of blocks (containing records of data) stored on networks of computers together is called a blockchain. *

Now let's come to its fetaures to understand it more clearly...

There are 3 features of blockchain which makes it unique and useful. These 3 are the main features for which blockchain will stand out.

- Decentralisation
- Immutability
- Transparency

From the previous, diagram we could see that the data is divided among the network of computers. So, no particular authority has any hold of it. So, no one can control the data. Everyone has equal access to the data.

The data record which is stored in the network cannot be altered or forged. This happens due to complex cryptographic, hashing concepts.

In blockchain network, there is no central authority, and the data stored in blockchain cannot be forged or altered. If you have the correct credentials about the block then you will be even able to see the data of a block. Otherwise no one can see it.

Let's understand this by an example:Do you know where the government spends its money? Even if you ask the question to the government it can just tell you. But can you see it. Can you see how much transaction is made? No. If you ask the government to show the proof, it can literally change the data and show it to you since the goverment is the central authority and it has the power to change any of the bank records. So you can understand, this system is not much transparent.

But if it the bank records would be stored in blockchain, then government had to show us the actual record and it cannot modify the record of any transactions as blockchain eliminates the requirement of a central authority.

Blockchain data, once verified is put up in the blockchain network, cannot be modified and since its distributed over a large network of computers, it is hard to destory thus making the blockchain network a transparent network and a more trustable network.

]]>In this workshop, we are going to build our own cryptocurrency on the ethereum network with solidity. The features of our coin will be as follows:

- Only the owner can make new coins
- Anyone can send coins to each other without a need for registration. You need is the ethereum address.

`pragma solidity ^0.8.4;contract Coin {}`

Since everything is accessed by a smart contract, we need to create this coin through a smart contract itself.

`minter`

`balances`

The `balances`

will be a mapping reference of solidity and it will have the key value pairs of the receiver's address and the amount each of them will get.

We will set the adress of the `minter`

in the constructor so that the one who deploys the contract becomes the owner of the cryptocurrency.

`pragma solidity ^0.8.4;contract SubCurrency { address public minter; mapping (address => uint) public balances; constructor () { minter = msg.sender; }}`

`mint`

function which will enable us to do 2 things:- Make new coins and send them to address
- Only the owner can send the coins

`pragma solidity ^0.8.4;contract SubCurrency { address public minter; mapping (address => uint) public balances; constructor () { minter = msg.sender; } function mint(address receiver, uint amount) public { require(msg.sender == minter); balances[receiver] += amount; }}`

This event will contain the address of the owner, the address of the client and the amount we send to them

`pragma solidity ^0.8.4;contract SubCurrency { address public minter; mapping (address => uint) public balances; constructor () { minter = msg.sender; } function mint(address receiver, uint amount) public { require(msg.sender == minter); balances[receiver] += amount; } event Sent(address from, address to, uint amount);}`

This even allows us to store the arguments passed in the transaction logs and these logs are stored on the blockchain and can be accessed using an address of the contract.

This function will enable us to send anyamount ot coins to existing addresses.

While we trigger this function, the amount of the owner should decrease the amount to be given to the reciever needs to increase.

`function send(address receiver, uint amount) public { balances[msg.sender] -= amount; balances[receiver] += amount;}`

But here's the catch. If the owner onwr himself doesn't have enough coins then also it can send the coins to its reciever. So we need to modify this function and make sure that the amount to be sent must not be greater than the balance of the owner. And last but not the least, we need to emit the event.

`error insuffieientBalance(uint requested, uint available); function send(address receiver, uint amount) public { if (amount > balances[msg.sender]) revert insuffieientBalance({ requested: amount, available: balances[msg.sender] }); balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, reciever, amount); }`

`pragma solidity ^0.8.4;contract SubCurrency { address public minter; mapping (address => uint) public balances; constructor () { minter = msg.sender; } function mint(address receiver, uint amount) public { require(msg.sender == minter); balances[receiver] += amount; } event Sent(address from, address to, uint amount); error insuffieientBalance(uint requested, uint available); function send(address receiver, uint amount) public { if (amount > balances[msg.sender]) revert insuffieientBalance({ requested: amount, available: balances[msg.sender] }); balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, receiver, amount); }}`

Deploy the contract after compiling and test it. You are good to go.

]]>