Saturday, September 2, 2023

UDP Pinger testing

 Objective: 

In this assignment, you will write a client ping program in Python. Your client will send a simple ping message to a server, receive a corresponding pong message back from the server, and determine the delay between when the client sent the ping message and received the pong message. This delay is called the Round-Trip Time (RTT). The functionality provided by the client and server is similar to the functionality provided by standard ping program available in modern operating systems. However, standard ping programs use the Internet Control Message Protocol (ICMP) Here we will create a nonstandard (but simple!)  

Method UDP-based on :

1. Generate a random sequence number.

2. Create a ping message with the sequence number & the current time.

3. Send the ping message to the server.

4. Set a timeout of 1 second.

5. Try to receive a response from the server.

6. If a response is received, print it.

7. Calculate and print the round-trip time (RTT).

8. If no response is received within 1 second, print "Request timed out".

Techniques 

1. Create a UDP Ping Server Python program alter Compile and run this code before running your client program. You do not need to modify this code. In this server code, 30% of the client’s packets are simulated to be lost. Study this code carefully, as it will help you write your ping client program.

2. When the server program is running, you should see loop listening for incoming UDP packets. When a packet comes in and if a randomized integer is greater than or equal to 11, the server simply capitalizes the encapsulated data and sends it back to the client.

+ Source code for UDP Server

import random

from socket import * 

serverSocket = socket(AF_INET, SOCK_DGRAM) 

serverSocket.bind(('127.0.0.1', 5090)) 

print("Started UDP server on ip: 127.0.0.1 and port 5090") 

while True: 

rand = random.randint(0, 10)

 message, address = serverSocket.recvfrom(1024) 

 message = message.upper() 

 if rand < 4: 

     continue 

 serverSocket.sendto(message, address) 


-------------------------------------------------------------------------------------------------Result 




Type : Python UDPServer.py


UDPClient.py 






Share:

Comparing multi-thread and single threads

1. Introduction

Briefly explain the purpose the background of the multithreaded sorting application. Highlight the importance of sorting algorithms and the need for efficient sorting techniques in various domains.

Multithreaded sorting application is a program that sorts a data set using multiple threads and single thread. Each multi-thread is responsible for sorting a portion of the data set, and the results are then merged together to form the sorted output.

Here are some of the most common sorting algorithms that can be used in multithreaded applications

-        Quicksort

-        Merge sort

-        Tree sort

-        Bubble sort

-        Insertion sort

The choice of sorting algorithm will depend on the specific application and the characteristics of the data set. For my opinion, I am going to choose two algorithms are insertion sort is a good choice sort data sets that are randomly distributed, while merge sort is a good choice for data sets that are already partially sorted

2.    2. Objective

The main objective of a multithreaded sorting application is improved performance and reduced execution time compared to traditional single-threaded sorting algorithms. By using multiple threads, it can distribute the task of sorting data across available CPU cores or processing units, thereby making better use of system resources and achieving faster results.

3.     3. Sorting algorithm

3.1            Insertion sort algorithm

Insertion sort is a simple sorting algorithm that works by repeatedly inserting a new element into the correct position in a sorted list. The algorithm starts with the first element in the list, which is considered to be sorted. Then, each subsequent element is inserted into the sorted list in its correct place.

How to insertion sort work:


1.       We start by making the second element of the given array, i.e. element at index 1, the key.

2.  We compare the key element with the element(s) before it, in this case,

element at index 0:

• If the key element is less than the first element, we insert the key element

before the first element.

• If the key element is greater than the first element, then we insert it after

the first element.

3. Then, we make the third element of the array as key and will compare it with

elements to it's left and insert it at the right position.

4.       And we go on repeating this, until the array is sorted.

 

3.1  3.2 merge sort algorithm

Sure. Merge sort is a sorting algorithm that works by dividing an array into smaller subarrays, sorting each subarray, and then merging the sorted subarrays back together to form the final sorted array.

·       Merge Sort uses a divide and conquer paradigm for sorting.

·       It divides the problem into sub problems and solves them individually.

·       It then combines the results of sub problems to get the solution of the original problem

Merge Sort Algorithm works in the following steps-

• It divides the given unsorted array into two halves- left and right sub arrays.

• The sub arrays are divided recursively.

• This division continues until the size of each sub array becomes 1.

• After each sub array contains only a single element then merge procedure is

called.

• The merge procedure combines these trivially sorted arrays to produce a final sorted array.

4.4.   Result

                The figure of graph that compares the execution time of a task with a single thread and multiple threads. The x-axis represents the number of threads, while the y-axis represents the execution time. The line labeled "Single Thread" indicates that the execution time increases as the number of array increases. This is because each thread must share the CPU, so the less time each thread has to execute its code as the number of threads grows. The line labeled "multi-threads" indicates that the execution time decreases as the number of array increases. This is because multiple threads can run concurrently, which

For example, consider the array size of 100: the single-threaded approach takes 2 ms to complete, while the multi-threaded approach takes only 1 ms. Similarly, for larger array sizes, the multi-threaded approach consistently demonstrates faster execution times compared to the single-threaded approach and when the array size is 500, the improvement from using multi-threaded processing is quite significant, but as the array size reaches 500,000, the improvement becomes less pronounced. This is likely because as the array size gets larger, the overhead of managing and synchronizing multiple threads becomes more significant, which can offset some of the benefits of parallel.

5.  Conclusion

based on the graph comparing single and multi-thread, we can conclude that as the array size increases, the processing time also increases. Additionally, using multi-threaded processing can result in faster processing times compared to single-threaded processing, particularly for larger array sizes. However, the improvement in processing time diminishes as the array size gets larger.

In general, the multi-threaded approach yields significant speed improvements over the single-threaded approach, which is expected as it allows for parallel processing and utilization of multiple CPU cores.


+ Source code in java 

Main: 

import java.lang.reflect.Array;

import java.util.Arrays;

import java.util.Scanner;

import java.util.Random;

public class Main {

    public static void main(String[] args) throws InterruptedException {

        int ArraySize, i, j, k; // Set matrix size by Rows = Column

        long begintime, endtime; // Start and stop time sortime calculate

        Scanner scan = new Scanner(System.in);

        System.out.print("Input size of array element: ");

        ArraySize = scan.nextInt();

        Random rand = new Random();

        // Input array element by random

        int[] array = new int[ArraySize];

        for(i=0; i<ArraySize; i++)

        {

            array[i] = rand.nextInt(100000000);

        }

begintime = System.currentTimeMillis();

        // Separate array to two part (array1 & array2)

        int array1[];

        int array2[];

        if(ArraySize % 2 == 0)

        {

            array1 = new int[ArraySize/2];

            array2 = new int[ArraySize/2];

            for(i=0; i<array1.length; i++)

            {

                array1[i] = array[i];

                array2[i] = array[(ArraySize/2)+i];

            }

        }

        else

        {

            array1 = new int[(ArraySize+1)/2];

            array2 = new int[(ArraySize-1)/2];

            for(i=0; i<array1.length; i++)

            {

                array1[i] = array[i];

            }

            for(i=0; i<array2.length; i++)

            {

                array2[i] = array[array1.length + i];

            }

        }

        endtime = System.currentTimeMillis();

        // Print original array element

        System.out.println("\nOriginal Array, generate by random");

        System.out.println(Arrays.toString(array));

        System.out.print("\nSeparate to two parts for calculate multi thread\n");

        System.out.println(" Part 1: " + Arrays.toString(array1));

        System.out.println(" Part 2: " + Arrays.toString(array2));

    //Single Thread (1 Thread)

        // Print sorted array element using single thread

        begintime = System.currentTimeMillis();

        Try_insertionSort ResultSthread = new Try_insertionSort(array, ArraySize, ArraySize);

        Thread Sthread = new Thread(ResultSthread);

        Sthread.start();

        Sthread.join();

        System.out.println("\nSingle thread, sorted array");

        System.out.println(Arrays.toString(ResultSthread.result()));

        endtime = System.currentTimeMillis();

        long timesingle = endtime - begintime;

        // Multi Thread (2 Threads) calculate

        //Print sorted array element using multi thread

        begintime = System.currentTimeMillis();

        Try_insertionSort ResultThread1 = new Try_insertionSort(array1, array1.length, array1.length);

        Thread Thread1 = new Thread(ResultThread1);

        Thread1.start();

        Thread1.join();

        Try_insertionSort ResultThread2 = new Try_insertionSort(array2, array2.length, array2.length);

        Thread Thread2 = new Thread(ResultThread2);

        Thread2.start();

        Thread2.join();

        System.out.println("\n\nMultiple thread, sorted array");

        System.out.println("thread 1: " + Arrays.toString(array1));

        System.out.println("Thread 2: " + Arrays.toString(array2));

        endtime = System.currentTimeMillis();

        long timemulti = endtime - begintime;

        i=0; j = 0; k=0;

        int [] mergedArray = new int[array1.length + array2.length];


        // sort array after divide to sublist already

        while(i<array1.length && j< array2.length)

        {

            if(array1[i] <= array2[j])

            {

                mergedArray[k++] = array1[i++];

            }

            else

            {

                mergedArray[k++] = array2[j++];

            }

        }

        while (i< array1.length)

        {

            mergedArray[k++] = array1[i++];

        }

        while (j< array2.length)

        {

            mergedArray[k++] = array2[j++];

        }

        System.out.println("Merged Thread: " + Arrays.toString(mergedArray));

        System.out.println("---------------------------------");

        System.out.println("Elapsed Time single thread: " +timesingle+ " mili seconds");

        System.out.println("Elapsed Time Maged time : " + timemulti+ " mili seconds");

    }

}

------------------------------------------------------------------------------------------------------------------------
create function for sort 

public class Try_insertionSort  implements Runnable {

    private int array[];

    private int i, j, n;

    public Try_insertionSort(int[] array, int i, int j) {

        n = array.length;

        this.array = array;

        this.i = i;

        this.j = j;

    }

    public int[] result() {

        return array;

    }

    @Override

    public void run() {

        for (int i = 1; i < array.length; i++) {

            int key = array[i];

            int j = i - 1;

            while (j >= 0 && array[j] > key) {

                array[j + 1] = array[j];

                j--;

            }

            array[j + 1] = key;

        }

    }

}



Share:

Wednesday, August 30, 2023

Calculate Determinant matrix with n dimension user input




Result in python code













2. Source code 

def calculate_determinant(matrix):

    dimension = len(matrix)

    if dimension == 1:

        return matrix[0][0]

    determinant = 0

    for col in range(dimension):

        sub_matrix = [[0] * (dimension - 1) for _ in range(dimension - 1)]

        for i in range(1, dimension):

            curr_col = 0

            for j in range(dimension):

                if j != col:

                    sub_matrix[i - 1][curr_col] = matrix[i][j]

                    curr_col += 1

        sub_determinant = calculate_determinant(sub_matrix)

        determinant += ((-1) ** col) * matrix[0][col] * sub_determinant

    return determinant

while True:

    try:

        dimension = int(input("Enter the dimension of the matrix: "))

        matrix = []

        for i in range(dimension):

            row = []

            for j in range(dimension):

                while True:

                    try:

                        element = int(input(f"Enter element at position a{i+1}{j+1}: "))

                        break

                    except ValueError:

                        print("Invalid input. Please enter a numeric value.")

                row.append(element)

            matrix.append(row)

        print("\nMatrix:")

        for row in matrix:

            print(" ".join(str(num) for num in row))

        determinant = calculate_determinant(matrix)

        print("\nDeterminant:", determinant)

    except ValueError:

        print("Invalid matrix input. Please enter numeric values only.")

Share:

Calculate Determinant, Inverse, calculate inverse matrix with Gaussian elimination using with python programming

 Final exam math using python for calculates result. 



លំហាត់


Answer with python programming

We use Jupyter Notebook in anaconda, and you can use python online ide for run simulations.

1. Result 

Exercises 8



Source code combine exercise  8

def calculate_determinant(matrix):
    dimension = len(matrix)

    if dimension == 1:
        return matrix[0][0]

    determinant = 0

    for col in range(dimension):
        sub_matrix = [[0] * (dimension - 1) for _ in range(dimension - 1)]
        for i in range(1, dimension):
            curr_col = 0
            for j in range(dimension):
                if j != col:
                    sub_matrix[i - 1][curr_col] = matrix[i][j]
                    curr_col += 1
        sub_determinant = calculate_determinant(sub_matrix)
        determinant += ((-1) ** col) * matrix[0][col] * sub_determinant

    return determinant


def get_cofactor(matrix, row, col):
    return [row[:col] + row[col + 1:] for row in (matrix[:row] + matrix[row + 1:])]


def calculate_adjoint(matrix):
    dimension = len(matrix)

    adj = [[0] * dimension for _ in range(dimension)]

    for i in range(dimension):
        for j in range(dimension):
            cofactor = get_cofactor(matrix, i, j)
            adj[j][i] = ((-1) ** (i + j)) * calculate_determinant(cofactor)

    return adj


def calculate_inverse(matrix):
    det = calculate_determinant(matrix)

    if det == 0:
        print("Singular matrix, can't find its inverse")
        return None

    dimension = len(matrix)
    inv = [[0] * dimension for _ in range(dimension)]

    adj = calculate_adjoint(matrix)

    for i in range(dimension):
        for j in range(dimension):
            inv[i][j] = adj[i][j] / det

    return inv


def display(matrix):
    for row in matrix:
        print(" ".join(str(num) for num in row))


def enter_matrix():
    dimension = int(input("Enter the dimension of the matrix: "))

    matrix = []
    for i in range(dimension):
        row = []
        for j in range(dimension):
            while True:
                try:
                    element = int(input(f"Enter element at position a{i+1}{j+1}: "))
                    break
                except ValueError:
                    print("Invalid input. Please enter a numeric value.")
            row.append(element)
        matrix.append(row)

    return matrix


def gaussian_elimination(matrix):
    dimension = len(matrix)
    augmented_matrix = []
    for i in range(dimension):
        row = list(matrix[i]) + [1 if j == i else 0 for j in range(dimension)]
        augmented_matrix.append(row)

    for i in range(dimension):
        pivot_row = i
        for j in range(i + 1, dimension):
            if abs(augmented_matrix[j][i]) > abs(augmented_matrix[pivot_row][i]):
                pivot_row = j

        augmented_matrix[i], augmented_matrix[pivot_row] = augmented_matrix[pivot_row], augmented_matrix[i]

        pivot = augmented_matrix[i][i]
        augmented_matrix[i] = [elem / pivot for elem in augmented_matrix[i]]

        for j in range(dimension):
            if j != i:
                factor = augmented_matrix[j][i]
                augmented_matrix[j] = [elem - factor * augmented_matrix[i][idx] for idx, elem in
                                       enumerate(augmented_matrix[j])]

    inverse = [row[dimension:] for row in augmented_matrix]
    return inverse


while True:
    try:
        matrix = enter_matrix()

        print("\nMatrix:")
        display(matrix)

        determinant = calculate_determinant(matrix)
        print("\nDeterminant:", determinant)

        print("\nAdjoint:")
        adjoint_matrix = calculate_adjoint(matrix)
        display(adjoint_matrix)

        print("\nInverse using adjoint_matrix/determinant:")
        inverse_matrix = calculate_inverse(matrix)
        if inverse_matrix is not None:
            display(inverse_matrix)

        inverse_matrix_ge = gaussian_elimination(matrix)
        for i in range(len(inverse_matrix_ge)):
            for j in range(len(inverse_matrix_ge[i])):
                inverse_matrix_ge[i][j] = round(inverse_matrix_ge[i][j])
        print("Inverse Matrix using gaussian_elimination  :")
        for row in inverse_matrix_ge:
            print(row)

    except ValueError:
        print("Invalid matrix input. Please enter numeric values only.")



Exercises 9

1. Calculate crammer's rule

source code for only crammer's rule
def calculate_determinant(matrix):
    # for 2x2 matrix
    if len(matrix) == 2:
        determinant_2x2 = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
        return determinant_2x2

    determinant_ndimension = 0
    for k in range(len(matrix)):
        sign = (-1) ** k
        sub_matrix = [row[:k] + row[k+1:] for row in matrix[1:]]
        sub_det = calculate_determinant(sub_matrix)
        determinant_ndimension += sign * matrix[0][k] * sub_det

    return determinant_ndimension


def calculate_cramer(matrix, result):
    determinant = calculate_determinant(matrix)
    if determinant == 0:
        return None  # Unable to solve, determinant is zero
    
    dimension = len(matrix)
    solutions = []
    for i in range(dimension):
        modified_matrix = [row.copy() for row in matrix]  # Create a copy of the original matrix
        
        for j in range(dimension):
            modified_matrix[j][i] = result[j]
        
        solution = calculate_determinant(modified_matrix) / determinant
        solutions.append(solution)
    
    return solutions

def display(matrix):
    print("Matrix:")
    for row in matrix:
        print(" ".join(str(num) for num in row))

def main():
    try:
        dimension = int(input("Enter the dimension of the matrix: "))
    except ValueError:
        print("Invalid input. Please enter a numeric value.")
        return
  
    matrix = []  
    print("Enter the matrix:")
    for i in range(dimension):
        row = []
        for j in range(dimension):
            variable = chr(ord('x') + j)  # Convert 0-based index to variable label
            while True:
                try:
                    element = int(input(f"Simultaneous equation {i+1}, {variable}(a){i+1}{j+1}: "))
                    break
                except ValueError:
                    print("Invalid input. Please enter a numeric value.")
            row.append(element)
        matrix.append(row)
    
    result = []
    print("Enter the result b of Simultaneous equation:")
    for i in range(dimension):
        variable = chr(ord('x') + i)  # Convert 0-based index to variable label
        while True:
            try:
                element = int(input(f"Enter result for equation b{i+1} of Simultaneous equation {i+1}: "))
                break
            except ValueError:
                print("Invalid input. Please enter a numeric value.")
        result.append(element)
    display(matrix)
    solutions = calculate_cramer(matrix, result)
    if solutions is None:
        print("Unable to solve the system of equations. Determinant is zero.")
    else:
        print("Solutions:")
        for i, solution in enumerate(solutions):
            variable = chr(ord('x') + i)  # Convert 0-based index to variable label
            print(f"{variable} = {solution}")
    
    

if __name__ == "__main__":
    main()















 

















Share: