giulio98/xlcost-single-prompt huggingface dataset:
# sum of matrix in which each element is absolute difference of its row and column numbers | return the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; 
def findSum(n):
    sum = 0
    for i in range(n):
        sum += i * (n - i)
    return 2 * sum


n = 3
print(findSum(n))

# Expected output:
8
# sum of matrix in which each element is absolute difference of its row and column numbers | return the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; 
def findSum(n):
    n -= 1
    sum = 0
    sum += (n * (n + 1)) / 2
    sum += (n * (n + 1) * (2 * n + 1)) / 6
    return int(sum)


n = 3
print(findSum(n))

# Expected output:
8
# sum of both diagonals of a spiral odd | function returns sum of diagonals ; as order should be only odd we should pass only odd integers ; 
def spiralDiaSum(n):
    if n == 1:
        return 1
    return (4 * n * n - 6 * n + 6 + spiralDiaSum(n - 2))


n = 7
print(spiralDiaSum(n))

# Expected output:
261
# find perimeter of shapes formed with 1 s in binary matrix | python3 program to find perimeter of area covered by 1 in 2d matrix consisits of 0 ' s ▁ and ▁ 1' s . ; find the number of covered side for mat [ i ] [ j ] . ; up ; left ; down ; right ; returns sum of perimeter of shapes formed with 1 s ; traversing the matrix and finding ones to calculate their contribution . ; 

R = 3
C = 5


def numofneighbour(mat, i, j):
    count = 0
    if (i > 0 and mat[i - 1][j]):
        count += 1
    if (j > 0 and mat[i][j - 1]):
        count += 1
    if (i < R - 1 and mat[i + 1][j]):
        count += 1
    if (j < C - 1 and mat[i][j + 1]):
        count += 1
    return count


def findperimeter(mat):
    perimeter = 0
    for i in range(0, R):
        for j in range(0, C):
            if (mat[i][j]):
                perimeter += (4 - numofneighbour(mat, i, j))
    return perimeter


mat = [[0, 1, 0, 0, 0], [1, 1, 1, 0, 0], [1, 0, 0, 0, 0]]
print(findperimeter(mat), end="")

# Expected output:
12
# print matrix in diagonal pattern | python 3 program to print matrix in diagonal order ; initialize indexes of element to be printed next ; direction is initially from down to up ; traverse the matrix till all elements get traversed ; if isup = true then traverse from downward to upward ; set i and j according to direction ; if isup = 0 then traverse up to down ; set i and j according to direction ; revert the isup to change the direction ; 

MAX = 100


def printMatrixDiagonal(mat, n):
    i = 0
    j = 0
    k = 0
    isUp = True
    while k < n * n:
        if isUp:
            while i >= 0 and j < n:
                print(str(mat[i][j]), end=" ")
                k += 1
                j += 1
                i -= 1
            if i < 0 and j <= n - 1:
                i = 0
            if j == n:
                i = i + 2
                j -= 1
        else:
            while j >= 0 and i < n:
                print(mat[i][j], end=" ")
                k += 1
                i += 1
                j -= 1
            if j < 0 and i <= n - 1:
                j = 0
            if i == n:
                j = j + 2
                i -= 1
        isUp = not isUp


if __name__ == "__main__":
    mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    n = 3
    printMatrixDiagonal(mat, n)

# Expected output:
1 2 4 7 5 3 6 8 9
# maximum difference of sum of elements in two rows in a matrix | function to find maximum difference of sum of elements of two rows such that second row appears before first row . ; auxiliary array to store sum of all elements of each row ; calculate sum of each row and store it in rowsum array ; calculating maximum difference of two elements such that rowsum [ i ] < rowsum [ j ] ; if current difference is greater than previous then update it ; if new element is less than previous minimum element then update it so that we may get maximum difference in remaining array ; 
def maxRowDiff(mat, m, n):
    rowSum = [0] * m
    for i in range(0, m):
        sum = 0
        for j in range(0, n):
            sum += mat[i][j]
        rowSum[i] = sum
    max_diff = rowSum[1] - rowSum[0]
    min_element = rowSum[0]
    for i in range(1, m):
        if (rowSum[i] - min_element > max_diff):
            max_diff = rowSum[i] - min_element
        if (rowSum[i] < min_element):
            min_element = rowSum[i]
    return max_diff


m = 5
n = 4
mat = [[-1, 2, 3, 4], [5, 3, -2, 1],
       [6, 7, 2, -3], [2, 9, 1, 4], [2, 1, -2, 0]]
print(maxRowDiff(mat, m, n))

# Expected output:
9
# total coverage of all zeros in a binary matrix | python3 program to get total coverage of all zeros in a binary matrix ; returns total coverage of all zeros in mat [ ] [ ] ; looping for all rows of matrix ; 1 is not seen yet ; looping in columns from left to right direction to get left ones ; if one is found from left ; if 0 is found and we have found a 1 before . ; repeat the above process for right to left direction . ; traversing across columms for up and down directions . ; 1 is not seen yet ; 

R = 4
C = 4


def getTotalCoverageOfMatrix(mat):
    res = 0
    for i in range(R):
        isOne = False
        for j in range(C):
            if (mat[i][j] == 1):
                isOne = True
            elif (isOne):
                res += 1
        isOne = False
        for j in range(C - 1, -1, -1):
            if (mat[i][j] == 1):
                isOne = True
            elif (isOne):
                res += 1
    for j in range(C):
        isOne = False
        for i in range(R):
            if (mat[i][j] == 1):
                isOne = True
            elif (isOne):
                res += 1
        isOne = False
        for i in range(R - 1, -1, -1):
            if (mat[i][j] == 1):
                isOne = True
            elif (isOne):
                res += 1
    return res


mat = [[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 0]]
print(getTotalCoverageOfMatrix(mat))

# Expected output:
20
# count all sorted rows in a matrix | function to count all sorted rows in a matrix ; initialize result ; start from left side of matrix to count increasing order rows ; check if there is any pair ofs element that are not in increasing order . ; if the loop didn 't break (all elements of current row were in increasing order) ; start from right side of matrix to count increasing order rows ( reference to left these are in decreasing order ) ; check if there is any pair ofs element that are not in decreasing order . ; note c > 1 condition is required to make sure that a single column row is not counted twice ( note that a single column row is sorted both in increasing and decreasing order ) ; 
def sortedCount(mat, r, c):
    result = 0
    for i in range(r):
        j = 0
        for j in range(c - 1):
            if mat[i][j + 1] <= mat[i][j]:
                break
        if j == c - 2:
            result += 1
    for i in range(0, r):
        j = 0
        for j in range(c - 1, 0, -1):
            if mat[i][j - 1] <= mat[i][j]:
                break
        if c > 1 and j == 1:
            result += 1
    return result


m, n = 4, 5
mat = [[1, 2, 3, 4, 5], [4, 3, 1, 2, 6], [8, 7, 6, 5, 4], [5, 7, 8, 9, 10]]
print(sortedCount(mat, m, n))

# Expected output:
3
# maximum xor value in matrix | python3 program to find maximum xor value in matrix either row / column wise maximum number of row and column ; function return the maximum xor value that is either row or column wise ; for row xor and column xor ; traverse matrix ; xor row element ; for each column : j is act as row & i act as column xor column element ; update maximum between r_xor , c_xor ; return maximum xor value ; 

MAX = 1000


def maxXOR(mat, N):
    max_xor = 0
    for i in range(N):
        r_xor = 0
        c_xor = 0
        for j in range(N):
            r_xor = r_xor ^ mat[i][j]
            c_xor = c_xor ^ mat[j][i]
        if (max_xor < max(r_xor, c_xor)):
            max_xor = max(r_xor, c_xor)
    return max_xor


N = 3
mat = [[1, 5, 4], [3, 7, 2], [5, 9, 10]]
print("maximum XOR value : ", maxXOR(mat, N))

# Expected output:
maximum XOR value :  12
# direction at last square block | function which tells the current direction ; 
def direction(R, C):
    if (R != C and R % 2 == 0 and C % 2 != 0 and R < C):
        print("Left")
        return
    if (R != C and R % 2 == 0 and C % 2 == 0 and R > C):
        print("Up")
        return
    if R == C and R % 2 != 0 and C % 2 != 0:
        print("Right")
        return
    if R == C and R % 2 == 0 and C % 2 == 0:
        print("Left")
        return
    if (R != C and R % 2 != 0 and C % 2 != 0 and R < C):
        print("Right")
        return
    if (R != C and R % 2 != 0 and C % 2 != 0 and R > C):
        print("Down")
        return
    if (R != C and R % 2 == 0 and C % 2 != 0 and R < C):
        print("Left")
        return
    if (R != C and R % 2 == 0 and C % 2 == 0 and R > C):
        print("Up")
        return
    if (R != C and R % 2 != 0 and C % 2 != 0 and R > C):
        print("Down")
        return
    if (R != C and R % 2 != 0 and C % 2 != 0 and R < C):
        print("Right")
        return


R = 3
C = 1
direction(R, C)

# Expected output:
Down
# print k 'th element in spiral form of matrix |  ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; check the first row from the remaining rows ; check the last column from the remaining columns ; check the last row from the remaining rows ; check the first column from the remaining columns ; 

R = 3
C = 6


def spiralPrint(m, n, a, c):
    k = 0
    l = 0
    count = 0
    while (k < m and l < n):
        for i in range(l, n):
            count += 1
            if (count == c):
                print(a[k][i], end=" ")
        k += 1
        for i in range(k, m):
            count += 1
            if (count == c):
                print(a[i][n - 1], end=" ")
        n -= 1
        if (k < m):
            for i in range(n - 1, l - 1, -1):
                count += 1
                if (count == c):
                    print(a[m - 1][i], end=" ")
            m -= 1
        if (l < n):
            for i in range(m - 1, k - 1, -1):
                count += 1
                if (count == c):
                    print(a[i][l], end=" ")
            l += 1


a = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]
k = 17
spiralPrint(R, C, a, k)

# Expected output:
10
# print k 'th element in spiral form of matrix | python3 program for kth element in spiral form of matrix ; function for kth element ; element is in first row ; element is in last column ; element is in last row ; element is in first column ; recursion for sub - matrix . & a [ 1 ] [ 1 ] is address to next inside sub matrix . ; 

MAX = 100


def findK(A, n, m, k):
    if (n < 1 or m < 1):
        return -1
    if (k <= m):
        return A[0][k - 1]
    if (k <= (m + n - 1)):
        return A[(k - m)][m - 1]
    if (k <= (m + n - 1 + m - 1)):
        return A[n - 1][m - 1 - (k - (m + n - 1))]
    if (k <= (m + n - 1 + m - 1 + n - 2)):
        return A[n - 1 - (k - (m + n - 1 + m - 1))][0]
    A .pop(0)
    [j .pop(0)for j in A]
    return findK(A, n - 2, m - 2, k - (2 * n + 2 * m - 4))


a = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]
k = 17
print(findK(a, 3, 6, k))

# Expected output:
10
# find if given matrix is toeplitz or not | python3 program to check whether given matrix is a toeplitz matrix or not ; function to check if all elements present in descending diagonal starting from position ( i , j ) in the matrix are all same or not ; mismatch found ; we only reach here when all elements in given diagonal are same ; function to check whether given matrix is a toeplitz matrix or not ; do for each element in first row ; check descending diagonal starting from position ( 0 , j ) in the matrix ; do for each element in first column ; check descending diagonal starting from position ( i , 0 ) in the matrix ; we only reach here when each descending diagonal from left to right is same ; 

N = 5
M = 4


def checkDiagonal(mat, i, j):
    res = mat[i][j]
    i += 1
    j += 1
    while (i < N and j < M):
        if (mat[i][j] != res):
            return False
        i += 1
        j += 1
    return True


def isToeplitz(mat):
    for j in range(M):
        if not (checkDiagonal(mat, 0, j)):
            return False
    for i in range(1, N):
        if not (checkDiagonal(mat, i, 0)):
            return False
    return True


if __name__ == "__main__":
    mat = [[6, 7, 8, 9], [4, 6, 7, 8], [
        1, 4, 6, 7], [0, 1, 4, 6], [2, 0, 1, 4]]
    if (isToeplitz(mat)):
        print("Matrix is a Toeplitz")
    else:
        print("Matrix is not a Toeplitz")

# Expected output:
Matrix is a Toeplitz
# find if given matrix is toeplitz or not | python3 program to check whether given matrix is a toeplitz matrix or not ; row = number of rows col = number of columns ; dictionary to store key , value pairs ; if key value exists in the map , ; we check whether the current value stored in this key matches to element at current index or not . if not , return false ; else we put key , value pair in map ; 
def isToeplitz(matrix):
    row = len(matrix)
    col = len(matrix[0])
    map = {}
    for i in range(row):
        for j in range(col):
            key = i - j
            if (key in map):
                if (map[key] != matrix[i][j]):
                    return False
            else:
                map[key] = matrix[i][j]
    return True


if __name__ == "__main__":
    matrix = [[12, 23, -32], [-20, 12, 23], [56, -20, 12], [38, 56, -20]]
    if (isToeplitz(matrix)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count zeros in a row wise and column wise sorted matrix | python program to count number of 0 s in the given row - wise and column - wise sorted binary matrix . ; function to count number of 0 s in the given row - wise and column - wise sorted binary matrix . ; start from bottom - left corner of the matrix ; stores number of zeroes in the matrix ; move up until you find a 0 ; if zero is not found in current column , we are done ; add 0 s present in current column to result ; move right to next column ; 

N = 5


def countZeroes(mat):
    row = N - 1
    col = 0
    count = 0
    while (col < N):
        while (mat[row][col]):
            if (row < 0):
                return count
            row = row - 1
        count = count + (row + 1)
        col = col + 1
    return count


mat = [[0, 0, 0, 0, 1], [0, 0, 0, 1, 1], [
    0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
print(countZeroes(mat))

# Expected output:
8
# find size of the largest ' + ' formed by all ones in a binary matrix | size of binary square matrix ; function to find the size of the largest ' + ' formed by all 1 's in given binary matrix ; left [ j ] [ j ] , right [ i ] [ j ] , top [ i ] [ j ] and bottom [ i ] [ j ] store maximum number of consecutive 1 's present to the left,  right, top and bottom of mat[i][j] including  cell(i, j) respectively ; initialize above four matrix ; initialize first row of top ; initialize last row of bottom ; initialize first column of left ; initialize last column of right ; fill all cells of above four matrix ; calculate left matrix ( filled left to right ) ; calculate top matrix ; calculate new value of j to calculate value of bottom ( i , j ) and right ( i , j ) ; calculate bottom matrix ; calculate right matrix ; revert back to old j ; n stores length of longest ' + ' found so far ; compute longest + ; find minimum of left ( i , j ) , right ( i , j ) , top ( i , j ) , bottom ( i , j ) ; largest + would be formed by a cell that has maximum value ; 4 directions of length n - 1 and 1 for middle cell ; matrix contains all 0 's ; 

N = 10


def findLargestPlus(mat):
    left = [[0 for x in range(N)]for y in range(N)]
    right = [[0 for x in range(N)]for y in range(N)]
    top = [[0 for x in range(N)]for y in range(N)]
    bottom = [[0 for x in range(N)]for y in range(N)]
    for i in range(N):
        top[0][i] = mat[0][i]
        bottom[N - 1][i] = mat[N - 1][i]
        left[i][0] = mat[i][0]
        right[i][N - 1] = mat[i][N - 1]
    for i in range(N):
        for j in range(1, N):
            if (mat[i][j] == 1):
                left[i][j] = left[i][j - 1] + 1
            else:
                left[i][j] = 0
            if (mat[j][i] == 1):
                top[j][i] = top[j - 1][i] + 1
            else:
                top[j][i] = 0
            j = N - 1 - j
            if (mat[j][i] == 1):
                bottom[j][i] = bottom[j + 1][i] + 1
            else:
                bottom[j][i] = 0
            if (mat[i][j] == 1):
                right[i][j] = right[i][j + 1] + 1
            else:
                right[i][j] = 0
            j = N - 1 - j
    n = 0
    for i in range(N):
        for j in range(N):
            l = min(min(top[i][j], bottom[i][j]), min(left[i][j], right[i][j]))
            if (l > n):
                n = l
    if (n):
        return 4 * (n - 1) + 1
    return 0


if __name__ == "__main__":
    mat = [
        [
            1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [
            1, 0, 1, 0, 1, 1, 1, 0, 1, 1], [
                1, 1, 1, 0, 1, 1, 0, 1, 0, 1], [
                    0, 0, 0, 0, 1, 0, 0, 1, 0, 0], [
                        1, 1, 1, 0, 1, 1, 1, 1, 1, 1], [
                            1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [
                                1, 0, 0, 0, 1, 0, 0, 1, 0, 1], [
                                    1, 0, 1, 1, 1, 1, 0, 0, 1, 1], [
                                        1, 1, 0, 0, 1, 0, 1, 0, 0, 1], [
                                            1, 0, 1, 1, 1, 1, 0, 1, 0, 0]]
    print(findLargestPlus(mat))

# Expected output:
17
# return previous element in an expanding matrix | returns left of str in an expanding matrix of a , b , c , and d . ; start from rightmost position ; if the current character is b or d , change to a or c respectively and break the loop ; if the current character is a or c , change it to b or d respectively ; 
def findLeft(str):
    n = len(str) - 1
    while (n > 0):
        if (str[n] == 'd'):
            str = str[0:n] + 'c' + str[n + 1:]
            break
        if (str[n] == 'b'):
            str = str[0:n] + 'a' + str[n + 1:]
            break
        if (str[n] == 'a'):
            str = str[0:n] + 'b' + str[n + 1:]
        elif (str[n] == 'c'):
            str = str[0:n] + 'd' + str[n + 1:]
        n -= 1
    return str


if __name__ == '__main__':
    str = "aacbddc"
    print("Left of", str, "is", findLeft(str))

# Expected output:
Left of aacbddc is aacbdcd
# print n x n spiral matrix using o ( 1 ) extra space | prints spiral matrix of size n x n containing numbers from 1 to n x n ; finds minimum of four inputs ; for upper right half ; for lower left half ; 
def printSpiral(n):
    for i in range(0, n):
        for j in range(0, n):
            x = min(min(i, j), min(n - 1 - i, n - 1 - j))
            if (i <= j):
                print((n - 2 * x) * (n - 2 * x) -
                      (i - x) - (j - x), end="TABSYMBOL")
            else:
                print(((n - 2 * x - 2) * (n - 2 * x - 2) +
                      (i - x) + (j - x)), end="TABSYMBOL")
        print()


n = 5
printSpiral(n)

# Expected output:
25TABSYMBOL24TABSYMBOL23TABSYMBOL22TABSYMBOL21TABSYMBOL
10TABSYMBOL9TABSYMBOL8TABSYMBOL7TABSYMBOL20TABSYMBOL
11TABSYMBOL2TABSYMBOL1TABSYMBOL6TABSYMBOL19TABSYMBOL
12TABSYMBOL3TABSYMBOL4TABSYMBOL5TABSYMBOL18TABSYMBOL
13TABSYMBOL14TABSYMBOL15TABSYMBOL16TABSYMBOL17TABSYMBOL
# shortest path in a binary maze | python program to find the shortest path between a given source cell to a destination cell . ; to store matrix cell cordinates ; a data structure for queue used in bfs ; the cordinates of the cell ; cell 's distance from the source ; check whether given cell ( row , col ) is a valid cell or not ; return true if row number and column number is in range ; these arrays are used to get row and column numbers of 4 neighbours of a given cell ; function to find the shortest path between a given source cell to a destination cell . ; check source and destination cell of the matrix have value 1 ; mark the source cell as visited ; create a queue for bfs ; distance of source cell is 0 ; enqueue source cell ; do a bfs starting from source cell ; if we have reached the destination cell , we are done ; otherwise enqueue its adjacent cells ; if adjacent cell is valid , has path and not visited yet , enqueue it . ; mark cell as visited and enqueue it ; return - 1 if destination cannot be reached ; 

from collections import deque
ROW = 9
COL = 10


class Point:
    def __init__(self, x: int, y: int):
        self .x = x
        self .y = y


class queueNode:
    def __init__(self, pt: Point, dist: int):
        self .pt = pt
        self .dist = dist


def isValid(row: int, col: int):
    return (row >= 0) and (row < ROW) and (col >= 0) and (col < COL)


rowNum = [-1, 0, 0, 1]
colNum = [0, -1, 1, 0]


def BFS(mat, src: Point, dest: Point):
    if mat[src .x][src .y] != 1 or mat[dest .x][dest .y] != 1:
        return -1
    visited = [[False for i in range(COL)]for j in range(ROW)]
    visited[src .x][src .y] = True
    q = deque()
    s = queueNode(src, 0)
    q .append(s)
    while q:
        curr = q .popleft()
        pt = curr .pt
        if pt .x == dest .x and pt .y == dest .y:
            return curr .dist
        for i in range(4):
            row = pt .x + rowNum[i]
            col = pt .y + colNum[i]
            if (isValid(row, col) and mat[row][col]
                    == 1 and not visited[row][col]):
                visited[row][col] = True
                Adjcell = queueNode(Point(row, col), curr .dist + 1)
                q .append(Adjcell)
    return -1


def main():
    mat = [
        [
            1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [
            1, 0, 1, 0, 1, 1, 1, 0, 1, 1], [
                1, 1, 1, 0, 1, 1, 0, 1, 0, 1], [
                    0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [
                        1, 1, 1, 0, 1, 1, 1, 0, 1, 0], [
                            1, 0, 1, 1, 1, 1, 0, 1, 0, 0], [
                                1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [
                                    1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [
                                        1, 1, 0, 0, 0, 0, 1, 0, 0, 1]]
    source = Point(0, 0)
    dest = Point(3, 4)
    dist = BFS(mat, source, dest)
    if dist != -1:
        print("Shortest Path is", dist)
    else:
        print("Shortest Path doesn't exist")


main()

# Expected output:
Shortest Path is 11
def find(arr):
    n = len(arr)
    i = 0
    j = n - 1
    res = -1
    while i < n and j >= 0:
        if arr[i][j] == 0:
            while j >= 0 and (arr[i][j] == 0 or i == j):
                j -= 1
            if j == -1:
                res = i
                break
            else:
                i += 1
        else:
            while i < n and (arr[i][j] == 1 or i == j):
                i += 1
            if i == n:
                res = j
                break
            else:
                j -= 1
    if res == -1:
        return res
    for i in range(0, n):
        if res != i and arr[i][res] != 1:
            return -1
    for j in range(0, j):
        if res != j and arr[res][j] != 0:
            return -1
    return res


arr = [[0, 0, 1, 1, 0], [0, 0, 0, 1, 0], [
    1, 1, 1, 1, 0], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1]]
print(find(arr))

# Expected output:
3