Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the twentytwenty domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in C:\inetpub\wwwroot\blogs\wp-includes\functions.php on line 6121
Club TechKnowHow! – Page 8 – Born to learn…
Categories
Data Structures & Algorithms

Removing nth Node From End of Linked List

The most basic approach to this problem would be to iterate over the entire linked list once to find out the length of the list. Then iterate over it again to locate the node to be removed. This can be done in the following way:

Let n be the length of the list and we need to remove the mth element from the end so we will have to remove the (n-m)th element from the list.

However this approach requires having to iterate over the list twice and hence the time complexity will be O(2n). We can solve this problem in O(n) time complexity also by using the following approach:

  • Declare 2 pointers – last and prev and initialize both of them to to point to head
  • Iterate the last pointer m times.
  • Iterate both the pointers last and prev till last.next == null.

After following these 3 steps out prev pointer will be pointing to the node just before the one that needs to be removed from the list. Now we can simply remove the required node by pointing prev.next to prev.next.next

 

static void remove_nth_node(LinkedList l, int n) 
{
        Node last = l.head;
        Node prev = l.head;
        for (int i = 0; i < n; i++)
        {
            last = last.next;
        }
        while (last.next != null)
        {
            last = last.next;
            prev = prev.next;
        }
        prev.next = prev.next.next;
}

 

Categories
Data Structures & Algorithms

Reversing a Linked List

If we had to reverse the elements of an array we would have to iterate over then entire array and swap the ith element with the (n-i-1)th element where n is the size of the array.

Now in a linked list we are not required to swap the data in the nodes. Instead we can achieve the same by just reversing the pointers, initializing the head to the last element of the given linked list and point the head of the original linked list to null.

So we will create 2 variables; one of them will always point to the node that the current node needs to point at, and the other will always point to the node the current node is currently pointing at. If we iterate till the current node – starting from head is not ‘null’ then we would have reversed the entire linked list.

 

static void reverse_linked_list(LinkedList l) {
        Node prev = null;
        Node temp = l.head;
        while (l.head != null) {
            temp = l.head.next;
            l.head.next = prev;
            prev = l.head;
            l.head = temp;
        }
        l.head = prev;
}

 

Categories
Data Structures & Algorithms

Linked Lists

Linked lists are linear data structures, which consist of nodes. These nodes store data in them as well as point to the next node in the list. So each node in the list has 2 attributes, one of the datatype you are trying to store which will hold the actual data and one of the datatype ‘Node’ which will point to the next node in the list. Linked lists are better than arrays as we do not have to move around as many elements in the list when doing operations such as insertions, deletions and updations at the beginning, end or at a random node in the list as compared to arrays. This makes using them more efficient.

I will be posting solutions of questions solved in java based on the comcepts of linked lists.

Categories
Uncategorized

Snake Game in Java

In my third semester at university, I had taken the ‘Computer Programming in Java’, while learning all the core concepts of java I thought it would be fun to try and make a game in the process. I tried making the snake game! The logic of the game is very simple and straight forward. If the snake head hits its own body or the edges of the screen then game over, if the snake head hits the apple then increment the length of the snake by 1 and increment the score also by 1, allow turning only in 90 degrees to avoid turning the snake head into itself – say for instance the snake is moving forward and the user presses the down arrow key; we would not want the snake to make a 180 degree turn as that will lead to a game over.

I learnt a lot of new stuff while making this game like – how to build a basic graphic user interface in java using the inbuilt packages, and how to use Key Adapters : they were used in making the snake turn when the arrow keys were pressed.

You can find the source code to the game here – https://github.com/AryanBhirud/SnakeGame_in_Java/

Categories
Python

Determinant of matrices using Python

 

In this article, I will teach you to find the determinant of a matrix using the Python programming language.

Prerequisites:

  • In programming (Python) –
    • Lists and operations on lists
    • Concept and understanding of Recursion
  • In Maths –

Revision:

A list in Python is a sequence of objects and is denoted by square brackets.

my_list = [1, 5, 3, 7]

Recursion is a concept of calling the same function inside the function itself.

def factorial(n):
   if n == 1:
       return n
   else:
       return n * factorial(n-1)

 

A matrix is an arrangement of numbers in a specific, systematic order of rows and columns, like this –

A determinant of a matrix is an operation on a matrix which returns a single number, and is often denoted like :
Determinant of a matrix A = |A|

A determinant of a matrix is calculated as follows-

Determinant of a matrix calculation

= 3 × (2×6 - 4×3)   -   4 × (2×6 - 3×5)   +   7 × (2×4 - 5×2)
= 3 × 0   -   4 × (-3)   +   7 × (-2)
= 0 + 12 - 14
= -2

 

Solution:

We will design a function that takes in a 2d list as input and gives a single number as the output. The input 2d-list would be our matrix and the output would be the determinant, or the final answer.

We can find the determinant of the matrix using the standard technique (Laplace expansion)-

So, we will take the first row of the matrix element-by-element and multiply it with the determinant of the remaining matrix, like,

a11 × |a22  a23 …|
⠀        |a32  a33 …|
⠀        |…     …        |

Thus, we will use the technique of recursion in this way:

def determinant(matrix):
    ans = 0
    for my_element in first_row_of_matrix:
        ans = ans + (-1)^index_of_my_element * my_element * determinant(matrix_without_the_row_and_column_of_my_element)
    return ans

But we need to define the end-condition for our recursion somewhere. So, the best and the simplest way is when the input matrix is just a 2×2 matrix, and we can just cross-multiply its elements.

So, our code becomes –

def determinant(matrix):
    if size(matrix) == (2×2):
        return cross_multiplication_of_elements_in_matrix
    else:
        ans = 0
        for my_element in first_row_of_matrix:
            ans = ans + (-1)^index_of_my_element * my_element * determinant(matrix_without_the_row_and_column_of_my_element)
        return ans

That’s it! This is the whole logic, and now we just have code this in python!

The first ‘if’ statement is simple to write –

def determinant(matrix):
    if len(matrix) == 2:
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]

In the else statement, we first have to slice the matrix so that the row and the column of the selected element are not present in the sliced matrix.
A matrix ‘matrix2’ is initialized which is the sliced version of the input matrix.

def determinant(matrix):
    if len(matrix) == 2:
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
    else:
        ans = 0
        for element in range(len(matrix)):
            matrix2 = []
            # This part of the code slices matrix to matrix2
            for count in range(len(matrix)-1):
                matrix3 = []
                for count2 in range(len(matrix)-1):
                    matrix3.append(0)
                matrix2.append(matrix3)
            # Now, matrix2 is a blank matrix of filled with zeros of the required size (size when one row and one column is sliced from original matrix)
            # Now, we start 'filling' matrix2 with the required elements from input matrix
            i = 0
            while i < len(matrix)-1:
                j = 0
                a = 0
                while j < len(matrix)-1:
                    if j == element:
                        a += 1
                    matrix2[i][j] = matrix[i+1][j+a]
                    j += 1
                i += 1
            # matrix2 is created, we just now calculate the determinant and add it to the ans
                        
            ans += ((-1)**elementx) * matrix[0][element] * (determinant(matrix2))
        return ans

Footnotes:

The code written by us is in no way fast – there are many optimizations available. This code is written from the perspective of understanding and not from the perspective of speed.

Thank you for taking out time to read this. I hope you learnt something new!