diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..7d434e2 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,50 @@ +{ + "files.associations": { + "array": "cpp", + "atomic": "cpp", + "bit": "cpp", + "*.tcc": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "compare": "cpp", + "concepts": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "string": "cpp", + "unordered_map": "cpp", + "vector": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "functional": "cpp", + "iterator": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "random": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "initializer_list": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "new": "cpp", + "numbers": "cpp", + "ostream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "typeinfo": "cpp", + "sstream": "cpp" + }, + "C_Cpp.errorSquiggles": "disabled" +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..a6d8aad --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,28 @@ +{ + "tasks": [ + { + "type": "cppbuild", + "label": "C/C++: gcc.exe build active file", + "command": "C:\\MinGW\\bin\\gcc.exe", + "args": [ + "-fdiagnostics-color=always", + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${fileDirname}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + }, + "detail": "Task generated by Debugger." + } + ], + "version": "2.0.0" +} \ No newline at end of file diff --git a/December 01/java_Sunandita.java b/December 01/java_Sunandita.java new file mode 100644 index 0000000..ecc72a7 --- /dev/null +++ b/December 01/java_Sunandita.java @@ -0,0 +1,37 @@ +/* ******* INPUT FORMAT ******** + +Line 1 contains number of values n +Line two consists n space separated values + +EXAMPLE + + 9 + 10 20 30 40 50 60 70 80 90 + + */ + + +import java.util.*; +public class java_Sunandita { + + public static void main(String args[]){ + int max=0; + int sums=0; + try (Scanner s = new Scanner(System.in)) { + int n=s.nextInt(); + int arr[]=new int[n]; + for(int i=0;iarr[max]){ + max=i; + } + } + } + System.out.println(sums); + System.out.println(max); + } +} \ No newline at end of file diff --git a/December 02/python3_Sunandita-R.py b/December 02/python3_Sunandita-R.py new file mode 100644 index 0000000..4635984 --- /dev/null +++ b/December 02/python3_Sunandita-R.py @@ -0,0 +1,16 @@ +""" + +INPUT FORMAT :One line of Space separated integers +Example : 2 2 3 4 5 6 2 4 6 7 + +""" + + +l=[int(x) for x in input().split()] +freq=[] +visited=[] +for i in l: + if i not in visited: + freq.append(l.count(i)) + visited.append(i) +print(freq) \ No newline at end of file diff --git a/December 03/c_Sunandita-R.c b/December 03/c_Sunandita-R.c new file mode 100644 index 0000000..2c27507 --- /dev/null +++ b/December 03/c_Sunandita-R.c @@ -0,0 +1,29 @@ +/* ******* INPUT FORMAT ******** + +Line 1 contains number of values n +Line two consists n space separated values + +EXAMPLE + + 5 + 7 4 8 2 9 + + */ + + +#include +int main(){ +int n,i; +scanf("%d",&n); +int arr[n]; +for(i=0;imax){ + count++; + max=arr[i]; + } +} +printf("%d",count); +} \ No newline at end of file diff --git a/December 04/c_Sunandita-R_mirrormagic.c b/December 04/c_Sunandita-R_mirrormagic.c new file mode 100644 index 0000000..b87da2e --- /dev/null +++ b/December 04/c_Sunandita-R_mirrormagic.c @@ -0,0 +1,61 @@ +/* + + INPUT FORMAT: A single spaceless string without quotes + Example : Hollow + +*/ + + +#include +#include +#include + +bool isPalindrome(char str[], int start, int end) { + while (start < end) { + if (str[start] != str[end]) { + return false; + } + start++; + end--; + } + return true; +} + +void generateSmallestPalindrome(char str[]) { + int len = strlen(str); + int start=0; + int end=len-1; + int min=end-start; + char res[len]; + bool flag=false; + while(start=avg): + gtl.append(i) +sum=0 +for i in gtl: + sum+=i +print(sum) \ No newline at end of file diff --git a/December 06/python_Sunandita-R_LostAlgorithmScrolls.py b/December 06/python_Sunandita-R_LostAlgorithmScrolls.py new file mode 100644 index 0000000..80b0bcd --- /dev/null +++ b/December 06/python_Sunandita-R_LostAlgorithmScrolls.py @@ -0,0 +1,62 @@ +""" +Approach chosen : All the words that can be obtained by adding/removing the first or last letter + from the previous word is also chosen to be a part of a chain. + +Example : [ dot, dote, eagle] +Output: [ dot, dote] Here since addition of single letter in the end to dot gives the next word dote + The two words form a sequence. + +In case of 2 or more sequence : Sequence with greatest length is chosen + +If the sequences are equal in length the first valid chain is chosen + + + *********** INPUT FORMAT ****** + + Single line of space separated strings without quotes + + Example: cat cot dog doll coat + +""" + +l=[str(x) for x in input().split()] + +l2=[] +res=[] +for i in range(0,len(l)-1): + flag=False + if(len(l[i])==len(l[i+1])): + count=0 + for j in range(0,len(l[i])): + + if(l[i][j]!=l[i+1][j]): + count+=1 + if(count==1): + flag=True + elif(len(l[i])+1==len(l[i+1])): + n=len(l[i]) + + if((l[i][0:n]==l[i+1][0:n]) or (l[i][0:n+1]==l[i+1][1:n+1])): + flag=True + elif(len(l[i])==len(l[i+1])+1): + n=len(l[i+1]) + + if((l[i][0:n]==l[i+1][0:n])or (l[i][1:n+1]==l[i+1][0:n+1]) ): + flag=True + + if(flag==True): + if(l2==[]): + l2.append(l[i]) + l2.append(l[i+1]) + else: + l2.append(l[i+1]) + if(len(l2)>len(res)): + res=l2 + else: + l2=[] +if(res==[]): + print("No valid chain") +else: + print(res) + + diff --git a/December 07/java_Sunandita_babyblocks.java b/December 07/java_Sunandita_babyblocks.java new file mode 100644 index 0000000..2b7bf40 --- /dev/null +++ b/December 07/java_Sunandita_babyblocks.java @@ -0,0 +1,38 @@ +/* + * First two lines in the output is the Sample input output of Testcase 1 + * + * It is followwed by a prompt to accept user input + * + * ****** INPUT FORMAT ***** + * + * A single line of Three space separated integers + * + * Example : 5 9 5 + */ + +import java.util.Scanner; + +public class java_Sunandita_babyblocks { + + public static void main(String args[]){ + int height,width,rad; + try (Scanner s = new Scanner(System.in)) { + System.out.println("rectangleInCircle(8, 6, 5)"); + block(8,6,5); + width=s.nextInt(); + height=s.nextInt(); + rad=s.nextInt(); + block(width, height, rad); + } + + } + protected static void block(int wt,int ht,int r){ + double hyp=Math.sqrt((ht*ht)+(wt*wt)); + if( hyp>2*r){ + System.out.println("false"); + } + else + System.out.println("true"); + } + +} \ No newline at end of file diff --git a/December 08/c++_Sunandita-R.cpp b/December 08/c++_Sunandita-R.cpp new file mode 100644 index 0000000..e3cbc07 --- /dev/null +++ b/December 08/c++_Sunandita-R.cpp @@ -0,0 +1,63 @@ +/* + The input ā€˜n’ is an odd integer (3<=n<=15) + +*/ + +#include +#include + +std::vector> find_path(int n) { + if (n % 2 == 0 || n < 3 || n > 15) { + throw std::invalid_argument("Input must be an odd integer between 3 and 15."); + } + + std::vector> magic_square(n, std::vector(n, 0)); + + int i = 0, j = n / 2; + int num = n * n; + + while (num >= 1) { + magic_square[i][j] = num; + num--; + + int newi = (i - 1 + n) % n; + int newj = (j + 1) % n; + + if (magic_square[newi][newj] == 0) { + i = newi; + j = newj; + } else { + i++; + } + } + + // Transpose the magic square + std::vector> transposed_square(n, std::vector(n, 0)); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + transposed_square[j][i] = magic_square[i][j]; + } + } + + return transposed_square; +} + +int main() { + int n; + std::cin >> n; + + try { + std::vector> result = find_path(n); + + for (const auto& row : result) { + for (int num : row) { + std::cout << num << " "; + } + std::cout << std::endl; + } + } catch (const std::invalid_argument& e) { + std::cerr << e.what() << std::endl; + } + + return 0; +} diff --git a/December 09/java_Sunandita_Camelcase.java b/December 09/java_Sunandita_Camelcase.java new file mode 100644 index 0000000..1c71dde --- /dev/null +++ b/December 09/java_Sunandita_Camelcase.java @@ -0,0 +1,28 @@ +/* INPUT FORMAT: Sequence of words in camel case as a string of letters without space + * Example : SaveChangesInTheEditor +*/ + +import java.util.Scanner; +public class java_Sunandita_Camelcase { + + public static void main(String[] args) { + try (Scanner s = new Scanner(System.in)) { + String camelCaseString =s.nextLine() ; + int wordCount = countWordsInCamelCase(camelCaseString); + System.out.println(wordCount); + } + } + private static int countWordsInCamelCase(String s) { + + if (s == null || s.isEmpty()) { + return 0; + } + int wordCount = 1; + for (int i=1;i + +int main() { + int num1, num2, sum; + scanf("%d %d", &num1, &num2); + + sum = num1 + num2; + printBinary(sum); + return 0; +} +void printBinary(int num) { + if (num == 0) { + printf("0"); + return; + } + + int binary[32]; + int i = 0; + while (num > 0) { + binary[i] = num % 2; + num = num / 2; + i++; + } + for (int j = i - 1; j >= 0; j--) { + printf("%d", binary[j]); + } + + printf("\n"); +} diff --git a/December 12/python3_Sunandita-R.py b/December 12/python3_Sunandita-R.py new file mode 100644 index 0000000..eced8f7 --- /dev/null +++ b/December 12/python3_Sunandita-R.py @@ -0,0 +1,42 @@ +""" +INPUT FORMAT : Three lines of input as and when prompted + Each line consists of space separated strings without quotes + +Example : Gold silver plat ruby + Silver emerald + Diamond ruby +""" + +print("Box1 = ") +l1=[str(x) for x in input().split()] +print("Box2 = ") +l2=[str(x) for x in input().split()] +print("Box3 = ") +l3=[str(x) for x in input().split()] + +l1.sort() +l2.sort() +l3.sort() +def binary_search(arr, target): + low, high = 0, len(arr) - 1 + + while low <= high: + mid = (low + high) // 2 + + if arr[mid] == target: + return 1 + + elif arr[mid] < target: + low = mid + 1 + else: + high = mid - 1 + + return -1 + +if(binary_search(l1,"Gold")==1): + print("Box1 Contains the Gold") +elif(binary_search(l2,"Gold")==1): + print("Box2 Contains the Gold") +else: + print("Box3 Contains the Gold") + \ No newline at end of file diff --git a/December 13/c_Sunandita-R.c b/December 13/c_Sunandita-R.c new file mode 100644 index 0000000..00bdcb9 --- /dev/null +++ b/December 13/c_Sunandita-R.c @@ -0,0 +1,46 @@ +/* + INPUT FORMAT : A spaceless string with combinations of capital letters and numbers without quotes + + **********************INPUT FORMAT EXAMPLE ****************** + + 653-TRY-THIS + +*/ + +#include +#include + +void textToNum(char *input) { + int len = strlen(input); + for (int i = 0; i < len; i++) { + if (input[i] >= 'A' && input[i] <= 'Z') { + if (input[i] >= 'A' && input[i] <= 'C') { + input[i] = '2'; + } else if (input[i] >= 'D' && input[i] <= 'F') { + input[i] = '3'; + } else if (input[i] >= 'G' && input[i] <= 'I') { + input[i] = '4'; + } else if (input[i] >= 'J' && input[i] <= 'L') { + input[i] = '5'; + } else if (input[i] >= 'M' && input[i] <= 'O') { + input[i] = '6'; + } else if (input[i] >= 'P' && input[i] <= 'S') { + input[i] = '7'; + } else if (input[i] >= 'T' && input[i] <= 'V') { + input[i] = '8'; + } else if (input[i] >= 'W' && input[i] <= 'Z') { + input[i] = '9'; + } + } + } +} + +int main() { + char input[] = ""; + scanf("%s",input); + textToNum(input); + printf("%s\n", input); + + return 0; +} + diff --git a/December 14/c++_Sunandita-R_CallOFJustice.cpp b/December 14/c++_Sunandita-R_CallOFJustice.cpp new file mode 100644 index 0000000..3bb8e93 --- /dev/null +++ b/December 14/c++_Sunandita-R_CallOFJustice.cpp @@ -0,0 +1,118 @@ +/* + Since the task here is only to complete the KDistanceNodes function, + I have assumed the values of all the tree nodes to be fixed programatically + You can change it manually in the code itself under createBinaryTree function + + _____The tree constructed is the one given in test case 1 of the question______ + + INPUT FORMAT : Two space separated Integers denoting Target and K values + Example : 7 3 +*/ + + +#include +#include +#include + +class TreeNode { +public: + int value; + TreeNode* left; + TreeNode* right; + + TreeNode(int val) : value(val), left(nullptr), right(nullptr) {} +}; + +void KDistanceNodes(TreeNode* root, TreeNode* target, int k, std::vector& result) { + if (!root || k < 0) { + return; + } + + if (k == 0) { + result.push_back(root->value); + return; + } + + KDistanceNodes(root->left, target, k - 1, result); + KDistanceNodes(root->right, target, k - 1, result); +} + +int findKDistanceSubtree(TreeNode* node, TreeNode* target, int k, std::vector& result) { + if (!node) { + return -1; + } + + if (node == target) { + KDistanceNodes(node, nullptr, k, result); + return 0; + } + + int leftDistance = findKDistanceSubtree(node->left, target, k, result); + if (leftDistance >= 0) { + if (leftDistance + 1 == k) { + result.push_back(node->value); + } else { + KDistanceNodes(node->right, nullptr, k - leftDistance - 2, result); + } + return leftDistance + 1; + } + + int rightDistance = findKDistanceSubtree(node->right, target, k, result); + if (rightDistance >= 0) { + if (rightDistance + 1 == k) { + result.push_back(node->value); + } else { + KDistanceNodes(node->left, nullptr, k - rightDistance - 2, result); + } + return rightDistance + 1; + } + + return -1; +} + +TreeNode* createBinaryTree() { + TreeNode* root = new TreeNode(14); + root->left = new TreeNode(7); + root->right = new TreeNode(20); + root->left->left = new TreeNode(4); + root->left->right = new TreeNode(3); + root->left->right->left = new TreeNode(2); + root->left->right->left->left = new TreeNode(1); + root->left->right->left->right = new TreeNode(4); + root->right->right = new TreeNode(30); + return root; +} + +int main() { + int targetValue, kValue; + std::cin >> targetValue >> kValue; + + TreeNode* treeRoot = createBinaryTree(); + + TreeNode* targetNode = nullptr; + std::function findTargetNode = [&](TreeNode* node, int targetValue) -> TreeNode* { + if (!node) { + return nullptr; + } + if (node->value == targetValue) { + return node; + } + TreeNode* leftResult = findTargetNode(node->left, targetValue); + return leftResult ? leftResult : findTargetNode(node->right, targetValue); + }; + + targetNode = findTargetNode(treeRoot, targetValue); + + if (targetNode) { + std::vector result; + findKDistanceSubtree(treeRoot, targetNode, kValue, result); + + for (int val : result) { + std::cout << val << " "; + } + } else { + std::cout << "Target node not found in the binary tree."; + } + + return 0; +} diff --git a/December 15/c_Sunandita-R_subsequence.c b/December 15/c_Sunandita-R_subsequence.c new file mode 100644 index 0000000..c5111d7 --- /dev/null +++ b/December 15/c_Sunandita-R_subsequence.c @@ -0,0 +1,35 @@ +/* INPUT FORMAT : A spaceless string + Example : ice +*/ + +#include +#include + +int countDistinctSubsequences(char* str) { + int n = strlen(str); + int dp[n + 1]; + int last[256]; + + memset(last, -1, sizeof(last)); + dp[0] = 1; + + for (int i = 1; i <= n; i++) { + dp[i] = 2 * dp[i - 1]; + + if (last[str[i - 1]] != -1) { + dp[i] -= dp[last[str[i - 1]]]; + } + + last[str[i - 1]] = i - 1; + } + + return dp[n]; +} + +int main() { + char input[100]; + scanf("%s", input); + int result = countDistinctSubsequences(input); + printf("%d",result); + return 0; +} diff --git a/December 16/python3_Sunandita_OutbreakDynamics.py b/December 16/python3_Sunandita_OutbreakDynamics.py new file mode 100644 index 0000000..a54fbbb --- /dev/null +++ b/December 16/python3_Sunandita_OutbreakDynamics.py @@ -0,0 +1,102 @@ +""" +Going by the way I assessed the problem statement I had a different understanding regarding the output +of both the sample test cases. + +For the Testcase 1 given Output is 3 minutes +But according to my approach i arrived at 2 minutes. + + +I have documented my approach below: + +At 0th minute- The initial grid + +grid = [ + [0, 1, 0, 0], + [1, 1, 1, 1], Each zombie can infect every human at a distance of 1 unit + [0, 1, -1, 0], every minute + [0, 0, 0, 0] +] + +After first minute: + +grid = [ + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, -1, 1], + [0, 1, 0, 0] +] + +After 2nd Minute +grid = [ + [1, 1, 1, 1], + [1, 1, 1, 1], So it takes 2 minutes to infect all humans + [1, 1, -1, 1], + [1, 1, 1, 1] +] + +Simiarly for the second Test case too the output is 2 minutes But the output +given in the question is 4. + +The first section is output for Testcase 1 + +INPUT FORMAT : A nested list with comma separated integers + +************************ INPUT FORMAT Example************* +[[0,1,1],[0,-1,1],[1,1,1]] + +Eval is used to parse the input so follow the above input format without line breaks + +If there is only one row even then give it as nested list. +Example : [[1,1,-1,0]] + +""" + +from collections import deque + +def min_hours_to_infect(grid): + rows, cols = len(grid), len(grid[0]) + zombies = deque() + total_humans = 0 + for i in range(rows): + for j in range(cols): + if grid[i][j] == 1: + zombies.append((i, j, 0)) + elif grid[i][j] == 0: + total_humans += 1 + + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] + + while zombies: + x, y, hours = zombies.popleft() + + for dx, dy in directions: + nx, ny = x + dx, y + dy + + if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 0: + grid[nx][ny] = 1 + total_humans -= 1 + zombies.append((nx, ny, hours + 1)) + + if total_humans == 0: + return hours + + return -1 + +# Example usage: +print("input : \n grid = [\n[0, 1, 0, 0],\n[1, 1, 1, 1],\n[0, 1, -1, 0],\n[0, 0, 0, 0]]") +grid = [ + [0, 1, 0, 0], + [1, 1, 1, 1], + [0, 1, -1, 0], + [0, 0, 0, 0] +] + +result = min_hours_to_infect(grid) +print("Output :" ,result,"\n") + +grid=eval(input("Grid = ")) +for i in range(0,len(grid)): + for j in range(0,len(grid[i])): + grid[i][j]=int(grid[i][j]) +result = min_hours_to_infect(grid) +print(result,"\n") \ No newline at end of file diff --git a/December 17/python3_Sunandita-R_BookshelfDilemma.py b/December 17/python3_Sunandita-R_BookshelfDilemma.py new file mode 100644 index 0000000..89e5c8d --- /dev/null +++ b/December 17/python3_Sunandita-R_BookshelfDilemma.py @@ -0,0 +1,69 @@ +""" + Since the task here is only to complete the DetectandRemoveLoop function, + I have assumed the values of all the nodes to be fixed programatically + You can add more nodes; change the linked list structure in the main part of the program + + The linked list constructed is that of testcase 1 in the question + + No input needs to be given. Pls test by changing the values in the program itself. + +""" + +class Node: + def __init__(self, value): + self.value = value + self.next = None + +def detect_and_remove_loop(head): + slow = fast = head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + if slow == fast: + break + + if not fast or not fast.next: + return + + slow = head + + while slow != fast: + slow = slow.next + fast = fast.next + + while fast.next != slow: + fast = fast.next + + fast.next = None + +def print_list(head): + current = head + print(current.value,end=" ") + while current.next: + + current = current.next + print(" --> ",end=" ") + print(current.value, end=" ") + + + +node1 = Node(1) +node2 = Node(2) +node3 = Node(3) +node4 = Node(4) +node5 = Node(5) +node6 = Node(6) +node7 = Node(7) +node8 = Node(8) +node1.next = node2 +node2.next = node3 +node4.next = node5 +node3.next=node8 +node8.next=node7 +node3.next = node4 +node7.next=node6 +node6.next=node1 +detect_and_remove_loop(node1) +print_list(node1) diff --git a/December 18/python3_Sunandita-R_ItsChristmasDay.py b/December 18/python3_Sunandita-R_ItsChristmasDay.py new file mode 100644 index 0000000..3507a25 --- /dev/null +++ b/December 18/python3_Sunandita-R_ItsChristmasDay.py @@ -0,0 +1,117 @@ +""" + INPUT FORMAT : + +. The first line of the input contains an integer T, representing the number of test cases. +. The first line of each test case contains 2 integers , N, X. +. Next line of each test case contains N integers separated by a space, representing the array arr. +. The next N-1 lines of each test case contain 2 integers each, representing an edge of the tree. + + EXAMPLE: +2 +5 3 +3 2 3 2 5 +1 2 +1 3 +2 4 +2 5 +5 1 +1 2 3 4 5 +1 2 +1 5 +2 3 +2 4 + +""" +import sys +sys.setrecursionlimit(10 ** 6) +N = 100000 +l=[] +MOD = 10 ** 9 + 7 +f = [0] * (N + 1) +invf = [0] * (N + 1) + +def dfs(node, p, g, a, x): + for c in g[node]: + if c != p: + dfs(c, node, g, a, x) + a[node] += a[c] + if a[node] >= x: + a[node] -= x + +def powmod(a, b, mod): + res = 1 + a %= mod + while b: + if b & 1: + res = res * a % mod + a = a * a % mod + b >>= 1 + return res + +def cn(u, v, MOD): + if u > v: + return 0 + if u == v: + return 1 + if u == 1 or u + 1 == v: + return v + return f[v] * invf[u] % MOD * invf[v - u] % MOD + +def dfs_count(node, p, g, a): + cnt = 1 if a[node] == 0 else 0 + for c in g[node]: + if c != p: + cnt += dfs_count(c, node, g, a) + return cnt + +def solve(): + global N, MOD, f, invf + n, x = map(int, input().split()) + a = list(map(int, input().split())) + a = [ai % x for ai in a] + g = [[] for _ in range(n)] + for _ in range(n - 1): + u, v = map(int, input().split()) + u -= 1 + v -= 1 + g[u].append(v) + g[v].append(u) + + dfs(0, -1, g, a, x) + + if a[0] != 0: + print(' '.join(['0'] * n)) + return + + result = [1] + cnt = dfs_count(0, -1, g, a) + + for i in range(2, n + 1): + result.append(cn(i - 1, cnt - 1, MOD)) + + #print(' '.join(map(str, result))) + l.append(list(''.join(map(str,result)))) + +def main(): + global N, MOD, f, invf + f[0] = 1 + + for i in range(1, N + 1): + f[i] = f[i - 1] * i % MOD + + invf[N] = powmod(f[N], MOD - 2, MOD) + + for i in range(N, 0, -1): + invf[i - 1] = invf[i] * i % MOD + + t = int(input()) + + for _ in range(t): + solve() + for i in l: + for j in i: + print(int(j),end=" ") + print() + +if __name__ == "__main__": + main() diff --git a/December 19/c++_Sunandita-R.cpp b/December 19/c++_Sunandita-R.cpp new file mode 100644 index 0000000..f4e53c2 --- /dev/null +++ b/December 19/c++_Sunandita-R.cpp @@ -0,0 +1,100 @@ +/* Forming a right-most tree with X3 as root node + +For the Sample input 1: [X3, 3, X2, 2, X1, 1, 4] + + Constructed Tree: +0 (X3) + 3 (X1) + 0 (X2) + 2 (X1) + 0 (X1) + 1 (X1) + 4 (X1) + + + + ****** First 2 Lines of output is the input and output of first test case.****** + + The cursor in the next line accepts user input. + + + *********** INPUT FORMAT ********* + + space separated node values without quotes (X must be in capital) + + Example : X3 3 X2 2 X1 1 4 + + */ + +#include +#include +#include +#include + +class TreeNode { +public: + int val; + int multiplier; + std::vector children; + + TreeNode(int v, int m = 1) : val(v), multiplier(m) {} +}; + +TreeNode* constructTree(const std::vector& sequence) { + std::vector stack; + TreeNode* root = nullptr; + + for (const auto& elem : sequence) { + TreeNode* node; + if (elem[0] == 'X') { + int multiplier = std::stoi(elem.substr(1)); + node = new TreeNode(0, multiplier); + } else { + node = new TreeNode(std::stoi(elem)); + } + + if (stack.empty()) { + root = node; + } else { + TreeNode* parent = stack.back(); + parent->children.push_back(node); + } + + stack.push_back(node); + } + + return root; +} + +int symbolicSum(TreeNode* node) { + if (!node) { + return 0; + } + + int totalSum = 0; + for (TreeNode* child : node->children) { + totalSum += symbolicSum(child); + } + + return node->multiplier * totalSum + (node->val ? node->val : 0); +} +int main() { + std::vector inputSequence = {"X3", "3", "X2", "2", "X1", "1", "4"}; + TreeNode* root = constructTree(inputSequence); + std::cout<<"\nINPUT : [X3, 3, X2, 2, X1, 1, 4]"; + int result = symbolicSum(root); + std::cout << "\nOUTPUT : " << result << std::endl; + + std::string input; + std::getline(std::cin, input); + std::istringstream iss(input); + std::string word; + std::vector inputsequence={}; + while (iss >> word) { + inputsequence.push_back(word); + } + TreeNode* r = constructTree(inputsequence); + int res = symbolicSum(r); + std::cout<< res << std::endl; + return 0; +} diff --git a/December 20/python_Sunandita-R.py b/December 20/python_Sunandita-R.py new file mode 100644 index 0000000..6be2779 --- /dev/null +++ b/December 20/python_Sunandita-R.py @@ -0,0 +1,128 @@ +""" +First set of output is the sample input-output of testcase 1 in the question" + +It is followed by a prompt for user input for the graph,start and end caves + +************************ INPUT FORMAT Example************* + +Line 1 of input: +{'Cave_A': {'Cave_B': 4, 'Cave_C': 6},'Cave_B': {'Cave_C': 2, 'Cave_D': 5, 'Cave_E': 8},'Cave_C': {'Cave_A': 6, 'Cave_D': 7},'Cave_D': {'Cave_B': 5, 'Cave_E': 3},'Cave_E': {}} + +Eval is used so give the dictionary in one line without line breaks. + +Line 2 of input - Start cave: +Cave_B + +Line 3 of input - End cave: +Cave_C + +""" + + +class Cave: + def __init__(self, name, interference): + self.name = name + self.interference = interference + +def treasure_hunt(graph, weights, num_caves, start, end): + distance = [float('inf')] * num_caves + interference = [float('inf')] * num_caves + visited = [0] * num_caves + parent = [-1] * num_caves + + start_index = -1 + end_index = -1 + + for i in range(num_caves): + distance[i] = float('inf') + interference[i] = float('inf') + visited[i] = 0 + parent[i] = -1 + + if graph[i].name == start: + start_index = i + if graph[i].name == end: + end_index = i + + distance[start_index] = 0 + interference[start_index] = 0 + + for i in range(num_caves - 1): + min_interference = float('inf') + current_index = -1 + + for j in range(num_caves): + if not visited[j] and interference[j] < min_interference: + min_interference = interference[j] + current_index = j + + visited[current_index] = 1 + + for j in range(num_caves): + if not visited[j] and weights[current_index][j] != -1: + total_distance = distance[current_index] + weights[current_index][j] + total_interference = interference[current_index] + graph[j].interference + + if total_interference < interference[j] or (total_interference == interference[j] and total_distance <= distance[j]): + distance[j] = total_distance + interference[j] = total_interference + parent[j] = current_index + + current = end_index + result = [] + while current != -1: + result.append(graph[current].name) + current = parent[current] + + result.reverse() + return result +print("Sample Output for test case 1:\n Input: ",end=" ") +print("""graph ={ + 'Cave_A': {'Cave_B': 3, 'Cave_C': 5}, + 'Cave_B': {'Cave_D': 7, 'Cave_E': 1}, + 'Cave_C': {'Cave_D': 3}, + 'Cave_D': {'Cave_E': 5}, + 'Cave_E': {} + }""") +print("start_cave = 'Cave_A'") +print("end_cave = 'Cave_E'") +graph_data={ + 'Cave_A': {'Cave_B': 3, 'Cave_C': 5}, + 'Cave_B': {'Cave_D': 7, 'Cave_E': 1}, + 'Cave_C': {'Cave_D': 3}, + 'Cave_D': {'Cave_E': 5}, + 'Cave_E': {} + } +start_cave = 'Cave_A' +end_cave = 'Cave_E' +num_caves = len(graph_data) +graph = [Cave(name, 0) for name in graph_data.keys()] +weights = [[-1] * num_caves for _ in range(num_caves)] + +for i, (cave, connections) in enumerate(graph_data.items()): + for neighbor, weight in connections.items(): + j = list(graph_data.keys()).index(neighbor) + weights[i][j] = int(weight) +result = treasure_hunt(graph, weights, num_caves, start_cave, end_cave) +print("\nOutput: ",end=" ") +print(result) +print("\nEnter user input\n") +print("graph = ",end=" ") +graph_data = eval(input()) + +num_caves = len(graph_data) +graph = [Cave(name, 0) for name in graph_data.keys()] +weights = [[-1] * num_caves for _ in range(num_caves)] + +for i, (cave, connections) in enumerate(graph_data.items()): + for neighbor, weight in connections.items(): + j = list(graph_data.keys()).index(neighbor) + weights[i][j] = int(weight) + +print("start_cave",end=" ") +start_cave = input() +print("end_cave",end=" ") +end_cave = input() + +result = treasure_hunt(graph, weights, num_caves, start_cave, end_cave) +print(result) diff --git a/December 21/c_Sunandita-R.c b/December 21/c_Sunandita-R.c new file mode 100644 index 0000000..91a5aea --- /dev/null +++ b/December 21/c_Sunandita-R.c @@ -0,0 +1,29 @@ +/* + Since the task is just to decode the riddler's code the Input is fixed and the program is static + The shift used is 25 and the bomb location after decoding is SRIPERUMBUDUR. +*/ + +#include +#include +#include +#include + +void encrypt(char text[], int shift) { + char result[100]; + + for (int i = 0; text[i] != '\0'; i++) { + char base = isupper(text[i]) ? 'A' : 'a'; + result[i] = (char)(((text[i] - shift + base) % 26) + base); + } + + result[strlen(text)] = '\0'; + printf("The Bomb Location is %s - Shift %d", result,shift); +} + +int main() { + char text[] = "RQHODQTLATCTQ"; + printf("Input Text : %s\n", text); + int shift = 25; + encrypt(text,shift); + return 0; +} diff --git a/December 22/python3_Sunandita-r.py b/December 22/python3_Sunandita-r.py new file mode 100644 index 0000000..897bca6 --- /dev/null +++ b/December 22/python3_Sunandita-r.py @@ -0,0 +1,59 @@ +""" +INPUT FORMAT : A nested list with comma separated integers + +************************ INPUT FORMAT Example************* +[[0,1,2],[0,1,2],[2,1,1]] + +Eval is used to parse the input so follow the above input format without line breaks + +If there is only one row even then give it as nested list. +Example : [[2,2,0,1]] + +""" + +from collections import deque + +def oranges_rotting(grid): + rows, cols = len(grid), len(grid[0]) + minutes = 0 + + dx = [-1, 1, 0, 0] + dy = [0, 0, -1, 1] + + rotten_queue = deque() + + for i in range(rows): + for j in range(cols): + if grid[i][j] == 2: + rotten_queue.append((i, j)) + + while rotten_queue: + size = len(rotten_queue) + + for _ in range(size): + x, y = rotten_queue.popleft() + + for d in range(4): + nx, ny = x + dx[d], y + dy[d] + + if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 1: + grid[nx][ny] = 2 + rotten_queue.append((nx, ny)) + + if rotten_queue: + minutes += 1 + + if any(1 in row for row in grid): + return -1 + + return minutes + +grid=eval(input()) +for i in range(0,len(grid)): + for j in range(0,len(grid[i])): + grid[i][j]=int(grid[i][j]) + + +print(oranges_rotting(grid)) + + diff --git a/December 23/java_Sunandita.java b/December 23/java_Sunandita.java new file mode 100644 index 0000000..c76b594 --- /dev/null +++ b/December 23/java_Sunandita.java @@ -0,0 +1,62 @@ +/* + * + * INPUT FORMAT: First line contains number of dominos n. + * Subsequent n Lines have the first number as upper half value and the next is lower half value + * + * INPUT FORMAT EXAMPLE + * + * 2 + * 4 3 + * 5 4 + * + */ + +import java.util.Scanner; + +public class java_Sunandita { + public static void main(String[] args) { + try (Scanner scanner = new Scanner(System.in)) { + int n = scanner.nextInt(); + int[][] dominoes = new int[n][2]; + + for (int i = 0; i < n; i++) { + dominoes[i][0] = scanner.nextInt(); + dominoes[i][1] = scanner.nextInt(); + } + + int result = minRotationTime(n, dominoes); + System.out.println(result); + } + } + + private static int minRotationTime(int n, int[][] dominoes) { + int upperSum = 0, lowerSum = 0; + + for (int i = 0; i < n; i++) { + upperSum += dominoes[i][0]; + lowerSum += dominoes[i][1]; + } + + if (upperSum % 2 == 0 && lowerSum % 2 == 0) { + return 0; + } + + for (int i = 0; i < n; i++) { + if ((upperSum + dominoes[i][1] - dominoes[i][0]) % 2 == 0 && + (lowerSum + dominoes[i][0] - dominoes[i][1]) % 2 == 0) { + return 1; + } + } + + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if ((upperSum + dominoes[i][1] - dominoes[i][0] + dominoes[j][1] - dominoes[j][0]) % 2 == 0 && + (lowerSum + dominoes[i][0] - dominoes[i][1] + dominoes[j][0] - dominoes[j][1]) % 2 == 0) { + return 2; + } + } + } + + return -1; + } +} diff --git a/December 24/c_Sunandita-R.c b/December 24/c_Sunandita-R.c new file mode 100644 index 0000000..4abe69d --- /dev/null +++ b/December 24/c_Sunandita-R.c @@ -0,0 +1,36 @@ +/* + INPUT FORMAT : First Line consists number of values n + Second line contains n space separated integers. + + + ******** INPUT FORMAT EXAMPLE ******** + 5 + 5 4 3 2 1 +*/ + +#include +int countViolations(int array[], int n) { + int violations = 0; + + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { + if (array[i] > array[j]) { + violations++; + } + } + } + + return violations; +} +int main() { + int n; + scanf("%d", &n); + int array[n]; + for (int i = 0; i < n; i++) { + scanf("%d", &array[i]); + } + + int violations = countViolations(array, n); + printf("%d\n", violations); + return 0; +} diff --git a/December 25/python3_Sunandita-R.py b/December 25/python3_Sunandita-R.py new file mode 100644 index 0000000..9885025 --- /dev/null +++ b/December 25/python3_Sunandita-R.py @@ -0,0 +1,55 @@ +""" +First section of output is the sample IO for testcase 1 + +It is then followed by user input with two linen + +INPUT FORMAT : Line 1 has a list of tasks with comma separated numbers + Line 2 has a nested list with comma separated numbers. + +INPUT EXAMPLE: + +[1,2,3,4,5] +[[],[1],[2],[3],[4,1]] + +Both use Eval for taking input so maintain format and give the lists without quotes + +""" + +from collections import defaultdict + +def min_completion_time(tasks, dependencies): + graph = defaultdict(list) + in_degree = [0] * len(tasks) + + for i, deps in enumerate(dependencies): + for dep in deps: + graph[dep].append(i) + in_degree[i] += 1 + + completion_time = [0] * len(tasks) + + for i in range(len(tasks)): + for node in range(len(tasks)): + if in_degree[node] == 0: + completion_time[node] = max(completion_time[node], i) + tasks[node] + + for neighbor in graph[node]: + in_degree[neighbor] -= 1 + + for node in range(len(tasks)): + if len(dependencies[node]) >= 2: + completion_time[node] += 1 + + return max(completion_time)+len(dependencies[node])-1 + return max(completion_time) + +print("INPUT 1 : \ntasks=[1,2,3,4,5]\ndependencies=[[],[1],[2],[3],[4,1]]") +tasks1 = [1, 2, 3, 4, 5] +dependencies1 = [[], [1], [2], [3], [4, 1]] +output1 = min_completion_time(tasks1, dependencies1) +print("Output 1:", output1,"\n") +tasks2=eval(input("tasks = ")) +dependencies2=eval(input("dependencies = ")) +tasks=[int(x) for x in tasks2] +output1 = min_completion_time(tasks, dependencies2) +print( output1) diff --git a/December 26/c_Sunandita-R.c b/December 26/c_Sunandita-R.c new file mode 100644 index 0000000..527bd38 --- /dev/null +++ b/December 26/c_Sunandita-R.c @@ -0,0 +1,107 @@ +/* + INPUT FORMAT : + + A single string representing the Linked List without spaces. + + Example: 1->2->3->4->5->1 +*/ + +#include +#include +#include + +struct Node* insert(struct Node* head, struct Node* node); +struct Node* newNode(int data); +void insertNode(struct Node** head, int data); +void parseAndCreateList(struct Node** head, const char* input); + +struct Node { + int data; + struct Node* next; +}; + +int contains(struct Node* head, struct Node* target) { + while (head != NULL) { + if (head->data == target->data) { + return 1; + } + head = head->next; + } + return 0; +} + +int hasCycle(struct Node* head) { + struct Node* current = head; + struct Node* visitedNodes = NULL; + + while (current != NULL) { + if (contains(visitedNodes, current)) { + return 1; + } + visitedNodes = insert(visitedNodes, current); + current = current->next; + } + + return 0; +} + +struct Node* insert(struct Node* head, struct Node* node) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = node->data; + newNode->next = head; + return newNode; +} + +struct Node* newNode(int data) { + struct Node* node = (struct Node*)malloc(sizeof(struct Node)); + node->data = data; + node->next = NULL; + return node; +} + +void insertNode(struct Node** head, int data) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = data; + newNode->next = NULL; + + if (*head == NULL) { + *head = newNode; + } else { + struct Node* temp = *head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = newNode; + } +} + +void parseAndCreateList(struct Node** head, const char* input) { + const char* delimiter = "->"; + char* strCopy = strdup(input); + char* token = strtok(strCopy, delimiter); + + while (token != NULL) { + int data = atoi(token); + insertNode(head, data); + token = strtok(NULL, delimiter); + } + + free(strCopy); +} + +int main() { + struct Node* head = NULL; + char input[100]; + fgets(input, sizeof(input), stdin); + input[strcspn(input, "\n")] = '\0'; + + parseAndCreateList(&head, input); + + if (hasCycle(head)) { + printf("Cycle Found\n"); + } else { + printf("No Cycle Found\n"); + } + + return 0; +} diff --git a/December 27/java_Sunandita.java b/December 27/java_Sunandita.java new file mode 100644 index 0000000..60dc91b --- /dev/null +++ b/December 27/java_Sunandita.java @@ -0,0 +1,71 @@ +/* + * The Test case-2 output given in the question is wrong. There is no tour possible. + * In the given program if no tour is possible the output is 0 + * + * ******** INPUT FORMAT ********* + * + * Three lines of input. + * Line 1 is number of petrol stations N ( Enter an integer ) + * Line 2 has N space seperated integers for number of litres of petrol + * Line 3 has N space seperated integers for distance. + * + * ****** INPUT EXAMPLE ****** + * + * 4 + * 4 6 7 4 + * 6 5 3 5 + * + */ + +import java.util.Scanner; + +class PetrolPump { + int petrol; + int distance; + + public PetrolPump(int petrol, int distance) { + this.petrol = petrol; + this.distance = distance; + } +} + +public class java_Sunandita { + static int findStartingPoint(PetrolPump[] petrolPumps) { + int n = petrolPumps.length; + int start = 0, totalPetrol = 0, currentPetrol = 0; + + for (int i = 0; i < n; i++) { + totalPetrol += petrolPumps[i].petrol - petrolPumps[i].distance; + currentPetrol += petrolPumps[i].petrol - petrolPumps[i].distance; + + if (currentPetrol < 0) { + start = i + 1; + currentPetrol = 0; + } + } + return (totalPetrol >= 0) ? start % n : -1; + } + + public static void main(String[] args) { + try (Scanner s = new Scanner(System.in)) { + // Example 1 + System.out.print("N = "); + int n1=s.nextInt(); + int[] petrol1 = new int[n1]; + int[] distance1 = new int[n1]; + PetrolPump[] petrolPumps1 = new PetrolPump[n1]; + System.out.print("Petrol = "); + for(int i=0;i +#include +#include + +using namespace std; + +bool isValidWalk(const vector& walk) { + if (walk.size() != 10) { + return false; + } + + int nsCount = 0; + int ewCount = 0; + + for (char direction : walk) { + if (direction == 'n') { + nsCount++; + } else if (direction == 's') { + nsCount--; + } else if (direction == 'e') { + ewCount++; + } else if (direction == 'w') { + ewCount--; + } + } + + return nsCount == 0 && ewCount == 0; +} + +int main() { + cout << "walk = "; + string input; + getline(cin, input); + + string cleanedInput; + for (char c : input) { + if (c == '/' && !cleanedInput.empty() && cleanedInput.back() == '/') { + break; + } else { + cleanedInput += c; + } + } + + vector directions; + for (char c : cleanedInput) { + if (c != ' ' && c != ',') { + directions.push_back(c); + } + } + + bool result = isValidWalk(directions); + + cout << (result ? "TRUE" : "FALSE") << endl; + + return 0; +} diff --git a/December 30/c++_Sunandita-R.cpp b/December 30/c++_Sunandita-R.cpp new file mode 100644 index 0000000..1e65a19 --- /dev/null +++ b/December 30/c++_Sunandita-R.cpp @@ -0,0 +1,157 @@ +/* + INPUT FORMAT : As specified in the question + + INPUT EXAMPLE: + + 1 + 8 7 + 1 2 3 1 2 1 3 1 + 1 2 + 1 3 + 2 4 + 3 5 + 3 6 + 5 7 + 6 8 + 4 6 + 7 8 + 5 4 + 7 6 + 3 8 + 1 2 + 4 8 + +*/ + +#include +using namespace std; + +void addEdge(vector v[], int x, int y) { + v[x].push_back(y); + v[y].push_back(x); +} + +int mergeAndCount(int arr[], int left, int mid, int right) { + int n1 = mid - left + 1; + int n2 = right - mid; + + vector L(n1), R(n2); + + for (int i = 0; i < n1; i++) + L[i] = arr[left + i]; + + for (int j = 0; j < n2; j++) + R[j] = arr[mid + 1 + j]; + + int inversions = 0; + + int i = 0, j = 0, k = left; + + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k++] = L[i++]; + } else { + arr[k++] = R[j++]; + inversions += (mid - left + 1) - i; + } + } + + while (i < n1) { + arr[k++] = L[i++]; + } + + while (j < n2) { + arr[k++] = R[j++]; + } + + return inversions; +} + +int mergeSortAndCount(int arr[], int left, int right) { + int inversions = 0; + + if (left < right) { + int mid = left + (right - left) / 2; + + inversions += mergeSortAndCount(arr, left, mid); + inversions += mergeSortAndCount(arr, mid + 1, right); + inversions += mergeAndCount(arr, left, mid, right); + } + + return inversions; +} + +int countInversions(int arr[], int n) { + return mergeSortAndCount(arr, 0, n - 1); +} + +int printPath(vector stack, int color[]) { + int i; + int val[(int)stack.size()]; + for (i = 0; i < (int)stack.size(); i++) { + val[i] = color[stack[i] - 1]; + } + int inversions = countInversions(val, (int)stack.size()); + return inversions; +} + +int DFS(vector v[], bool vis[], int x, int y, vector stack, int color[]) { + int res = 0; + stack.push_back(x); + if (x == y) { + res = printPath(stack, color); + return res; + } + vis[x] = true; + if (!v[x].empty()) { + for (int j = 0; j < v[x].size(); j++) { + if (vis[v[x][j]] == false) + res += DFS(v, vis, v[x][j], y, stack, color); + } + } + + stack.pop_back(); + return res; +} + +int DFSCall(int x, int y, vector v[], int n, vector stack, int color[]) { + int sum = 0; + bool vis[n + 1]; + memset(vis, false, sizeof(vis)); + sum = DFS(v, vis, x, y, stack, color); + return sum; +} + +int main() { + int T, sum1, sum2; + cin >> T; + while (T > 0) { + int n, q; + cin >> n >> q; + int color[n]; + for (int m = 0; m < n; m++) { + cin >> color[m]; + } + vector> edges(n - 1); + vector> queries(n - 1); + for (int i = 1; i < n; ++i) { + cin >> edges[i - 1].first >> edges[i - 1].second; + } + for (int j = 1; j <= q; ++j) { + cin >> queries[j - 1].first >> queries[j - 1].second; + } + n += 1; + vector v[n], stack; + for (int k = 0; k < n - 2; k++) { + addEdge(v, edges[k].first, edges[k].second); + } + cout<<"\n\nOUTPUT :\n\n"; + for (int l = 0; l < q; l++) { + sum1 = DFSCall(queries[l].first, queries[l].second, v, n, stack, color); + sum2 = DFSCall(queries[l].second, queries[l].first, v, n, stack, color); + cout << sum1 + sum2 << "\n"; + } + T -= 1; + } + return 0; +} diff --git a/December 31/java_Sunandita.java b/December 31/java_Sunandita.java new file mode 100644 index 0000000..a1dfb46 --- /dev/null +++ b/December 31/java_Sunandita.java @@ -0,0 +1,64 @@ +/* + * In The first test case the second line of the output seems to differ.... + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class java_Sunandita { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.print("Enter the value of N (between 1 and 8): "); + int N = scanner.nextInt(); + if (N < 1 || N > 8) { + System.out.println("Invalid input. N should be between 1 and 8."); + scanner.close(); + return; + } + List> solutions = solveNQueens(N); + printSolutions(solutions); + scanner.close(); + } + + private static List> solveNQueens(int N) { + List> solutions = new ArrayList<>(); + solveNQueensHelper(N, 0, new int[N], solutions); + return solutions; + } + + private static void solveNQueensHelper(int N, int row, int[] placement, List> solutions) { + if (row == N) { + solutions.add(generateSolution(placement)); + return; + } + + for (int col = 0; col < N; col++) { + if (isValidPlacement(placement, row, col)) { + placement[row] = col; + solveNQueensHelper(N, row + 1, placement, solutions); + } + } + } + private static boolean isValidPlacement(int[] placement, int row, int col) { + for (int i = 0; i < row; i++) { + if (placement[i] == col || Math.abs(placement[i] - col) == Math.abs(i - row)) { + return false; + } + } + return true; + } + private static List generateSolution(int[] placement) { + List solution = new ArrayList<>(); + for (int i = 0; i < placement.length; i++) { + solution.add("(" + (i + 1) + ", " + (placement[i] + 1) + ")"); + } + return solution; + } + private static void printSolutions(List> solutions) { + for (List solution : solutions) { + System.out.println(String.join(" ", solution)); + } + } +}