for Robot Artificial Inteligence

6.Functions

|

Example 1

#include <iostream>

using namespace std;
/*functions / methods */
//parameter
void welcome(); //declaration of function, procedure
bool isNumber(string);
void enterName();
double add(double a, double b) {return a + b;}
void changeValueTo10(int a)
{
  a = 10;
}
int main()
{
   // welcome();
   /* enterName();
    enterName();
    enterName();*/
    char ch;
    cout << "Do you want to end the program? (Y/N)" << endl;

    cin >> ch;
    if (ch == 'Y' || ch == 'y')
    return 0;
   // cout << add(4,5);
    int a = 5;

    changeValueTo10(a);

    cout << a;

    return 0;
}

void welcome()
{
    cout << "HEllo, welcome in my program!! :-)" << endl;
}
bool isNumber(string tmp)
{
    if (tmp[0] == '0')
        return false;
    for (int i = 0; i < tmp.length(); i++)
    {
        if (!(tmp[i] >= 48 && tmp[i] <= 57))
            return false;
    }

    return true;
}
void enterName()
{
    string tmp;

    cout << "Enter the number: " << endl;
    cin >> tmp; //124

    if (isNumber(tmp))
        cout << "Number entered properly " << endl;
    else
        cout << "Number wasn't entered properly " << endl;
}

Example 2

#include <iostream>
#define PI 3.14
using namespace std;
// the belows are declaration of function
void initMenu();
void menuDecision(int);
double areaCircle(double);
double areaSquare(double);
double areaRectangle(double, double);
double areaTriangle(double, double);
int main()
{
    int choice;
    char cont;
    do
    {
        system("cls"); //clear screen = cls
        initMenu();

        cin >> choice;

        menuDecision(choice);

        do
        {
            cout << "Do you want to continue the program? (Y/N)" << endl;
            cin >> cont;
        } while(cont != 'y' && cont != 'Y' && cont != 'N' && cont != 'n');


    } while(cont == 'y' || cont == 'Y');

    return 0;
}
void initMenu()
{
    cout << "Enter option:" << endl;
    cout << "1. Circle" << endl;
    cout << "2. Square" << endl;
    cout << "3. Rectangle" << endl;
    cout << "4. Triangle" << endl;
}
void menuDecision(int choice)
{
    double r, a, b, h;
    switch(choice)
    {
        case 1:
            cout << "Enter the radius: " << endl;
            cin >> r;
            areaCircle(r);
            break;
        case 2:
            cout << "Enter the side of a square: " << endl;
            cin >> a;
            areaSquare(a);
            break;
        case 3:
            cout << "Enter the width and height of a rectangle: " << endl;
            cin >> a >> b;
            areaRectangle(a, b);
            break;
        case 4:
            cout << "Enter the base and height of a triangle: " << endl;
            cin >> a >> h;
            areaTriangle(a, h);
            break;
        default:
            cout << "You didn't choose any of the option from above" << endl;

    }
}
double areaCircle(double r)
{
    double result = PI * r * r;

    cout << "The area of a circle that radius is " << r << " = " << result << endl;

    return result;
}
double areaSquare(double a)
{
    double result = a * a;

    cout << "The area of a square that side is " << a << " = " << result << endl;

    return result;
}
double areaRectangle(double a, double b)
{
    double result = a * b;

    cout << "The area of a rectangle that first side is " << a << " the second side is " << b << " = " << result << endl;

    return result;
}
double areaTriangle(double a, double h)
{
    double result = (1/2.0) * a * h;

    cout << "The area of a rectangle that first side is " << a << " the second side is " << h << " = " << result << endl;

    return result;
}

Example 3

#include <iostream>

using namespace std;

/* overloading functions */
int power(int, int);
double power(double, int);
int main()
{

    cout << power(2, 6) << endl;

    return 0;
}

/*
    2 ^ 3 = 2 * 2 * 2

    2 ^ 1 = 2
    2 ^ 2 = 4
    2 ^ 3 = 8
*/
int power(int b, int e) // b = 8, e = 1
{
    int tmp = b; //tmp = 2
    int i = 0;

    while(i++ < e)
    {
        cout << tmp << " ^ " << i << " = " << b << endl;
        if (i != e)
            b *= tmp; //b = b * tmp;
    }

    return b;
}
double power(double b, int e)
{
    double tmp = b; //tmp = 2
    while(e-- > 1)
        b *= tmp; //b = b * tmp;

    return b;
}

Example 4

#include <iostream>

using namespace std;
/*scope / range of varables */

int globalVariable;

main()
{
    int localVariable;
/*
    cout << "value of globalVariable: " << globalVariable << endl;
    cout << "value of localVariable: " << localVariable << endl;
*/
    int a = 10;
/*
    if (a == 10)
    {
        int result = a * 10;
    }



    cout << result << endl;*/

    int nr, result = 0;
    int i = 0;
    for (; i < 3; i++) // 3,2,3 - will the result be 8??? NOOOOOOOOO, we have to assign 0 to the result!
    {
        cout << "Enter " << (i + 1) << " number" << endl;
        cin >> nr;
        result += nr; //result = result + nr;
    }

    cout << result << endl;
    cout << "we added " << i << " numbers" << endl;
}

Example 5

#include <iostream>
#include <cstdlib>

using namespace std;

double minValue(double tab[]);
double maxValue(double tab[]);


int main ()
{
    double tab[5];

    for (int i = 0; i < 5; i++)
    {
        cout << "Input " << i+1 << " number: ";
        cin >> tab[i];
    }

    cout << "The minimum value was: " << minValue(tab) << endl;
    cout << "The maximum value was: " << maxValue(tab) << endl;

    return 0;
}

double minValue(double tab[])
{
    double minValue = tab[0];

    for (int i = 1; i < 5; i++)
    {
        if (minValue > tab[i])
            minValue = tab[i];

    }

    return minValue;
}
double maxValue(double tab[])
{
    double maxValue = tab[0];

    for (int i = 1; i < 5; i++)
    {
        if (maxValue < tab[i])
            maxValue = tab[i];

    }

    return maxValue;
}

Example 6

#include <iostream>
#include <limits> // to make "cin.ignore(numeric_limits<streamsize>::max(), '\n');"r active
#define PI 3.14
using namespace std;
/*validating data
    buffer - temporary array
*/
void initMenu();
void menuDecision(int);
double areaCircle(double);
double areaSquare(double);
double areaRectangle(double, double);
double areaTriangle(double, double);
bool isValid(string);
bool isValid();
int main()
{
    int choice;
    char cont;
    do
    {
        system("cls"); //clear screen = cls
        initMenu();

        while(!(cin >> choice))
        {
            //cout << "state before: " << cin.rdstate() << endl;
            cin.clear();
            //cout << "state after: " << cin.rdstate() << endl;
            cin.ignore(numeric_limits<streamsize>::max(), '\n'); // skip the '\n' charcter left in the input buffer
            // 정수를 입력받은 후에 문자열을 입력받지 않고 다음 코드로 넘어간다. 버퍼에 정수값을 누른 엔터가 남아있어 그렇다. getline을 이용하기 위해서는 정수값을 입력받은뒤 ignore을 사용한다.

            system("cls");
            initMenu();
            cout << "You've just typed the wrong data to the input. " << endl;
        }

        menuDecision(choice);

        do
        {
            cout << "Do you want to continue the program? (Y/N)" << endl;
            cin >> cont; //asdfg
            cin.ignore(numeric_limits<streamsize>::max(), '\n');

        } while(cont != 'y' && cont != 'Y' && cont != 'N' && cont != 'n');


    } while(cont == 'y' || cont == 'Y');

    return 0;
}
void initMenu()
{
    cout << "Enter option:" << endl;
    cout << "1. Circle" << endl;
    cout << "2. Square" << endl;
    cout << "3. Rectangle" << endl;
    cout << "4. Triangle" << endl;
}
void menuDecision(int choice)
{
    double r, a, b, h;
    switch(choice)
    {
        case 1:

            do { cout << "Enter the radius: " << endl; cin >> r; } while(!isValid());
            areaCircle(r);
            break;
        case 2:
            cout << "Enter the side of a square: " << endl;
            do { cin >> a; } while(!isValid("The data is wrong, please type it again:"));
            areaSquare(a);
            break;
        case 3:
            cout << "Enter the width and height of a rectangle: " << endl;
            do { cin >> a >> b; } while(!isValid("The data is wrong, please type it again:"));
            areaRectangle(a, b);
            break;
        case 4:
            cout << "Enter the base and height of a triangle: " << endl;
            do { cin >> a >> h; } while(!isValid("The data is wrong, please type it again:"));
            areaTriangle(a, h);
            break;
        default:
            cout << "You didn't choose any of the option from above" << endl;

    }
}
double areaCircle(double r)
{
    double result = PI * r * r;

    cout << "The area of a circle that radius is " << r << " = " << result << endl;

    return result;
}
double areaSquare(double a)
{
    double result = a * a;

    cout << "The area of a square that side is " << a << " = " << result << endl;

    return result;
}
double areaRectangle(double a, double b)
{
    double result = a * b;

    cout << "The area of a rectangle that first side is " << a << " the second side is " << b << " = " << result << endl;

    return result;
}
double areaTriangle(double a, double h)
{
    double result = (1/2.0) * a * h;

    cout << "The area of a rectangle that first side is " << a << " the second side is " << h << " = " << result << endl;

    return result;
}
bool isValid(string error_msg)
{
    if (cin.rdstate()) //state is wrong when it is not equal to 0
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        system("cls");
        initMenu();
        cout << error_msg << endl;
        return false;
    }

    return true;
}
bool isValid()
{
    if (cin.rdstate()) //state is wrong when it is not equal to 0 // state is not wrong when it is equal to 0
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); // skip the enter key left in the buffer
        system("cls");
        initMenu();
        return false;
    }

    return true;
}


Comment  Read more

5. Zodiac Sign

|

Zodiac Sign

from datetime import date

Year = input("What's your year of birth? [ex: 1992]" )
Month = input("What's your month of birth? [ex: 10]" )
Day = input("What's your day of birth? [ex: 25]" )
print('Your Date of Birth is ', (Day + "/" + Month + "/" + Year))
today_day = date.today()
today_day
age = today_day.year - int(Year)
print('You are', age, 'years old')


if ((int(Month)==12 and int(Day) >= 22) or (int(Month)==1 and int(Day)<= 19)):
    sign = ("\n Capricorn")
elif ((int(Month)==1 and int(Day) >= 20)or(int(Month)==2 and int(Day)<= 18)):
    sign = ("\n aquarius")
elif ((int(Month)==2 and int(Day) >= 19)or(int(Month)==3 and int(Day)<= 20)):
    sign = ("\n Pisces")
elif ((int(Month)==3 and int(Day) >= 21)or(int(Month)==4 and int(Day)<= 19)):
    sign = ("\n Aries")
elif ((int(Month)==4 and int(Day) >= 20)or(int(Month)==5 and int(Day)<= 20)):
    sign = ("\n Taurus")
elif ((int(Month)==5 and int(Day) >= 21)or(int(Month)==6 and int(Day)<= 20)):
    sign = ("\n Gemini")
elif ((int(Month)==6 and int(Day) >= 21)or(int(Month)==7 and int(Day)<= 22)):
    sign = ("\n Cancer")
elif ((int(Month)==7 and int(Day) >= 23)or(int(Month)==8 and int(Day)<= 22)):
    sign = ("\n Leo")
elif ((int(Month)==8 and int(Day) >= 23)or(int(Month)==9 and int(Day)<= 22)):
    sign = ("\n Virgo")
elif ((int(Month)==9 and int(Day) >= 23)or(int(Month)==10 and int(Day)<= 22)):
    sign = ("\n Libra")
elif ((int(Month)==10 and int(Day) >= 23)or(int(Month)==11 and int(Day)<= 21)):
    sign = ("\n Scorpio")
elif ((int(Month)==11 and int(Day) >= 22)or(int(Month)==12 and int(Day)<= 21)):
    sign = ("\n Sagittarius")

print(sign)

Comment  Read more

5.Loops

|

Example 1

#include <iostream>

using namespace std;
/* loops - break and continue */

main()
{
    /*
        1 2 3 4 5  6  7  8  9  10
        2 4 6 8 10 12 14 16 18 20
        3 6 9 12 15 ....
        4 ...
        5 ...
    */
/*
    for (int i = 1; i <= 10; i++) //amount of rows, length of column
    {

        if (i == 5)
            continue; //EVERYTHING AFTER continue instruction WONT BE executed BUT LOOP WON'T END BECAUSE OF IT

        if (i == 5)
            break; //EVERYTHING after break WON't be executed AND we are LEAVING the ACTUAL LOOP


        for (int j = 1; j <= 10; j++) //amount of columns, length of row
        {
            if (j == 5)
                continue;
            cout.width(4);
            cout << i * j;
        }
        cout << endl;
    }
*/


    for (int i = 1, j = 1; i <= 10; i++)
    {
        cout.width(4); // 4 spaces
        cout << i * j;

        if (i == 10)
        {
            j++;
            i = 0;
            cout << endl;
        }

        if (j == 10 + 1)
            break;
    }
}


Example 2

#include <iostream>

using namespace std;

main()
{
    const int SIZEOFARRAY = 10;
    int i = 0;
    int array[SIZEOFARRAY];

    while(i < SIZEOFARRAY) //i = 0
    {
        array[i] = 10 * i;
        cout << array[i++] << endl;
    }

}

Example 3

#include <iostream>
#include <cstdlib>

using namespace std;

main ()
{
     int pin, checkPin;
     int counter = 5;

     cout << "Input your pin number for the first time: ";
     cin >> pin;

     system("cls");

     do
     {
         cout << "Input your pin(" << counter << " tries left): ";
         cin >> checkPin;

         system("cls");
         counter--;

     } while ((checkPin != pin) && (counter > 0));

     if (checkPin == pin)
     {
        cout << "Correct pin, welcome !";
     }
     else
        cout << "You have entered a wrong PIN code for 5 times !";

}


Example 4

#include <iostream>

using namespace std;

main ()
{
    char coordinates[3][3];
    char value = '1';

    for (int i = 0; i < 3; i++)
    {
        cout << endl << endl;
        for (int j = 0; j < 3; j++)
        {
            coordinates[i][j] = value;
            value++;

            cout.width(5);
            cout << coordinates[i][j] << " ";

        }
        cout << endl << endl;
    }

}

Example 5

#include <iostream>
#include <cstdlib>

using namespace std;

main ()
{
    char coordinates[3][3];
    int startingValue = '1';
    int player = 2;

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            coordinates[i][j] = startingValue;
            startingValue++;
        }
    }

    while (true)
    {
        for (int i = 0; i < 3; i++)
        {
            cout << endl << endl;
            for (int j = 0; j < 3; j++)
            {
                cout.width(5);
                cout << coordinates[i][j] << " ";
            }
            cout << endl << endl;
        }

        int xCoordinate, yCoordinate;

        if (player % 2 == 0)
        {
            cout << "Input x and y coordinates of a cell to put X (7 is on x:1 y:3)" << endl;

            cout << "x: ";
            cin >> xCoordinate;

            cout << "y: ";
            cin >> yCoordinate;

            coordinates[yCoordinate-1][xCoordinate-1] = 'X';
            player = 1;
            system("cls");
        }
        else
        {

            cout << "Input x and y coordinates of a cell to put O (7 is on x:1 y:3)" << endl;

            cout << "x: ";
            cin >> xCoordinate;

            cout << "y: ";
            cin >> yCoordinate;

            coordinates[yCoordinate-1][xCoordinate-1] = 'O';
            player = 2;
            system("cls");

        }
    }
}


Example 6

#include <iostream>
#include <cstdlib>

using namespace std;

main ()
{
    char coordinates[3][3];
    int startingValue = '1';
    int player = 2;
    bool moveAccepted;

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            coordinates[i][j] = startingValue;
            startingValue++;
        }
    }

    while (true)
    {

        int xCoordinate, yCoordinate;


            do
            {
                for (int i = 0; i < 3; i++)
                {
                    cout << endl << endl;
                    for (int j = 0; j < 3; j++)
                    {
                        cout.width(5);
                        cout << coordinates[i][j] << " ";
                    }
                    cout << endl << endl;
                }

                if (player % 2 == 0)
                {
                    cout << "Input x and y coordinates (values from 1 to 3) of a cell to put X (7 is on x:1 y:3)" << endl;
                }
                else
                {
                    cout << "Input x and y coordinates (values from 1 to 3) of a cell to put O (7 is on x:1 y:3)" << endl;
                }

                do
                {
                    cout << "x: ";
                    cin >> xCoordinate;

                } while(xCoordinate <= 0 || xCoordinate > 3);


                do
                {
                    cout << "y: ";
                    cin >> yCoordinate;

                } while(yCoordinate <= 0 || yCoordinate > 3);

                if (coordinates[yCoordinate-1][xCoordinate-1] != 'X' && coordinates[yCoordinate-1][xCoordinate-1] != 'O')
                {
                    if (player % 2 == 0)
                    {
                        coordinates[yCoordinate-1][xCoordinate-1] = 'X';
                        player = 1;
                    }
                    else
                    {
                        coordinates[yCoordinate-1][xCoordinate-1] = 'O';
                        player = 2;
                    }
                    moveAccepted = true;
                    system ("cls");
                }
                else
                {
                    moveAccepted = false;
                    system ("cls");
                }
            } while(moveAccepted == false);



        }
}


Example 7

#include <iostream>
#include <cstdlib>

using namespace std;

main ()
{
    int chosenNumbersSum = 0;
    char choice;

    for (int i = 1; ; i++)
    {

        cout << "The current sum is: " << chosenNumbersSum << endl << endl;
        cout << "Do you want to add " << i << " ?" << endl;

        cout << "Y - yes / N - no / Anything else - end : ";
        cin >> choice;

        if (choice == 'Y' || choice == 'y')
        {
            chosenNumbersSum += i;
        }
        else if (choice == 'N' || choice == 'n')
        {
            system ("cls");
            continue;
        }
        else
        {
            system ("cls");
            break;
        }
        system ("cls");
    }

    cout << "Good bye !";

}

Comment  Read more

Singapore 3 Day

|

Comment  Read more

4. Detect Lane in Camera images

|

CODE TO SELECT WHITE PIXELS OUT OF THE IMAGE

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
image_color = mpimg.imread('image_lane_c.jpg')
image_color.shape
# (540, 960, 3)
plt.imshow(image_color)

image_copy = np.copy(image_color)
image_copy.shape
#(540, 960, 3)
image_copy[ (image_copy[:,:,0] < 200) | (image_copy[:,:,1] < 200) | (image_copy[:,:,2] < 200) ] = 0  # any value that is not white colour
# Display the image                 
plt.imshow(image_copy, cmap = 'gray')
plt.show()

plt.imshow(image_color)

CODE TO PERFORM COLOR SELECTION

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
image_color = mpimg.imread('image_lane_c.jpg')
image_color.shape
# (540, 960, 3)
plt.imshow(image_color)

image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)
plt.imshow(image_gray, cmap = 'gray')
image_gray.shape
# (540, 960)

image_copy = np.copy(image_gray) #copy image_gray
image_copy.shape
# (540, 960)
image_copy
array([[191, 191, 192, ..., 191, 191, 191],
       [191, 191, 191, ..., 191, 191, 191],
       [191, 191, 191, ..., 191, 191, 191],
       ...,
       [161, 163, 160, ..., 190, 191, 191],
       [170, 168, 160, ..., 185, 186, 187],
       [164, 156, 145, ..., 172, 173, 173]], dtype=uint8)
image_copy[ (image_copy[:,:] < 250) ] = 0  # any value that is not white colour
# any of the pixel value less than 250, 0
# it store new array from [(image_copy[:,:])]
# Display the image                 
plt.imshow(image_copy, cmap = 'gray')
plt.show()

CODE TO PERFORM REGION OF INTEREST (ROI) SELECTION

import cv2
import numpy as np
import matplotlib.image as mpimg
#from matplotlib import pyplot as plt #plotting fram work.
import matplotlib.pyplot as plt # it is same as from matplotlib import pyplot as plt
%matplotlib inline
# magic function in python, it help to see picture immediately in notebook jupiter

image_color = cv2.imread('image_lane_c.jpg')
#image_color = mpimg.imread('image_lane_c.jpg') # import image as RGB instead of BGR

cv2.imshow('Original Image', image_color) # opencv open with RGB as real picture
cv2.waitKey()
cv2.destroyAllWindows()
image_color.shape
# (540, 960, 3)
height, width = image_color.shape[:2] # give to valeu height, width by list
# height 540
# width 960
plt.imshow(image_color) # plt. fucntion open with BGR color by matplotlib
# that's why the cv.imshow and plt.imshow picture difference

image_color.shape
# (540, 960, 3)
image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)
plt.imshow(image_gray, cmap = 'gray')

image_gray.shape # when it change to gray, the number of color is eare
# (540, 960)
# Select points of the region of interest (ROI)
ROI = np.array([[(0, height),(400, 330), (550, 330), (width, height)]], dtype=np.int32)    
# first point, second point, third point.
# (0,height) means we gonna stop when height is reached ( corner point)
# (width,height) means we gonna stop when width and height is reached ( corner point)

# define a blank image with all zeros (ie: black)
blank = np.zeros_like(image_gray)   
blank.shape
#(540, 960)

# Fill the Region of interest with white color (ie: 255)!
mask = cv2.fillPoly(blank, ROI, 255)
#polyynomial specifying any of it our image which is our blank image our ROI
#255 because we want to fill that rigion of interest with once(white)
# Perform bitwise AND operation to select only the region of interest
masked_image = cv2.bitwise_and(image_gray, mask)
# take our image_gray and take mask.
# like it all together.
# bitwise means that put together
masked_image.shape
#(540, 960)
plt.imshow(mask,'gray')


plt.imshow(masked_image, cmap = 'gray')

Comment  Read more