Code_ID,Code_Text,Label,Source_Type,Generation_Prompt,Language,normalized_code,original_line_count,normalized_line_count ,"class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList or beginWord == endWord: return 0 m = len(wordList[0]) wordSet = set(wordList) qb, qe = deque([beginWord]), deque([endWord]) fromBegin, fromEnd = {beginWord: 1}, {endWord: 1} while qb and qe: if len(qb) > len(qe): qb, qe = qe, qb fromBegin, fromEnd = fromEnd, fromBegin for _ in range(len(qb)): word = qb.popleft() steps = fromBegin[word] for i in range(m): for c in range(97, 123): if chr(c) == word[i]: continue nei = word[:i] + chr(c) + word[i + 1:] if nei not in wordSet: continue if nei in fromEnd: return steps + fromEnd[nei] if nei not in fromBegin: fromBegin[nei] = steps + 1 qb.append(nei) return 0",0.0,GFG,,python,"class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList or beginWord == endWord: return 0 m = len(wordList[0]) wordSet = set(wordList) qb, qe = deque([beginWord]), deque([endWord]) fromBegin, fromEnd = {beginWord: 1}, {endWord: 1} while qb and qe: if len(qb) > len(qe): qb, qe = qe, qb fromBegin, fromEnd = fromEnd, fromBegin for _ in range(len(qb)): word = qb.popleft() steps = fromBegin[word] for i in range(m): for c in range(97, 123): if chr(c) == word[i]: continue nei = word[:i] + chr(c) + word[i + 1:] if nei not in wordSet: continue if nei in fromEnd: return steps + fromEnd[nei] if nei not in fromBegin: fromBegin[nei] = steps + 1 qb.append(nei) return 0",29,29 ,"class DiagonalMatrix { public static void main(String args[]) { int[][] a = new int[][] { { 1, 0, 1},{ 0, 3, 0},{ 0, 0, 3} }; boolean setValue = true; abc: for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { if(i == j) { if(a[i][j] == 0) { setValue = false; break abc; } } else if(a[i][j] != 0) { setValue = false; break abc; } } } System.out.println(""The Given Matrix Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(a[i][j] + "" ""); } System.out.println(); } if(setValue == true) { System.out.println(""The Given Matrix is a Diagonal Matrix""); } else { System.out.println(""The Given Matrix is not a Diagonal Matrix""); } } } ",0.0,IPSGWALIOR.ORG,,java,"class DiagonalMatrix { public static void main(String args[]) { int[][] a = new int[][] { { 1, 0, 1},{ 0, 3, 0},{ 0, 0, 3} }; boolean setValue = true; abc: for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { if(i == j) { if(a[i][j] == 0) { setValue = false; break abc; } } else if(a[i][j] != 0) { setValue = false; break abc; } } } System.out.println(""The Given Matrix Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(a[i][j] + "" ""); } System.out.println(); } if(setValue == true) { System.out.println(""The Given Matrix is a Diagonal Matrix""); } else { System.out.println(""The Given Matrix is not a Diagonal Matrix""); } } }",47,47 ,"class Solution { Trie root; public String replaceWords(List dictionary, String sentence) { root = new Trie(); for(String word : dictionary){ insert(word); } StringBuilder result = new StringBuilder(); String [] input = sentence.split("" ""); for(String i : input){ result.append(search(i)); result.append("" ""); } return result.toString().trim(); } public String search(String word){ Trie node = root; int j = 0; for(char c : word.toCharArray()){ int i = c - 'a'; j++; if(node.children[i] == null){ return word; }else if(node.children[i].isEnd){ return word.substring(0, j); }else{ node = node.children[i]; } } return word; } public void insert(String word){ Trie node = root; for(char c: word.toCharArray()){ int i = c - 'a'; if(node.children[i] == null){ node.children[i] = new Trie(); } node = node.children[i]; } node.isEnd = true; } } class Trie{ Trie [] children; boolean isEnd; public Trie(){ children = new Trie[26]; isEnd =false; } } ",0.0,leetcode,,java,"class Solution { Trie root; public String replaceWords(List dictionary, String sentence) { root = new Trie(); for(String word : dictionary){ insert(word); } StringBuilder result = new StringBuilder(); String [] input = sentence.split("" ""); for(String i : input){ result.append(search(i)); result.append("" ""); } return result.toString().trim(); } public String search(String word){ Trie node = root; int j = 0; for(char c : word.toCharArray()){ int i = c - 'a'; j++; if(node.children[i] == null){ return word; }else if(node.children[i].isEnd){ return word.substring(0, j); }else{ node = node.children[i]; } } return word; } public void insert(String word){ Trie node = root; for(char c: word.toCharArray()){ int i = c - 'a'; if(node.children[i] == null){ node.children[i] = new Trie(); } node = node.children[i]; } node.isEnd = true; } } class Trie{ Trie [] children; boolean isEnd; public Trie(){ children = new Trie[26]; isEnd =false; } } ",53,53 ,"class Solution { public int numBusesToDestination(int[][] routes, int source, int target) { if (source == target) { return 0; } int maxStop = -1; for (int[] route : routes) { for (int stop : route) { maxStop = Math.max(maxStop, stop); } } if (maxStop < target) { return -1; } int n = routes.length; int[] minBusesToReach = new int[maxStop + 1]; Arrays.fill(minBusesToReach, n + 1); minBusesToReach[source] = 0; boolean flag = true; while (flag) { flag = false; for (int[] route : routes) { int min = n + 1; for (int stop : route) { min = Math.min(min, minBusesToReach[stop]); } min++; for (int stop : route) { if (minBusesToReach[stop] > min) { minBusesToReach[stop] = min; flag = true; } } } } return (minBusesToReach[target] < n + 1 ? minBusesToReach[target] : -1); } }",0.0,leetcode,,java,"class Solution { public int numBusesToDestination(int[][] routes, int source, int target) { if (source == target) { return 0; } int maxStop = -1; for (int[] route : routes) { for (int stop : route) { maxStop = Math.max(maxStop, stop); } } if (maxStop < target) { return -1; } int n = routes.length; int[] minBusesToReach = new int[maxStop + 1]; Arrays.fill(minBusesToReach, n + 1); minBusesToReach[source] = 0; boolean flag = true; while (flag) { flag = false; for (int[] route : routes) { int min = n + 1; for (int stop : route) { min = Math.min(min, minBusesToReach[stop]); } min++; for (int stop : route) { if (minBusesToReach[stop] > min) { minBusesToReach[stop] = min; flag = true; } } } } return (minBusesToReach[target] < n + 1 ? minBusesToReach[target] : -1); } }",39,39 ,"class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { HashMap map =new HashMap<>(); int count=0; for(int a:nums1) { for(int b:nums2) { int sum=a+b; map.put(sum,map.getOrDefault(sum,0)+1); } } for(int c : nums3) { for(int d:nums4) { int sum=c+d; if(map.containsKey(-sum)) { count += map.get(-sum); } } } return count; } }",0.0,leetcode,,java,"class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { HashMap map =new HashMap<>(); int count=0; for(int a:nums1) { for(int b:nums2) { int sum=a+b; map.put(sum,map.getOrDefault(sum,0)+1); } } for(int c : nums3) { for(int d:nums4) { int sum=c+d; if(map.containsKey(-sum)) { count += map.get(-sum); } } } return count; } }",26,26 ," class Solution { public int[] findErrorNums(int[] nums) { int dup = -1, missing = -1; for (int i = 1; i <= nums.length; i++) { int count = 0; for (int j = 0; j < nums.length; j++) { if (nums[j] == i) { count++; } } if (count == 2) { dup = i; } else if (count == 0) { missing = i; } } return new int[] {dup, missing}; } } ",0.0,leetcode,,java,"class Solution { public int[] findErrorNums(int[] nums) { int dup = -1, missing = -1; for (int i = 1; i <= nums.length; i++) { int count = 0; for (int j = 0; j < nums.length; j++) { if (nums[j] == i) { count++; } } if (count == 2) { dup = i; } else if (count == 0) { missing = i; } } return new int[] {dup, missing}; } }",21,21 ,"def quickSort(data_list): quickSortHlp(data_list,0,len(data_list)-1) def quickSortHlp(data_list,first,last): if first < last: splitpoint = partition(data_list,first,last) quickSortHlp(data_list,first,splitpoint-1) quickSortHlp(data_list,splitpoint+1,last) def partition(data_list,first,last): pivotvalue = data_list[first] leftmark = first+1 rightmark = last done = False while not done: while leftmark <= rightmark and data_list[leftmark] <= pivotvalue: leftmark = leftmark + 1 while data_list[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark = rightmark -1 if rightmark < leftmark: done = True else: temp = data_list[leftmark] data_list[leftmark] = data_list[rightmark] data_list[rightmark] = temp temp = data_list[first] data_list[first] = data_list[rightmark] data_list[rightmark] = temp return rightmark data_list = [54,26,93,17,77,31,44,55,20] quickSort(data_list) print(data_list)",0.0,W3RESOURCE,,python,"def quickSort(data_list): quickSortHlp(data_list,0,len(data_list)-1) def quickSortHlp(data_list,first,last): if first < last: splitpoint = partition(data_list,first,last) quickSortHlp(data_list,first,splitpoint-1) quickSortHlp(data_list,splitpoint+1,last) def partition(data_list,first,last): pivotvalue = data_list[first] leftmark = first+1 rightmark = last done = False while not done: while leftmark <= rightmark and data_list[leftmark] <= pivotvalue: leftmark = leftmark + 1 while data_list[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark = rightmark -1 if rightmark < leftmark: done = True else: temp = data_list[leftmark] data_list[leftmark] = data_list[rightmark] data_list[rightmark] = temp temp = data_list[first] data_list[first] = data_list[rightmark] data_list[rightmark] = temp return rightmark data_list = [54,26,93,17,77,31,44,55,20] quickSort(data_list) print(data_list)",44,44 ,"class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(gas) < sum(cost): return -1 total = 0 res = 0 for i in range(len(gas)): total += (gas[i] - cost[i]) if total < 0: total = 0 res = i + 1 return res",0.0,GFG,,python,"class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(gas) < sum(cost): return -1 total = 0 res = 0 for i in range(len(gas)): total += (gas[i] - cost[i]) if total < 0: total = 0 res = i + 1 return res",15,15 ,"static String decode(String s){ Stack n=new Stack<>(); Stack st=new Stack<>(); String cur=""""; int k=0; for(char c:s.toCharArray()){ if(Character.isDigit(c)) k=k*10+c-'0'; else if(c=='['){ n.push(k); st.push(cur); k=0; cur=""""; } else if(c==']'){ cur=st.pop()+cur.repeat(n.pop()); } else cur+=c; } return cur; } ",1.0,GPT,"write a java program toDecode strings like ""3[a2[c]]"" → ""accaccacc"".",java,"static String decode(String s){ Stack n=new Stack<>(); Stack st=new Stack<>(); String cur=""""; int k=0; for(char c:s.toCharArray()){ if(Character.isDigit(c)) k=k*10+c-'0'; else if(c=='['){ n.push(k); st.push(cur); k=0; cur=""""; } else if(c==']'){ cur=st.pop()+cur.repeat(n.pop()); } else cur+=c; } return cur; }",12,12 ,"class Solution: def numDecodings(self, s: str) -> int: dp = dp2 = 0 dp1 = 1 for i in range(len(s) - 1, -1, -1): if s[i] == ""0"": dp = 0 else: dp = dp1 if i + 1 < len(s) and (s[i] == ""1"" or s[i] == ""2"" and s[i + 1] in ""0123456"" ): dp += dp2 dp, dp1, dp2 = 0, dp, dp1 return dp1",0.0,GFG,,python,"class Solution: def numDecodings(self, s: str) -> int: dp = dp2 = 0 dp1 = 1 for i in range(len(s) - 1, -1, -1): if s[i] == ""0"": dp = 0 else: dp = dp1 if i + 1 < len(s) and (s[i] == ""1"" or s[i] == ""2"" and s[i + 1] in ""0123456"" ): dp += dp2 dp, dp1, dp2 = 0, dp, dp1 return dp1",16,16 ,"class TrieNode { TrieNode[] branch = new TrieNode[26]; Boolean isEmpty = true; } class Solution { public int minimumLengthEncoding(String[] W) { TrieNode trie = new TrieNode(); trie.branch = new TrieNode[26]; int ans = 1; for (String word : W) { TrieNode curr = trie; Boolean newWord = false; for (int i = word.length() - 1; i >= 0; i--) { int c = word.charAt(i) - 'a'; if (curr.isEmpty && !newWord) ans -= word.length() - i; if (curr.branch[c] == null) { curr.branch[c] = new TrieNode(); newWord = true; curr.isEmpty = false; } curr = curr.branch[c]; } if (newWord) ans += word.length() + 1; } return ans; } }",0.0,leetcode,,java,"class TrieNode { TrieNode[] branch = new TrieNode[26]; Boolean isEmpty = true; } class Solution { public int minimumLengthEncoding(String[] W) { TrieNode trie = new TrieNode(); trie.branch = new TrieNode[26]; int ans = 1; for (String word : W) { TrieNode curr = trie; Boolean newWord = false; for (int i = word.length() - 1; i >= 0; i--) { int c = word.charAt(i) - 'a'; if (curr.isEmpty && !newWord) ans -= word.length() - i; if (curr.branch[c] == null) { curr.branch[c] = new TrieNode(); newWord = true; curr.isEmpty = false; } curr = curr.branch[c]; } if (newWord) ans += word.length() + 1; } return ans; } }",28,28 ,"import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class DatabaseConnectionPool { private final BlockingQueue availableConnections; private final AtomicInteger activeConnections = new AtomicInteger(0); private final int maxPoolSize; private final String url; private final String username; private final String password; private volatile boolean isClosed = false; public DatabaseConnectionPool(String url, String username, String password, int maxPoolSize) { this.url = url; this.username = username; this.password = password; this.maxPoolSize = maxPoolSize; this.availableConnections = new LinkedBlockingQueue<>(maxPoolSize); initializePool(); } private void initializePool() { for (int i = 0; i < maxPoolSize / 2; i++) { try { availableConnections.offer(createConnection()); } catch (SQLException e) { throw new RuntimeException(""Failed to initialize connection pool"", e); } } } private PooledConnection createConnection() throws SQLException { Connection connection = DriverManager.getConnection(url, username, password); return new PooledConnection(connection, this); } public Connection getConnection() throws SQLException { return getConnection(30, TimeUnit.SECONDS); } public Connection getConnection(long timeout, TimeUnit unit) throws SQLException { if (isClosed) { throw new SQLException(""Connection pool is closed""); } try { // Try to get existing connection PooledConnection pooledConn = availableConnections.poll(timeout, unit); if (pooledConn != null) { if (!pooledConn.getConnection().isValid(2)) { closeQuietly(pooledConn.getConnection()); pooledConn = createConnection(); } activeConnections.incrementAndGet(); return pooledConn; } // Create new connection if pool not full if (activeConnections.get() < maxPoolSize) { PooledConnection newConn = createConnection(); activeConnections.incrementAndGet(); return newConn; } throw new SQLException(""Connection pool exhausted""); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new SQLException(""Interrupted while waiting for connection""); } } void returnConnection(PooledConnection connection) { if (isClosed) { closeQuietly(connection.getConnection()); return; } try { if (connection.getConnection().isClosed() || !connection.getConnection().isValid(2)) { closeQuietly(connection.getConnection()); availableConnections.offer(createConnection()); } else { availableConnections.offer(connection); } } catch (SQLException e) { // Connection is invalid, create new one closeQuietly(connection.getConnection()); try { availableConnections.offer(createConnection()); } catch (SQLException ex) { // Log error but don't throw } } finally { activeConnections.decrementAndGet(); } } public void close() { isClosed = true; availableConnections.forEach(conn -> closeQuietly(conn.getConnection()) ); availableConnections.clear(); } public int getActiveConnections() { return activeConnections.get(); } public int getIdleConnections() { return availableConnections.size(); } private void closeQuietly(Connection connection) { try { if (connection != null && !connection.isClosed()) { connection.close(); } } catch (SQLException e) { // Ignore } } private class PooledConnection extends ConnectionWrapper { private final DatabaseConnectionPool pool; PooledConnection(Connection connection, DatabaseConnectionPool pool) { super(connection); this.pool = pool; } @Override public void close() throws SQLException { pool.returnConnection(this); } } private abstract class ConnectionWrapper implements Connection { protected final Connection delegate; ConnectionWrapper(Connection delegate) { this.delegate = delegate; } // Delegate all Connection methods to the wrapped connection @Override public Statement createStatement() throws SQLException { return delegate.createStatement(); } // ... implement all other Connection methods similarly @Override public boolean isWrapperFor(Class iface) throws SQLException { return iface.isInstance(delegate) || delegate.isWrapperFor(iface); } @SuppressWarnings(""unchecked"") @Override public T unwrap(Class iface) throws SQLException { if (iface.isInstance(delegate)) { return (T) delegate; } return delegate.unwrap(iface); } } }",1.0,DEEPSEEK,Create a generic connection pool for managing database connections.,java,"import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class DatabaseConnectionPool { private final BlockingQueue availableConnections; private final AtomicInteger activeConnections = new AtomicInteger(0); private final int maxPoolSize; private final String url; private final String username; private final String password; private volatile boolean isClosed = false; public DatabaseConnectionPool(String url, String username, String password, int maxPoolSize) { this.url = url; this.username = username; this.password = password; this.maxPoolSize = maxPoolSize; this.availableConnections = new LinkedBlockingQueue<>(maxPoolSize); initializePool(); } private void initializePool() { for (int i = 0; i < maxPoolSize / 2; i++) { try { availableConnections.offer(createConnection()); } catch (SQLException e) { throw new RuntimeException(""Failed to initialize connection pool"", e); } } } private PooledConnection createConnection() throws SQLException { Connection connection = DriverManager.getConnection(url, username, password); return new PooledConnection(connection, this); } public Connection getConnection() throws SQLException { return getConnection(30, TimeUnit.SECONDS); } public Connection getConnection(long timeout, TimeUnit unit) throws SQLException { if (isClosed) { throw new SQLException(""Connection pool is closed""); } ... truncated ... } } catch (SQLException e) { // Ignore } } private class PooledConnection extends ConnectionWrapper { private final DatabaseConnectionPool pool; PooledConnection(Connection connection, DatabaseConnectionPool pool) { super(connection); this.pool = pool; } @Override public void close() throws SQLException { pool.returnConnection(this); } } private abstract class ConnectionWrapper implements Connection { protected final Connection delegate; ConnectionWrapper(Connection delegate) { this.delegate = delegate; } // Delegate all Connection methods to the wrapped connection @Override public Statement createStatement() throws SQLException { return delegate.createStatement(); } // ... implement all other Connection methods similarly @Override public boolean isWrapperFor(Class iface) throws SQLException { return iface.isInstance(delegate) || delegate.isWrapperFor(iface); } @SuppressWarnings(""unchecked"") @Override public T unwrap(Class iface) throws SQLException { if (iface.isInstance(delegate)) { return (T) delegate; } return delegate.unwrap(iface); } } }",174,101 ,"def findDuplicate(nums): slow = fast = nums[0] while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break slow = nums[0] while slow != fast: slow = nums[slow] fast = nums[fast] return slow ",1.0,GPT,"Solve the problem ""Find the Duplicate Number"". Given an array nums containing n+1 integers where each integer is in the range [1, n], return the duplicate number without modifying the array and using constant extra space. Provide Python solution using cycle detection. ",python,"def findDuplicate(nums): slow = fast = nums[0] while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break slow = nums[0] while slow != fast: slow = nums[slow] fast = nums[fast] return slow",15,15 ,"public ListNode mergeKLists(ListNode[] lists) { PriorityQueue pq = new PriorityQueue<>((a, b) -> a.val - b.val); for (ListNode l : lists) if (l != null) pq.add(l); ListNode dummy = new ListNode(0), tail = dummy; while (!pq.isEmpty()) { tail.next = pq.poll(); tail = tail.next; if (tail.next != null) pq.add(tail.next); } return dummy.next; }",1.0,GEMINI,write a program to Merge k sorted linked lists into one sorted linked list.,java,"public ListNode mergeKLists(ListNode[] lists) { PriorityQueue pq = new PriorityQueue<>((a, b) -> a.val - b.val); for (ListNode l : lists) if (l != null) pq.add(l); ListNode dummy = new ListNode(0), tail = dummy; while (!pq.isEmpty()) { tail.next = pq.poll(); tail = tail.next; if (tail.next != null) pq.add(tail.next); } return dummy.next; }",11,11 ,"public class CountWords { public static void main(String[] args) { String input=""Welcome to Java Session Session Session""; String[] words=input.split("" ""); int wrc=1; for(int i=0;i total or (total + target) % 2: return 0 s = (total + target) // 2 dp = [0] * (s + 1) dp[0] = 1 for num in nums: for i in range(s, num - 1, -1): dp[i] += dp[i - num] return dp[s] ",1.0,GPT,"Solve the problem ""Target Sum"". Given an array nums and a target, return the number of ways to assign + or - to reach target.",python,"def findTargetSumWays(nums, target): total = sum(nums) if abs(target) > total or (total + target) % 2: return 0 s = (total + target) // 2 dp = [0] * (s + 1) dp[0] = 1 for num in nums: for i in range(s, num - 1, -1): dp[i] += dp[i - num] return dp[s]",14,14 ,"static int subarraySum(int[] a,int k){ Map m=new HashMap<>(); m.put(0,1); int sum=0,res=0; for(int x:a){ sum+=x; res+=m.getOrDefault(sum-k,0); m.put(sum,m.getOrDefault(sum,0)+1); } return res; } ",1.0,GPT,"Given an integer array nums and integer k, return the number of continuous subarrays whose sum equals k.",java,"static int subarraySum(int[] a,int k){ Map m=new HashMap<>(); m.put(0,1); int sum=0,res=0; for(int x:a){ sum+=x; res+=m.getOrDefault(sum-k,0); m.put(sum,m.getOrDefault(sum,0)+1); } return res; }",10,10 ,"class Solution { public List findDuplicates(int[] nums) { List ans = new ArrayList<>(); int n = nums.length; for (int i = 0; i < n; i++) { int num = Math.abs(nums[i]); if (nums[num - 1] > 0) { nums[num - 1] *= -1; } else { ans.add(num); } } return ans; } }",0.0,leetcode,,java,"class Solution { public List findDuplicates(int[] nums) { List ans = new ArrayList<>(); int n = nums.length; for (int i = 0; i < n; i++) { int num = Math.abs(nums[i]); if (nums[num - 1] > 0) { nums[num - 1] *= -1; } else { ans.add(num); } } return ans; } }",16,16 ,"import json json_obj = '{ ""Name"":""David"", ""Class"":""I"", ""Age"":6 }' python_obj = json.loads(json_obj) print(""\nJSON data:"") print(python_obj) print(""\nName: "",python_obj[""Name""]) print(""Class: "",python_obj[""Class""]) print(""Age: "",python_obj[""Age""]) ",0.0,WE3RESOURCE,,python,"import json json_obj = '{ ""Name"":""David"", ""Class"":""I"", ""Age"":6 }' python_obj = json.loads(json_obj) print(""\nJSON data:"") print(python_obj) print(""\nName: "",python_obj[""Name""]) print(""Class: "",python_obj[""Class""]) print(""Age: "",python_obj[""Age""]) ",8,8 ,"import requests from bs4 import BeautifulSoup from datetime import datetime url = 'https://www.us-cert.gov/ncas/alerts' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # Current year current_year = datetime.now().year alerts = soup.find_all('article', {'data-year': str(current_year)}) print(f""US-CERT security alerts in {current_year}: {len(alerts)}"") ",1.0,PERPLEXITY,"Write a Python program get the number of security alerts issued by US-CERT in the current year. Source: https://www.us-cert.gov/ncas/alerts",python,"import requests from bs4 import BeautifulSoup from datetime import datetime url = 'https://www.us-cert.gov/ncas/alerts' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # Current year current_year = datetime.now().year alerts = soup.find_all('article', {'data-year': str(current_year)}) print(f""US-CERT security alerts in {current_year}: {len(alerts)}"")",13,13 ,"public enum Singleton { INSTANCE; private Singleton() {} public void doSomething() { System.out.println(""Singleton instance method""); } public static Singleton getInstance() { return INSTANCE; } } ",1.0,PERPLEXITY,Write a thread-safe singleton class in Java using enum pattern,java,"public enum Singleton { INSTANCE; private Singleton() {} public void doSomething() { System.out.println(""Singleton instance method""); } public static Singleton getInstance() { return INSTANCE; } }",10,10 ,"import ast, math SAFE = {k:v for k,v in vars(math).items() if not k.startswith(""_"")} def evaluate(expr): try: return eval(compile(ast.parse(expr, ""eval""), """", ""eval""), {}, SAFE) except Exception as e: return f""Error: {e}"" # ---------- USER INPUT ---------- expr = input(""Enter math expression: "") # ---------- OUTPUT ---------- print(""Result:"", evaluate(expr)) ",1.0,GPT,"# Import the Abstract Syntax Tree (AST) module import ast # Import the math module for mathematical functions and constants import math # Define a class for evaluating mathematical expressions class MathExpressionEvaluator: def __init__(self): pass # Method to evaluate mathematical expressions def evaluate(self, expression): try: # Parse the expression into an Abstract Syntax Tree (AST) parsed_expression = ast.parse(expression, mode='eval') # Define the allowed names (functions and constants) for evaluation allowed_names = { 'sin': math.sin, 'cos': math.cos, 'tan': math.tan, 'log': math.log, 'sqrt': math.sqrt, **vars(math) # Include all functions and constants from the math module } # Evaluate the AST using a custom namespace that includes the allowed names result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names) return result except SyntaxError: print(""Invalid expression syntax."") return None except Exception as e: print(""Error:"", e) return None # Example usage if __name__ == ""__main__"": evaluator = MathExpressionEvaluator() # Evaluate mathematical expressions print(""Evaluation Results:"") print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4"")) print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4"")) print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)"")) print(""log(10) ="", evaluator.evaluate(""log(10)"")) Write a Python library for parsing and evaluating mathematical expressions., THE ABOVE code is the solution i got from one of the websites make this shorter and give me the effective one with a feature of user entering the inputs ",python,"import ast, math SAFE = {k:v for k,v in vars(math).items() if not k.startswith(""_"")} def evaluate(expr): try: return eval(compile(ast.parse(expr, ""eval""), """", ""eval""), {}, SAFE) except Exception as e: return f""Error: {e}"" # ---------- USER INPUT ---------- expr = input(""Enter math expression: "") # ---------- OUTPUT ---------- print(""Result:"", evaluate(expr))",15,15 ,"public int numberOfBoomerangs(int[][] points) { if(points == null || points.length == 0 || points[0].length == 0){ return 0; } int count = 0; Map hashMap = new HashMap<>(); for (int i = 0;i < points.length;i++){ //count distances for every i with an empty hashMap,and hashMap.clear() is more faster than new HashMap() hashMap.clear(); for (int j = 0;j < points.length;j++){ //it's unnecessary when i == j if (i == j){ continue; } //multiple them directly is more faster than use Math.pow() int distance = (points[j][0]-points[i][0])*(points[j][0]-points[i][0]) + (points[j][1]-points[i][1]) * (points[j][1]-points[i][1]); //First, select one position to place your new point by distance with number of hashMap.get(distance) //and then you can change the order of the two elements,so multiple 2 count += hashMap.getOrDefault(distance,0) * 2; hashMap.put(distance,hashMap.getOrDefault(distance,0) + 1); } } return count; }",0.0,leetcode,,java,"public int numberOfBoomerangs(int[][] points) { if(points == null || points.length == 0 || points[0].length == 0){ return 0; } int count = 0; Map hashMap = new HashMap<>(); for (int i = 0;i < points.length;i++){ //count distances for every i with an empty hashMap,and hashMap.clear() is more faster than new HashMap() hashMap.clear(); for (int j = 0;j < points.length;j++){ //it's unnecessary when i == j if (i == j){ continue; } //multiple them directly is more faster than use Math.pow() int distance = (points[j][0]-points[i][0])*(points[j][0]-points[i][0]) + (points[j][1]-points[i][1]) * (points[j][1]-points[i][1]); //First, select one position to place your new point by distance with number of hashMap.get(distance) //and then you can change the order of the two elements,so multiple 2 count += hashMap.getOrDefault(distance,0) * 2; hashMap.put(distance,hashMap.getOrDefault(distance,0) + 1); } } return count; }",24,24 ,"def test(a): def add(b): nonlocal a a += 1 return a + b return add a = int(input(""Enter value for a: "")) func = test(a) b = int(input(""Enter value for b: "")) print(""Result:"", func(b)) ",1.0,PERPLEXITY,Write a Python program to access a function inside a function.,python,"def test(a): def add(b): nonlocal a a += 1 return a + b return add a = int(input(""Enter value for a: "")) func = test(a) b = int(input(""Enter value for b: "")) print(""Result:"", func(b))",11,11 ,"import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(""/api/users"") public class UserController { @GetMapping(""/{id}"") public String getUser(@PathVariable Long id) { return ""User: "" + id; } @PostMapping public String createUser(@RequestBody String name) { return ""Created user: "" + name; } } ",1.0,PERPLEXITY,"Create a basic Spring Boot REST controller with GET, POST endpoints.",java,"import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(""/api/users"") public class UserController { @GetMapping(""/{id}"") public String getUser(@PathVariable Long id) { return ""User: "" + id; } @PostMapping public String createUser(@RequestBody String name) { return ""Created user: "" + name; } }",15,15 ,"import requests from pprint import pprint def weather_data(query): res=requests.get('http://api.openweathermap.org/data/2.5/weather?'+query+'&APPID=****************************8&units=metric'); return res.json(); def print_weather(result,city): print(""{}'s temperature: {}°C "".format(city,result['main']['temp'])) print(""Wind speed: {} m/s"".format(result['wind']['speed'])) print(""Description: {}"".format(result['weather'][0]['description'])) print(""Weather: {}"".format(result['weather'][0]['main'])) def main(): city=input('Enter the city:') print() try: query='q='+city; w_data=weather_data(query); print_weather(w_data, city) print() except: print('City name not found...') if __name__=='__main__': main() ",0.0,WERESOURCE,,python,"import requests from pprint import pprint def weather_data(query): res=requests.get('http://api.openweathermap.org/data/2.5/weather?'+query+'&APPID=****************************8&units=metric'); return res.json(); def print_weather(result,city): print(""{}'s temperature: {}°C "".format(city,result['main']['temp'])) print(""Wind speed: {} m/s"".format(result['wind']['speed'])) print(""Description: {}"".format(result['weather'][0]['description'])) print(""Weather: {}"".format(result['weather'][0]['main'])) def main(): city=input('Enter the city:') print() try: query='q='+city; w_data=weather_data(query); print_weather(w_data, city) print() except: print('City name not found...') if __name__=='__main__': main()",22,22 ,"static String reverseWords(String s){ String[] w=s.trim().split(""\\s+""); StringBuilder b=new StringBuilder(); for(int i=w.length-1;i>=0;i--) b.append(w[i]).append("" ""); return b.toString().trim(); } ",1.0,GPT,"Given a sentence, reverse the order of words without reversing characters.",java,"static String reverseWords(String s){ String[] w=s.trim().split(""\\s+""); StringBuilder b=new StringBuilder(); for(int i=w.length-1;i>=0;i--) b.append(w[i]).append("" ""); return b.toString().trim(); }",6,6 ,"public class Solution { private static final Map A = new HashMap<>(); static { A.put('A',0); A.put('C',1); A.put('G',2); A.put('T',3); } private final int A_SIZE_POW_9 = (int) Math.pow(A.size(), 9); public List findRepeatedDnaSequences(String s) { Set res = new HashSet<>(); Set hashes = new HashSet<>(); for (int i = 0, rhash = 0; i < s.length(); i++) { if (i > 9) rhash -= A_SIZE_POW_9 * A.get(s.charAt(i-10)); rhash = A.size() * rhash + A.get(s.charAt(i)); if (i > 8 && !hashes.add(rhash)) res.add(s.substring(i-9,i+1)); } return new ArrayList<>(res); } }",0.0,leetcode,,java,"public class Solution { private static final Map A = new HashMap<>(); static { A.put('A',0); A.put('C',1); A.put('G',2); A.put('T',3); } private final int A_SIZE_POW_9 = (int) Math.pow(A.size(), 9); public List findRepeatedDnaSequences(String s) { Set res = new HashSet<>(); Set hashes = new HashSet<>(); for (int i = 0, rhash = 0; i < s.length(); i++) { if (i > 9) rhash -= A_SIZE_POW_9 * A.get(s.charAt(i-10)); rhash = A.size() * rhash + A.get(s.charAt(i)); if (i > 8 && !hashes.add(rhash)) res.add(s.substring(i-9,i+1)); } return new ArrayList<>(res); } }",16,16 ,"public class ValidationException extends Exception { public ValidationException(String message) { super(message); } } public class UserValidationException extends ValidationException { public UserValidationException(String field) { super(""Invalid "" + field + "" value provided""); } } public class Validator { public static void validateEmail(String email) throws UserValidationException { if (!email.contains(""@"")) throw new UserValidationException(""email""); } } ",1.0,PERPLEXITY,Define a custom exception class hierarchy with validation exception in Java,java,"public class ValidationException extends Exception { public ValidationException(String message) { super(message); } } public class UserValidationException extends ValidationException { public UserValidationException(String field) { super(""Invalid "" + field + "" value provided""); } } public class Validator { public static void validateEmail(String email) throws UserValidationException { if (!email.contains(""@"")) throw new UserValidationException(""email""); } }",13,13 ,"class MatrixAddition { public static void main(String args[]) { int[][] a = new int[][] { { 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9} }; int[][] b = new int[][] { { 10, 11, 12},{ 13, 14, 15},{ 16, 17, 18} }; int[][] c = new int[3][3]; if(a.length == b.length && a[0].length == b[0].length) { for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { c[i][j] = a[i][j] + b[i][j]; } } } else { System.out.println(""'A' and 'B' Matrix are not SAME""); return; } System.out.println(""The Matrix 'A' Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(a[i][j] + "" ""); } System.out.println(); } System.out.println(""The Matrix 'B' Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(b[i][j]+ "" ""); } System.out.println(); } System.out.println(""The Addition Matrix of 'A' and 'B' Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(c[i][j] + "" ""); } System.out.println(); } } }",0.0,IPSGWALIOR.ORG,,java,"class MatrixAddition { public static void main(String args[]) { int[][] a = new int[][] { { 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9} }; int[][] b = new int[][] { { 10, 11, 12},{ 13, 14, 15},{ 16, 17, 18} }; int[][] c = new int[3][3]; if(a.length == b.length && a[0].length == b[0].length) { for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { c[i][j] = a[i][j] + b[i][j]; } } } else { System.out.println(""'A' and 'B' Matrix are not SAME""); return; } System.out.println(""The Matrix 'A' Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(a[i][j] + "" ""); } System.out.println(); } System.out.println(""The Matrix 'B' Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(b[i][j]+ "" ""); } System.out.println(); } System.out.println(""The Addition Matrix of 'A' and 'B' Value:""); for(int i = 0;i < a.length;i++) { for(int j = 0;j < a[i].length;j++) { System.out.print(c[i][j] + "" ""); } System.out.println(); } } }",53,53 ,"def rob(nums): prev, curr = 0, 0 for n in nums: prev, curr = curr, max(curr, prev + n) return curr ",1.0,GPT,"Solve the problem ""House Robber"". Given an integer array nums representing the amount of money in each house, return the maximum amount of money you can rob without robbing adjacent houses. ",python,"def rob(nums): prev, curr = 0, 0 for n in nums: prev, curr = curr, max(curr, prev + n) return curr",5,5 ,"import tweepy # Replace with your actual bearer token from X Developer Portal BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE' # Initialize the client with bearer token (sufficient for read access) client = tweepy.Client(bearer_token=BEARER_TOKEN) # Input for Twitter username (without @) username = input(""Enter Twitter username: "") try: # Get the user by username user = client.get_user(username=username, user_fields=['public_metrics']) if user.data: # Access public_metrics.like_count for number of liked posts public_metrics = user.data.public_metrics likes_count = public_metrics['like_count'] print(f""@{username} has liked {likes_count:,} posts."") else: print(""User not found."") except tweepy.TweepyException as e: print(f""Error: {e}"") ",1.0,PERPLEXITY,Write a Python program to get the number of post on Twitter liked by a given account,python,"import tweepy # Replace with your actual bearer token from X Developer Portal BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE' # Initialize the client with bearer token (sufficient for read access) client = tweepy.Client(bearer_token=BEARER_TOKEN) # Input for Twitter username (without @) username = input(""Enter Twitter username: "") try: # Get the user by username user = client.get_user(username=username, user_fields=['public_metrics']) if user.data: # Access public_metrics.like_count for number of liked posts public_metrics = user.data.public_metrics likes_count = public_metrics['like_count'] print(f""@{username} has liked {likes_count:,} posts."") else: print(""User not found."") except tweepy.TweepyException as e: print(f""Error: {e}"")",26,26 ,"// With comments class RandomizedCollection { private Map> map; // Map to store values and their indices in the list private List list; // List to store the values in the order they were inserted public RandomizedCollection() { this.map = new HashMap<>(); this.list = new ArrayList<>(); } // Inserts a value into the collection, returns true if the value was not present before public boolean insert(int val) { boolean ans = map.containsKey(val); // Check if the value is already present map.computeIfAbsent(val, key -> new HashSet<>()).add(list.size()); // Add the index to the set in the map list.add(val); // Add the value to the list return !ans; // Return true if the value was not present before } // Removes a value from the collection, returns true if the value was present public boolean remove(int val) { if (!map.containsKey(val)) return false; // If the value is not present, return false int indexVal = map.get(val).iterator().next(); // Get one of the indices of the value map.get(val).remove(indexVal); // Remove the index from the set in the map if (map.get(val).isEmpty()) map.remove(val); // If the set is empty, remove the value from the map if (indexVal != list.size() - 1) { // If the index to be removed is not the last index in the list // Update the map for the last value in the list map.get(list.get(list.size() - 1)).remove(list.size() - 1); map.get(list.get(list.size() - 1)).add(indexVal); list.set(indexVal, list.get(list.size() - 1)); // Replace the value at indexVal with the last value } list.remove(list.size() - 1); // Remove the last element from the list return true; // Return true since the value was present and removed } // Returns a random element from the collection public int getRandom() { Random random = new Random(); int ind = random.nextInt(list.size()); // Generate a random index return list.get(ind); // Return the value at the random index } }",0.0,leetcode,,java,"// With comments class RandomizedCollection { private Map> map; // Map to store values and their indices in the list private List list; // List to store the values in the order they were inserted public RandomizedCollection() { this.map = new HashMap<>(); this.list = new ArrayList<>(); } // Inserts a value into the collection, returns true if the value was not present before public boolean insert(int val) { boolean ans = map.containsKey(val); // Check if the value is already present map.computeIfAbsent(val, key -> new HashSet<>()).add(list.size()); // Add the index to the set in the map list.add(val); // Add the value to the list return !ans; // Return true if the value was not present before } // Removes a value from the collection, returns true if the value was present public boolean remove(int val) { if (!map.containsKey(val)) return false; // If the value is not present, return false int indexVal = map.get(val).iterator().next(); // Get one of the indices of the value map.get(val).remove(indexVal); // Remove the index from the set in the map if (map.get(val).isEmpty()) map.remove(val); // If the set is empty, remove the value from the map if (indexVal != list.size() - 1) { // If the index to be removed is not the last index in the list // Update the map for the last value in the list map.get(list.get(list.size() - 1)).remove(list.size() - 1); map.get(list.get(list.size() - 1)).add(indexVal); list.set(indexVal, list.get(list.size() - 1)); // Replace the value at indexVal with the last value } list.remove(list.size() - 1); // Remove the last element from the list return true; // Return true since the value was present and removed } // Returns a random element from the collection public int getRandom() { Random random = new Random(); int ind = random.nextInt(list.size()); // Generate a random index return list.get(ind); // Return the value at the random index } }",48,48 ,"static int max=Integer.MIN_VALUE; static int path(Node n){ if(n==null) return 0; int l=Math.max(0,path(n.left)), r=Math.max(0,path(n.right)); max=Math.max(max,l+r+n.val); return Math.max(l,r)+n.val; } ",1.0,GPT,write a java program to Find max sum of any path in tree.,java,"static int max=Integer.MIN_VALUE; static int path(Node n){ if(n==null) return 0; int l=Math.max(0,path(n.left)), r=Math.max(0,path(n.right)); max=Math.max(max,l+r+n.val); return Math.max(l,r)+n.val; }",7,7 ,"def findMedianSortedArrays(nums1, nums2): A, B = nums1, nums2 if len(A) > len(B): A, B = B, A total = len(A) + len(B) half = total // 2 l, r = 0, len(A) while True: i = (l + r) // 2 j = half - i Aleft = A[i - 1] if i > 0 else float('-inf') Aright = A[i] if i < len(A) else float('inf') Bleft = B[j - 1] if j > 0 else float('-inf') Bright = B[j] if j < len(B) else float('inf') if Aleft <= Bright and Bleft <= Aright: if total % 2: return min(Aright, Bright) return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 elif Aleft > Bright: r = i - 1 else: l = i + 1 ",1.0,GPT,"Solve the problem ""Median of Two Sorted Arrays"". Given two sorted arrays nums1 and nums2, return the median of the two sorted arrays. The overall time complexity must be O(log(min(n, m))).",python,"def findMedianSortedArrays(nums1, nums2): A, B = nums1, nums2 if len(A) > len(B): A, B = B, A total = len(A) + len(B) half = total // 2 l, r = 0, len(A) while True: i = (l + r) // 2 j = half - i Aleft = A[i - 1] if i > 0 else float('-inf') Aright = A[i] if i < len(A) else float('inf') Bleft = B[j - 1] if j > 0 else float('-inf') Bright = B[j] if j < len(B) else float('inf') if Aleft <= Bright and Bleft <= Aright: if total % 2: return min(Aright, Bright) return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 elif Aleft > Bright: r = i - 1 else: l = i + 1",26,26 ,"static int maxRect(int[] h){ Stack s=new Stack<>(); int max=0; for(int i=0;i<=h.length;i++){ int cur=i==h.length?0:h[i]; while(!s.isEmpty()&&cur s=new Stack<>(); int max=0; for(int i=0;i<=h.length;i++){ int cur=i==h.length?0:h[i]; while(!s.isEmpty()&&cur int: mp = defaultdict(int) res = 0 for num in nums: if not mp[num]: mp[num] = mp[num - 1] + mp[num + 1] + 1 mp[num - mp[num - 1]] = mp[num] mp[num + mp[num + 1]] = mp[num] res = max(res, mp[num]) return res",0.0,GFG,,python,"class Solution: def longestConsecutive(self, nums: List[int]) -> int: mp = defaultdict(int) res = 0 for num in nums: if not mp[num]: mp[num] = mp[num - 1] + mp[num + 1] + 1 mp[num - mp[num - 1]] = mp[num] mp[num + mp[num + 1]] = mp[num] res = max(res, mp[num]) return res",12,12 ,"// Define the Singleton class public class Singleton { // Private static variable to hold the single instance private static Singleton singleInstance = null; // Private constructor to prevent instantiation private Singleton() { // Print a message indicating the creation of the instance System.out.println(""Singleton instance created.""); } // Public static method to get the single instance of the class public static Singleton getInstance() { // If the single instance is null, create a new instance if (singleInstance == null) { singleInstance = new Singleton(); } // Return the single instance return singleInstance; } // Main method to test the Singleton class public static void main(String[] args) { // Get the single instance of Singleton Singleton instance1 = Singleton.getInstance(); // Try to get another instance of Singleton Singleton instance2 = Singleton.getInstance(); // Check if both instances are the same if (instance1 == instance2) { System.out.println(""Both instances are the same.""); } else { System.out.println(""Instances are different.""); } } } ",0.0,WE3RESOURCE,,java,"// Define the Singleton class public class Singleton { // Private static variable to hold the single instance private static Singleton singleInstance = null; // Private constructor to prevent instantiation private Singleton() { // Print a message indicating the creation of the instance System.out.println(""Singleton instance created.""); } // Public static method to get the single instance of the class public static Singleton getInstance() { // If the single instance is null, create a new instance if (singleInstance == null) { singleInstance = new Singleton(); } // Return the single instance return singleInstance; } // Main method to test the Singleton class public static void main(String[] args) { // Get the single instance of Singleton Singleton instance1 = Singleton.getInstance(); // Try to get another instance of Singleton Singleton instance2 = Singleton.getInstance(); // Check if both instances are the same if (instance1 == instance2) { System.out.println(""Both instances are the same.""); } else { System.out.println(""Instances are different.""); } } }",36,36 ,"import numpy as np ids = np.array([101, 102, 103, 104, 105]) heights = np.array([165, 170.5, 168.2, 172, 160.4]) idx = np.argsort(heights) print(""Indices:"", idx) print(""Sorted IDs:"", ids[idx])",1.0,DEEPAI,Write a NumPy program to sort the student id with increasing height of the students from given students id and height. Print the integer indices that describes the sort order by multiple columns and the sorted data,python,"import numpy as np ids = np.array([101, 102, 103, 104, 105]) heights = np.array([165, 170.5, 168.2, 172, 160.4]) idx = np.argsort(heights) print(""Indices:"", idx) print(""Sorted IDs:"", ids[idx])",7,7 ,"import java.io.IOException; public class FindTtalCountWords { public static void main(String args[]) throws IOException { countWords(""apple banna apple fruit fruit apple hello hi hi hello hi""); } static void countWords(String st) { String[] words = st.split(""\\s""); int[] fr = new int[words.length]; for (int i = 0; i < fr.length; i++) fr[i] = 0; for (int i = 0; i < words.length; i++) { for (int j = 0; j < words.length; j++) { if (words[i].equals(words[j])) { fr[i]++; } } } for (int i = 0; i < words.length; i++) { for (int j = 0; j < words.length; j++) { if (words[i].equals(words[j])) { if (i != j) { words[i] = """"; } } } } int total = 0; System.out.println(""Words and words count:""); for (int i = 0; i < words.length; i++) { if (words[i] != """") { System.out.println(words[i] + ""="" + fr[i]); total += fr[i]; } } System.out.println(""Total words counted: "" + total); } } ",0.0,IPSGWALIOR.ORG,,java,"import java.io.IOException; public class FindTtalCountWords { public static void main(String args[]) throws IOException { countWords(""apple banna apple fruit fruit apple hello hi hi hello hi""); } static void countWords(String st) { String[] words = st.split(""\\s""); int[] fr = new int[words.length]; for (int i = 0; i < fr.length; i++) fr[i] = 0; for (int i = 0; i < words.length; i++) { for (int j = 0; j < words.length; j++) { if (words[i].equals(words[j])) { fr[i]++; } } } for (int i = 0; i < words.length; i++) { for (int j = 0; j < words.length; j++) { if (words[i].equals(words[j])) { if (i != j) { words[i] = """"; } } } } int total = 0; System.out.println(""Words and words count:""); for (int i = 0; i < words.length; i++) { if (words[i] != """") { System.out.println(words[i] + ""="" + fr[i]); total += fr[i]; } } System.out.println(""Total words counted: "" + total); } }",60,60 ,"class Solution { public boolean checkInclusion(String s1, String s2) { if (s1.length() > s2.length()) { return false; } HashMap s1Count = new HashMap<>(); HashMap s2Count = new HashMap<>(); for (int i = 0; i < s1.length(); i++) { s1Count.put(s1.charAt(i), s1Count.getOrDefault(s1.charAt(i), 0) + 1); s2Count.put(s2.charAt(i), s2Count.getOrDefault(s2.charAt(i), 0) + 1); } if (s1Count.equals(s2Count)) { return true; } int left = 0; for (int right = s1.length(); right < s2.length(); right++) { char charRight = s2.charAt(right); s2Count.put(charRight, s2Count.getOrDefault(charRight, 0) + 1); char charLeft = s2.charAt(left); s2Count.put(charLeft, s2Count.get(charLeft) - 1); if (s2Count.get(charLeft) == 0) { s2Count.remove(charLeft); } left++; if (s1Count.equals(s2Count)) { return true; } } return false; } }",0.0,leetcode,,java,"class Solution { public boolean checkInclusion(String s1, String s2) { if (s1.length() > s2.length()) { return false; } HashMap s1Count = new HashMap<>(); HashMap s2Count = new HashMap<>(); for (int i = 0; i < s1.length(); i++) { s1Count.put(s1.charAt(i), s1Count.getOrDefault(s1.charAt(i), 0) + 1); s2Count.put(s2.charAt(i), s2Count.getOrDefault(s2.charAt(i), 0) + 1); } if (s1Count.equals(s2Count)) { return true; } int left = 0; for (int right = s1.length(); right < s2.length(); right++) { char charRight = s2.charAt(right); s2Count.put(charRight, s2Count.getOrDefault(charRight, 0) + 1); char charLeft = s2.charAt(left); s2Count.put(charLeft, s2Count.get(charLeft) - 1); if (s2Count.get(charLeft) == 0) { s2Count.remove(charLeft); } left++; if (s1Count.equals(s2Count)) { return true; } } return false; } }",39,39 ,"#https://bit.ly/2lVhlLX # landing page: # http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php import csv import requests csvurl = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv' rows = list(csv.DictReader(requests.get(csvurl).text.splitlines())) print(""The number of magnitude 4.5+ earthquakes detected worldwide by the USGS:"", len(rows)) ",0.0,WERESOURCE,,python,"#https://bit.ly/2lVhlLX # landing page: # http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php import csv import requests csvurl = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv' rows = list(csv.DictReader(requests.get(csvurl).text.splitlines())) print(""The number of magnitude 4.5+ earthquakes detected worldwide by the USGS:"", len(rows))",8,8 ,"import json def is_complex_num(objct): if '__complex__' in objct: return complex(objct['real'], objct['img']) return objct complex_object =json.loads('{""__complex__"": true, ""real"": 4, ""img"": 5}', object_hook = is_complex_num) simple_object =json.loads('{""real"": 4, ""img"": 3}', object_hook = is_complex_num) print(""Complex_object: "",complex_object) print(""Without complex object: "",simple_object) ",0.0,WE3RESOURCE,,python,"import json def is_complex_num(objct): if '__complex__' in objct: return complex(objct['real'], objct['img']) return objct complex_object =json.loads('{""__complex__"": true, ""real"": 4, ""img"": 5}', object_hook = is_complex_num) simple_object =json.loads('{""real"": 4, ""img"": 3}', object_hook = is_complex_num) print(""Complex_object: "",complex_object) print(""Without complex object: "",simple_object)",10,10 ,"def check_if_complex(data): """""" Checks if the provided data instance is of the complex type. """""" if isinstance(data, complex): print(f""✓ {data} is a complex number."") print(f"" - Real part: {data.real}"") print(f"" - Imaginary part: {data.imag}"") else: print(f""✗ {data} (type: {type(data).__name__}) is NOT a complex number."") # --- Testing various instances --- # A standard complex number val1 = 5 + 3j # A complex number created via constructor val2 = complex(10, -2) # A standard integer val3 = 100 # A float val4 = 7.5 print(""Starting Instance Check:\n"" + ""-""*25) check_if_complex(val1) check_if_complex(val2) check_if_complex(val3) check_if_complex(val4)",1.0,GEMINI,Write a Python program to check whether an instance is complex or not.,python,"def check_if_complex(data): """""" Checks if the provided data instance is of the complex type. """""" if isinstance(data, complex): print(f""✓ {data} is a complex number."") print(f"" - Real part: {data.real}"") print(f"" - Imaginary part: {data.imag}"") else: print(f""✗ {data} (type: {type(data).__name__}) is NOT a complex number."") # --- Testing various instances --- # A standard complex number val1 = 5 + 3j # A complex number created via constructor val2 = complex(10, -2) # A standard integer val3 = 100 # A float val4 = 7.5 print(""Starting Instance Check:\n"" + ""-""*25) check_if_complex(val1) check_if_complex(val2) check_if_complex(val3) check_if_complex(val4)",30,30 ,"import numpy as np arr = np.array([9, 3, 5, 1, 8, 2, 7]) k = 3 # Partition index partitioned_arr = np.partition(arr, k) print(""Partitioned array:"", partitioned_arr)",1.0,DEEPAI,"Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice)",python,"import numpy as np arr = np.array([9, 3, 5, 1, 8, 2, 7]) k = 3 # Partition index partitioned_arr = np.partition(arr, k) print(""Partitioned array:"", partitioned_arr)",7,7 ,"import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class CircularBuffer { private final T[] buffer; private final int capacity; private int head; private int tail; private int count; private final ReentrantLock lock; private final Condition notEmpty; private final Condition notFull; private volatile boolean isShutdown; @SuppressWarnings(""unchecked"") public CircularBuffer(int capacity) { this.capacity = capacity; this.buffer = (T[]) new Object[capacity]; this.lock = new ReentrantLock(); this.notEmpty = lock.newCondition(); this.notFull = lock.newCondition(); this.isShutdown = false; } public boolean put(T item) throws InterruptedException { return put(item, -1); } public boolean put(T item, long timeoutMillis) throws InterruptedException { if (item == null) throw new NullPointerException(); lock.lock(); try { // Wait until buffer is not full or shutdown while (count == capacity && !isShutdown) { if (timeoutMillis <= 0) { notFull.await(); } else { if (!notFull.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) { return false; } } } if (isShutdown) return false; buffer[tail] = item; tail = (tail + 1) % capacity; count++; notEmpty.signal(); return true; } finally { lock.unlock(); } } public T take() throws InterruptedException { return take(-1); } public T take(long timeoutMillis) throws InterruptedException { lock.lock(); try { // Wait until buffer is not empty or shutdown while (count == 0 && !isShutdown) { if (timeoutMillis <= 0) { notEmpty.await(); } else { if (!notEmpty.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) { return null; } } } if (count == 0 && isShutdown) return null; T item = buffer[head]; buffer[head] = null; // Help GC head = (head + 1) % capacity; count--; notFull.signal(); return item; } finally { lock.unlock(); } } public boolean offer(T item) { if (item == null) throw new NullPointerException(); lock.lock(); try { if (count == capacity || isShutdown) { return false; } buffer[tail] = item; tail = (tail + 1) % capacity; count++; notEmpty.signal(); return true; } finally { lock.unlock(); } } public T poll() { lock.lock(); try { if (count == 0) { return null; } T item = buffer[head]; buffer[head] = null; head = (head + 1) % capacity; count--; notFull.signal(); return item; } finally { lock.unlock(); } } public int size() { lock.lock(); try { return count; } finally { lock.unlock(); } } public boolean isEmpty() { lock.lock(); try { return count == 0; } finally { lock.unlock(); } } public boolean isFull() { lock.lock(); try { return count == capacity; } finally { lock.unlock(); } } public void shutdown() { lock.lock(); try { isShutdown = true; notEmpty.signalAll(); notFull.signalAll(); } finally { lock.unlock(); } } public void clear() { lock.lock(); try { for (int i = 0; i < capacity; i++) { buffer[i] = null; } head = tail = count = 0; notFull.signalAll(); } finally { lock.unlock(); } } }",1.0,DEEPSEEK,Implement a thread-safe circular buffer (ring buffer) with fixed capacity that supports concurrent producers and consumers.,java,"import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class CircularBuffer { private final T[] buffer; private final int capacity; private int head; private int tail; private int count; private final ReentrantLock lock; private final Condition notEmpty; private final Condition notFull; private volatile boolean isShutdown; @SuppressWarnings(""unchecked"") public CircularBuffer(int capacity) { this.capacity = capacity; this.buffer = (T[]) new Object[capacity]; this.lock = new ReentrantLock(); this.notEmpty = lock.newCondition(); this.notFull = lock.newCondition(); this.isShutdown = false; } public boolean put(T item) throws InterruptedException { return put(item, -1); } public boolean put(T item, long timeoutMillis) throws InterruptedException { if (item == null) throw new NullPointerException(); lock.lock(); try { // Wait until buffer is not full or shutdown while (count == capacity && !isShutdown) { if (timeoutMillis <= 0) { notFull.await(); } else { if (!notFull.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) { return false; } } } if (isShutdown) return false; buffer[tail] = item; tail = (tail + 1) % capacity; count++; notEmpty.signal(); ... truncated ... lock.lock(); try { return count; } finally { lock.unlock(); } } public boolean isEmpty() { lock.lock(); try { return count == 0; } finally { lock.unlock(); } } public boolean isFull() { lock.lock(); try { return count == capacity; } finally { lock.unlock(); } } public void shutdown() { lock.lock(); try { isShutdown = true; notEmpty.signalAll(); notFull.signalAll(); } finally { lock.unlock(); } } public void clear() { lock.lock(); try { for (int i = 0; i < capacity; i++) { buffer[i] = null; } head = tail = count = 0; notFull.signalAll(); } finally { lock.unlock(); } } }",175,101 ,"# Define a class representing a node in a tree class TreeNode: def __init__(self, value): self.value = value self.children = [] # Initialize an empty list to store child nodes def add_child(self, child_node): self.children.append(child_node) # Add a child node to the list of children # Define a class implementing a custom iterator for tree traversal class TreeIterator: def __init__(self, root): self.stack = [root] # Initialize stack with root node def __iter__(self): return self def __next__(self): if not self.stack: # If stack is empty, no more nodes to traverse raise StopIteration node = self.stack.pop() # Get the top node from stack for child in reversed(node.children): # Add children to stack in reverse order self.stack.append(child) return node.value # Example usage: if __name__ == ""__main__"": # Create a tree with a root node and some child nodes root = TreeNode(1) root.add_child(TreeNode(2)) root.add_child(TreeNode(3)) root.children[0].add_child(TreeNode(4)) root.children[0].add_child(TreeNode(5)) root.children[1].add_child(TreeNode(6)) # Create a TreeIterator instance and iterate over the tree tree_iterator = TreeIterator(root) for value in tree_iterator: print(value)",0.0,W3RESOURCE,,python,"# Define a class representing a node in a tree class TreeNode: def __init__(self, value): self.value = value self.children = [] # Initialize an empty list to store child nodes def add_child(self, child_node): self.children.append(child_node) # Add a child node to the list of children # Define a class implementing a custom iterator for tree traversal class TreeIterator: def __init__(self, root): self.stack = [root] # Initialize stack with root node def __iter__(self): return self def __next__(self): if not self.stack: # If stack is empty, no more nodes to traverse raise StopIteration node = self.stack.pop() # Get the top node from stack for child in reversed(node.children): # Add children to stack in reverse order self.stack.append(child) return node.value # Example usage: if __name__ == ""__main__"": # Create a tree with a root node and some child nodes root = TreeNode(1) root.add_child(TreeNode(2)) root.add_child(TreeNode(3)) root.children[0].add_child(TreeNode(4)) root.children[0].add_child(TreeNode(5)) root.children[1].add_child(TreeNode(6)) # Create a TreeIterator instance and iterate over the tree tree_iterator = TreeIterator(root) for value in tree_iterator: print(value)",39,39 ,"def get_unique_values(data_obj): # We use set() because sets automatically remove duplicates unique_values = set(data_obj.values()) return list(unique_values) # Example: Several keys share the same value employee_roles = { ""Alice"": ""Engineer"", ""Bob"": ""Manager"", ""Charlie"": ""Engineer"", ""David"": ""Intern"", ""Eve"": ""Manager"" } print(f""Unique Roles: {get_unique_values(employee_roles)}"")",1.0,GEMINI,Write a Python program to access only unique key value of a Python object.,python,"def get_unique_values(data_obj): # We use set() because sets automatically remove duplicates unique_values = set(data_obj.values()) return list(unique_values) # Example: Several keys share the same value employee_roles = { ""Alice"": ""Engineer"", ""Bob"": ""Manager"", ""Charlie"": ""Engineer"", ""David"": ""Intern"", ""Eve"": ""Manager"" } print(f""Unique Roles: {get_unique_values(employee_roles)}"")",15,15 ,"def exist(board, word): rows, cols = len(board), len(board[0]) def dfs(r, c, i): if i == len(word): return True if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[i]: return False tmp = board[r][c] board[r][c] = ""#"" found = (dfs(r+1, c, i+1) or dfs(r-1, c, i+1) or dfs(r, c+1, i+1) or dfs(r, c-1, i+1)) board[r][c] = tmp return found for r in range(rows): for c in range(cols): if dfs(r, c, 0): return True return False ",1.0,GPT,"Solve the problem ""Word Search"". Given a 2D board of characters and a word, return true if the word exists in the grid. The word can be constructed from adjacent cells (horizontal or vertical) without reusing a cell.",python,"def exist(board, word): rows, cols = len(board), len(board[0]) def dfs(r, c, i): if i == len(word): return True if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[i]: return False tmp = board[r][c] board[r][c] = ""#"" found = (dfs(r+1, c, i+1) or dfs(r-1, c, i+1) or dfs(r, c+1, i+1) or dfs(r, c-1, i+1)) board[r][c] = tmp return found for r in range(rows): for c in range(cols): if dfs(r, c, 0): return True return False",21,21 ,"from bs4 import BeautifulSoup import requests handle = input('Input your account name on Twitter: ') temp = requests.get('https://twitter.com/'+handle) bs = BeautifulSoup(temp.text,'lxml') try: following_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--following'}) following = following_box.find('a').find('span',{'class':'ProfileNav-value'}) print(""{} is following {} people."".format(handle,following.get('data-count'))) except: print('Account name not found...') ",0.0,WERESOURCE,,python,"from bs4 import BeautifulSoup import requests handle = input('Input your account name on Twitter: ') temp = requests.get('https://twitter.com/'+handle) bs = BeautifulSoup(temp.text,'lxml') try: following_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--following'}) following = following_box.find('a').find('span',{'class':'ProfileNav-value'}) print(""{} is following {} people."".format(handle,following.get('data-count'))) except: print('Account name not found...')",14,14 ,"import json import io def convert_json_to_object(data_source): """""" Converts JSON data from various forms (string, file, or stream) into a Python object. """""" try: # Case 1: If data_source is already a file-like object/stream if hasattr(data_source, 'read'): return json.load(data_source) # Case 2: If data_source is a string if isinstance(data_source, str): # Check if it's a file path by looking for a .json extension if data_source.strip().endswith('.json'): with open(data_source, 'r', encoding='utf-8') as f: return json.load(f) # Otherwise, treat it as a raw JSON string return json.loads(data_source) # Case 3: If data_source is bytes if isinstance(data_source, bytes): return json.loads(data_source.decode('utf-8')) raise ValueError(""Unsupported data format."") except json.JSONDecodeError as e: return f""Invalid JSON: {e}"" except FileNotFoundError: return ""Error: The specified file was not found."" # --- Examples of Usage --- # 1. From a JSON String json_string = '{""name"": ""Alice"", ""role"": ""Engineer"", ""active"": true}' obj_from_str = convert_json_to_object(json_string) # 2. From a File-like object (Stream) stream = io.StringIO('[1, 2, 3, {""key"": ""value""}]') obj_from_stream = convert_json_to_object(stream) print(f""String conversion: {obj_from_str['name']}"") print(f""Stream conversion: {obj_from_stream[3]['key']}"")",1.0,GEMINI,Write a Python program to convert JSON data to Python object.Make the code effiecient to accept the json in various countforms,python,"import json import io def convert_json_to_object(data_source): """""" Converts JSON data from various forms (string, file, or stream) into a Python object. """""" try: # Case 1: If data_source is already a file-like object/stream if hasattr(data_source, 'read'): return json.load(data_source) # Case 2: If data_source is a string if isinstance(data_source, str): # Check if it's a file path by looking for a .json extension if data_source.strip().endswith('.json'): with open(data_source, 'r', encoding='utf-8') as f: return json.load(f) # Otherwise, treat it as a raw JSON string return json.loads(data_source) # Case 3: If data_source is bytes if isinstance(data_source, bytes): return json.loads(data_source.decode('utf-8')) raise ValueError(""Unsupported data format."") except json.JSONDecodeError as e: return f""Invalid JSON: {e}"" except FileNotFoundError: return ""Error: The specified file was not found."" # --- Examples of Usage --- # 1. From a JSON String json_string = '{""name"": ""Alice"", ""role"": ""Engineer"", ""active"": true}' obj_from_str = convert_json_to_object(json_string) # 2. From a File-like object (Stream) stream = io.StringIO('[1, 2, 3, {""key"": ""value""}]') obj_from_stream = convert_json_to_object(stream) print(f""String conversion: {obj_from_str['name']}"") print(f""Stream conversion: {obj_from_stream[3]['key']}"")",45,45 ,"public class RemoveDuplicate { public static void main(String[] args) { String input=""Welcome to Java Session Java Session Session Java""; String[] words=input.split("" ""); for(int i=0;i set = new HashSet<>(); public boolean findTarget(TreeNode root, int k) { // Base case: null node if (root == null) return false; // If complement is found, return true if (set.contains(k - root.val)) return true; // Otherwise, add current node value to the set set.add(root.val); // Recurse on left and right subtrees return findTarget(root.left, k) || findTarget(root.right, k); } }",0.0,leetcode,,java,"class Solution { HashSet set = new HashSet<>(); public boolean findTarget(TreeNode root, int k) { // Base case: null node if (root == null) return false; // If complement is found, return true if (set.contains(k - root.val)) return true; // Otherwise, add current node value to the set set.add(root.val); // Recurse on left and right subtrees return findTarget(root.left, k) || findTarget(root.right, k); } }",17,17 ,"def longestConsecutive(nums): num_set = set(nums) longest = 0 for num in num_set: if num - 1 not in num_set: length = 1 while num + length in num_set: length += 1 longest = max(longest, length) return longest ",1.0,GPT,"Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. The solution must run in O(n) time.",python,"def longestConsecutive(nums): num_set = set(nums) longest = 0 for num in num_set: if num - 1 not in num_set: length = 1 while num + length in num_set: length += 1 longest = max(longest, length) return longest",12,12 ,"from collections import deque def wallsAndGates(rooms): rows, cols = len(rooms), len(rooms[0]) q = deque() for r in range(rows): for c in range(cols): if rooms[r][c] == 0: q.append((r, c)) directions = [(1,0), (-1,0), (0,1), (0,-1)] while q: r, c = q.popleft() for dr, dc in directions: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == 2147483647: rooms[nr][nc] = rooms[r][c] + 1 q.append((nr, nc)) ",1.0,GPT,"Solve the problem ""Walls and Gates"" (Islands and Treasure). Given a grid with: -1 = wall, 0 = gate, INF = empty room, fill each empty room with distance to its nearest gate.",python,"from collections import deque def wallsAndGates(rooms): rows, cols = len(rooms), len(rooms[0]) q = deque() for r in range(rows): for c in range(cols): if rooms[r][c] == 0: q.append((r, c)) directions = [(1,0), (-1,0), (0,1), (0,-1)] while q: r, c = q.popleft() for dr, dc in directions: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == 2147483647: rooms[nr][nc] = rooms[r][c] + 1 q.append((nr, nc))",20,20 ,"# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value def make_bold(fn): def wrapped(): return """" + fn() + """" return wrapped # Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value def make_italic(fn): def wrapped(): return """" + fn() + """" return wrapped # Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value def make_underline(fn): def wrapped(): return """" + fn() + """" return wrapped # Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function @make_bold @make_italic @make_underline def hello(): return ""hello world"" # Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline print(hello()) ## returns ""hello world""",0.0,W3RESOURCE,,python,"# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value def make_bold(fn): def wrapped(): return """" + fn() + """" return wrapped # Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value def make_italic(fn): def wrapped(): return """" + fn() + """" return wrapped # Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value def make_underline(fn): def wrapped(): return """" + fn() + """" return wrapped # Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function @make_bold @make_italic @make_underline def hello(): return ""hello world"" # Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline print(hello()) ## returns ""hello world""",28,28 ,"public class BubbleSort { public static void sort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } } ",1.0,PERPLEXITY,Create a Java class with a static method to sort an integer array using bubble sort in-place.,java,"public class BubbleSort { public static void sort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } }",14,14 ,"public class LetterPositionCount { public static void main(String args[]) { String s = ""CANDIDJAVA""; char[] a = s.toCharArray(); int i = 1; { for (char output : a) { System.out.print(output + "" "" + i + "" ""); i++; } } } } ",0.0,IPSGWALIOR.ORG,,java,"public class LetterPositionCount { public static void main(String args[]) { String s = ""CANDIDJAVA""; char[] a = s.toCharArray(); int i = 1; { for (char output : a) { System.out.print(output + "" "" + i + "" ""); i++; } } } }",21,21 ,"from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://www.wikipedia.org/') bs = BeautifulSoup(html, ""html.parser"") nameList = bs.findAll('a', {'class' : 'link-box'}) for name in nameList: print(name.get_text()) ",0.0,WE3RESOURCE,,python,"from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://www.wikipedia.org/') bs = BeautifulSoup(html, ""html.parser"") nameList = bs.findAll('a', {'class' : 'link-box'}) for name in nameList: print(name.get_text())",7,7 ,"class Solution { public List findAnagrams(String s, String p) { ArrayList ans= new ArrayList<>(); int pfreq []=new int [256]; int sfreq []=new int [256]; int low=0; int len=0; for(int i=0;ip.length()){ sfreq[s.charAt(low)]--; low++; len = high - low + 1; } if(isAnagram(sfreq,pfreq)){ ans.add(low); } } return ans; } public boolean isAnagram(int []sfreq, int [] pfreq){ for(int i=0;i<256; i++ ){ if(pfreq[i]!=sfreq[i]){ return false; } } return true; } }",0.0,leetcode,,java,"class Solution { public List findAnagrams(String s, String p) { ArrayList ans= new ArrayList<>(); int pfreq []=new int [256]; int sfreq []=new int [256]; int low=0; int len=0; for(int i=0;ip.length()){ sfreq[s.charAt(low)]--; low++; len = high - low + 1; } if(isAnagram(sfreq,pfreq)){ ans.add(low); } } return ans; } public boolean isAnagram(int []sfreq, int [] pfreq){ for(int i=0;i<256; i++ ){ if(pfreq[i]!=sfreq[i]){ return false; } } return true; } }",36,36 ,"// Define the Point class public class Point { // Private instance variables private int x; private int y; // Constructor that takes int parameters public Point(int x, int y) { // Initialize instance variables this.x = x; this.y = y; } // Constructor that takes double parameters public Point(double x, double y) { // Initialize instance variables by casting double to int this.x = (int) x; this.y = (int) y; } // Method to print the values of x and y public void printPoint() { System.out.println(""Point (x, y): ("" + x + "", "" + y + "")""); } // Main method to test the Point class public static void main(String[] args) { // Create a Point object using the int constructor Point point1 = new Point(4, 5); // Print the values of point1 point1.printPoint(); // Create a Point object using the double constructor Point point2 = new Point(4.5, 5.5); // Print the values of point2 point2.printPoint(); } } ",0.0,WE3RESOURCE,,java,"// Define the Point class public class Point { // Private instance variables private int x; private int y; // Constructor that takes int parameters public Point(int x, int y) { // Initialize instance variables this.x = x; this.y = y; } // Constructor that takes double parameters public Point(double x, double y) { // Initialize instance variables by casting double to int this.x = (int) x; this.y = (int) y; } // Method to print the values of x and y public void printPoint() { System.out.println(""Point (x, y): ("" + x + "", "" + y + "")""); } // Main method to test the Point class public static void main(String[] args) { // Create a Point object using the int constructor Point point1 = new Point(4, 5); // Print the values of point1 point1.printPoint(); // Create a Point object using the double constructor Point point2 = new Point(4.5, 5.5); // Print the values of point2 point2.printPoint(); } }",38,38 ,"static int[][] kClose(int[][] p,int k){ PriorityQueue q=new PriorityQueue<>( (a,b)->b[0]*b[0]+b[1]*b[1]-a[0]*a[0]-a[1]*a[1]); for(int[] x:p){ q.add(x); if(q.size()>k) q.poll(); } return q.toArray(new int[k][2]); } ",1.0,GPT,"WRITE A JAVA PROGRAM WHERE THE Given points in 2D, return k closest points to origin.",java,"static int[][] kClose(int[][] p,int k){ PriorityQueue q=new PriorityQueue<>( (a,b)->b[0]*b[0]+b[1]*b[1]-a[0]*a[0]-a[1]*a[1]); for(int[] x:p){ q.add(x); if(q.size()>k) q.poll(); } return q.toArray(new int[k][2]); }",6,6 ,"// SharedResourceExercise.java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SharedResourceExercise { private static final int NUM_THREADS = 3; private static final int NUM_ITERATIONS = 5; public static void main(String[] args) { Lock lock = new ReentrantLock(); SharedResource sharedResource = new SharedResource(); Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Worker(lock, sharedResource)); threads[i].start(); } try { for (Thread thread: threads) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } } static class Worker implements Runnable { private Lock lock; private SharedResource sharedResource; public Worker(Lock lock, SharedResource sharedResource) { this.lock = lock; this.sharedResource = sharedResource; } public void run() { for (int i = 0; i < NUM_ITERATIONS; i++) { lock.lock(); try { sharedResource.doWork(); } finally { lock.unlock(); } } } } static class SharedResource { public void doWork() { String threadName = Thread.currentThread().getName(); System.out.println(""Thread-> "" + threadName + "" is performing work.""); // Perform work on the shared resource } } } ",0.0,WE3RESOURCE,,java,"// SharedResourceExercise.java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SharedResourceExercise { private static final int NUM_THREADS = 3; private static final int NUM_ITERATIONS = 5; public static void main(String[] args) { Lock lock = new ReentrantLock(); SharedResource sharedResource = new SharedResource(); Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Worker(lock, sharedResource)); threads[i].start(); } try { for (Thread thread: threads) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } } static class Worker implements Runnable { private Lock lock; private SharedResource sharedResource; public Worker(Lock lock, SharedResource sharedResource) { this.lock = lock; this.sharedResource = sharedResource; } public void run() { for (int i = 0; i < NUM_ITERATIONS; i++) { lock.lock(); try { sharedResource.doWork(); } finally { lock.unlock(); } } } } static class SharedResource { public void doWork() { String threadName = Thread.currentThread().getName(); System.out.println(""Thread-> "" + threadName + "" is performing work.""); // Perform work on the shared resource } } }",56,56 ,"def isBalanced(root): def dfs(node): if not node: return 0 left = dfs(node.left) if left == -1: return -1 right = dfs(node.right) if right == -1: return -1 if abs(left - right) > 1: return -1 return 1 + max(left, right) return dfs(root) != -1 ",1.0,GPT,"Solve the problem ""Balanced Binary Tree"". Given a binary tree, determine if it is height-balanced. Provide Python solution. ",python,"def isBalanced(root): def dfs(node): if not node: return 0 left = dfs(node.left) if left == -1: return -1 right = dfs(node.right) if right == -1: return -1 if abs(left - right) > 1: return -1 return 1 + max(left, right) return dfs(root) != -1",18,18 ,"// 6 ms. 98.66% public int distributeCandies(int[] candyType) { BitSet bits = new BitSet(200001); int count = 0, max = candyType.length / 2; for(int candy: candyType) { int t = candy + 100000; if(!bits.get(t)) { if(++count == max) return max; bits.set(t); } } return count; }",0.0,leetcode,,java,"// 6 ms. 98.66% public int distributeCandies(int[] candyType) { BitSet bits = new BitSet(200001); int count = 0, max = candyType.length / 2; for(int candy: candyType) { int t = candy + 100000; if(!bits.get(t)) { if(++count == max) return max; bits.set(t); } } return count; }",13,13 ,"public class StringCapital { public static void main(String[] args) { String str = ""welcome to candid java program""; StringBuilder result = new StringBuilder(str.length()); String words[] = str.split(""\\ ""); for (int i = 0; i < words.length; i++) { result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append ("" ""); } System.out.println(result); } }",0.0,IPSGWALIOR.ORG,,java,"public class StringCapital { public static void main(String[] args) { String str = ""welcome to candid java program""; StringBuilder result = new StringBuilder(str.length()); String words[] = str.split(""\\ ""); for (int i = 0; i < words.length; i++) { result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append ("" ""); } System.out.println(result); } }",22,22 ,"import tweepy client = tweepy.Client(bearer_token='YOUR_BEARER_TOKEN_HERE') username = input(""Enter Twitter username: "") try: user = client.get_user(username=username, user_fields=['public_metrics']) print(f""@{username} has {user.data.public_metrics['followers_count']:,} followers"") except: print(""Error fetching data"") ",1.0,PERPLEXITY,Write a Python program to get the number of followers of a given twitter account. GIVE THE CODE IN FEWER LINES FOR EFFECTIVENESS,python,"import tweepy client = tweepy.Client(bearer_token='YOUR_BEARER_TOKEN_HERE') username = input(""Enter Twitter username: "") try: user = client.get_user(username=username, user_fields=['public_metrics']) print(f""@{username} has {user.data.public_metrics['followers_count']:,} followers"") except: print(""Error fetching data"")",10,10 ,"import requests import json url = 'https://analytics.usa.gov/data/live/realtime.json' data = requests.get(url).json() active_users = data['totals']['activeUsers'] print(f""Currently {active_users:,} people visiting U.S. government websites"") ",1.0,PERPLEXITY,"Write a Python program to get the number of people visiting a U.S. government website right now. Source: https://analytics.usa.gov/data/live/realtime.json",python,"import requests import json url = 'https://analytics.usa.gov/data/live/realtime.json' data = requests.get(url).json() active_users = data['totals']['activeUsers'] print(f""Currently {active_users:,} people visiting U.S. government websites"")",7,7 ,"def perfect_number(n): sum_div = 0 for x in range(1, n): if n % x == 0: sum_div += x return sum_div == n # Test print(perfect_number(6)) # True (1+2+3=6) ",1.0,PERPLEXITY,"Write a Python function to check whether a number is ""Perfect"" or not.",python,"def perfect_number(n): sum_div = 0 for x in range(1, n): if n % x == 0: sum_div += x return sum_div == n # Test print(perfect_number(6)) # True (1+2+3=6)",9,9 ,"import requests import datetime def get_m4_5_plus_count(start_time: str, end_time: str) -> int: """""" Returns the number of earthquakes globally with magnitude >= 4.5 between start_time and end_time (ISO format). """""" url = ""https://earthquake.usgs.gov/fdsnws/event/1/query"" params = { ""format"": ""geojson"", ""starttime"": start_time, ""endtime"": end_time, ""minmagnitude"": 4.5, } response = requests.get(url, params=params) if response.status_code == 200: data = response.json() # 'count' field in 'metadata' holds the number of matching events return data.get(""metadata"", {}).get(""count"", 0) else: print(f""Error: {response.status_code}"") return 0 if __name__ == ""__main__"": # Set time period (last 30 days) end_time = datetime.datetime.utcnow().date().isoformat() start_time = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).date().isoformat() count = get_m4_5_plus_count(start_time, end_time) print(f""Number of earthquakes with magnitude >= 4.5 between {start_time} and {end_time}: {count}"") ",1.0,GPT,Write a Python program to get the number of magnitude 4.5+ earthquakes detected worldwide by the USGS.,python,"import requests import datetime def get_m4_5_plus_count(start_time: str, end_time: str) -> int: """""" Returns the number of earthquakes globally with magnitude >= 4.5 between start_time and end_time (ISO format). """""" url = ""https://earthquake.usgs.gov/fdsnws/event/1/query"" params = { ""format"": ""geojson"", ""starttime"": start_time, ""endtime"": end_time, ""minmagnitude"": 4.5, } response = requests.get(url, params=params) if response.status_code == 200: data = response.json() # 'count' field in 'metadata' holds the number of matching events return data.get(""metadata"", {}).get(""count"", 0) else: print(f""Error: {response.status_code}"") return 0 if __name__ == ""__main__"": # Set time period (last 30 days) end_time = datetime.datetime.utcnow().date().isoformat() start_time = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).date().isoformat() count = get_m4_5_plus_count(start_time, end_time) print(f""Number of earthquakes with magnitude >= 4.5 between {start_time} and {end_time}: {count}"")",33,33 ,"# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n' def pascal_triangle(n): # Initialize the first row of Pascal's Triangle with value 1 as a starting point trow = [1] # Create a list 'y' filled with zeros to be used for calculations y = [0] # Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negative 'n') for x in range(max(n, 0)): # Print the current row of Pascal's Triangle print(trow) # Update the current row based on the previous row by calculating the next row using list comprehension # The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elements trow = [l + r for l, r in zip(trow + y, y + trow)] # Return True if 'n' is greater than or equal to 1, else return False return n >= 1 # Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function pascal_triangle(6) ",0.0,W3RESOURCE,,python,"# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n' def pascal_triangle(n): # Initialize the first row of Pascal's Triangle with value 1 as a starting point trow = [1] # Create a list 'y' filled with zeros to be used for calculations y = [0] # Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negative 'n') for x in range(max(n, 0)): # Print the current row of Pascal's Triangle print(trow) # Update the current row based on the previous row by calculating the next row using list comprehension # The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elements trow = [l + r for l, r in zip(trow + y, y + trow)] # Return True if 'n' is greater than or equal to 1, else return False return n >= 1 # Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function pascal_triangle(6) ",22,22 ,"import numpy as np x = np.arange(10) print(""Original:"", x) print(""Floor division by 3:"", np.floor_divide(x, 3)) ",1.0,PERPLEXITY,Write a NumPy program to get the largest integer smaller or equal to the division of the inputs.,python,"import numpy as np x = np.arange(10) print(""Original:"", x) print(""Floor division by 3:"", np.floor_divide(x, 3))",5,5 ,"public class NumberPrinter implements Runnable { private int id; public NumberPrinter(int id) { this.id = id; } @Override public void run() { for (int i = 1; i <= 10; i++) { System.out.println(""Thread "" + id + "": "" + i); try { Thread.sleep(100); } catch (InterruptedException e) {} } } } ",1.0,PERPLEXITY,Create a Java Thread class that implements Runnable to print numbers from 1 to 10,java,"public class NumberPrinter implements Runnable { private int id; public NumberPrinter(int id) { this.id = id; } @Override public void run() { for (int i = 1; i <= 10; i++) { System.out.println(""Thread "" + id + "": "" + i); try { Thread.sleep(100); } catch (InterruptedException e) {} } } }",11,11 ,"class Solution: def minWindow(self, s: str, t: str) -> str: if t == """": return """" countT, window = {}, {} for c in t: countT[c] = 1 + countT.get(c, 0) have, need = 0, len(countT) res, resLen = [-1, -1], float(""infinity"") l = 0 for r in range(len(s)): c = s[r] window[c] = 1 + window.get(c, 0) if c in countT and window[c] == countT[c]: have += 1 while have == need: if (r - l + 1) < resLen: res = [l, r] resLen = r - l + 1 window[s[l]] -= 1 if s[l] in countT and window[s[l]] < countT[s[l]]: have -= 1 l += 1 l, r = res return s[l : r + 1] if resLen != float(""infinity"") else """"",0.0,GFG,,python,"class Solution: def minWindow(self, s: str, t: str) -> str: if t == """": return """" countT, window = {}, {} for c in t: countT[c] = 1 + countT.get(c, 0) have, need = 0, len(countT) res, resLen = [-1, -1], float(""infinity"") l = 0 for r in range(len(s)): c = s[r] window[c] = 1 + window.get(c, 0) if c in countT and window[c] == countT[c]: have += 1 while have == need: if (r - l + 1) < resLen: res = [l, r] resLen = r - l + 1 window[s[l]] -= 1 if s[l] in countT and window[s[l]] < countT[s[l]]: have -= 1 l += 1 l, r = res return s[l : r + 1] if resLen != float(""infinity"") else """"",30,30 ,"class Solution: def maxArea(self, heights: List[int]) -> int: l, r = 0, len(heights) - 1 res = 0 while l < r: area = min(heights[l], heights[r]) * (r - l) res = max(res, area) if heights[l] <= heights[r]: l += 1 else: r -= 1 return res",0.0,GFG,,python,"class Solution: def maxArea(self, heights: List[int]) -> int: l, r = 0, len(heights) - 1 res = 0 while l < r: area = min(heights[l], heights[r]) * (r - l) res = max(res, area) if heights[l] <= heights[r]: l += 1 else: r -= 1 return res",13,13 ,"class Solution { public int minStickers(String[] stickers, String target) { int n = stickers.length; target = sortChars(target); for (int i = 0; i < n; ++i) stickers[i] = sortChars(stickers[i]); Queue q = new LinkedList(); q.offer(target); int steps = 0; Set visited = new HashSet<>(); while (!q.isEmpty()) { steps++; int size = q.size(); while(size-- > 0) { String x = q.poll(); for (int i = 0; i < n; ++i) { String now = filter(x, stickers[i]); if (now.isEmpty()) return steps; if (!now.equals(x) && !visited.contains(now)) { visited.add(now); q.offer(now); } } } } return -1; } public String filter(String a, String b) { StringBuilder ret = new StringBuilder(); int idx = 0; for (char c : a.toCharArray()) { boolean found = false; while (idx < b.length() && b.charAt(idx) <= c) { if (b.charAt(idx++) == c) { found = true; break; } } if (!found) ret.append(c); } return ret.toString(); } private String sortChars(String s) { char[] chars = s.toCharArray(); Arrays.sort(chars); return new String(chars); } } ",0.0,leetcode,,java,"class Solution { public int minStickers(String[] stickers, String target) { int n = stickers.length; target = sortChars(target); for (int i = 0; i < n; ++i) stickers[i] = sortChars(stickers[i]); Queue q = new LinkedList(); q.offer(target); int steps = 0; Set visited = new HashSet<>(); while (!q.isEmpty()) { steps++; int size = q.size(); while(size-- > 0) { String x = q.poll(); for (int i = 0; i < n; ++i) { String now = filter(x, stickers[i]); if (now.isEmpty()) return steps; if (!now.equals(x) && !visited.contains(now)) { visited.add(now); q.offer(now); } } } } return -1; } public String filter(String a, String b) { StringBuilder ret = new StringBuilder(); int idx = 0; for (char c : a.toCharArray()) { boolean found = false; while (idx < b.length() && b.charAt(idx) <= c) { if (b.charAt(idx++) == c) { found = true; break; } } if (!found) ret.append(c); } return ret.toString(); } private String sortChars(String s) { char[] chars = s.toCharArray(); Arrays.sort(chars); return new String(chars); } }",50,50 ,"import json def convert_to_json(data, indent=4): """""" Converts a Python object to a JSON string. Includes a fallback for custom objects that aren't natively serializable. """""" try: # indent=4 makes the output 'pretty' and readable # sort_keys=True organizes the dictionary keys alphabetically return json.dumps(data, indent=indent, sort_keys=True, default=str) except Exception as e: return f""Error converting to JSON: {e}"" # --- Examples of Usage --- # 1. Converting a standard Dictionary user_profile = { ""username"": ""coder_123"", ""id"": 882, ""tags"": [""python"", ""api"", ""json""], ""is_premium"": False, ""location"": None } json_output = convert_to_json(user_profile) print(""--- Standard Dictionary to JSON ---"") print(json_output) # 2. Converting to a JSON File with open(""data.json"", ""w"", encoding=""utf-8"") as f: json.dump(user_profile, f, indent=4) print(""\n[System] Data successfully written to data.json"")",1.0,GEMINI,Write a Python program to convert Python object to JSON data.,python,"import json def convert_to_json(data, indent=4): """""" Converts a Python object to a JSON string. Includes a fallback for custom objects that aren't natively serializable. """""" try: # indent=4 makes the output 'pretty' and readable # sort_keys=True organizes the dictionary keys alphabetically return json.dumps(data, indent=indent, sort_keys=True, default=str) except Exception as e: return f""Error converting to JSON: {e}"" # --- Examples of Usage --- # 1. Converting a standard Dictionary user_profile = { ""username"": ""coder_123"", ""id"": 882, ""tags"": [""python"", ""api"", ""json""], ""is_premium"": False, ""location"": None } json_output = convert_to_json(user_profile) print(""--- Standard Dictionary to JSON ---"") print(json_output) # 2. Converting to a JSON File with open(""data.json"", ""w"", encoding=""utf-8"") as f: json.dump(user_profile, f, indent=4) print(""\n[System] Data successfully written to data.json"")",33,33 ,"public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; public static DayOfWeek[] values() { return values(); } public static DayOfWeek getByName(String name) { for (DayOfWeek day : values()) { if (day.name().equalsIgnoreCase(name)) return day; } throw new IllegalArgumentException(""Invalid day: "" + name); } } ",1.0,PERPLEXITY,Create a Java enum for days of week with a custom values method and getByName,java,"public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; public static DayOfWeek[] values() { return values(); } public static DayOfWeek getByName(String name) { for (DayOfWeek day : values()) { if (day.name().equalsIgnoreCase(name)) return day; } throw new IllegalArgumentException(""Invalid day: "" + name); } }",14,14 ,"class PC { LinkedList list = new LinkedList<>(); public void produce() throws InterruptedException { synchronized(this) { while (list.size() == 1) wait(); list.add(1); notify(); } } public void consume() throws InterruptedException { synchronized(this) { while (list.isEmpty()) wait(); list.removeFirst(); notify(); } } }",1.0,GEMINI,give me a java program to Implement the Producer-Consumer pattern using wait() and notify(),java,"class PC { LinkedList list = new LinkedList<>(); public void produce() throws InterruptedException { synchronized(this) { while (list.size() == 1) wait(); list.add(1); notify(); } } public void consume() throws InterruptedException { synchronized(this) { while (list.isEmpty()) wait(); list.removeFirst(); notify(); } } }",15,15 ,"class Solution { public int leastBricks(List> wall) { HashMap edge_frequency = new HashMap<>(); // HashMap to store the number of common edges among the rows int max_frequency = 0; // Variable to store the frequency of most occuring edge for(int row=0; row> wall) { HashMap edge_frequency = new HashMap<>(); // HashMap to store the number of common edges among the rows int max_frequency = 0; // Variable to store the frequency of most occuring edge for(int row=0; row float: A, B = nums1, nums2 total = len(nums1) + len(nums2) half = total // 2 if len(B) < len(A): A, B = B, A l, r = 0, len(A) - 1 while True: i = (l + r) // 2 j = half - i - 2 Aleft = A[i] if i >= 0 else float(""-infinity"") Aright = A[i + 1] if (i + 1) < len(A) else float(""infinity"") Bleft = B[j] if j >= 0 else float(""-infinity"") Bright = B[j + 1] if (j + 1) < len(B) else float(""infinity"") if Aleft <= Bright and Bleft <= Aright: if total % 2: return min(Aright, Bright) return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 elif Aleft > Bright: r = i - 1 else: l = i + 1",0.0,GFG,,python,"class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: A, B = nums1, nums2 total = len(nums1) + len(nums2) half = total // 2 if len(B) < len(A): A, B = B, A l, r = 0, len(A) - 1 while True: i = (l + r) // 2 j = half - i - 2 Aleft = A[i] if i >= 0 else float(""-infinity"") Aright = A[i + 1] if (i + 1) < len(A) else float(""infinity"") Bleft = B[j] if j >= 0 else float(""-infinity"") Bright = B[j + 1] if (j + 1) < len(B) else float(""infinity"") if Aleft <= Bright and Bleft <= Aright: if total % 2: return min(Aright, Bright) return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 elif Aleft > Bright: r = i - 1 else: l = i + 1",27,27 ,"public class MinHeapPQ { private int[] heap; private int size; public MinHeapPQ(int capacity) { heap = new int[capacity]; size = 0; } private void heapifyUp(int index) { while (index > 0 && heap[(index - 1) / 2] > heap[index]) { swap((index - 1) / 2, index); index = (index - 1) / 2; } } private void heapifyDown(int index) { int smallest = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < size && heap[left] < heap[smallest]) smallest = left; if (right < size && heap[right] < heap[smallest]) smallest = right; if (smallest != index) { swap(index, smallest); heapifyDown(smallest); } } private void swap(int i, int j) { int temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; } } ",1.0,PERPLEXITY,Implement a min-heap priority queue in Java for integers using an array,java,"public class MinHeapPQ { private int[] heap; private int size; public MinHeapPQ(int capacity) { heap = new int[capacity]; size = 0; } private void heapifyUp(int index) { while (index > 0 && heap[(index - 1) / 2] > heap[index]) { swap((index - 1) / 2, index); index = (index - 1) / 2; } } private void heapifyDown(int index) { int smallest = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < size && heap[left] < heap[smallest]) smallest = left; if (right < size && heap[right] < heap[smallest]) smallest = right; if (smallest != index) { swap(index, smallest); heapifyDown(smallest); } } private void swap(int i, int j) { int temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; } }",22,22 ,"import java.util.HashMap; import java.util.Scanner; public class IntegertoRoman { private static int[] bases = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; private static HashMap map = new HashMap(); private static void setup() { map.put(1, ""I""); map.put(4, ""IV""); map.put(5, ""V""); map.put(9, ""IX""); map.put(10, ""X""); map.put(40, ""XL""); map.put(50, ""L""); map.put(90, ""XC""); map.put(100, ""C""); map.put(400, ""CD""); map.put(500, ""D""); map.put(900, ""CM""); map.put(1000, ""M""); } public String intToRoman(int num) { setup(); String result = new String(); for (int i : bases) { while (num >= i) { result += map.get(i); num -= i; } } return result; } public static void main(String arg[]) { System.out.println(""Enter the number : ""); Scanner sc = new Scanner(System.in); int no = sc.nextInt(); IntegertoRoman in = new IntegertoRoman(); int value=no; String sd = in.intToRoman(value); System.out.println(value+"" ---> "" + sd); } } ",0.0,IPSGWALIOR.ORG,,java,"import java.util.HashMap; import java.util.Scanner; public class IntegertoRoman { private static int[] bases = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; private static HashMap map = new HashMap(); private static void setup() { map.put(1, ""I""); map.put(4, ""IV""); map.put(5, ""V""); map.put(9, ""IX""); map.put(10, ""X""); map.put(40, ""XL""); map.put(50, ""L""); map.put(90, ""XC""); map.put(100, ""C""); map.put(400, ""CD""); map.put(500, ""D""); map.put(900, ""CM""); map.put(1000, ""M""); } public String intToRoman(int num) { setup(); String result = new String(); for (int i : bases) { while (num >= i) { result += map.get(i); num -= i; } } return result; } public static void main(String arg[]) { System.out.println(""Enter the number : ""); Scanner sc = new Scanner(System.in); int no = sc.nextInt(); IntegertoRoman in = new IntegertoRoman(); int value=no; String sd = in.intToRoman(value); System.out.println(value+"" ---> "" + sd); } }",48,48 ,"import java.net.*; import java.io.*; public class EchoServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8080); while (true) { Socket client = server.accept(); new Thread(() -> { try (BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream(), true)) { String line; while ((line = in.readLine()) != null) { out.println(""Echo: "" + line); } } catch (IOException e) {} }).start(); } } } ",1.0,PERPLEXITY,Create a simple TCP socket server in Java that echoes client messages,java,"import java.net.*; import java.io.*; public class EchoServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8080); while (true) { Socket client = server.accept(); new Thread(() -> { try (BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream(), true)) { String line; while ((line = in.readLine()) != null) { out.println(""Echo: "" + line); } } catch (IOException e) {} }).start(); } } }",20,20 ,"def test_prime(n): if n <= 1: return False for x in range(2, n): if n % x == 0: return False return True # Accepts input from user n = int(input(""Enter a number: "")) print(test_prime(n)) ",1.0,PERPLEXITY,"Write a Python function that takes a number as a parameter and checks whether the number is prime or not. Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself.",python,"def test_prime(n): if n <= 1: return False for x in range(2, n): if n % x == 0: return False return True # Accepts input from user n = int(input(""Enter a number: "")) print(test_prime(n))",11,11 ,"import json, threading, time, signal, os from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class Config: def __init__(s,f): s.f, s.d, s.l = f, {}, threading.Lock() s.load() def load(s): with s.l: s.d = json.load(open(s.f)) print(""Reloaded:"", s.d) def get(s): with s.l: return s.d class Watch(FileSystemEventHandler): def __init__(s,c): s.c, s.p = c, os.path.abspath(c.f) def on_modified(s,e): if os.path.abspath(e.src_path)==s.p: s.c.load() # ---------- INPUT ---------- CFG_FILE = ""config.json"" cfg = Config(CFG_FILE) stop = threading.Event() def shutdown(sig, frm): stop.set() signal.signal(signal.SIGINT, shutdown) obs = Observer() obs.schedule(Watch(cfg), ""."", False) obs.start() # ---------- OUTPUT ---------- try: while not stop.is_set(): print(""Current:"", cfg.get()) time.sleep(3) finally: obs.stop(); obs.join() print(""Stopped"") ",1.0,GPT,Write a Python program to create a dynamic configuration manager that reloads settings at runtime. MAKE THE CODE MORE SHORTER AND EFFECTIVE TO PASS ALL THE TEST CASES,python,"import json, threading, time, signal, os from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class Config: def __init__(s,f): s.f, s.d, s.l = f, {}, threading.Lock() s.load() def load(s): with s.l: s.d = json.load(open(s.f)) print(""Reloaded:"", s.d) def get(s): with s.l: return s.d class Watch(FileSystemEventHandler): def __init__(s,c): s.c, s.p = c, os.path.abspath(c.f) def on_modified(s,e): if os.path.abspath(e.src_path)==s.p: s.c.load() # ---------- INPUT ---------- CFG_FILE = ""config.json"" cfg = Config(CFG_FILE) stop = threading.Event() def shutdown(sig, frm): stop.set() signal.signal(signal.SIGINT, shutdown) obs = Observer() obs.schedule(Watch(cfg), ""."", False) obs.start() # ---------- OUTPUT ---------- try: while not stop.is_set(): print(""Current:"", cfg.get()) time.sleep(3) finally: obs.stop(); obs.join() print(""Stopped"")",41,41 ,"public class RemoveAllVovels { public static void main(String[] args) { String string = ""Welcome to Candid Java Programming""; System.out.println(""Input String : ""+string); string = string.replaceAll(""[AaEeIiOoUu]"", """"); System.out.println(string); } } ",0.0,IPSGWALIOR.ORG,,java,"public class RemoveAllVovels { public static void main(String[] args) { String string = ""Welcome to Candid Java Programming""; System.out.println(""Input String : ""+string); string = string.replaceAll(""[AaEeIiOoUu]"", """"); System.out.println(string); } }",9,9 ,"import java.util.*; public class LambdaComparator { public static void sortStrings(List list) { list.sort((s1, s2) -> { if (s1.length() != s2.length()) return s1.length() - s2.length(); return s1.compareTo(s2); }); } } ",1.0,PERPLEXITY,Create a lambda comparator to sort a list of strings by length then alphabetically.,java,"import java.util.*; public class LambdaComparator { public static void sortStrings(List list) { list.sort((s1, s2) -> { if (s1.length() != s2.length()) return s1.length() - s2.length(); return s1.compareTo(s2); }); } }",10,10 ,"class Solution { public boolean isValidSudoku(char[][] board) { boolean[][] rows = new boolean[9][9]; boolean[][] cols = new boolean[9][9]; boolean[][] boxes = new boolean[9][9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.') { int num = board[i][j] - '1'; int boxIndex = (i / 3) * 3 + (j / 3); if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) { return false; } rows[i][num] = cols[j][num] = boxes[boxIndex][num] = true; } } } return true; } }",0.0,leetcode,,java,"class Solution { public boolean isValidSudoku(char[][] board) { boolean[][] rows = new boolean[9][9]; boolean[][] cols = new boolean[9][9]; boolean[][] boxes = new boolean[9][9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.') { int num = board[i][j] - '1'; int boxIndex = (i / 3) * 3 + (j / 3); if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) { return false; } rows[i][num] = cols[j][num] = boxes[boxIndex][num] = true; } } } return true; } }",23,23 ,"class Solution { public int longestPalindrome(String s) { HashMap hm = new HashMap(); int cnt=0; Boolean odd=false; for(char ch : s.toCharArray()) hm.put(ch, hm.getOrDefault(ch,0)+1 ); for(int i : hm.values()) { if(i%2==0) cnt+=i; else { cnt+=i-1; odd =true; } } if(odd) return ++cnt; else return cnt; } }class Solution { public int longestPalindrome(String s) { HashMap hm = new HashMap(); int cnt=0; Boolean odd=false; for(char ch : s.toCharArray()) hm.put(ch, hm.getOrDefault(ch,0)+1 ); for(int i : hm.values()) { if(i%2==0) cnt+=i; else { cnt+=i-1; odd =true; } } if(odd) return ++cnt; else return cnt; } }",0.0,leetcode,,java,"class Solution { public int longestPalindrome(String s) { HashMap hm = new HashMap(); int cnt=0; Boolean odd=false; for(char ch : s.toCharArray()) hm.put(ch, hm.getOrDefault(ch,0)+1 ); for(int i : hm.values()) { if(i%2==0) cnt+=i; else { cnt+=i-1; odd =true; } } if(odd) return ++cnt; else return cnt; } }class Solution { public int longestPalindrome(String s) { HashMap hm = new HashMap(); int cnt=0; Boolean odd=false; for(char ch : s.toCharArray()) hm.put(ch, hm.getOrDefault(ch,0)+1 ); for(int i : hm.values()) { if(i%2==0) cnt+=i; else { cnt+=i-1; odd =true; } } if(odd) return ++cnt; else return cnt; } }",47,47 ,"class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: ROWS, COLS = len(grid), len(grid[0]) fresh = 0 time = 0 for r in range(ROWS): for c in range(COLS): if grid[r][c] == 1: fresh += 1 directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] while fresh > 0: flag = False for r in range(ROWS): for c in range(COLS): if grid[r][c] == 2: for dr, dc in directions: row, col = r + dr, c + dc if (row in range(ROWS) and col in range(COLS) and grid[row][col] == 1): grid[row][col] = 3 fresh -= 1 flag = True if not flag: return -1 for r in range(ROWS): for c in range(COLS): if grid[r][c] == 3: grid[r][c] = 2 time += 1 return time",0.0,GFG,,python,"class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: ROWS, COLS = len(grid), len(grid[0]) fresh = 0 time = 0 for r in range(ROWS): for c in range(COLS): if grid[r][c] == 1: fresh += 1 directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] while fresh > 0: flag = False for r in range(ROWS): for c in range(COLS): if grid[r][c] == 2: for dr, dc in directions: row, col = r + dr, c + dc if (row in range(ROWS) and col in range(COLS) and grid[row][col] == 1): grid[row][col] = 3 fresh -= 1 flag = True if not flag: return -1 for r in range(ROWS): for c in range(COLS): if grid[r][c] == 3: grid[r][c] = 2 time += 1 return time",38,38 ,"public class User { private String name, email, phone; private int age; private User(Builder builder) { this.name = builder.name; this.email = builder.email; this.phone = builder.phone; this.age = builder.age; } public static class Builder { private String name, email, phone; private int age; public Builder name(String name) { this.name = name; return this; } public Builder email(String email) { this.email = email; return this; } public Builder phone(String phone) { this.phone = phone; return this; } public Builder age(int age) { this.age = age; return this; } public User build() { return new User(this); } } } ",1.0,PERPLEXITY,Write Java builder pattern for a complex User object with multiple optional fields,java,"public class User { private String name, email, phone; private int age; private User(Builder builder) { this.name = builder.name; this.email = builder.email; this.phone = builder.phone; this.age = builder.age; } public static class Builder { private String name, email, phone; private int age; public Builder name(String name) { this.name = name; return this; } public Builder email(String email) { this.email = email; return this; } public Builder phone(String phone) { this.phone = phone; return this; } public Builder age(int age) { this.age = age; return this; } public User build() { return new User(this); } } }",19,19 ,"import time # Import the time module to measure execution time class LogExecutionTime: # Define a class for the decorator def __init__(self, func): # Initialize the decorator with the function to be decorated self.func = func # Store the function to be decorated def __get__(self, instance, owner): # Define the descriptor method to handle instance methods return lambda *args, **kwargs: self(instance, *args, **kwargs) # Return a lambda that passes the instance def __call__(self, *args, **kwargs): # Make the class instance callable instance = args[0] # Extract the instance from the arguments start_time = time.time() # Record the start time result = self.func(instance, *args[1:], **kwargs) # Call the original function with its arguments end_time = time.time() # Record the end time execution_time = end_time - start_time # Calculate the execution time print(f""Execution time of {self.func.__name__}: {execution_time:.4f} seconds"") # Log the execution time return result # Return the result of the original function call # Example usage: class ExampleClass: # Define an example class to demonstrate the decorator @LogExecutionTime # Apply the decorator to the method def example_method(self): # Define a method in the class for _ in range(1000000): # A sample computation to add some delay pass # Do nothing # Instantiate the example class and call the decorated method example = ExampleClass() # Create an instance of the ExampleClass example.example_method() # Call the decorated method to see the execution time log",0.0,W3RESOURCE,,python,"import time # Import the time module to measure execution time class LogExecutionTime: # Define a class for the decorator def __init__(self, func): # Initialize the decorator with the function to be decorated self.func = func # Store the function to be decorated def __get__(self, instance, owner): # Define the descriptor method to handle instance methods return lambda *args, **kwargs: self(instance, *args, **kwargs) # Return a lambda that passes the instance def __call__(self, *args, **kwargs): # Make the class instance callable instance = args[0] # Extract the instance from the arguments start_time = time.time() # Record the start time result = self.func(instance, *args[1:], **kwargs) # Call the original function with its arguments end_time = time.time() # Record the end time execution_time = end_time - start_time # Calculate the execution time print(f""Execution time of {self.func.__name__}: {execution_time:.4f} seconds"") # Log the execution time return result # Return the result of the original function call # Example usage: class ExampleClass: # Define an example class to demonstrate the decorator @LogExecutionTime # Apply the decorator to the method def example_method(self): # Define a method in the class for _ in range(1000000): # A sample computation to add some delay pass # Do nothing # Instantiate the example class and call the decorated method example = ExampleClass() # Create an instance of the ExampleClass example.example_method() # Call the decorated method to see the execution time log",29,29 ,"class Solution: def combinationSum(self, nums: List[int], target: int) -> List[List[int]]: res = [] nums.sort() def dfs(i, cur, total): if total == target: res.append(cur.copy()) return for j in range(i, len(nums)): if total + nums[j] > target: return cur.append(nums[j]) dfs(j, cur, total + nums[j]) cur.pop() dfs(0, [], 0) return res",0.0,GFG,,python,"class Solution: def combinationSum(self, nums: List[int], target: int) -> List[List[int]]: res = [] nums.sort() def dfs(i, cur, total): if total == target: res.append(cur.copy()) return for j in range(i, len(nums)): if total + nums[j] > target: return cur.append(nums[j]) dfs(j, cur, total + nums[j]) cur.pop() dfs(0, [], 0) return res",19,19 ,"import java.util.concurrent.Semaphore; public class SemaphoreExample { private static Semaphore semaphore = new Semaphore(3); public static void accessResource(int id) { try { semaphore.acquire(); System.out.println(""Resource accessed by "" + id); Thread.sleep(2000); } catch (InterruptedException e) {} finally { semaphore.release(); } } } ",1.0,PERPLEXITY,Implement a semaphore in Java to limit concurrent access to 3 resources,java,"import java.util.concurrent.Semaphore; public class SemaphoreExample { private static Semaphore semaphore = new Semaphore(3); public static void accessResource(int id) { try { semaphore.acquire(); System.out.println(""Resource accessed by "" + id); Thread.sleep(2000); } catch (InterruptedException e) {} finally { semaphore.release(); } } }",12,12 ,"def in_range(n, low, high): return low <= n <= high # ---------- INPUT ---------- n, low, high = 5, 3, 8 # ---------- OUTPUT ---------- if in_range(n, low, high): print(f""{n} is in the range {low} to {high}"") else: print(f""{n} is outside the range {low} to {high}"") ",1.0,GPT,Write a Python function to check whether a number falls within a given range.,python,"def in_range(n, low, high): return low <= n <= high # ---------- INPUT ---------- n, low, high = 5, 3, 8 # ---------- OUTPUT ---------- if in_range(n, low, high): print(f""{n} is in the range {low} to {high}"") else: print(f""{n} is outside the range {low} to {high}"")",11,11 ,"class Solution: def solveNQueens(self, n: int) -> List[List[str]]: col = 0 posDiag = 0 negDiag = 0 res = [] board = [["".""] * n for i in range(n)] def backtrack(r): nonlocal col, posDiag, negDiag if r == n: copy = ["""".join(row) for row in board] res.append(copy) return for c in range(n): if ((col & (1 << c)) or (posDiag & (1 << (r + c))) or (negDiag & (1 << (r - c + n)))): continue col ^= (1 << c) posDiag ^= (1 << (r + c)) negDiag ^= (1 << (r - c + n)) board[r][c] = ""Q"" backtrack(r + 1) col ^= (1 << c) posDiag ^= (1 << (r + c)) negDiag ^= (1 << (r - c + n)) board[r][c] = ""."" backtrack(0) return res",0.0,GFG,,python,"class Solution: def solveNQueens(self, n: int) -> List[List[str]]: col = 0 posDiag = 0 negDiag = 0 res = [] board = [["".""] * n for i in range(n)] def backtrack(r): nonlocal col, posDiag, negDiag if r == n: copy = ["""".join(row) for row in board] res.append(copy) return for c in range(n): if ((col & (1 << c)) or (posDiag & (1 << (r + c))) or (negDiag & (1 << (r - c + n)))): continue col ^= (1 << c) posDiag ^= (1 << (r + c)) negDiag ^= (1 << (r - c + n)) board[r][c] = ""Q"" backtrack(r + 1) col ^= (1 << c) posDiag ^= (1 << (r + c)) negDiag ^= (1 << (r - c + n)) board[r][c] = ""."" backtrack(0) return res",32,32 ,"import json def python_to_json_display(data): # Convert Python object to a JSON formatted string # indent=4 adds whitespace for readability # sort_keys=True keeps the output consistent json_string = json.dumps(data, indent=4, sort_keys=True) print(""--- Generated JSON String ---"") print(json_string) # To ""print all values"" specifically from the resulting JSON # we first load it back to iterate through it print(""\n--- Individual Values Extracted ---"") parsed_data = json.loads(json_string) if isinstance(parsed_data, dict): for key, value in parsed_data.items(): print(f""Key: {key:12} | Value: {value} ({type(value).__name__})"") # Example Python Object (Dictionary) employee_data = { ""name"": ""Marcus Aurelius"", ""department"": ""Philosophy"", ""years_active"": 19, ""is_remote"": True, ""skills"": [""Leadership"", ""Writing"", ""Logic""], ""office_id"": None } if __name__ == ""__main__"": python_to_json_display(employee_data)",1.0,GEMINI,Write a Python program to convert Python objects into JSON strings. Print all the values.,python,"import json def python_to_json_display(data): # Convert Python object to a JSON formatted string # indent=4 adds whitespace for readability # sort_keys=True keeps the output consistent json_string = json.dumps(data, indent=4, sort_keys=True) print(""--- Generated JSON String ---"") print(json_string) # To ""print all values"" specifically from the resulting JSON # we first load it back to iterate through it print(""\n--- Individual Values Extracted ---"") parsed_data = json.loads(json_string) if isinstance(parsed_data, dict): for key, value in parsed_data.items(): print(f""Key: {key:12} | Value: {value} ({type(value).__name__})"") # Example Python Object (Dictionary) employee_data = { ""name"": ""Marcus Aurelius"", ""department"": ""Philosophy"", ""years_active"": 19, ""is_remote"": True, ""skills"": [""Leadership"", ""Writing"", ""Logic""], ""office_id"": None } if __name__ == ""__main__"": python_to_json_display(employee_data)",32,32 ,"import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class ApiRateLimiter { private final Map limiters; private final RateLimitConfig config; public ApiRateLimiter(RateLimitConfig config) { this.limiters = new ConcurrentHashMap<>(); this.config = config; } public boolean allowRequest(String clientId, String endpoint) { String key = clientId + "":"" + endpoint; RateLimiter limiter = limiters.computeIfAbsent(key, k -> createRateLimiter(endpoint) ); return limiter.tryAcquire(); } private Rate",1.0,DEEPSEEK,Create an API gateway rate limiter with multiple rate limiting strategies.,java,"import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class ApiRateLimiter { private final Map limiters; private final RateLimitConfig config; public ApiRateLimiter(RateLimitConfig config) { this.limiters = new ConcurrentHashMap<>(); this.config = config; } public boolean allowRequest(String clientId, String endpoint) { String key = clientId + "":"" + endpoint; RateLimiter limiter = limiters.computeIfAbsent(key, k -> createRateLimiter(endpoint) ); return limiter.tryAcquire(); } private Rate",25,25 ,"def string_test(s): upper_count = 0 lower_count = 0 for ch in s: if ch.isupper(): upper_count += 1 elif ch.islower(): lower_count += 1 print(""No. of Upper case characters :"", upper_count) print(""No. of Lower case Characters :"", lower_count) # Example usage string_test('The quick Brow Fox') ",1.0,PERPLEXITY,"Write a Python function that accepts a string and counts the number of upper and lower case letters. Sample String : 'The quick Brow Fox' Expected Output : No. of Upper case characters : 3 No. of Lower case Characters : 12",python,"def string_test(s): upper_count = 0 lower_count = 0 for ch in s: if ch.isupper(): upper_count += 1 elif ch.islower(): lower_count += 1 print(""No. of Upper case characters :"", upper_count) print(""No. of Lower case Characters :"", lower_count) # Example usage string_test('The quick Brow Fox')",15,15 ,"static void ser(Node r,StringBuilder b){ if(r==null){b.append(""#,"");return;} b.append(r.val).append("",""); ser(r.left,b); ser(r.right,b); } static Node des(Queue q){ String s=q.poll(); if(s.equals(""#"")) return null; Node n=new Node(Integer.parseInt(s)); n.left=des(q); n.right=des(q); return n; } ",1.0,GPT,Convert binary tree to string and restore it.,java,"static void ser(Node r,StringBuilder b){ if(r==null){b.append(""#,"");return;} b.append(r.val).append("",""); ser(r.left,b); ser(r.right,b); } static Node des(Queue q){ String s=q.poll(); if(s.equals(""#"")) return null; Node n=new Node(Integer.parseInt(s)); n.left=des(q); n.right=des(q); return n; }",12,12 ,"class Solution { public String reorganizeString(String s) { // count ch Map freq = new HashMap<>(); for (char ch : s.toCharArray()) { freq.put(ch, freq.getOrDefault(ch, 0) + 1); } // sort by cnt List> list = new ArrayList<>(freq.entrySet()); list.sort((a,b) -> b.getValue() - a.getValue()); // create buckets of str int maxFreq = list.get(0).getValue(); StringBuilder[] buckets = new StringBuilder[maxFreq]; // iterate over ch and cnts and fill buckets in circular fashion int k = 0; // bucket ind for (int i = 0; i < freq.size(); i++) { for (int j = 0; j < list.get(i).getValue(); j++) { int id = k % maxFreq; if (buckets[id] == null) buckets[id] = new StringBuilder(); buckets[id].append(list.get(i).getKey()); k++; } } // merge StringBuilder res = new StringBuilder(); for (StringBuilder sb : buckets) { res.append(sb); } String resStr = res.toString(); // validate for (int i = 0; i < resStr.length() - 1; i++) { if (resStr.charAt(i) == resStr.charAt(i+1)) return """"; } return resStr; } } // ababb // bbbb // cccc - 3 // aaa // bbb // ca cb cx c // abcabccc // c // abcdabcdabcdddddddd",0.0,leetcode,,java,"class Solution { public String reorganizeString(String s) { // count ch Map freq = new HashMap<>(); for (char ch : s.toCharArray()) { freq.put(ch, freq.getOrDefault(ch, 0) + 1); } // sort by cnt List> list = new ArrayList<>(freq.entrySet()); list.sort((a,b) -> b.getValue() - a.getValue()); // create buckets of str int maxFreq = list.get(0).getValue(); StringBuilder[] buckets = new StringBuilder[maxFreq]; // iterate over ch and cnts and fill buckets in circular fashion int k = 0; // bucket ind for (int i = 0; i < freq.size(); i++) { for (int j = 0; j < list.get(i).getValue(); j++) { int id = k % maxFreq; if (buckets[id] == null) buckets[id] = new StringBuilder(); buckets[id].append(list.get(i).getKey()); k++; } } // merge StringBuilder res = new StringBuilder(); for (StringBuilder sb : buckets) { res.append(sb); } String resStr = res.toString(); // validate for (int i = 0; i < resStr.length() - 1; i++) { if (resStr.charAt(i) == resStr.charAt(i+1)) return """"; } return resStr; } } // ababb // bbbb // cccc - 3 // aaa // bbb // ca cb cx c // abcabccc // c // abcdabcdabcdddddddd",61,61 ,"def matmul(A, B): return [[sum(a*b for a,b in zip(r,c)) for c in zip(*B)] for r in A] r1,c1 = map(int,input(""A rows cols: "").split()) A = [list(map(int,input().split())) for _ in range(r1)] r2,c2 = map(int,input(""B rows cols: "").split()) B = [list(map(int,input().split())) for _ in range(r2)] print(matmul(A,B)) ",1.0,GPT,give me a pythoncode for Matrix Multiplication via List Comprehensions also add a way to give input and get the result of the matrix multiplication within a shorter lines of code,python,"def matmul(A, B): return [[sum(a*b for a,b in zip(r,c)) for c in zip(*B)] for r in A] r1,c1 = map(int,input(""A rows cols: "").split()) A = [list(map(int,input().split())) for _ in range(r1)] r2,c2 = map(int,input(""B rows cols: "").split()) B = [list(map(int,input().split())) for _ in range(r2)] print(matmul(A,B))",10,10 ,"public class Solution { public int findLHS(int[] nums) { Arrays.sort(nums); int j = 0; int maxLength = 0; for (int i = 0; i < nums.length; i++) { while (nums[i] - nums[j] > 1) { j++; } if (nums[i] - nums[j] == 1) { maxLength = Math.max(maxLength, i - j + 1); } } return maxLength; } }",0.0,leetcode,,java,"public class Solution { public int findLHS(int[] nums) { Arrays.sort(nums); int j = 0; int maxLength = 0; for (int i = 0; i < nums.length; i++) { while (nums[i] - nums[j] > 1) { j++; } if (nums[i] - nums[j] == 1) { maxLength = Math.max(maxLength, i - j + 1); } } return maxLength; } }",17,17 ,"class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: ROWS, COLS = len(matrix), len(matrix[0]) rowZero = False for r in range(ROWS): for c in range(COLS): if matrix[r][c] == 0: matrix[0][c] = 0 if r > 0: matrix[r][0] = 0 else: rowZero = True for r in range(1, ROWS): for c in range(1, COLS): if matrix[0][c] == 0 or matrix[r][0] == 0: matrix[r][c] = 0 if matrix[0][0] == 0: for r in range(ROWS): matrix[r][0] = 0 if rowZero: for c in range(COLS): matrix[0][c] = 0",0.0,GFG,,python,"class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: ROWS, COLS = len(matrix), len(matrix[0]) rowZero = False for r in range(ROWS): for c in range(COLS): if matrix[r][c] == 0: matrix[0][c] = 0 if r > 0: matrix[r][0] = 0 else: rowZero = True for r in range(1, ROWS): for c in range(1, COLS): if matrix[0][c] == 0 or matrix[r][0] == 0: matrix[r][c] = 0 if matrix[0][0] == 0: for r in range(ROWS): matrix[r][0] = 0 if rowZero: for c in range(COLS): matrix[0][c] = 0",26,26 ,"class Solution { public String frequencySort(String s) { char str[] = s.toCharArray(); HashMap map = new HashMap<>(); for(char n:str){ map.put(n, map.getOrDefault(n, 0) + 1); } ArrayList list = new ArrayList<>(map.keySet()); Collections.sort(list, (a, b) -> map.get(b) - map.get(a)); StringBuilder sb = new StringBuilder(); for(char ch:list){ for(int i = 0; i < map.get(ch); i++){ sb.append(ch); } } return sb.toString(); } }",0.0,leetcode,,java,"class Solution { public String frequencySort(String s) { char str[] = s.toCharArray(); HashMap map = new HashMap<>(); for(char n:str){ map.put(n, map.getOrDefault(n, 0) + 1); } ArrayList list = new ArrayList<>(map.keySet()); Collections.sort(list, (a, b) -> map.get(b) - map.get(a)); StringBuilder sb = new StringBuilder(); for(char ch:list){ for(int i = 0; i < map.get(ch); i++){ sb.append(ch); } } return sb.toString(); } }",18,18 ,"def binary_search(item_list,item): first = 0 last = len(item_list)-1 found = False while( first<=last and not found): mid = (first + last)//2 if item_list[mid] == item : found = True else: if item < item_list[mid]: last = mid - 1 else: first = mid + 1 return found print(binary_search([1,2,3,5,8], 6)) print(binary_search([1,2,3,5,8], 5))",0.0,W3RESOURCE,,python,"def binary_search(item_list,item): first = 0 last = len(item_list)-1 found = False while( first<=last and not found): mid = (first + last)//2 if item_list[mid] == item : found = True else: if item < item_list[mid]: last = mid - 1 else: first = mid + 1 return found print(binary_search([1,2,3,5,8], 6)) print(binary_search([1,2,3,5,8], 5))",17,17 ,"import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateUtil { public static String format(LocalDate date) { DateTimeFormatter fmt = DateTimeFormatter.ofPattern(""yyyy-MM-dd""); return date.format(fmt); } } ",1.0,PERPLEXITY,Create a Java utility class with a method to format LocalDate as yyyy-MM-dd string,java,"import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateUtil { public static String format(LocalDate date) { DateTimeFormatter fmt = DateTimeFormatter.ofPattern(""yyyy-MM-dd""); return date.format(fmt); } }",8,8 ,"import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; public class ForkJoinPoolExercise { public static void main(String[] args) { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; ForkJoinPool forkJoinPool = new ForkJoinPool(); int sum = forkJoinPool.invoke(new SumTask(array, 0, array.length)); System.out.println(""Sum: "" + sum); } static class SumTask extends RecursiveTask < Integer > { private final int[] array; private final int start; private final int end; public SumTask(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override protected Integer compute() { if (end - start <= 2) { int sum = 0; for (int i = start; i < end; i++) { sum += array[i]; } return sum; } else { int mid = start + (end - start) / 2; SumTask leftTask = new SumTask(array, start, mid); SumTask rightTask = new SumTask(array, mid, end); invokeAll(leftTask, rightTask); return leftTask.join() + rightTask.join(); } } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; public class ForkJoinPoolExercise { public static void main(String[] args) { int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; ForkJoinPool forkJoinPool = new ForkJoinPool(); int sum = forkJoinPool.invoke(new SumTask(array, 0, array.length)); System.out.println(""Sum: "" + sum); } static class SumTask extends RecursiveTask < Integer > { private final int[] array; private final int start; private final int end; public SumTask(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override protected Integer compute() { if (end - start <= 2) { int sum = 0; for (int i = start; i < end; i++) { sum += array[i]; } return sum; } else { int mid = start + (end - start) / 2; SumTask leftTask = new SumTask(array, start, mid); SumTask rightTask = new SumTask(array, mid, end); invokeAll(leftTask, rightTask); return leftTask.join() + rightTask.join(); } } } }",58,58 ,"def uniquePaths(m, n): dp = [1] * n for _ in range(m - 1): for j in range(1, n): dp[j] += dp[j - 1] return dp[-1] ",1.0,GPT,"Solve the problem ""Unique Paths"". Given m and n representing grid dimensions, return the number of unique paths from top-left to bottom-right.",python,"def uniquePaths(m, n): dp = [1] * n for _ in range(m - 1): for j in range(1, n): dp[j] += dp[j - 1] return dp[-1]",6,6 ,"static int longestSeq(int[] a){ Set s=new HashSet<>(); for(int x:a) s.add(x); int best=0; for(int x:s) if(!s.contains(x-1)){ int y=x; while(s.contains(y)) y++; best=Math.max(best,y-x); } return best; } ",1.0,GPT,Find the length of the longest sequence of consecutive integers in an unsorted array,java,"static int longestSeq(int[] a){ Set s=new HashSet<>(); for(int x:a) s.add(x); int best=0; for(int x:s) if(!s.contains(x-1)){ int y=x; while(s.contains(y)) y++; best=Math.max(best,y-x); } return best; }",12,12 ,"import java.util.concurrent.locks.StampedLock; public class StampedLockExercise { public static void main(String[] args) { SharedResource sharedResource = new SharedResource(); // Start multiple reader threads for (int i = 0; i < 5; i++) { new Thread(() -> { int value = sharedResource.getValue(); System.out.println(""Reader thread: "" + Thread.currentThread().getName() + "", value: "" + value); }).start(); } // Start a writer thread new Thread(() -> { sharedResource.setValue(42); System.out.println(""Writer thread: "" + Thread.currentThread().getName() + "" set value to 42""); }).start(); } static class SharedResource { private int value; private final StampedLock lock = new StampedLock(); public int getValue() { long stamp = lock.tryOptimisticRead(); // Optimistically acquire a read lock int currentValue = value; if (!lock.validate(stamp)) { // Check for concurrent write stamp = lock.readLock(); // Upgrade to a read lock try { currentValue = value; } finally { lock.unlockRead(stamp); // Release the read lock } } return currentValue; } public void setValue(int value) { long stamp = lock.writeLock(); // Acquire a write lock try { this.value = value; } finally { lock.unlockWrite(stamp); // Release the write lock } } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.locks.StampedLock; public class StampedLockExercise { public static void main(String[] args) { SharedResource sharedResource = new SharedResource(); // Start multiple reader threads for (int i = 0; i < 5; i++) { new Thread(() -> { int value = sharedResource.getValue(); System.out.println(""Reader thread: "" + Thread.currentThread().getName() + "", value: "" + value); }).start(); } // Start a writer thread new Thread(() -> { sharedResource.setValue(42); System.out.println(""Writer thread: "" + Thread.currentThread().getName() + "" set value to 42""); }).start(); } static class SharedResource { private int value; private final StampedLock lock = new StampedLock(); public int getValue() { long stamp = lock.tryOptimisticRead(); // Optimistically acquire a read lock int currentValue = value; if (!lock.validate(stamp)) { // Check for concurrent write stamp = lock.readLock(); // Upgrade to a read lock try { currentValue = value; } finally { lock.unlockRead(stamp); // Release the read lock } } return currentValue; } public void setValue(int value) { long stamp = lock.writeLock(); // Acquire a write lock try { this.value = value; } finally { lock.unlockWrite(stamp); // Release the write lock } } } }",54,54 ,"def isPalindrome(string): left_pos = 0 right_pos = len(string) - 1 while right_pos >= left_pos: if string[left_pos] != string[right_pos]: return False left_pos += 1 right_pos -= 1 return True # Test print(isPalindrome('aza')) # True ",1.0,PERPLEXITY,Write a Python function that checks whether a passed string is a palindrome or not.,python,"def isPalindrome(string): left_pos = 0 right_pos = len(string) - 1 while right_pos >= left_pos: if string[left_pos] != string[right_pos]: return False left_pos += 1 right_pos -= 1 return True # Test print(isPalindrome('aza')) # True",14,14 ,"import numpy as np x = np.arange(7) print(""Original:"", x) print(""Powers (element-wise ^3):"", np.power(x, 3)) ",1.0,PERPLEXITY,Write a NumPy program to get the powers of an array values element-wise.,python,"import numpy as np x = np.arange(7) print(""Original:"", x) print(""Powers (element-wise ^3):"", np.power(x, 3))",5,5 ,"# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: res = [] q = collections.deque() q.append(root) while q: qLen = len(q) level = [] for i in range(qLen): node = q.popleft() if node: level.append(node.val) q.append(node.left) q.append(node.right) if level: res.append(level) return res",0.0,GFG,,python,"# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: res = [] q = collections.deque() q.append(root) while q: qLen = len(q) level = [] for i in range(qLen): node = q.popleft() if node: level.append(node.val) q.append(node.left) q.append(node.right) if level: res.append(level) return res",27,27 ,"class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: ROWS, COLS = len(matrix), len(matrix[0]) l, r = 0, ROWS * COLS - 1 while l <= r: m = l + (r - l) // 2 row, col = m // COLS, m % COLS if target > matrix[row][col]: l = m + 1 elif target < matrix[row][col]: r = m - 1 else: return True return False",0.0,GFG,,python,"class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: ROWS, COLS = len(matrix), len(matrix[0]) l, r = 0, ROWS * COLS - 1 while l <= r: m = l + (r - l) // 2 row, col = m // COLS, m % COLS if target > matrix[row][col]: l = m + 1 elif target < matrix[row][col]: r = m - 1 else: return True return False",15,15 ,"public int ladderLength(String begin, String end, List wordList) { Set set = new HashSet<>(wordList); Queue q = new LinkedList<>(); q.add(begin); int step = 1; while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { char[] cur = q.poll().toCharArray(); for (int j = 0; j < cur.length; j++) { char tmp = cur[j]; for (char c = 'a'; c <= 'z'; c++) { cur[j] = c; String next = new String(cur); if (set.contains(next)) { if (next.equals(end)) return step + 1; q.add(next); set.remove(next); } } cur[j] = tmp; } } step++; } return 0; }",1.0,GEMINI,give me an java program to Find the length of shortest transformation sequence from beginWord to endWord.,java,"public int ladderLength(String begin, String end, List wordList) { Set set = new HashSet<>(wordList); Queue q = new LinkedList<>(); q.add(begin); int step = 1; while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { char[] cur = q.poll().toCharArray(); for (int j = 0; j < cur.length; j++) { char tmp = cur[j]; for (char c = 'a'; c <= 'z'; c++) { cur[j] = c; String next = new String(cur); if (set.contains(next)) { if (next.equals(end)) return step + 1; q.add(next); set.remove(next); } } cur[j] = tmp; } } step++; } return 0; }",24,24 ,"from queue import PriorityQueue from threading import Thread q = PriorityQueue() def producer(): for _ in range(int(input(""Items: ""))): x,p = map(int,input(""item priority: "").split()) q.put((p,x)) q.put((None,None)) def consumer(): while (p,x := q.get()) != (None,None): print(""Consumed:"", x) Thread(target=producer).start() Thread(target=consumer).start() ",1.0,GPT,"# Import the queue module to use PriorityQueue import queue # Import the threading module to use threads and locks import threading # Define a class for a thread-safe priority queue class ThreadSafePriorityQueue: def __init__(self): # Initialize a PriorityQueue object to hold the items self._queue = queue.PriorityQueue() # Initialize a lock to ensure thread safety self._lock = threading.Lock() # Method to put an item into the priority queue def put(self, item, priority): # Acquire the lock to ensure thread safety with self._lock: # Put the item into the queue with its priority self._queue.put((priority, item)) # Method to get an item from the priority queue def get(self): # Acquire the lock to ensure thread safety with self._lock: # Check if the queue is not empty if not self._queue.empty(): # Get the item with the highest priority (lowest priority number) priority, item = self._queue.get() # Return the item return item else: # Return None if the queue is empty return None # Example usage to demonstrate the thread-safe priority queue if __name__ == ""__main__"": # Define a producer function to add items to the queue def producer(q): # Add 5 items to the queue with their priority as their value for i in range(5): q.put(i, i) # Define a consumer function to get items from the queue def consumer(q): # Continuously get items from the queue while True: # Get an item from the queue item = q.get() # If the item is None, break the loop (end of processing) if item is None: break # Print the consumed item print(""Consumed:"", item) # Create an instance of the thread-safe priority queue q = ThreadSafePriorityQueue() # Create a producer thread to add items to the queue producer_thread = threading.Thread(target=producer, args=(q,)) # Create a consumer thread to get items from the queue consumer_thread = threading.Thread(target=consumer, args=(q,)) # Start the producer thread producer_thread.start() # Start the consumer thread consumer_thread.start() # Wait for the producer thread to finish producer_thread.join() # Add a sentinel value to the queue to signal the consumer to stop q.put(None, None) # Wait for the consumer thread to finish consumer_thread.join() refer this code and give me the shorter version of this code with minimal lines to implement it efficiently",python,"from queue import PriorityQueue from threading import Thread q = PriorityQueue() def producer(): for _ in range(int(input(""Items: ""))): x,p = map(int,input(""item priority: "").split()) q.put((p,x)) q.put((None,None)) def consumer(): while (p,x := q.get()) != (None,None): print(""Consumed:"", x) Thread(target=producer).start() Thread(target=consumer).start()",17,17 ,"def max_of_three(a, b, c): return max(a, b, c) # ---------- INPUT ---------- x, y, z = 3, 6, -5 # ---------- OUTPUT ---------- print(""Maximum:"", max_of_three(x, y, z)) ",1.0,GPT,Write a Python function to find the maximum of three numbers.,python,"def max_of_three(a, b, c): return max(a, b, c) # ---------- INPUT ---------- x, y, z = 3, 6, -5 # ---------- OUTPUT ---------- print(""Maximum:"", max_of_three(x, y, z))",8,8 ,"# Import necessary modules import json import threading import time import signal import os from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # Define the ConfigManager class to manage configurations class ConfigManager: def __init__(self, config_file): # Initialize with the configuration file path self.config_file = config_file # Initialize the configuration data dictionary self.config_data = {} # Create a lock for thread-safe operations self.lock = threading.Lock() # Load the initial configuration self.load_config() def load_config(self): # Load the configuration file in a thread-safe manner with self.lock: with open(self.config_file, 'r') as f: self.config_data = json.load(f) # Print the loaded configuration for debugging print(""Configuration reloaded:"", self.config_data) def get_config(self): # Get the current configuration in a thread-safe manner with self.lock: return self.config_data def start_watching(self): # Create a file system event handler for the configuration file event_handler = ConfigFileHandler(self, self.config_file) # Create an observer to monitor file system changes observer = Observer() # Schedule the observer to watch the current directory for changes observer.schedule(event_handler, path='.', recursive=False) # Start the observer observer.start() print(""Started watching for configuration changes..."") try: # Continuously check if the stop event is set while not stop_event.is_set(): time.sleep(1) except KeyboardInterrupt: pass finally: # Stop the observer when shutting down print(""Stopping observer..."") observer.stop() observer.join() print(""Observer stopped."") # Define the file system event handler class for configuration file changes class ConfigFileHandler(FileSystemEventHandler): def __init__(self, config_manager, config_file): # Initialize with the config manager and the configuration file path self.config_manager = config_manager self.config_file = os.path.abspath(config_file) def on_modified(self, event): # Check if the modified file is the configuration file if os.path.abspath(event.src_path) == self.config_file: # Print the modification event for debugging print(f""Configuration file {event.src_path} changed, reloading..."") # Reload the configuration self.config_manager.load_config() # Define a signal handler for SIGINT to handle graceful shutdown def handle_sigint(signal, frame): global stop_event print(""Shutting down..."") # Set the stop event to terminate the program stop_event.set() # Example usage if __name__ == ""__main__"": # Define the path to the configuration file config_file = 'config.json' # Create an instance of ConfigManager with the configuration file config_manager = ConfigManager(config_file) # Create an event to signal stopping stop_event = threading.Event() # Register the signal handler for SIGINT signal.signal(signal.SIGINT, handle_sigint) # Start watching for configuration changes in a separate thread watcher_thread = threading.Thread(target=config_manager.start_watching) watcher_thread.start() # Simulate application usage try: while not stop_event.is_set(): # Get and print the current configuration periodically config = config_manager.get_config() print(""Current configuration:"", config) time.sleep(5) except KeyboardInterrupt: pass # Signal the watcher thread to stop stop_event.set() # Wait for the watcher thread to finish watcher_thread.join() print(""Program terminated."")",0.0,W3RESOURCE,,python,"# Import necessary modules import json import threading import time import signal import os from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # Define the ConfigManager class to manage configurations class ConfigManager: def __init__(self, config_file): # Initialize with the configuration file path self.config_file = config_file # Initialize the configuration data dictionary self.config_data = {} # Create a lock for thread-safe operations self.lock = threading.Lock() # Load the initial configuration self.load_config() def load_config(self): # Load the configuration file in a thread-safe manner with self.lock: with open(self.config_file, 'r') as f: self.config_data = json.load(f) # Print the loaded configuration for debugging print(""Configuration reloaded:"", self.config_data) def get_config(self): # Get the current configuration in a thread-safe manner with self.lock: return self.config_data def start_watching(self): # Create a file system event handler for the configuration file event_handler = ConfigFileHandler(self, self.config_file) # Create an observer to monitor file system changes observer = Observer() # Schedule the observer to watch the current directory for changes observer.schedule(event_handler, path='.', recursive=False) # Start the observer observer.start() print(""Started watching for configuration changes..."") try: # Continuously check if the stop event is set while not stop_event.is_set(): time.sleep(1) except KeyboardInterrupt: ... truncated ... # Initialize with the config manager and the configuration file path self.config_manager = config_manager self.config_file = os.path.abspath(config_file) def on_modified(self, event): # Check if the modified file is the configuration file if os.path.abspath(event.src_path) == self.config_file: # Print the modification event for debugging print(f""Configuration file {event.src_path} changed, reloading..."") # Reload the configuration self.config_manager.load_config() # Define a signal handler for SIGINT to handle graceful shutdown def handle_sigint(signal, frame): global stop_event print(""Shutting down..."") # Set the stop event to terminate the program stop_event.set() # Example usage if __name__ == ""__main__"": # Define the path to the configuration file config_file = 'config.json' # Create an instance of ConfigManager with the configuration file config_manager = ConfigManager(config_file) # Create an event to signal stopping stop_event = threading.Event() # Register the signal handler for SIGINT signal.signal(signal.SIGINT, handle_sigint) # Start watching for configuration changes in a separate thread watcher_thread = threading.Thread(target=config_manager.start_watching) watcher_thread.start() # Simulate application usage try: while not stop_event.is_set(): # Get and print the current configuration periodically config = config_manager.get_config() print(""Current configuration:"", config) time.sleep(5) except KeyboardInterrupt: pass # Signal the watcher thread to stop stop_event.set() # Wait for the watcher thread to finish watcher_thread.join() print(""Program terminated."")",111,101 ,"class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { int[] ans = new int[nums1.length]; Arrays.fill(ans, -1); int index = 0; for(int i=0; i nums2[j]){ ans[i] = nums2[k]; break; } } } } } return ans; } }",0.0,leetcode,,java,"class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { int[] ans = new int[nums1.length]; Arrays.fill(ans, -1); int index = 0; for(int i=0; i nums2[j]){ ans[i] = nums2[k]; break; } } } } } return ans; } }",22,22 ,"def climbStairs(n): if n <= 2: return n a, b = 1, 2 for _ in range(3, n + 1): a, b = b, a + b return b ",1.0,GPT,"Solve the problem ""Climbing Stairs"". You can climb 1 or 2 steps at a time. Given n steps, return how many distinct ways you can climb.",python,"def climbStairs(n): if n <= 2: return n a, b = 1, 2 for _ in range(3, n + 1): a, b = b, a + b return b",9,9 ,"public class WordCount { public static void main(String args[]) { String s = ""welcome to candid java tutorial""; int count = 1; for (int i = 0; i < s.length() - 1; i++) { if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' ')) { count++; } } System.out.println(""Number of words in a string = "" + count); } ",0.0,IPSGWALIOR.ORG,,java,"public class WordCount { public static void main(String args[]) { String s = ""welcome to candid java tutorial""; int count = 1; for (int i = 0; i < s.length() - 1; i++) { if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' ')) { count++; } } System.out.println(""Number of words in a string = "" + count); }",15,15 ,"def bold(fn): return lambda: f""{fn()}"" def italic(fn): return lambda: f""{fn()}"" def underline(fn): return lambda: f""{fn()}"" text = input(""Enter text: "") hello = underline(italic(bold(lambda: text))) print(hello()) ",1.0,PERPLEXITY,"Write a Python program to create a chain of function decorators (bold, italic, underline etc.).",python,"def bold(fn): return lambda: f""{fn()}"" def italic(fn): return lambda: f""{fn()}"" def underline(fn): return lambda: f""{fn()}"" text = input(""Enter text: "") hello = underline(italic(bold(lambda: text))) print(hello())",7,7 ,"import requests response = requests.get('https://python.org') print(""Status Code: "",response.status_code) print(""Headers: "",response.headers) print(""Url: "",response.url) print(""History: "",response.history) print(""Encoding: "",response.encoding) print(""Reason: "",response.reason) print(""Cookies: "",response.cookies) print(""Elapsed: "",response.elapsed) print(""Request: "",response.request) print(""Content: "",response._content) ",0.0,WERESOURCE,,python,"import requests response = requests.get('https://python.org') print(""Status Code: "",response.status_code) print(""Headers: "",response.headers) print(""Url: "",response.url) print(""History: "",response.history) print(""Encoding: "",response.encoding) print(""Reason: "",response.reason) print(""Cookies: "",response.cookies) print(""Elapsed: "",response.elapsed) print(""Request: "",response.request) print(""Content: "",response._content)",12,12 ,"public int evaluate(String expression) { return eval(expression, new HashMap<>()); } private int eval(String expr, Map scope) { // 1. If it's a number, return it directly if (Character.isDigit(expr.charAt(0)) || expr.charAt(0) == '-') return Integer.parseInt(expr); // 2. If it's a variable, get its value from the scope if (Character.isLowerCase(expr.charAt(0)) && !expr.startsWith(""("")) return scope.get(expr); //e.g. scope={ ""x"": 2, ""y"": 3 } so return 2 for eval(x, scope) // 3. Remove outer parentheses and tokenize the expression expr=expr.substring(1, expr.length() - 1); // Remove outer parentheses List tokens = new ArrayList<>(); int balance=0, start=0; for (int i=0; i newScope = new HashMap<>(scope); // Create a new scope // Scope: {} for (int i=1;i()); } private int eval(String expr, Map scope) { // 1. If it's a number, return it directly if (Character.isDigit(expr.charAt(0)) || expr.charAt(0) == '-') return Integer.parseInt(expr); // 2. If it's a variable, get its value from the scope if (Character.isLowerCase(expr.charAt(0)) && !expr.startsWith(""("")) return scope.get(expr); //e.g. scope={ ""x"": 2, ""y"": 3 } so return 2 for eval(x, scope) // 3. Remove outer parentheses and tokenize the expression expr=expr.substring(1, expr.length() - 1); // Remove outer parentheses List tokens = new ArrayList<>(); int balance=0, start=0; for (int i=0; i newScope = new HashMap<>(scope); // Create a new scope // Scope: {} for (int i=1;i preorderQueue = new ArrayDeque<>(); for (int val : preorder) { preorderQueue.offer(val); } return build(preorderQueue, inorder); } private TreeNode build(Deque preorder, int[] inorder) { if (inorder.length > 0) { int idx = indexOf(inorder, preorder.poll()); TreeNode root = new TreeNode(inorder[idx]); root.left = build(preorder, Arrays.copyOfRange(inorder, 0, idx)); root.right = build(preorder, Arrays.copyOfRange(inorder, idx + 1, inorder.length)); return root; } return null; } private int indexOf(int[] arr, int value) { for (int i = 0; i < arr.length; i++) { if (arr[i] == value) { return i; } } return -1; // shouldn't happen with valid input } }",0.0,leetcode,,java,"class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { Deque preorderQueue = new ArrayDeque<>(); for (int val : preorder) { preorderQueue.offer(val); } return build(preorderQueue, inorder); } private TreeNode build(Deque preorder, int[] inorder) { if (inorder.length > 0) { int idx = indexOf(inorder, preorder.poll()); TreeNode root = new TreeNode(inorder[idx]); root.left = build(preorder, Arrays.copyOfRange(inorder, 0, idx)); root.right = build(preorder, Arrays.copyOfRange(inorder, idx + 1, inorder.length)); return root; } return null; } private int indexOf(int[] arr, int value) { for (int i = 0; i < arr.length; i++) { if (arr[i] == value) { return i; } } return -1; // shouldn't happen with valid input } }",32,32 ,"# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: prev, curr = None, head while curr: temp = curr.next curr.next = prev prev = curr curr = temp return prev",0.0,GFG,,python,"# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: prev, curr = None, head while curr: temp = curr.next curr.next = prev prev = curr curr = temp return prev",16,16 ,"class Solution { public boolean isIsomorphic(String s, String t) { HashMap charIndexS = new HashMap<>(); HashMap charIndexT = new HashMap<>(); for (int i = 0; i < s.length(); i++) { if (!charIndexS.containsKey(s.charAt(i))) { charIndexS.put(s.charAt(i), i); } if (!charIndexT.containsKey(t.charAt(i))) { charIndexT.put(t.charAt(i), i); } if (!charIndexS.get(s.charAt(i)).equals(charIndexT.get(t.charAt(i)))) { return false; } } return true; } }",0.0,leetcode,,java,"class Solution { public boolean isIsomorphic(String s, String t) { HashMap charIndexS = new HashMap<>(); HashMap charIndexT = new HashMap<>(); for (int i = 0; i < s.length(); i++) { if (!charIndexS.containsKey(s.charAt(i))) { charIndexS.put(s.charAt(i), i); } if (!charIndexT.containsKey(t.charAt(i))) { charIndexT.put(t.charAt(i), i); } if (!charIndexS.get(s.charAt(i)).equals(charIndexT.get(t.charAt(i)))) { return false; } } return true; } }",22,22 ,"// Define the Book class public class Book { // Private instance variables private String title; private String author; private double price; // Default constructor public Book() { // Initialize title to ""Unknown"" this.title = ""Unknown""; // Initialize author to ""Unknown"" this.author = ""Unknown""; // Initialize price to 0.0 this.price = 0.0; } // Parameterized constructor (title, author) public Book(String title, String author) { // Initialize title with the provided parameter this.title = title; // Initialize author with the provided parameter this.author = author; // Initialize price to 0.0 this.price = 0.0; } // Parameterized constructor (title, author, price) public Book(String title, String author, double price) { // Initialize title with the provided parameter this.title = title; // Initialize author with the provided parameter this.author = author; // Initialize price with the provided parameter this.price = price; } // Main method to test the Book class public static void main(String[] args) { // Create a new Book object using the default constructor Book book1 = new Book(); // Print the values of the instance variables for book1 System.out.println(""Book1 Title: "" + book1.title); System.out.println(""Book1 Author: "" + book1.author); System.out.println(""Book1 Price: "" + book1.price); // Create a new Book object using the parameterized constructor (title, author) Book book2 = new Book(""Amatka"", ""Karin Tidbeck""); // Print the values of the instance variables for book2 System.out.println(""Book2 Title: "" + book2.title); System.out.println(""Book2 Author: "" + book2.author); System.out.println(""Book2 Price: "" + book2.price); // Create a new Book object using the parameterized constructor (title, author, price) Book book3 = new Book(""Altered Carbon"", ""Richard K. Morgan"", 18.99); // Print the values of the instance variables for book3 System.out.println(""Book3 Title: "" + book3.title); System.out.println(""Book3 Author: "" + book3.author); System.out.println(""Book3 Price: "" + book3.price); } } ",0.0,WE3RESOURCE,,java,"// Define the Book class public class Book { // Private instance variables private String title; private String author; private double price; // Default constructor public Book() { // Initialize title to ""Unknown"" this.title = ""Unknown""; // Initialize author to ""Unknown"" this.author = ""Unknown""; // Initialize price to 0.0 this.price = 0.0; } // Parameterized constructor (title, author) public Book(String title, String author) { // Initialize title with the provided parameter this.title = title; // Initialize author with the provided parameter this.author = author; // Initialize price to 0.0 this.price = 0.0; } // Parameterized constructor (title, author, price) public Book(String title, String author, double price) { // Initialize title with the provided parameter this.title = title; // Initialize author with the provided parameter this.author = author; // Initialize price with the provided parameter this.price = price; } // Main method to test the Book class public static void main(String[] args) { // Create a new Book object using the default constructor Book book1 = new Book(); // Print the values of the instance variables for book1 System.out.println(""Book1 Title: "" + book1.title); System.out.println(""Book1 Author: "" + book1.author); System.out.println(""Book1 Price: "" + book1.price); // Create a new Book object using the parameterized constructor (title, author) Book book2 = new Book(""Amatka"", ""Karin Tidbeck""); // Print the values of the instance variables for book2 System.out.println(""Book2 Title: "" + book2.title); System.out.println(""Book2 Author: "" + book2.author); System.out.println(""Book2 Price: "" + book2.price); // Create a new Book object using the parameterized constructor (title, author, price) Book book3 = new Book(""Altered Carbon"", ""Richard K. Morgan"", 18.99); // Print the values of the instance variables for book3 System.out.println(""Book3 Title: "" + book3.title); System.out.println(""Book3 Author: "" + book3.author); System.out.println(""Book3 Price: "" + book3.price); } }",61,61 ,"# Take user input and split it into a list based on the hyphen (""-"") separator, creating a list named 'items' items = [n for n in input().split('-')] # Sort the elements in the 'items' list in lexicographical order (alphabetical and numerical sorting) items.sort() # Join the sorted elements in the 'items' list using the hyphen (""-"") separator and print the resulting string print('-'.join(items)) ",0.0,W3RESOURCE,,python,"# Take user input and split it into a list based on the hyphen (""-"") separator, creating a list named 'items' items = [n for n in input().split('-')] # Sort the elements in the 'items' list in lexicographical order (alphabetical and numerical sorting) items.sort() # Join the sorted elements in the 'items' list using the hyphen (""-"") separator and print the resulting string print('-'.join(items)) ",8,8 ,"public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); return left == null ? right : right == null ? left : root; }",1.0,GEMINI,Find the lowest common ancestor of two given nodes in a tree.,java,"public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); return left == null ? right : right == null ? left : root; }",6,6 ,"import requests from bs4 import BeautifulSoup url = ""https://mlh.io/seasons/2026/events"" headers = {""User-Agent"":""Mozilla/5.0""} # Fetch event list resp = requests.get(url, headers=headers) soup = BeautifulSoup(resp.text, ""html.parser"") events = soup.select("".event-card"")[:25] # next 25 events print(f""{'Date':<20}{'Days':<10}{'Title':<50}{'City':<20}{'Country'}"") for e in events: date = e.select_one("".event-date"").text.strip() if e.select_one("".event-date"") else ""N/A"" title = e.select_one("".event-name"").text.strip() if e.select_one("".event-name"") else ""N/A"" location = e.select_one("".event-location"").text.strip().split("","") if e.select_one("".event-location"") else [""N/A""] city = location[0].strip() if len(location)>0 else ""N/A"" country = location[-1].strip() if len(location)>1 else ""N/A"" # compute approximate event duration if date range present days = ""1"" if ""-"" not in date else date.split(""-"")[1].strip() print(f""{date:<20}{days:<10}{title:<50}{city:<20}{country}"") ",1.0,GPT,"Write a Python program to display the date, days, title, city, country of next 25 Hackevents.",python,"import requests from bs4 import BeautifulSoup url = ""https://mlh.io/seasons/2026/events"" headers = {""User-Agent"":""Mozilla/5.0""} # Fetch event list resp = requests.get(url, headers=headers) soup = BeautifulSoup(resp.text, ""html.parser"") events = soup.select("".event-card"")[:25] # next 25 events print(f""{'Date':<20}{'Days':<10}{'Title':<50}{'City':<20}{'Country'}"") for e in events: date = e.select_one("".event-date"").text.strip() if e.select_one("".event-date"") else ""N/A"" title = e.select_one("".event-name"").text.strip() if e.select_one("".event-name"") else ""N/A"" location = e.select_one("".event-location"").text.strip().split("","") if e.select_one("".event-location"") else [""N/A""] city = location[0].strip() if len(location)>0 else ""N/A"" country = location[-1].strip() if len(location)>1 else ""N/A"" # compute approximate event duration if date range present days = ""1"" if ""-"" not in date else date.split(""-"")[1].strip() print(f""{date:<20}{days:<10}{title:<50}{city:<20}{country}"")",25,25 ,"# Importing the NumPy library import numpy as np # Calculating the natural logarithm of 1e-50 and 2.5e-50 l1 = np.log(1e-50) l2 = np.log(2.5e-50) # Displaying the logarithm of the sum of exponentiations print(""Logarithm of the sum of exponentiations:"") print(np.logaddexp(l1, l2)) # Displaying the logarithm of the sum of exponentiations of the inputs in base-2 print(""Logarithm of the sum of exponentiations of the inputs in base-2:"") print(np.logaddexp2(l1, l2)) ",0.0,W3RESOURCE,,python,"# Importing the NumPy library import numpy as np # Calculating the natural logarithm of 1e-50 and 2.5e-50 l1 = np.log(1e-50) l2 = np.log(2.5e-50) # Displaying the logarithm of the sum of exponentiations print(""Logarithm of the sum of exponentiations:"") print(np.logaddexp(l1, l2)) # Displaying the logarithm of the sum of exponentiations of the inputs in base-2 print(""Logarithm of the sum of exponentiations of the inputs in base-2:"") print(np.logaddexp2(l1, l2)) ",14,14 ,"class Printer { boolean oddTurn = true; synchronized void print(int n, boolean isOdd) throws Exception { while (oddTurn != isOdd) wait(); System.out.println(n); oddTurn = !isOdd; notifyAll(); } } // Logic: Thread 1 calls print(i, true), Thread 2 calls print(i, false)",1.0,GEMINI,Create two threads—one printing odd numbers and one even—ensuring they print in perfect sequence up to $N$.,java,"class Printer { boolean oddTurn = true; synchronized void print(int n, boolean isOdd) throws Exception { while (oddTurn != isOdd) wait(); System.out.println(n); oddTurn = !isOdd; notifyAll(); } } // Logic: Thread 1 calls print(i, true), Thread 2 calls print(i, false)",10,10 ,"public int flipgame(int[] f, int[] b) { HashSet same = new HashSet<>(); for (int i = 0; i < f.length; ++i) if (f[i] == b[i]) same.add(f[i]); int res = 3000; for (int i : f) if (!same.contains(i)) res = Math.min(res, i); for (int i : b) if (!same.contains(i)) res = Math.min(res, i); return res % 3000; }",0.0,leetcode,,java,"public int flipgame(int[] f, int[] b) { HashSet same = new HashSet<>(); for (int i = 0; i < f.length; ++i) if (f[i] == b[i]) same.add(f[i]); int res = 3000; for (int i : f) if (!same.contains(i)) res = Math.min(res, i); for (int i : b) if (!same.contains(i)) res = Math.min(res, i); return res % 3000; }",14,14 ,"public List flattenAndProcess(List> nested) { return nested.stream() .flatMap(Collection::stream) .map(String::toUpperCase) .distinct() .collect(Collectors.toList()); }",1.0,GEMINI,"Write a Java Stream pipeline to flatten a List> into a single list of uppercase strings, removing duplicates.",java,"public List flattenAndProcess(List> nested) { return nested.stream() .flatMap(Collection::stream) .map(String::toUpperCase) .distinct() .collect(Collectors.toList()); }",7,7 ,"class Solution { public String originalDigits(String s) { int[] charCount = new int[26]; for (char c : s.toCharArray()) { charCount[c - 'a']++; } int[] digitCount = new int[10]; digitCount[0] = charCount['z' - 'a']; digitCount[2] = charCount['w' - 'a']; digitCount[4] = charCount['u' - 'a']; digitCount[6] = charCount['x' - 'a']; digitCount[8] = charCount['g' - 'a']; digitCount[3] = charCount['h' - 'a'] - digitCount[8]; digitCount[5] = charCount['f' - 'a'] - digitCount[4]; digitCount[7] = charCount['s' - 'a'] - digitCount[6]; digitCount[1] = charCount['o' - 'a'] - digitCount[0] - digitCount[2] - digitCount[4]; digitCount[9] = charCount['i' - 'a'] - digitCount[5] - digitCount[6] - digitCount[8]; StringBuilder result = new StringBuilder(); for (int i = 0; i < 10; i++) { for (int j = 0; j < digitCount[i]; j++) { result.append(i); } } return result.toString(); } }",0.0,leetcode,,java,"class Solution { public String originalDigits(String s) { int[] charCount = new int[26]; for (char c : s.toCharArray()) { charCount[c - 'a']++; } int[] digitCount = new int[10]; digitCount[0] = charCount['z' - 'a']; digitCount[2] = charCount['w' - 'a']; digitCount[4] = charCount['u' - 'a']; digitCount[6] = charCount['x' - 'a']; digitCount[8] = charCount['g' - 'a']; digitCount[3] = charCount['h' - 'a'] - digitCount[8]; digitCount[5] = charCount['f' - 'a'] - digitCount[4]; digitCount[7] = charCount['s' - 'a'] - digitCount[6]; digitCount[1] = charCount['o' - 'a'] - digitCount[0] - digitCount[2] - digitCount[4]; digitCount[9] = charCount['i' - 'a'] - digitCount[5] - digitCount[6] - digitCount[8]; StringBuilder result = new StringBuilder(); for (int i = 0; i < 10; i++) { for (int j = 0; j < digitCount[i]; j++) { result.append(i); } } return result.toString(); } }",32,32 ,"import requests, time from bs4 import BeautifulSoup B=""https://www.imdb.com""; H={""User-Agent"":""Mozilla/5.0""} s=BeautifulSoup(requests.get(B+""/chart/top/"",headers=H).text,""html.parser"") for m in s.select(""td.titleColumn""): t=m.a.text; y=m.span.text.strip(""()""); u=B+m.a[""href""] d=BeautifulSoup(requests.get(u,headers=H).text,""html.parser"").select(""div.credit_summary_item"") dr="", "".join(a.text for a in d[0].select(""a"")) st="", "".join(a.text for a in d[1].select(""a"") if ""name"" in a[""href""]) print(f""{t} ({y}) | Dir: {dr} | Stars: {st}"") time.sleep(0.5) ",1.0,GPT,"Write a Python program to download IMDB's Top 250 data (movie name, Initial release, director name and stars).GIVE ME THE CODE AS SHORT AS POSSIBLE",python,"import requests, time from bs4 import BeautifulSoup B=""https://www.imdb.com""; H={""User-Agent"":""Mozilla/5.0""} s=BeautifulSoup(requests.get(B+""/chart/top/"",headers=H).text,""html.parser"") for m in s.select(""td.titleColumn""): t=m.a.text; y=m.span.text.strip(""()""); u=B+m.a[""href""] d=BeautifulSoup(requests.get(u,headers=H).text,""html.parser"").select(""div.credit_summary_item"") dr="", "".join(a.text for a in d[0].select(""a"")) st="", "".join(a.text for a in d[1].select(""a"") if ""name"" in a[""href""]) print(f""{t} ({y}) | Dir: {dr} | Stars: {st}"") time.sleep(0.5)",13,13 ,"import random, numpy as np f = lambda x: 10*len(x) + sum(x*x - 10*np.cos(2*np.pi*x)) def GA(pop=50, n=5, gen=50): P = [np.random.uniform(-5,5,n) for _ in range(pop)] for g in range(gen): P = sorted(P, key=f) print(f""Gen {g+1} Best:"", f(P[0])) N = P[:10] while len(N) stack[-1]: stack.append(time) return len(stack) ",1.0,GPT,"Given target, position, and speed arrays, return the number of car fleets that will arrive at the destination.",python,"def carFleet(target, position, speed): cars = sorted(zip(position, speed), reverse=True) stack = [] for pos, spd in cars: time = (target - pos) / spd if not stack or time > stack[-1]: stack.append(time) return len(stack)",10,10 ,"import java.util.Arrays; import java.util.List; public class StreamExample { public static int sumSquares(List numbers) { return numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .reduce(0, Integer::sum); } } ",1.0,PERPLEXITY,"""Write Java stream operations to filter even numbers, map to squares, and reduce to sum.",java,"import java.util.Arrays; import java.util.List; public class StreamExample { public static int sumSquares(List numbers) { return numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .reduce(0, Integer::sum); } }",10,10 ,"static int dfs(int[][] m,int i,int j,int[][] d){ if(d[i][j]>0) return d[i][j]; int r=1; for(int[] x:new int[][]{{1,0},{-1,0},{0,1},{0,-1}}){ int a=i+x[0],b=j+x[1]; if(a>=0&&b>=0&&am[i][j]) r=Math.max(r,1+dfs(m,a,b,d)); } return d[i][j]=r; } ",1.0,GPT,"You are given an m x n integer matrix matrix. From any cell, you can move up, down, left, or right to another cell only if the next cell has a strictly larger value. Write a java function that returns the length of the longest strictly increasing path in the matrix.",java,"static int dfs(int[][] m,int i,int j,int[][] d){ if(d[i][j]>0) return d[i][j]; int r=1; for(int[] x:new int[][]{{1,0},{-1,0},{0,1},{0,-1}}){ int a=i+x[0],b=j+x[1]; if(a>=0&&b>=0&&am[i][j]) r=Math.max(r,1+dfs(m,a,b,d)); } return d[i][j]=r; }",10,10 ,"import requests import random API_KEY = ""YOUR_TMDB_API_KEY"" # <-- replace with your API key BASE_URL = ""https://api.themoviedb.org/3"" # Step 1: Get popular movies (several pages available) popular_url = f""{BASE_URL}/movie/popular"" params = { ""api_key"": API_KEY, ""language"": ""en-US"", ""page"": random.randint(1, 20) # random page for randomness } response = requests.get(popular_url, params=params) response.raise_for_status() movies = response.json()[""results""] # Step 2: Randomly select 10 movies random_movies = random.sample(movies, 10) print(""Top 10 Random Movies:\n"") for i, movie in enumerate(random_movies, start=1): title = movie[""title""] year = movie[""release_date""][:4] if movie[""release_date""] else ""N/A"" summary = movie[""overview""] print(f""{i}. Movie Name : {title}"") print(f"" Year : {year}"") print(f"" Summary : {summary}\n"") ",1.0,GPT,"Write a Python program to get movie name, year and a brief summary of the top 10 random movies",python,"import requests import random API_KEY = ""YOUR_TMDB_API_KEY"" # <-- replace with your API key BASE_URL = ""https://api.themoviedb.org/3"" # Step 1: Get popular movies (several pages available) popular_url = f""{BASE_URL}/movie/popular"" params = { ""api_key"": API_KEY, ""language"": ""en-US"", ""page"": random.randint(1, 20) # random page for randomness } response = requests.get(popular_url, params=params) response.raise_for_status() movies = response.json()[""results""] # Step 2: Randomly select 10 movies random_movies = random.sample(movies, 10) print(""Top 10 Random Movies:\n"") for i, movie in enumerate(random_movies, start=1): title = movie[""title""] year = movie[""release_date""][:4] if movie[""release_date""] else ""N/A"" summary = movie[""overview""] print(f""{i}. Movie Name : {title}"") print(f"" Year : {year}"") print(f"" Summary : {summary}\n"")",32,32 ,"import json jobj_dict = '{""name"": ""David"", ""age"": 6, ""class"": ""I""}' jobj_list = '[""Red"", ""Green"", ""Black""]' jobj_string = '""Python Json""' jobj_int = '1234' jobj_float = '21.34' python_dict = json.loads(jobj_dict) python_list = json.loads(jobj_list) python_str = json.loads(jobj_string) python_int = json.loads(jobj_int) python_float = json.loads(jobj_float) print(""Python dictionary: "", python_dict) print(""Python list: "", python_list) print(""Python string: "", python_str) print(""Python integer: "", python_int) print(""Python float: "", python_float) ",0.0,WE3RESOURCE,,python,"import json jobj_dict = '{""name"": ""David"", ""age"": 6, ""class"": ""I""}' jobj_list = '[""Red"", ""Green"", ""Black""]' jobj_string = '""Python Json""' jobj_int = '1234' jobj_float = '21.34' python_dict = json.loads(jobj_dict) python_list = json.loads(jobj_list) python_str = json.loads(jobj_string) python_int = json.loads(jobj_int) python_float = json.loads(jobj_float) print(""Python dictionary: "", python_dict) print(""Python list: "", python_list) print(""Python string: "", python_str) print(""Python integer: "", python_int) print(""Python float: "", python_float)",18,18 ,"class Solution: def maxCoins(self, nums): n = len(nums) new_nums = [1] + nums + [1] dp = [[0] * (n + 2) for _ in range(n + 2)] for l in range(n, 0, -1): for r in range(l, n + 1): for i in range(l, r + 1): coins = new_nums[l - 1] * new_nums[i] * new_nums[r + 1] coins += dp[l][i - 1] + dp[i + 1][r] dp[l][r] = max(dp[l][r], coins) return dp[1][n]",0.0,GFG,,python,"class Solution: def maxCoins(self, nums): n = len(nums) new_nums = [1] + nums + [1] dp = [[0] * (n + 2) for _ in range(n + 2)] for l in range(n, 0, -1): for r in range(l, n + 1): for i in range(l, r + 1): coins = new_nums[l - 1] * new_nums[i] * new_nums[r + 1] coins += dp[l][i - 1] + dp[i + 1][r] dp[l][r] = max(dp[l][r], coins) return dp[1][n]",14,14 ,"import java.util.ArrayList; public class Stack { private ArrayList stack = new ArrayList<>(); public void push(T item) { stack.add(item); } public T pop() { return stack.remove(stack.size() - 1); } public T peek() { return stack.get(stack.size() - 1); } public boolean isEmpty() { return stack.isEmpty(); } } ",1.0,PERPLEXITY,"Implement a generic Stack class in Java using ArrayList with push, pop, peek, and isEmpty methods",java,"import java.util.ArrayList; public class Stack { private ArrayList stack = new ArrayList<>(); public void push(T item) { stack.add(item); } public T pop() { return stack.remove(stack.size() - 1); } public T peek() { return stack.get(stack.size() - 1); } public boolean isEmpty() { return stack.isEmpty(); } }",8,8 ,"import java.util.Optional; public class OptionalExample { public static String getEmail(User user) { return Optional.ofNullable(user) .map(User::getEmail) .filter(email -> !email.isEmpty()) .orElse(""no-email@domain.com""); } } class User { private String email; public String getEmail() { return email; } } ",1.0,PERPLEXITY,Write Java code using Optional to safely extract user email or return defaul,java,"import java.util.Optional; public class OptionalExample { public static String getEmail(User user) { return Optional.ofNullable(user) .map(User::getEmail) .filter(email -> !email.isEmpty()) .orElse(""no-email@domain.com""); } } class User { private String email; public String getEmail() { return email; } }",10,10 ,"class Twitter { private static int timestamp = 0; private Map> tweets = new HashMap<>(); private Map> followMap = new HashMap<>(); public void postTweet(int userId, int tweetId) { tweets.putIfAbsent(userId, new ArrayList<>()); tweets.get(userId).add(new int[]{timestamp++, tweetId}); } public List getNewsFeed(int userId) { PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]); Set followees = followMap.getOrDefault(userId, new HashSet<>()); followees.add(userId); for (int followee : followees) { List tweetList = tweets.getOrDefault(followee, new ArrayList<>()); maxHeap.addAll(tweetList); } List res = new ArrayList<>(); while (!maxHeap.isEmpty() && res.size() < 10) { res.add(maxHeap.poll()[1]); } return res; } public void follow(int followerId, int followeeId) { followMap.putIfAbsent(followerId, new HashSet<>()); followMap.get(followerId).add(followeeId); } public void unfollow(int followerId, int followeeId) { if (followMap.containsKey(followerId)) { followMap.get(followerId).remove(followeeId); } } }",0.0,leetcode,,java,"class Twitter { private static int timestamp = 0; private Map> tweets = new HashMap<>(); private Map> followMap = new HashMap<>(); public void postTweet(int userId, int tweetId) { tweets.putIfAbsent(userId, new ArrayList<>()); tweets.get(userId).add(new int[]{timestamp++, tweetId}); } public List getNewsFeed(int userId) { PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]); Set followees = followMap.getOrDefault(userId, new HashSet<>()); followees.add(userId); for (int followee : followees) { List tweetList = tweets.getOrDefault(followee, new ArrayList<>()); maxHeap.addAll(tweetList); } List res = new ArrayList<>(); while (!maxHeap.isEmpty() && res.size() < 10) { res.add(maxHeap.poll()[1]); } return res; } public void follow(int followerId, int followeeId) { followMap.putIfAbsent(followerId, new HashSet<>()); followMap.get(followerId).add(followeeId); } public void unfollow(int followerId, int followeeId) { if (followMap.containsKey(followerId)) { followMap.get(followerId).remove(followeeId); } } }",38,38 ,"class LRUCache extends LinkedHashMap { private final int capacity; public LRUCache(int capacity) { super(capacity, 0.75f, true); this.capacity = capacity; } protected boolean removeEldestEntry(Map.Entry eldest) { return size() > capacity; } }",1.0,GEMINI,Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.,java,"class LRUCache extends LinkedHashMap { private final int capacity; public LRUCache(int capacity) { super(capacity, 0.75f, true); this.capacity = capacity; } protected boolean removeEldestEntry(Map.Entry eldest) { return size() > capacity; } }",10,10 ,"class Solution: def rob(self, nums: List[int]) -> int: rob1, rob2 = 0, 0 for num in nums: temp = max(num + rob1, rob2) rob1 = rob2 rob2 = temp return rob2",0.0,GFG,,python,"class Solution: def rob(self, nums: List[int]) -> int: rob1, rob2 = 0, 0 for num in nums: temp = max(num + rob1, rob2) rob1 = rob2 rob2 = temp return rob2",9,9 ,"class Solution { public int[] smallestRange(List> nums) { // Min-Heap: stores (value, list index, element index) PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); int curMax = Integer.MIN_VALUE; // Initialize the heap with the first element of each list for (int i = 0; i < nums.size(); i++) { minHeap.offer(new int[]{nums.get(i).get(0), i, 0}); curMax = Math.max(curMax, nums.get(i).get(0)); } // Track the smallest range int[] smallRange = new int[]{0, Integer.MAX_VALUE}; while (true) { // Get the minimum element from the heap int[] curr = minHeap.poll(); int curMin = curr[0], listIdx = curr[1], elemIdx = curr[2]; // Update the smallest range if a better one is found if (curMax - curMin < smallRange[1] - smallRange[0]) { smallRange[0] = curMin; smallRange[1] = curMax; } // Move to the next element in the same list if (elemIdx + 1 < nums.get(listIdx).size()) { int nextVal = nums.get(listIdx).get(elemIdx + 1); minHeap.offer(new int[]{nextVal, listIdx, elemIdx + 1}); curMax = Math.max(curMax, nextVal); } else { // If any list is exhausted, stop break; } } return smallRange; } }",0.0,leetcode,,java,"class Solution { public int[] smallestRange(List> nums) { // Min-Heap: stores (value, list index, element index) PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); int curMax = Integer.MIN_VALUE; // Initialize the heap with the first element of each list for (int i = 0; i < nums.size(); i++) { minHeap.offer(new int[]{nums.get(i).get(0), i, 0}); curMax = Math.max(curMax, nums.get(i).get(0)); } // Track the smallest range int[] smallRange = new int[]{0, Integer.MAX_VALUE}; while (true) { // Get the minimum element from the heap int[] curr = minHeap.poll(); int curMin = curr[0], listIdx = curr[1], elemIdx = curr[2]; // Update the smallest range if a better one is found if (curMax - curMin < smallRange[1] - smallRange[0]) { smallRange[0] = curMin; smallRange[1] = curMax; } // Move to the next element in the same list if (elemIdx + 1 < nums.get(listIdx).size()) { int nextVal = nums.get(listIdx).get(elemIdx + 1); minHeap.offer(new int[]{nextVal, listIdx, elemIdx + 1}); curMax = Math.max(curMax, nextVal); } else { // If any list is exhausted, stop break; } } return smallRange; } }",39,39 ,"import json # Define the Address and Person classes class Address: def __init__(self, street, city, state, zip_code): self.street = street self.city = city self.state = state self.zip_code = zip_code class Person: def __init__(self, name, age, address): self.name = name self.age = age self.address = address # Custom JSON Encoder class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Address): return { '__type__': 'Address', 'street': obj.street, 'city': obj.city, 'state': obj.state, 'zip_code': obj.zip_code } elif isinstance(obj, Person): return { '__type__': 'Person', 'name': obj.name, 'age': obj.age, 'address': obj.address } return json.JSONEncoder.default(self, obj) # Custom JSON Decoder def complex_decoder(dct): if '__type__' in dct: if dct['__type__'] == 'Address': return Address(dct['street'], dct['city'], dct['state'], dct['zip_code']) elif dct['__type__'] == 'Person': address = dct['address'] if isinstance(address, dict): address = complex_decoder(address) return Person(dct['name'], dct['age'], address) return dct # Example usage address = Address(""123 ABCD St."", ""Paris"", ""CA"", ""12345"") person = Person(""Roslindis Bronwen"", 30, address) # Serialize to JSON person_json = json.dumps(person, cls=ComplexEncoder) print(""Serialized JSON:"", person_json) # Deserialize from JSON decoded_person = json.loads(person_json, object_hook=complex_decoder) print(""\nDecoded Object:"", decoded_person.name, decoded_person.age, decoded_person.address.street)",0.0,W3RESOURCE,,python,"import json # Define the Address and Person classes class Address: def __init__(self, street, city, state, zip_code): self.street = street self.city = city self.state = state self.zip_code = zip_code class Person: def __init__(self, name, age, address): self.name = name self.age = age self.address = address # Custom JSON Encoder class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Address): return { '__type__': 'Address', 'street': obj.street, 'city': obj.city, 'state': obj.state, 'zip_code': obj.zip_code } elif isinstance(obj, Person): return { '__type__': 'Person', 'name': obj.name, 'age': obj.age, 'address': obj.address } return json.JSONEncoder.default(self, obj) # Custom JSON Decoder def complex_decoder(dct): if '__type__' in dct: if dct['__type__'] == 'Address': return Address(dct['street'], dct['city'], dct['state'], dct['zip_code']) elif dct['__type__'] == 'Person': address = dct['address'] if isinstance(address, dict): address = complex_decoder(address) return Person(dct['name'], dct['age'], address) return dct # Example usage address = Address(""123 ABCD St."", ""Paris"", ""CA"", ""12345"") person = Person(""Roslindis Bronwen"", 30, address) # Serialize to JSON person_json = json.dumps(person, cls=ComplexEncoder) print(""Serialized JSON:"", person_json) # Deserialize from JSON decoded_person = json.loads(person_json, object_hook=complex_decoder) print(""\nDecoded Object:"", decoded_person.name, decoded_person.age, decoded_person.address.street)",59,59 ,"# Define a function named 'isPalindrome' that checks if a string is a palindrome def isPalindrome(string): # Initialize left and right pointers to check characters from the start and end of the string left_pos = 0 right_pos = len(string) - 1 # Loop until the pointers meet or cross each other while right_pos >= left_pos: # Check if the characters at the left and right positions are not equal if not string[left_pos] == string[right_pos]: # If characters don't match, return False (not a palindrome) return False # Move the left pointer to the right and the right pointer to the left to continue checking left_pos += 1 right_pos -= 1 # If the loop finishes without returning False, the string is a palindrome, so return True return True # Print the result of checking if the string 'aza' is a palindrome by calling the 'isPalindrome' function print(isPalindrome('aza')) ",0.0,W3RESOURCE,,python,"# Define a function named 'isPalindrome' that checks if a string is a palindrome def isPalindrome(string): # Initialize left and right pointers to check characters from the start and end of the string left_pos = 0 right_pos = len(string) - 1 # Loop until the pointers meet or cross each other while right_pos >= left_pos: # Check if the characters at the left and right positions are not equal if not string[left_pos] == string[right_pos]: # If characters don't match, return False (not a palindrome) return False # Move the left pointer to the right and the right pointer to the left to continue checking left_pos += 1 right_pos -= 1 # If the loop finishes without returning False, the string is a palindrome, so return True return True # Print the result of checking if the string 'aza' is a palindrome by calling the 'isPalindrome' function print(isPalindrome('aza')) ",22,22 ,"class Solution { public boolean canConstruct(String ransomNote, String magazine) { if (ransomNote.length() > magazine.length()) return false; int[] alphabets_counter = new int[26]; for (char c : magazine.toCharArray()) alphabets_counter[c-'a']++; for (char c : ransomNote.toCharArray()){ if (alphabets_counter[c-'a'] == 0) return false; alphabets_counter[c-'a']--; } return true; } }",0.0,leetcode,,java,"class Solution { public boolean canConstruct(String ransomNote, String magazine) { if (ransomNote.length() > magazine.length()) return false; int[] alphabets_counter = new int[26]; for (char c : magazine.toCharArray()) alphabets_counter[c-'a']++; for (char c : ransomNote.toCharArray()){ if (alphabets_counter[c-'a'] == 0) return false; alphabets_counter[c-'a']--; } return true; } }",15,15 ,"class Solution: def climbStairs(self, n: int) -> int: one, two = 1, 1 for i in range(n - 1): temp = one one = one + two two = temp return one",0.0,GFG,,python,"class Solution: def climbStairs(self, n: int) -> int: one, two = 1, 1 for i in range(n - 1): temp = one one = one + two two = temp return one",10,10 ,"def counting_sort(array1, max_val): m = max_val + 1 count = [0] * m for a in array1: # count occurences count[a] += 1 i = 0 for a in range(m): for c in range(count[a]): array1[i] = a i += 1 return array1 print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))",0.0,GFG,,python,"def counting_sort(array1, max_val): m = max_val + 1 count = [0] * m for a in array1: # count occurences count[a] += 1 i = 0 for a in range(m): for c in range(count[a]): array1[i] = a i += 1 return array1 print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))",15,15 ,"# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def serialize(self, root: Optional[TreeNode]) -> str: if root == None: return ""$#"" return (""$"" + str(root.val) + self.serialize(root.left) + self.serialize(root.right)) def z_function(self, s: str) -> list: z = [0] * len(s) l, r, n = 0, 0, len(s) for i in range(1, n): if i <= r: z[i] = min(r - i + 1, z[i - l]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if i + z[i] - 1 > r: l, r = i, i + z[i] - 1 return z def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: serialized_root = self.serialize(root) serialized_subRoot = self.serialize(subRoot) combined = serialized_subRoot + ""|"" + serialized_root z_values = self.z_function(combined) sub_len = len(serialized_subRoot) for i in range(sub_len + 1, len(combined)): if z_values[i] == sub_len: return True return False",0.0,GFG,,python,"# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def serialize(self, root: Optional[TreeNode]) -> str: if root == None: return ""$#"" return (""$"" + str(root.val) + self.serialize(root.left) + self.serialize(root.right)) def z_function(self, s: str) -> list: z = [0] * len(s) l, r, n = 0, 0, len(s) for i in range(1, n): if i <= r: z[i] = min(r - i + 1, z[i - l]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if i + z[i] - 1 > r: l, r = i, i + z[i] - 1 return z def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: serialized_root = self.serialize(root) serialized_subRoot = self.serialize(subRoot) combined = serialized_subRoot + ""|"" + serialized_root z_values = self.z_function(combined) sub_len = len(serialized_subRoot) for i in range(sub_len + 1, len(combined)): if z_values[i] == sub_len: return True return False",38,38 ,"# Define a string variable 'mycode' containing a Python code as a string mycode = 'print(""hello world"")' # Define a multi-line string variable 'code' containing Python code as a string code = """""" def mutiply(x,y): return x*y print('Multiply of 2 and 3 is: ',mutiply(2,3)) """""" # Execute the Python code represented by the string stored in the variable 'mycode' exec(mycode) # Execute the Python code represented by the multi-line string stored in the variable 'code' exec(code) ",0.0,W3RESOURCE,,python,"# Define a string variable 'mycode' containing a Python code as a string mycode = 'print(""hello world"")' # Define a multi-line string variable 'code' containing Python code as a string code = """""" def mutiply(x,y): return x*y print('Multiply of 2 and 3 is: ',mutiply(2,3)) """""" # Execute the Python code represented by the string stored in the variable 'mycode' exec(mycode) # Execute the Python code represented by the multi-line string stored in the variable 'code' exec(code) ",16,16 ,"public class CustomEntry { private K key; private V value; private CustomEntry next; public CustomEntry(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } public CustomEntry getNext() { return next; } public void setNext(CustomEntry next) { this.next = next; } } ",1.0,PERPLEXITY,Define a custom Entry class for Java HashMap-like structure with key-value pairs.,java,"public class CustomEntry { private K key; private V value; private CustomEntry next; public CustomEntry(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } public CustomEntry getNext() { return next; } public void setNext(CustomEntry next) { this.next = next; } }",13,13 ,"import math def minEatingSpeed(piles, h): l, r = 1, max(piles) while l < r: m = (l + r) // 2 hours = sum(math.ceil(p / m) for p in piles) if hours <= h: r = m else: l = m + 1 return l ",1.0,GPT,"Given an array piles where piles[i] is the number of bananas in the ith pile, and an integer h representing hours, find the minimum integer eating speed k such that Koko can eat all bananas within h hours.",python,"import math def minEatingSpeed(piles, h): l, r = 1, max(piles) while l < r: m = (l + r) // 2 hours = sum(math.ceil(p / m) for p in piles) if hours <= h: r = m else: l = m + 1 return l",14,14 ,"# Define a function named 'test_prime' that checks if a number 'n' is a prime number def test_prime(n): # Check if 'n' is equal to 1 if (n == 1): # If 'n' is 1, return False (1 is not a prime number) return False # Check if 'n' is equal to 2 elif (n == 2): # If 'n' is 2, return True (2 is a prime number) return True else: # Iterate through numbers from 2 to (n-1) using 'x' as the iterator for x in range(2, n): # Check if 'n' is divisible by 'x' without any remainder if (n % x == 0): # If 'n' is divisible by 'x', return False (not a prime number) return False # If 'n' is not divisible by any number from 2 to (n-1), return True (prime number) return True # Print the result of checking if 9 is a prime number by calling the 'test_prime' function print(test_prime(9))",0.0,W3RESOURCE,,python,"# Define a function named 'test_prime' that checks if a number 'n' is a prime number def test_prime(n): # Check if 'n' is equal to 1 if (n == 1): # If 'n' is 1, return False (1 is not a prime number) return False # Check if 'n' is equal to 2 elif (n == 2): # If 'n' is 2, return True (2 is a prime number) return True else: # Iterate through numbers from 2 to (n-1) using 'x' as the iterator for x in range(2, n): # Check if 'n' is divisible by 'x' without any remainder if (n % x == 0): # If 'n' is divisible by 'x', return False (not a prime number) return False # If 'n' is not divisible by any number from 2 to (n-1), return True (prime number) return True # Print the result of checking if 9 is a prime number by calling the 'test_prime' function print(test_prime(9))",22,22 ,"class Solution { public boolean isSubsequence(String s1, String s2) { int m = s1.length(); int n = s2.length(); int j=0,i=0; while(i=n) return true; if(s1.charAt(i)==s2.charAt(j)){ i++; j++; } else i++; } if(j>=n) return true; return false; } public int numMatchingSubseq(String s1, String[] words) { int count = 0; HashMap map = new HashMap<>(); for (String w : words) map.put(w, map.getOrDefault(w, 0) + 1); for(String s2 : map.keySet()){ if(isSubsequence(s1,s2)) count+=map.get(s2); } return count; } }",0.0,leetcode,,java,"class Solution { public boolean isSubsequence(String s1, String s2) { int m = s1.length(); int n = s2.length(); int j=0,i=0; while(i=n) return true; if(s1.charAt(i)==s2.charAt(j)){ i++; j++; } else i++; } if(j>=n) return true; return false; } public int numMatchingSubseq(String s1, String[] words) { int count = 0; HashMap map = new HashMap<>(); for (String w : words) map.put(w, map.getOrDefault(w, 0) + 1); for(String s2 : map.keySet()){ if(isSubsequence(s1,s2)) count+=map.get(s2); } return count; } }",27,27 ,"public int romanToInt(String s) { int ans = 0, num = 0; for (int i = s.length()-1; i >= 0; i--) { switch(s.charAt(i)) { case 'I': num = 1; break; case 'V': num = 5; break; case 'X': num = 10; break; case 'L': num = 50; break; case 'C': num = 100; break; case 'D': num = 500; break; case 'M': num = 1000; break; } if (4 * num < ans) ans -= num; else ans += num; } return ans; }",0.0,leetcode,,java,"public int romanToInt(String s) { int ans = 0, num = 0; for (int i = s.length()-1; i >= 0; i--) { switch(s.charAt(i)) { case 'I': num = 1; break; case 'V': num = 5; break; case 'X': num = 10; break; case 'L': num = 50; break; case 'C': num = 100; break; case 'D': num = 500; break; case 'M': num = 1000; break; } if (4 * num < ans) ans -= num; else ans += num; } return ans; }",17,17 ,"static int[] prod(int[] a){ int n=a.length; int[] r=new int[n]; r[0]=1; for(int i=1;i=0;i--){ r[i]*=p; p*=a[i]; } return r; } ",1.0,GPT,Return an array where each element is product of all other elements without using division.,java,"static int[] prod(int[] a){ int n=a.length; int[] r=new int[n]; r[0]=1; for(int i=1;i=0;i--){ r[i]*=p; p*=a[i]; } return r; }",8,8 ,"// Define the Classroom class public class Classroom { // Private instance variables private String className; private String[] students; // Parameterized constructor that initializes className and students public Classroom(String className, String[] students) { // Initialize instance variables with provided parameters this.className = className; this.students = students; } // Method to print the values of className and students public void printClassroom() { System.out.println(""Class Name: "" + className); System.out.print(""Students: ""); for (String student : students) { System.out.print(student + "" ""); } System.out.println(); } // Main method to test the Classroom class public static void main(String[] args) { // Create an array of student names String[] studentArray = {""Andrine"", ""Ruslan"", ""Martin""}; // Create a Classroom object using the parameterized constructor Classroom classroom = new Classroom(""Science 101"", studentArray); // Print the values of the instance variables classroom.printClassroom(); } } ",0.0,WE3RESOURCE,,java,"// Define the Classroom class public class Classroom { // Private instance variables private String className; private String[] students; // Parameterized constructor that initializes className and students public Classroom(String className, String[] students) { // Initialize instance variables with provided parameters this.className = className; this.students = students; } // Method to print the values of className and students public void printClassroom() { System.out.println(""Class Name: "" + className); System.out.print(""Students: ""); for (String student : students) { System.out.print(student + "" ""); } System.out.println(); } // Main method to test the Classroom class public static void main(String[] args) { // Create an array of student names String[] studentArray = {""Andrine"", ""Ruslan"", ""Martin""}; // Create a Classroom object using the parameterized constructor Classroom classroom = new Classroom(""Science 101"", studentArray); // Print the values of the instance variables classroom.printClassroom(); } }",33,33 ," class RandomizedSet { private ArrayList list; private Map map; public RandomizedSet() { list = new ArrayList<>(); map = new HashMap<>(); } public boolean search(int val) { return map.containsKey(val); } public boolean insert(int val) { if (search(val)) return false; list.add(val); map.put(val, list.size() - 1); return true; } public boolean remove(int val) { if (!search(val)) return false; int index = map.get(val); list.set(index, list.get(list.size() - 1)); map.put(list.get(index), index); list.remove(list.size() - 1); map.remove(val); return true; } public int getRandom() { Random rand = new Random(); return list.get(rand.nextInt(list.size())); } } ",0.0,leetcode,,java,"class RandomizedSet { private ArrayList list; private Map map; public RandomizedSet() { list = new ArrayList<>(); map = new HashMap<>(); } public boolean search(int val) { return map.containsKey(val); } public boolean insert(int val) { if (search(val)) return false; list.add(val); map.put(val, list.size() - 1); return true; } public boolean remove(int val) { if (!search(val)) return false; int index = map.get(val); list.set(index, list.get(list.size() - 1)); map.put(list.get(index), index); list.remove(list.size() - 1); map.remove(val); return true; } public int getRandom() { Random rand = new Random(); return list.get(rand.nextInt(list.size())); } }",38,38 ,"static int ladder(String b,String e,List w){ Set s=new HashSet<>(w); Queue q=new LinkedList<>(); q.add(b); int lvl=1; while(!q.isEmpty()){ for(int i=q.size();i>0;i--){ String x=q.poll(); if(x.equals(e)) return lvl; for(int j=0;j w){ Set s=new HashSet<>(w); Queue q=new LinkedList<>(); q.add(b); int lvl=1; while(!q.isEmpty()){ for(int i=q.size();i>0;i--){ String x=q.poll(); if(x.equals(e)) return lvl; for(int j=0;j List[int]: n = len(temperatures) res = [0] * n for i in range(n - 2, -1, -1): j = i + 1 while j < n and temperatures[j] <= temperatures[i]: if res[j] == 0: j = n break j += res[j] if j < n: res[i] = j - i return res",0.0,GFG,,python,"class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: n = len(temperatures) res = [0] * n for i in range(n - 2, -1, -1): j = i + 1 while j < n and temperatures[j] <= temperatures[i]: if res[j] == 0: j = n break j += res[j] if j < n: res[i] = j - i return res",16,16 ,"public class Cube { public static void main(String arg[]) { int side=5; float volume=side * side * side; System.out.println(""Volume of Cube :""+ volume); } } ",0.0,IPSGWALIOR.ORG,,java,"public class Cube { public static void main(String arg[]) { int side=5; float volume=side * side * side; System.out.println(""Volume of Cube :""+ volume); } }",7,7 ,"class Solution { public String intToRoman(int num) { String Roman = """"; int[][] storeIntRoman = {{1000, ""M""}, {900, ""CM""}, {500, ""D""}, {400, ""CD""}, {100, ""C""}, {90, ""XC""}, {50, ""L""}, {40, ""XL""}, {10, ""X""}, {9, ""IX""}, {5, ""V""}, {4, ""IV""}, {1, ""I""}}; for (int i = 0; i < storeIntRoman.length; i++) { while (num >= storeIntRoman[i][0]) { Roman += storeIntRoman[i][1]; num -= storeIntRoman[i][0]; } } return Roman; } }",0.0,leetcode,,java,"class Solution { public String intToRoman(int num) { String Roman = """"; int[][] storeIntRoman = {{1000, ""M""}, {900, ""CM""}, {500, ""D""}, {400, ""CD""}, {100, ""C""}, {90, ""XC""}, {50, ""L""}, {40, ""XL""}, {10, ""X""}, {9, ""IX""}, {5, ""V""}, {4, ""IV""}, {1, ""I""}}; for (int i = 0; i < storeIntRoman.length; i++) { while (num >= storeIntRoman[i][0]) { Roman += storeIntRoman[i][1]; num -= storeIntRoman[i][0]; } } return Roman; } }",13,13 ,"class Solution { public String minWindow(String s, String t) { if (s == null || t == null || s.length() == 0 || t.length() == 0 || s.length() < t.length()) { return new String(); } int left = 0; int right = 0; int windowFreqArr[] = new int[256]; int targetFreqArr[] = new int[256]; int startIdx = -1; int minLength = Integer.MAX_VALUE; for (int i = 0; i < t.length(); i++) { char ch = t.charAt(i); targetFreqArr[ch]++; } int required = t.length(); for (right = 0; right < s.length(); right++) { char rightChar = s.charAt(right); windowFreqArr[rightChar]++; // If this character is needed (count > 0), decrement required if (targetFreqArr[rightChar] > 0) { required--; // One less character needed } targetFreqArr[rightChar]--; // When we have all characters, try to minimize window while (required == 0) { int length = right - left + 1; if (length < minLength) { minLength = length; startIdx = left; } // increment the left char leftChar = s.charAt(left); windowFreqArr[leftChar]--; left++; // If a needed character is removed, window becomes invalid targetFreqArr[leftChar]++; if (targetFreqArr[leftChar] > 0) { required++; // We now need this character again } } } return startIdx == -1 ? """" : s.substring(startIdx, startIdx + minLength); } }",0.0,leetcode,,java,"class Solution { public String minWindow(String s, String t) { if (s == null || t == null || s.length() == 0 || t.length() == 0 || s.length() < t.length()) { return new String(); } int left = 0; int right = 0; int windowFreqArr[] = new int[256]; int targetFreqArr[] = new int[256]; int startIdx = -1; int minLength = Integer.MAX_VALUE; for (int i = 0; i < t.length(); i++) { char ch = t.charAt(i); targetFreqArr[ch]++; } int required = t.length(); for (right = 0; right < s.length(); right++) { char rightChar = s.charAt(right); windowFreqArr[rightChar]++; // If this character is needed (count > 0), decrement required if (targetFreqArr[rightChar] > 0) { required--; // One less character needed } targetFreqArr[rightChar]--; // When we have all characters, try to minimize window while (required == 0) { int length = right - left + 1; if (length < minLength) { minLength = length; startIdx = left; } // increment the left char leftChar = s.charAt(left); windowFreqArr[leftChar]--; left++; // If a needed character is removed, window becomes invalid targetFreqArr[leftChar]++; if (targetFreqArr[leftChar] > 0) { required++; // We now need this character again } } } return startIdx == -1 ? """" : s.substring(startIdx, startIdx + minLength); } }",56,56 ,"class Solution { public List> findDuplicate(String[] paths) { List> al = new ArrayList<>(); HashMap> hashmap = new HashMap<>(); for(String path : paths) { String[] arr = path.split(""\\ ""); String dirPath = arr[0]; for(int i = 1; i < arr.length; i++) { StringBuilder content = new StringBuilder(); int j = 0; for(j = arr[i].length() - 2; j >= 0 && arr[i].charAt(j) != '('; j--) { content.insert(0, arr[i].charAt(j)); } String fileName = arr[i].substring(0, j); hashmap.putIfAbsent(content.toString(), new ArrayList<>()); hashmap.get(content.toString()).add(dirPath + ""/"" + fileName); } } for(String string : hashmap.keySet()) { if(hashmap.get(string).size() >= 2) { al.add(new ArrayList<>(hashmap.get(string))); } } return al; } }",0.0,leetcode,,java,"class Solution { public List> findDuplicate(String[] paths) { List> al = new ArrayList<>(); HashMap> hashmap = new HashMap<>(); for(String path : paths) { String[] arr = path.split(""\\ ""); String dirPath = arr[0]; for(int i = 1; i < arr.length; i++) { StringBuilder content = new StringBuilder(); int j = 0; for(j = arr[i].length() - 2; j >= 0 && arr[i].charAt(j) != '('; j--) { content.insert(0, arr[i].charAt(j)); } String fileName = arr[i].substring(0, j); hashmap.putIfAbsent(content.toString(), new ArrayList<>()); hashmap.get(content.toString()).add(dirPath + ""/"" + fileName); } } for(String string : hashmap.keySet()) { if(hashmap.get(string).size() >= 2) { al.add(new ArrayList<>(hashmap.get(string))); } } return al; } }",28,28 ,"# Import the Abstract Syntax Tree (AST) module import ast # Import the math module for mathematical functions and constants import math # Define a class for evaluating mathematical expressions class MathExpressionEvaluator: def __init__(self): pass # Method to evaluate mathematical expressions def evaluate(self, expression): try: # Parse the expression into an Abstract Syntax Tree (AST) parsed_expression = ast.parse(expression, mode='eval') # Define the allowed names (functions and constants) for evaluation allowed_names = { 'sin': math.sin, 'cos': math.cos, 'tan': math.tan, 'log': math.log, 'sqrt': math.sqrt, **vars(math) # Include all functions and constants from the math module } # Evaluate the AST using a custom namespace that includes the allowed names result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names) return result except SyntaxError: print(""Invalid expression syntax."") return None except Exception as e: print(""Error:"", e) return None # Example usage if __name__ == ""__main__"": evaluator = MathExpressionEvaluator() # Evaluate mathematical expressions print(""Evaluation Results:"") print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4"")) print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4"")) print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)"")) print(""log(10) ="", evaluator.evaluate(""log(10)""))",0.0,W3RESOURCE,,python,"# Import the Abstract Syntax Tree (AST) module import ast # Import the math module for mathematical functions and constants import math # Define a class for evaluating mathematical expressions class MathExpressionEvaluator: def __init__(self): pass # Method to evaluate mathematical expressions def evaluate(self, expression): try: # Parse the expression into an Abstract Syntax Tree (AST) parsed_expression = ast.parse(expression, mode='eval') # Define the allowed names (functions and constants) for evaluation allowed_names = { 'sin': math.sin, 'cos': math.cos, 'tan': math.tan, 'log': math.log, 'sqrt': math.sqrt, **vars(math) # Include all functions and constants from the math module } # Evaluate the AST using a custom namespace that includes the allowed names result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names) return result except SyntaxError: print(""Invalid expression syntax."") return None except Exception as e: print(""Error:"", e) return None # Example usage if __name__ == ""__main__"": evaluator = MathExpressionEvaluator() # Evaluate mathematical expressions print(""Evaluation Results:"") print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4"")) print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4"")) print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)"")) print(""log(10) ="", evaluator.evaluate(""log(10)""))",47,47 ,"public List topKFrequent(int[] nums, int k) { List[] bucket = new List[nums.length + 1]; Map frequencyMap = new HashMap(); for (int n : nums) { frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1); } for (int key : frequencyMap.keySet()) { int frequency = frequencyMap.get(key); if (bucket[frequency] == null) { bucket[frequency] = new ArrayList<>(); } bucket[frequency].add(key); } List res = new ArrayList<>(); for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) { if (bucket[pos] != null) { res.addAll(bucket[pos]); } } return res; }",0.0,leetcode,,java,"public List topKFrequent(int[] nums, int k) { List[] bucket = new List[nums.length + 1]; Map frequencyMap = new HashMap(); for (int n : nums) { frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1); } for (int key : frequencyMap.keySet()) { int frequency = frequencyMap.get(key); if (bucket[frequency] == null) { bucket[frequency] = new ArrayList<>(); } bucket[frequency].add(key); } List res = new ArrayList<>(); for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) { if (bucket[pos] != null) { res.addAll(bucket[pos]); } } return res; }",26,26 ,"class MapSum { Map map; public MapSum() { map = new HashMap<>(); } public void insert(String key, int val) { map.put(key, val); } public int sum(String prefix) { int sum = 0; for (String key : map.keySet()) { if (key.startsWith(prefix)) { sum += map.get(key); } } return sum; } }",0.0,leetcode,,java,"class MapSum { Map map; public MapSum() { map = new HashMap<>(); } public void insert(String key, int val) { map.put(key, val); } public int sum(String prefix) { int sum = 0; for (String key : map.keySet()) { if (key.startsWith(prefix)) { sum += map.get(key); } } return sum; } }",21,21 ,"class Solution { int[] arr; HashSet> hashSet = new HashSet<>(); public List> findSubsequences(int[] nums) { arr = nums; List arrayList = new ArrayList<>(); recursion(arrayList,0); List> result = new ArrayList<>(hashSet); return result; } public void recursion(List arrayList, int index){ if(arrayList.size()>=2) hashSet.add(new ArrayList(arrayList)); for(int i = index;i= arrayList.get(arrayList.size()-1)){ arrayList.add(arr[i]); recursion(arrayList,i+1); arrayList.remove(arrayList.size()-1); } } } }",0.0,leetcode,,java,"class Solution { int[] arr; HashSet> hashSet = new HashSet<>(); public List> findSubsequences(int[] nums) { arr = nums; List arrayList = new ArrayList<>(); recursion(arrayList,0); List> result = new ArrayList<>(hashSet); return result; } public void recursion(List arrayList, int index){ if(arrayList.size()>=2) hashSet.add(new ArrayList(arrayList)); for(int i = index;i= arrayList.get(arrayList.size()-1)){ arrayList.add(arr[i]); recursion(arrayList,i+1); arrayList.remove(arrayList.size()-1); } } } }",24,24 ,"import numpy as np arr = np.array([9, 3, 5, 1, 8, 2, 7]) n = 4 # Number of elements to sort from the beginning # Sort the first n elements sorted_part = np.sort(arr[:n]) # Concatenate sorted part with the rest of the array result = np.concatenate((sorted_part, arr[n:])) print(""Array after sorting first"", n, ""elements:"", result)",1.0,DEEPAI,Write a NumPy program to sort the specified number of elements from beginning of a given array.,python,"import numpy as np arr = np.array([9, 3, 5, 1, 8, 2, 7]) n = 4 # Number of elements to sort from the beginning # Sort the first n elements sorted_part = np.sort(arr[:n]) # Concatenate sorted part with the rest of the array result = np.concatenate((sorted_part, arr[n:])) print(""Array after sorting first"", n, ""elements:"", result)",12,12 ,"static boolean canFinish(int n,int[][] p){ List[] g=new ArrayList[n]; for(int i=0;i(); int[] in=new int[n]; for(int[] e:p){ g[e[1]].add(e[0]); in[e[0]]++; } Queue q=new LinkedList<>(); for(int i=0;i[] g=new ArrayList[n]; for(int i=0;i(); int[] in=new int[n]; for(int[] e:p){ g[e[1]].add(e[0]); in[e[0]]++; } Queue q=new LinkedList<>(); for(int i=0;i map; while (remainder != 0) { if (map.count(remainder)) { fraction.insert(map[remainder], ""(""); fraction += "")""; break; } map[remainder] = fraction.size(); remainder *= 10; fraction += to_string(remainder / divisor); remainder %= divisor; } return fraction; } };",0.0,leetcode,,java,"class Solution { public: string fractionToDecimal(int numerator, int denominator) { if (numerator == 0) return ""0""; string fraction; if ((numerator < 0) ^ (denominator < 0)) fraction += ""-""; long long dividend = llabs((long long)numerator); long long divisor = llabs((long long)denominator); fraction += to_string(dividend / divisor); long long remainder = dividend % divisor; if (remainder == 0) { return fraction; } fraction += "".""; unordered_map map; while (remainder != 0) { if (map.count(remainder)) { fraction.insert(map[remainder], ""(""); fraction += "")""; break; } map[remainder] = fraction.size(); remainder *= 10; fraction += to_string(remainder / divisor); remainder %= divisor; } return fraction; } };",35,35 ,"package SystemDesign.Easy; public class _705_Design_HashSet { // Custom HashSet implementation using bitset private static class MyHashSet { // Each int holds 32 bits → supports keys up to 10^6 private final int[] set; public MyHashSet() { // 10^6 / 32 ≈ 31250 this.set = new int[31251]; } public void add(int key) { set[key / 32] |= getMask(key); } public void remove(int key) { if (contains(key)) { set[key / 32] ^= getMask(key); } } public boolean contains(int key) { return (set[key / 32] & getMask(key)) != 0; } // Returns a bit mask for the given key private int getMask(int key) { return 1 << (key % 32); } } }",0.0,leetcode,,java,"package SystemDesign.Easy; public class _705_Design_HashSet { // Custom HashSet implementation using bitset private static class MyHashSet { // Each int holds 32 bits → supports keys up to 10^6 private final int[] set; public MyHashSet() { // 10^6 / 32 ≈ 31250 this.set = new int[31251]; } public void add(int key) { set[key / 32] |= getMask(key); } public void remove(int key) { if (contains(key)) { set[key / 32] ^= getMask(key); } } public boolean contains(int key) { return (set[key / 32] & getMask(key)) != 0; } // Returns a bit mask for the given key private int getMask(int key) { return 1 << (key % 32); } } }",35,35 ,"static String alien(String[] w){ Map> g=new HashMap<>(); Map in=new HashMap<>(); for(String s:w) for(char c:s.toCharArray()){g.putIfAbsent(c,new HashSet<>());in.putIfAbsent(c,0);} for(int i=0;i q=new LinkedList<>(); for(char c:in.keySet()) if(in.get(c)==0) q.add(c); StringBuilder r=new StringBuilder(); while(!q.isEmpty()){ char c=q.poll(); r.append(c); for(char n:g.get(c)) if(in.put(n,in.get(n)-1)==1) q.add(n); } return r.toString(); } ",1.0,GPT,give me an java code to Find character order from sorted alien words.,java,"static String alien(String[] w){ Map> g=new HashMap<>(); Map in=new HashMap<>(); for(String s:w) for(char c:s.toCharArray()){g.putIfAbsent(c,new HashSet<>());in.putIfAbsent(c,0);} for(int i=0;i q=new LinkedList<>(); for(char c:in.keySet()) if(in.get(c)==0) q.add(c); StringBuilder r=new StringBuilder(); while(!q.isEmpty()){ char c=q.poll(); r.append(c); for(char n:g.get(c)) if(in.put(n,in.get(n)-1)==1) q.add(n); } return r.toString(); }",20,20 ,"public class StringReverse { public static void main(String args[]) { String string = ""Welcome to Java Programming and Dotnet Programming""; String[] wordsCount = string.split("" ""); System.out.println(""The Given String is:\n"" + string + ""\n""); System.out.println(""After Reverse String is:""); for(int i = wordsCount.length;i > 0;i--) { System.out.print(wordsCount[i - 1] + "" ""); } } }",0.0,IPSGWALIOR.ORG,,java,"public class StringReverse { public static void main(String args[]) { String string = ""Welcome to Java Programming and Dotnet Programming""; String[] wordsCount = string.split("" ""); System.out.println(""The Given String is:\n"" + string + ""\n""); System.out.println(""After Reverse String is:""); for(int i = wordsCount.length;i > 0;i--) { System.out.print(wordsCount[i - 1] + "" ""); } } }",16,16 ,"import java.util.concurrent.ConcurrentLinkedQueue; public class ConcurrentQueueExercise { public static void main(String[] args) { ConcurrentLinkedQueue < String > queue = new ConcurrentLinkedQueue < > (); // Create and start the producer threads Thread producerThread1 = new Thread(new Producer(queue, ""Producer-1"")); Thread producerThread2 = new Thread(new Producer(queue, ""Producer-2"")); producerThread1.start(); producerThread2.start(); // Create and start the consumer threads Thread consumerThread1 = new Thread(new Consumer(queue, ""Consumer-1"")); Thread consumerThread2 = new Thread(new Consumer(queue, ""Consumer-2"")); consumerThread1.start(); consumerThread2.start(); } static class Producer implements Runnable { private ConcurrentLinkedQueue < String > queue; private String producerName; private int counter; public Producer(ConcurrentLinkedQueue < String > queue, String producerName) { this.queue = queue; this.producerName = producerName; this.counter = 0; } public void run() { while (true) { String item = producerName + ""-Item-"" + counter++; queue.offer(item); System.out.println(""Produced: "" + item); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class Consumer implements Runnable { private ConcurrentLinkedQueue < String > queue; private String consumerName; public Consumer(ConcurrentLinkedQueue < String > queue, String consumerName) { this.queue = queue; this.consumerName = consumerName; } public void run() { while (true) { String item = queue.poll(); if (item != null) { System.out.println(consumerName + "" consumed: "" + item); } try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } } } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.ConcurrentLinkedQueue; public class ConcurrentQueueExercise { public static void main(String[] args) { ConcurrentLinkedQueue < String > queue = new ConcurrentLinkedQueue < > (); // Create and start the producer threads Thread producerThread1 = new Thread(new Producer(queue, ""Producer-1"")); Thread producerThread2 = new Thread(new Producer(queue, ""Producer-2"")); producerThread1.start(); producerThread2.start(); // Create and start the consumer threads Thread consumerThread1 = new Thread(new Consumer(queue, ""Consumer-1"")); Thread consumerThread2 = new Thread(new Consumer(queue, ""Consumer-2"")); consumerThread1.start(); consumerThread2.start(); } static class Producer implements Runnable { private ConcurrentLinkedQueue < String > queue; private String producerName; private int counter; public Producer(ConcurrentLinkedQueue < String > queue, String producerName) { this.queue = queue; this.producerName = producerName; this.counter = 0; } public void run() { while (true) { String item = producerName + ""-Item-"" + counter++; queue.offer(item); System.out.println(""Produced: "" + item); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class Consumer implements Runnable { private ConcurrentLinkedQueue < String > queue; private String consumerName; public Consumer(ConcurrentLinkedQueue < String > queue, String consumerName) { this.queue = queue; this.consumerName = consumerName; } public void run() { while (true) { String item = queue.poll(); if (item != null) { System.out.println(consumerName + "" consumed: "" + item); } try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } } } } }",70,70 ,"public class PrimeChecker { public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } } ",1.0,PERPLEXITY,"Write an efficient Java method to check if a number is prime, optimized for large inputs.",java,"public class PrimeChecker { public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } }",11,11 ,"import requests from lxml import html url = 'https://www.state.gov/r/pa/ode/socialmedia/' doc = html.fromstring(requests.get(url).text) pinterest_links = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))] print(f""Number of Pinterest accounts: {len(pinterest_links)}"") ",1.0,PERPLEXITY," Write a Python program to get the number of Pinterest accounts maintained by U.S. State Department embassies and missions. Source: https://www.state.gov/r/pa/ode/socialmedia/",python,"import requests from lxml import html url = 'https://www.state.gov/r/pa/ode/socialmedia/' doc = html.fromstring(requests.get(url).text) pinterest_links = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))] print(f""Number of Pinterest accounts: {len(pinterest_links)}"")",7,7 ,"class Solution { public int[] intersect(int[] nums1, int[] nums2) { int l1 = nums1.length; int l2 = nums2.length; int i = 0, j = 0, k = 0; Arrays.sort(nums1); Arrays.sort(nums2); while( i < l1 && j < l2) { if(nums1[i] < nums2[j]) { i++; } else if(nums1[i] > nums2[j]) { j++; } else { nums1[k++] = nums1[i++]; j++; } } return Arrays.copyOfRange(nums1,0,k); } }",0.0,leetcode,,java,"class Solution { public int[] intersect(int[] nums1, int[] nums2) { int l1 = nums1.length; int l2 = nums2.length; int i = 0, j = 0, k = 0; Arrays.sort(nums1); Arrays.sort(nums2); while( i < l1 && j < l2) { if(nums1[i] < nums2[j]) { i++; } else if(nums1[i] > nums2[j]) { j++; } else { nums1[k++] = nums1[i++]; j++; } } return Arrays.copyOfRange(nums1,0,k); } }",26,26 ,"import heapq def astar(start, goal, g, h): pq = [(h(start), 0, start, [start])] seen = set() while pq: f,c,u,p = heapq.heappop(pq) if u == goal: return p, c if u in seen: continue seen.add(u) for v,w in g[u]: heapq.heappush(pq,(c+w+h(v), c+w, v, p+[v])) # ---------- INPUT ---------- graph = { 'A':[('B',1),('C',3)], 'B':[('D',1),('E',4)], 'C':[('F',5)], 'D':[('G',1)], 'E':[('G',1)], 'F':[('G',1)], 'G':[] } heuristic = {'A':5,'B':4,'C':4,'D':2,'E':2,'F':3,'G':0} path, cost = astar('A','G',graph,lambda n: heuristic[n]) # ---------- OUTPUT ---------- print(""Path:"", path) print(""Cost:"", cost) ",1.0,GPT,give me the code for A* Search Algorithm in shorter lines to implement it with i/o,python,"import heapq def astar(start, goal, g, h): pq = [(h(start), 0, start, [start])] seen = set() while pq: f,c,u,p = heapq.heappop(pq) if u == goal: return p, c if u in seen: continue seen.add(u) for v,w in g[u]: heapq.heappush(pq,(c+w+h(v), c+w, v, p+[v])) # ---------- INPUT ---------- graph = { 'A':[('B',1),('C',3)], 'B':[('D',1),('E',4)], 'C':[('F',5)], 'D':[('G',1)], 'E':[('G',1)], 'F':[('G',1)], 'G':[] } heuristic = {'A':5,'B':4,'C':4,'D':2,'E':2,'F':3,'G':0} path, cost = astar('A','G',graph,lambda n: heuristic[n]) # ---------- OUTPUT ---------- print(""Path:"", path) print(""Cost:"", cost)",30,30 ,"import json def has_complex_structure(data): """""" Recursively checks if a Python object contains nested collections (dict or list). """""" # If the root is a list, check its elements if isinstance(data, list): for item in data: if isinstance(item, (dict, list)): return True return False # If the root is a dict, check if any value is a dict or list if isinstance(data, dict): for value in data.values(): if isinstance(value, (dict, list)): return True return False def check_json_complexity(json_str): try: parsed = json.loads(json_str) if has_complex_structure(parsed): print(""Complexity Found: This JSON contains nested objects/arrays."") else: print(""Simple JSON: This is a flat key-value structure."") except json.JSONDecodeError: print(""Invalid JSON string."") # --- Test Cases --- simple_json = '{""name"": ""Alice"", ""age"": 30}' complex_json = '{""user"": {""id"": 1, ""name"": ""Alice""}, ""tags"": [""admin"", ""dev""]}' print(""Checking simple_json:"") check_json_complexity(simple_json) print(""\nChecking complex_json:"") check_json_complexity(complex_json)",1.0,GEMINI,Write a Python program to check whether a JSON string contains complex object or not,python,"import json def has_complex_structure(data): """""" Recursively checks if a Python object contains nested collections (dict or list). """""" # If the root is a list, check its elements if isinstance(data, list): for item in data: if isinstance(item, (dict, list)): return True return False # If the root is a dict, check if any value is a dict or list if isinstance(data, dict): for value in data.values(): if isinstance(value, (dict, list)): return True return False def check_json_complexity(json_str): try: parsed = json.loads(json_str) if has_complex_structure(parsed): print(""Complexity Found: This JSON contains nested objects/arrays."") else: print(""Simple JSON: This is a flat key-value structure."") except json.JSONDecodeError: print(""Invalid JSON string."") # --- Test Cases --- simple_json = '{""name"": ""Alice"", ""age"": 30}' complex_json = '{""user"": {""id"": 1, ""name"": ""Alice""}, ""tags"": [""admin"", ""dev""]}' print(""Checking simple_json:"") check_json_complexity(simple_json) print(""\nChecking complex_json:"") check_json_complexity(complex_json)",42,42 ,"#https://bit.ly/2lVhlLX import requests from lxml import html url = 'https://www.us-cert.gov/ncas/alerts' doc = html.fromstring(requests.get(url).text) print(""The number of security alerts issued by US-CERT in the current year:"") print(len(doc.cssselect('.item-list li'))) ",0.0,WE3RESOURCE,,python,"#https://bit.ly/2lVhlLX import requests from lxml import html url = 'https://www.us-cert.gov/ncas/alerts' doc = html.fromstring(requests.get(url).text) print(""The number of security alerts issued by US-CERT in the current year:"") print(len(doc.cssselect('.item-list li')))",7,7 ,"import java.util.Comparator; import java.util.PriorityQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class PriorityMessageQueue { private final PriorityQueue> queue; private final ReentrantLock lock; private final Condition notEmpty; private final Condition notFull; private final int maxCapacity; private volatile boolean shutdown; public enum Priority { HIGH, MEDIUM, LOW } private static class Message { final T payload; final Priority priority; final long timestamp; final String messageId; int deliveryAttempts; Message(T payload, Priority priority) { this.payload = payload; this.priority = priority; this.timestamp = System.currentTimeMillis(); this.messageId = java.util.UUID.randomUUID().toString(); this.deliveryAttempts = 0; } long getPriorityScore() { long priorityMultiplier; switch (priority) { case HIGH: priorityMultiplier = 1000; break; case MEDIUM: priorityMultiplier = 100; break; default: priorityMultiplier = 1; } return timestamp / priorityMultiplier; } } private static class MessageComparator implements Comparator> { @Override public int compare(Message m1, Message m2) { return Long.compare(m1.getPriorityScore(), m2.getPriorityScore()); } } public PriorityMessageQueue(int maxCapacity) { this.maxCapacity = maxCapacity; this.queue = new PriorityQueue<>(new MessageComparator<>()); this.lock = new ReentrantLock(); this.notEmpty = lock.newCondition(); this.notFull = lock.newCondition(); this.shutdown = false; } public boolean enqueue(T payload, Priority priority) { return enqueue(payload, priority, -1, TimeUnit.MILLISECONDS); } public boolean enqueue(T payload, Priority priority, long timeout, TimeUnit unit) { if (payload == null) throw new NullPointerException(); if (shutdown) throw new IllegalStateException(""Queue is shutdown""); lock.lock(); try { long nanos = unit.toNanos(timeout); while (queue.size() >= maxCapacity && !shutdown) { if (nanos <= 0) { return false; } nanos = notFull.awaitNanos(nanos); } if (shutdown) return false; Message message = new Message<>(payload, priority); queue.offer(message); notEmpty.signal(); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } finally { lock.unlock(); } } public Message dequeue() throws InterruptedException { return dequeue(-1, TimeUnit.MILLISECONDS); } public Message dequeue(long timeout, TimeUnit unit) throws InterruptedException { lock.lock(); try { long nanos = unit.toNanos(timeout); while (queue.isEmpty() && !shutdown) { if (nanos <= 0) { return null; } nanos = notEmpty.awaitNanos(nanos); } if (queue.isEmpty() && shutdown) { return null; } Message message = queue.poll(); notFull.signal(); if (message != null) { message.deliveryAttempts++; } return message; } finally { lock.unlock(); } } public void acknowledge(String messageId) { // In a real implementation, this would track delivery status // For simplicity, we just remove from queue lock.lock(); try { queue.removeIf(msg -> msg.messageId.equals(messageId)); notFull.signal(); } finally { lock.unlock(); } } public void requeue(Message message) { lock.lock(); try { if (message.deliveryAttempts < 3) { queue.offer(message); notEmpty.signal(); } else { // Move to dead letter queue or log System.err.println(""Message "" + message.messageId + "" exceeded max delivery attempts""); } } finally { lock.unlock(); } } public int size() { lock.lock(); try { return queue.size(); } finally { lock.unlock(); } } public boolean isEmpty() { lock.lock(); try { return queue.isEmpty(); } finally { lock.unlock(); } } public void shutdown() { lock.lock(); try { shutdown = true; notEmpty.signalAll(); notFull.signalAll(); } finally { lock.unlock(); } } public void clear() { lock.lock(); try { queue.clear(); notFull.signalAll(); } finally { lock.unlock(); } } }",1.0,DEEPSEEK,Create a thread-safe message queue with priority levels and delivery guarantees.,java,"import java.util.Comparator; import java.util.PriorityQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class PriorityMessageQueue { private final PriorityQueue> queue; private final ReentrantLock lock; private final Condition notEmpty; private final Condition notFull; private final int maxCapacity; private volatile boolean shutdown; public enum Priority { HIGH, MEDIUM, LOW } private static class Message { final T payload; final Priority priority; final long timestamp; final String messageId; int deliveryAttempts; Message(T payload, Priority priority) { this.payload = payload; this.priority = priority; this.timestamp = System.currentTimeMillis(); this.messageId = java.util.UUID.randomUUID().toString(); this.deliveryAttempts = 0; } long getPriorityScore() { long priorityMultiplier; switch (priority) { case HIGH: priorityMultiplier = 1000; break; case MEDIUM: priorityMultiplier = 100; break; default: priorityMultiplier = 1; } return timestamp / priorityMultiplier; } } private static class MessageComparator implements Comparator> { @Override public int compare(Message m1, Message m2) { return Long.compare(m1.getPriorityScore(), m2.getPriorityScore()); } } ... truncated ... notEmpty.signal(); } else { // Move to dead letter queue or log System.err.println(""Message "" + message.messageId + "" exceeded max delivery attempts""); } } finally { lock.unlock(); } } public int size() { lock.lock(); try { return queue.size(); } finally { lock.unlock(); } } public boolean isEmpty() { lock.lock(); try { return queue.isEmpty(); } finally { lock.unlock(); } } public void shutdown() { lock.lock(); try { shutdown = true; notEmpty.signalAll(); notFull.signalAll(); } finally { lock.unlock(); } } public void clear() { lock.lock(); try { queue.clear(); notFull.signalAll(); } finally { lock.unlock(); } } }",195,101 ,"class Solution { public boolean checkSubarraySum(int[] nums, int k) { // maintain a hash map to store Map map = new HashMap<>(); int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; sum %= k; // case 1 if (sum == 0 && i > 0) { return true; } // case 2 if (map.containsKey(sum) && i - map.get(sum) > 1) { return true; } if (!map.containsKey(sum)) { map.put(sum, i); } } return false; } }",0.0,leetcode,,java,"class Solution { public boolean checkSubarraySum(int[] nums, int k) { // maintain a hash map to store Map map = new HashMap<>(); int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; sum %= k; // case 1 if (sum == 0 && i > 0) { return true; } // case 2 if (map.containsKey(sum) && i - map.get(sum) > 1) { return true; } if (!map.containsKey(sum)) { map.put(sum, i); } } return false; } }",24,24 ,"class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: count = {} freq = [[] for i in range(len(nums) + 1)] for num in nums: count[num] = 1 + count.get(num, 0) for num, cnt in count.items(): freq[cnt].append(num) res = [] for i in range(len(freq) - 1, 0, -1): for num in freq[i]: res.append(num) if len(res) == k: return res",0.0,GFG,,python,"class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: count = {} freq = [[] for i in range(len(nums) + 1)] for num in nums: count[num] = 1 + count.get(num, 0) for num, cnt in count.items(): freq[cnt].append(num) res = [] for i in range(len(freq) - 1, 0, -1): for num in freq[i]: res.append(num) if len(res) == k: return res",16,16 ,"import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; public class HttpGetClient { public static String get(String url) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); return response.body(); } } ",1.0,PERPLEXITY,Write a Java method using HttpClient to make a GET request and return the response body as string,java,"import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; public class HttpGetClient { public static String get(String url) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); return response.body(); } }",16,16 ,"class Solution { public int numFactoredBinaryTrees(int[] arr) { Arrays.sort(arr); Map subtreeCount = new HashMap<>(); for (int root : arr) { subtreeCount.put(root, 1L); for (int factor : arr) { if (factor >= root) { break; } if (root % factor == 0 && subtreeCount.containsKey(root / factor)) { subtreeCount.put(root, (subtreeCount.get(root) + subtreeCount.get(factor) * subtreeCount.get(root / factor))); } } } long totalTrees = 0L; for (int key : subtreeCount.keySet()) { totalTrees = (totalTrees + subtreeCount.get(key)) % 1_000_000_007; } return (int) totalTrees; } }",0.0,leetcode,,java,"class Solution { public int numFactoredBinaryTrees(int[] arr) { Arrays.sort(arr); Map subtreeCount = new HashMap<>(); for (int root : arr) { subtreeCount.put(root, 1L); for (int factor : arr) { if (factor >= root) { break; } if (root % factor == 0 && subtreeCount.containsKey(root / factor)) { subtreeCount.put(root, (subtreeCount.get(root) + subtreeCount.get(factor) * subtreeCount.get(root / factor))); } } } long totalTrees = 0L; for (int key : subtreeCount.keySet()) { totalTrees = (totalTrees + subtreeCount.get(key)) % 1_000_000_007; } return (int) totalTrees; } }",27,27 ,"def selectionSort(nlist): for fillslot in range(len(nlist)-1,0,-1): maxpos=0 for location in range(1,fillslot+1): if nlist[location]>nlist[maxpos]: maxpos = location temp = nlist[fillslot] nlist[fillslot] = nlist[maxpos] nlist[maxpos] = temp nlist = [14,46,43,27,57,41,45,21,70] selectionSort(nlist) print(nlist) ",0.0,W3RESOURCE,,python,"def selectionSort(nlist): for fillslot in range(len(nlist)-1,0,-1): maxpos=0 for location in range(1,fillslot+1): if nlist[location]>nlist[maxpos]: maxpos = location temp = nlist[fillslot] nlist[fillslot] = nlist[maxpos] nlist[maxpos] = temp nlist = [14,46,43,27,57,41,45,21,70] selectionSort(nlist) print(nlist)",14,14 ,"def invertTree(root): if not root: return None root.left, root.right = invertTree(root.right), invertTree(root.left) return root ",1.0,GPT,"Solve the problem ""Invert Binary Tree"". Given the root of a binary tree, invert the tree and return its root. Provide Python solution. ",python,"def invertTree(root): if not root: return None root.left, root.right = invertTree(root.right), invertTree(root.left) return root",6,6 ,"import java.util.concurrent.*; public class CallableFutureExercise { public static void main(String[] args) { // Create a thread pool with a single worker thread ExecutorService executor = Executors.newSingleThreadExecutor(); // Submit a Callable task to the executor Future < String > future = executor.submit(new Task()); // Perform other operations while the task is executing try { // Wait for the task to complete and get the result String result = future.get(); System.out.println(""Task result: "" + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } // Shutdown the executor executor.shutdown(); } static class Task implements Callable < String > { @Override public String call() throws Exception { // Perform the task and return the result Thread.sleep(2000); // Simulate some time-consuming operation return ""Task completed!""; } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.*; public class CallableFutureExercise { public static void main(String[] args) { // Create a thread pool with a single worker thread ExecutorService executor = Executors.newSingleThreadExecutor(); // Submit a Callable task to the executor Future < String > future = executor.submit(new Task()); // Perform other operations while the task is executing try { // Wait for the task to complete and get the result String result = future.get(); System.out.println(""Task result: "" + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } // Shutdown the executor executor.shutdown(); } static class Task implements Callable < String > { @Override public String call() throws Exception { // Perform the task and return the result Thread.sleep(2000); // Simulate some time-consuming operation return ""Task completed!""; } } }",35,35 ,"import requests url = ""https://www.example.com"" # Send GET request response = requests.get(url) print(""URL:"", response.url) print(""Status Code:"", response.status_code) print(""Reason:"", response.reason) print(""Encoding:"", response.encoding) print(""\nHeaders:"") for key, value in response.headers.items(): print(f""{key}: {value}"") print(""\nHistory (Redirects):"") print(response.history) print(""\nCookies:"") print(response.cookies) print(""\nElapsed Time:"") print(response.elapsed) print(""\nRequest Info:"") print(""Method:"", response.request.method) print(""Request URL:"", response.request.url) print(""Request Headers:"", response.request.headers) print(""\nContent (first 500 bytes):"") print(response.content[:500]) ",1.0,GPT," Write a Python program to display the contains of different attributes like different attributes like status_code, headers, url, history, encoding, reason, cookies, elapsed, request and content of a specified resource.",python,"import requests url = ""https://www.example.com"" # Send GET request response = requests.get(url) print(""URL:"", response.url) print(""Status Code:"", response.status_code) print(""Reason:"", response.reason) print(""Encoding:"", response.encoding) print(""\nHeaders:"") for key, value in response.headers.items(): print(f""{key}: {value}"") print(""\nHistory (Redirects):"") print(response.history) print(""\nCookies:"") print(response.cookies) print(""\nElapsed Time:"") print(response.elapsed) print(""\nRequest Info:"") print(""Method:"", response.request.method) print(""Request URL:"", response.request.url) print(""Request Headers:"", response.request.headers) print(""\nContent (first 500 bytes):"") print(response.content[:500])",32,32 ,"// Simple BFS approach (can TLE on large inputs) class Solution { public List> findLadders(String beginWord, String endWord, List wordList) { Queue> q = new ArrayDeque<>(); Set set = new HashSet<>(wordList); List> ans = new ArrayList<>(); if (!set.contains(endWord)) return ans; q.add(new ArrayList<>(List.of(beginWord))); boolean found = false; while (!q.isEmpty() && !found) { int size = q.size(); Set used = new HashSet<>(); for (int k = 0; k < size; k++) { List path = q.poll(); String last = path.get(path.size() - 1); if (last.equals(endWord)) { ans.add(path); found = true; } char[] arr = last.toCharArray(); for (int i = 0; i < arr.length; i++) { char original = arr[i]; for (char c = 'a'; c <= 'z'; c++) { if (c == original) continue; arr[i] = c; String next = new String(arr); if (set.contains(next)) { List newPath = new ArrayList<>(path); newPath.add(next); q.add(newPath); used.add(next); } } arr[i] = original; } } for (String w : used) set.remove(w); } return ans; } }",0.0,leetcode,,java,"// Simple BFS approach (can TLE on large inputs) class Solution { public List> findLadders(String beginWord, String endWord, List wordList) { Queue> q = new ArrayDeque<>(); Set set = new HashSet<>(wordList); List> ans = new ArrayList<>(); if (!set.contains(endWord)) return ans; q.add(new ArrayList<>(List.of(beginWord))); boolean found = false; while (!q.isEmpty() && !found) { int size = q.size(); Set used = new HashSet<>(); for (int k = 0; k < size; k++) { List path = q.poll(); String last = path.get(path.size() - 1); if (last.equals(endWord)) { ans.add(path); found = true; } char[] arr = last.toCharArray(); for (int i = 0; i < arr.length; i++) { char original = arr[i]; for (char c = 'a'; c <= 'z'; c++) { if (c == original) continue; arr[i] = c; String next = new String(arr); if (set.contains(next)) { List newPath = new ArrayList<>(path); newPath.add(next); q.add(newPath); used.add(next); } } arr[i] = original; } } for (String w : used) set.remove(w); } return ans; } }",48,48 ,"public List> groupAnagrams(String[] strs) { Map> map = new HashMap<>(); for (String s : strs) { char[] ca = s.toCharArray(); Arrays.sort(ca); String key = String.valueOf(ca); map.computeIfAbsent(key, k -> new ArrayList<>()).add(s); } return new ArrayList<>(map.values()); }",1.0,GEMINI,"Given an array of strings, group anagrams together.",java,"public List> groupAnagrams(String[] strs) { Map> map = new HashMap<>(); for (String s : strs) { char[] ca = s.toCharArray(); Arrays.sort(ca); String key = String.valueOf(ca); map.computeIfAbsent(key, k -> new ArrayList<>()).add(s); } return new ArrayList<>(map.values()); }",10,10 ,"class Solution { /* * Disjoint Set Union over emails. * Each unique email is treated as a node. */ static class DSU { int[] parent; int[] size; /* * Initializes DSU with each email in its own set. */ DSU(int n) { parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } /* * Returns representative of the email's component. * Uses path compression to keep tree shallow. */ int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } /* * Merges two email components using union by size. */ void union(int a, int b) { int pa = find(a); int pb = find(b); if (pa == pb) return; if (size[pa] < size[pb]) { parent[pa] = pb; size[pb] += size[pa]; } else { parent[pb] = pa; size[pa] += size[pb]; } } } /* * Merges accounts that share at least one common email. * Emails in the result are sorted lexicographically. */ public List> accountsMerge(List> accounts) { /* * Maps each email to a unique DSU index. * Also keeps track of the owner name for each email. */ Map emailIndex = new HashMap<>(); Map emailName = new HashMap<>(); int idx = 0; for (List acc : accounts) { String name = acc.get(0); for (int i = 1; i < acc.size(); i++) { String email = acc.get(i); if (!emailIndex.containsKey(email)) { emailIndex.put(email, idx++); emailName.put(email, name); } } } DSU dsu = new DSU(idx); /* * Union all emails belonging to the same account. */ for (List acc : accounts) { int firstEmail = emailIndex.get(acc.get(1)); for (int i = 2; i < acc.size(); i++) { dsu.union(firstEmail, emailIndex.get(acc.get(i))); } } /* * Groups emails by their DSU representative. */ Map> groups = new HashMap<>(); for (String email : emailIndex.keySet()) { int root = dsu.find(emailIndex.get(email)); groups.computeIfAbsent(root, k -> new ArrayList<>()).add(email); } /* * Builds the final merged account list. */ List> result = new ArrayList<>(); for (List emails : groups.values()) { Collections.sort(emails); List merged = new ArrayList<>(); merged.add(emailName.get(emails.get(0))); merged.addAll(emails); result.add(merged); } return result; } }",0.0,leetcode,,java,"class Solution { /* * Disjoint Set Union over emails. * Each unique email is treated as a node. */ static class DSU { int[] parent; int[] size; /* * Initializes DSU with each email in its own set. */ DSU(int n) { parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } /* * Returns representative of the email's component. * Uses path compression to keep tree shallow. */ int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } /* * Merges two email components using union by size. */ void union(int a, int b) { int pa = find(a); int pb = find(b); if (pa == pb) return; if (size[pa] < size[pb]) { parent[pa] = pb; size[pb] += size[pa]; } else { parent[pb] = pa; size[pa] += size[pb]; ... truncated ... String email = acc.get(i); if (!emailIndex.containsKey(email)) { emailIndex.put(email, idx++); emailName.put(email, name); } } } DSU dsu = new DSU(idx); /* * Union all emails belonging to the same account. */ for (List acc : accounts) { int firstEmail = emailIndex.get(acc.get(1)); for (int i = 2; i < acc.size(); i++) { dsu.union(firstEmail, emailIndex.get(acc.get(i))); } } /* * Groups emails by their DSU representative. */ Map> groups = new HashMap<>(); for (String email : emailIndex.keySet()) { int root = dsu.find(emailIndex.get(email)); groups.computeIfAbsent(root, k -> new ArrayList<>()).add(email); } /* * Builds the final merged account list. */ List> result = new ArrayList<>(); for (List emails : groups.values()) { Collections.sort(emails); List merged = new ArrayList<>(); merged.add(emailName.get(emails.get(0))); merged.addAll(emails); result.add(merged); } return result; } }",123,101 ,"import requests API_KEY = ""YOUR_API_KEY_HERE"" # <-- put your API key here city = input(""Enter city name: "") url = ""https://api.openweathermap.org/data/2.5/weather"" params = { ""q"": city, ""appid"": API_KEY, ""units"": ""metric"" # Celsius } try: r = requests.get(url, params=params, timeout=10) r.raise_for_status() data = r.json() temp = data[""main""][""temp""] wind = data[""wind""][""speed""] weather = data[""weather""][0][""main""] desc = data[""weather""][0][""description""] print(""\nLive Weather Report"") print(""-------------------"") print(""City :"", city) print(""Temperature :"", temp, ""°C"") print(""Wind Speed :"", wind, ""m/s"") print(""Weather :"", weather) print(""Description :"", desc) except requests.exceptions.RequestException as e: print(""Error fetching weather data:"", e) ",1.0,GPT," Write a Python program to find the live weather report (temperature, wind speed, description and weather) of a given city.let the code u give me be efficient and clear ",python,"import requests API_KEY = ""YOUR_API_KEY_HERE"" # <-- put your API key here city = input(""Enter city name: "") url = ""https://api.openweathermap.org/data/2.5/weather"" params = { ""q"": city, ""appid"": API_KEY, ""units"": ""metric"" # Celsius } try: r = requests.get(url, params=params, timeout=10) r.raise_for_status() data = r.json() temp = data[""main""][""temp""] wind = data[""wind""][""speed""] weather = data[""weather""][0][""main""] desc = data[""weather""][0][""description""] print(""\nLive Weather Report"") print(""-------------------"") print(""City :"", city) print(""Temperature :"", temp, ""°C"") print(""Wind Speed :"", wind, ""m/s"") print(""Weather :"", weather) print(""Description :"", desc) except requests.exceptions.RequestException as e: print(""Error fetching weather data:"", e)",33,33 ,"class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [[]] prev_Idx = idx = 0 for i in range(len(nums)): idx = prev_idx if i >= 1 and nums[i] == nums[i - 1] else 0 prev_idx = len(res) for j in range(idx, prev_idx): tmp = res[j].copy() tmp.append(nums[i]) res.append(tmp) return res",0.0,GFG,,python,"class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [[]] prev_Idx = idx = 0 for i in range(len(nums)): idx = prev_idx if i >= 1 and nums[i] == nums[i - 1] else 0 prev_idx = len(res) for j in range(idx, prev_idx): tmp = res[j].copy() tmp.append(nums[i]) res.append(tmp) return res",15,15 ,"# Input user_input = input(""Enter hyphen-separated words: "") # Process items = [n for n in user_input.split('-')] items.sort() result = '-'.join(items) # Output print(""Sorted:"", result) ",1.0,PERPLEXITY,Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.,python,"# Input user_input = input(""Enter hyphen-separated words: "") # Process items = [n for n in user_input.split('-')] items.sort() result = '-'.join(items) # Output print(""Sorted:"", result)",10,10 ,"from collections import Counter def minWindow(s, t): if not t or not s: return """" t_count = Counter(t) window = {} have, need = 0, len(t_count) res, res_len = [-1, -1], float('inf') l = 0 for r in range(len(s)): c = s[r] window[c] = window.get(c, 0) + 1 if c in t_count and window[c] == t_count[c]: have += 1 while have == need: if (r - l + 1) < res_len: res = [l, r] res_len = r - l + 1 window[s[l]] -= 1 if s[l] in t_count and window[s[l]] < t_count[s[l]]: have -= 1 l += 1 l, r = res return s[l:r+1] if res_len != float('inf') else """" ",1.0,GPT,"Given strings s and t, return the minimum window in s which contains all characters of t. If no such window exists, return an empty string.",python,"from collections import Counter def minWindow(s, t): if not t or not s: return """" t_count = Counter(t) window = {} have, need = 0, len(t_count) res, res_len = [-1, -1], float('inf') l = 0 for r in range(len(s)): c = s[r] window[c] = window.get(c, 0) + 1 if c in t_count and window[c] == t_count[c]: have += 1 while have == need: if (r - l + 1) < res_len: res = [l, r] res_len = r - l + 1 window[s[l]] -= 1 if s[l] in t_count and window[s[l]] < t_count[s[l]]: have -= 1 l += 1 l, r = res return s[l:r+1] if res_len != float('inf') else """"",31,31 ,"import os, shutil, argparse def sync(src, dst): if not os.path.isdir(src) or not os.path.isdir(dst): print(""Invalid source or destination""); return for r,_,fs in os.walk(src): d = os.path.join(dst, os.path.relpath(r, src)) os.makedirs(d, exist_ok=True) for f in fs: shutil.copy2(os.path.join(r,f), os.path.join(d,f)) if __name__ == ""__main__"": p = argparse.ArgumentParser() p.add_argument(""src""); p.add_argument(""dst"") a = p.parse_args() sync(a.src, a.dst) print(""Sync complete"") ",1.0,GPT,"GIVE ME A python CODE FOR Command-Line File Synchronizer , make it more shorter for effective to pass all the testcases",python,"import os, shutil, argparse def sync(src, dst): if not os.path.isdir(src) or not os.path.isdir(dst): print(""Invalid source or destination""); return for r,_,fs in os.walk(src): d = os.path.join(dst, os.path.relpath(r, src)) os.makedirs(d, exist_ok=True) for f in fs: shutil.copy2(os.path.join(r,f), os.path.join(d,f)) if __name__ == ""__main__"": p = argparse.ArgumentParser() p.add_argument(""src""); p.add_argument(""dst"") a = p.parse_args() sync(a.src, a.dst) print(""Sync complete"")",17,17 ,"class Solution: def lastStoneWeight(self, stones: List[int]) -> int: maxStone = max(stones) bucket = [0] * (maxStone + 1) for stone in stones: bucket[stone] += 1 first = second = maxStone while first > 0: if bucket[first] % 2 == 0: first -= 1 continue j = min(first - 1, second) while j > 0 and bucket[j] == 0: j -= 1 if j == 0: return first second = j bucket[first] -= 1 bucket[second] -= 1 bucket[first - second] += 1 first = max(first - second, second) return first",0.0,GFG,,python,"class Solution: def lastStoneWeight(self, stones: List[int]) -> int: maxStone = max(stones) bucket = [0] * (maxStone + 1) for stone in stones: bucket[stone] += 1 first = second = maxStone while first > 0: if bucket[first] % 2 == 0: first -= 1 continue j = min(first - 1, second) while j > 0 and bucket[j] == 0: j -= 1 if j == 0: return first second = j bucket[first] -= 1 bucket[second] -= 1 bucket[first - second] += 1 first = max(first - second, second) return first",26,26 ,"import java.util.concurrent.CompletableFuture; public class CompletableFutureExample { public static CompletableFuture processAsync(int input) { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (Exception e) {} return ""Processed: "" + input; }).thenApply(result -> result.toUpperCase()); } } ",1.0,PERPLEXITY,Create a Java CompletableFuture example that chains two asynchronous operations,java,"import java.util.concurrent.CompletableFuture; public class CompletableFutureExample { public static CompletableFuture processAsync(int input) { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (Exception e) {} return ""Processed: "" + input; }).thenApply(result -> result.toUpperCase()); } }",9,9 ,"class Solution { public int longestConsecutive(int[] nums) { HashSet set = new HashSet<>(); if(nums.length==0){ return 0; } for(int i : nums){ set.add(i); } int max = 0; for(int i : nums){ if(!set.contains(i)){ continue; } int n = i; int m = i; int length = 1; while(set.contains(n+1)){ n=(n+1); set.remove(n); length++; } while(set.contains(m-1)){ m= m-1; set.remove(m); length++; } max = Math.max(length, max); } return max; } }",0.0,leetcode,,java,"class Solution { public int longestConsecutive(int[] nums) { HashSet set = new HashSet<>(); if(nums.length==0){ return 0; } for(int i : nums){ set.add(i); } int max = 0; for(int i : nums){ if(!set.contains(i)){ continue; } int n = i; int m = i; int length = 1; while(set.contains(n+1)){ n=(n+1); set.remove(n); length++; } while(set.contains(m-1)){ m= m-1; set.remove(m); length++; } max = Math.max(length, max); } return max; } }",34,34 ,"import java.util.*; public class Graph { private List> adjList; public Graph(int vertices) { adjList = new ArrayList<>(); for (int i = 0; i < vertices; i++) { adjList.add(new ArrayList<>()); } } public void addEdge(int u, int v) { adjList.get(u).add(v); adjList.get(v).add(u); // undirected } public List getNeighbors(int v) { return adjList.get(v); } } ",1.0,PERPLEXITY,Create a Java graph representation using adjacency list with List>,java,"import java.util.*; public class Graph { private List> adjList; public Graph(int vertices) { adjList = new ArrayList<>(); for (int i = 0; i < vertices; i++) { adjList.add(new ArrayList<>()); } } public void addEdge(int u, int v) { adjList.get(u).add(v); adjList.get(v).add(u); // undirected } public List getNeighbors(int v) { return adjList.get(v); } }",17,17 ,"public class FindHCFAndLCM { public static void main(String args[]) { int a, b, x, y, t, hcf, lcm; x = 6; y = 10; a = x; b = y; while (b != 0) { t = b; b = a % b; a = t; } hcf = a; lcm = (x * y) / hcf; System.out.print(""HCF and LCM of : "" + x + "" and "" + y + "" is :\n""); System.out.print(""HCF = "" + hcf); System.out.print(""\nLCM = "" + lcm); } } ",0.0,IPSGWALIOR.ORG,,java,"public class FindHCFAndLCM { public static void main(String args[]) { int a, b, x, y, t, hcf, lcm; x = 6; y = 10; a = x; b = y; while (b != 0) { t = b; b = a % b; a = t; } hcf = a; lcm = (x * y) / hcf; System.out.print(""HCF and LCM of : "" + x + "" and "" + y + "" is :\n""); System.out.print(""HCF = "" + hcf); System.out.print(""\nLCM = "" + lcm); } }",22,22 ,"def numIslands(grid): if not grid: return 0 rows, cols = len(grid), len(grid[0]) count = 0 def dfs(r, c): if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != ""1"": return grid[r][c] = ""0"" dfs(r+1, c) dfs(r-1, c) dfs(r, c+1) dfs(r, c-1) for r in range(rows): for c in range(cols): if grid[r][c] == ""1"": dfs(r, c) count += 1 return count ",1.0,GPT,"Solve the problem ""Number of Islands"". Given a 2D grid of '1's (land) and '0's (water), return the number of islands.",python,"def numIslands(grid): if not grid: return 0 rows, cols = len(grid), len(grid[0]) count = 0 def dfs(r, c): if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != ""1"": return grid[r][c] = ""0"" dfs(r+1, c) dfs(r-1, c) dfs(r, c+1) dfs(r, c-1) for r in range(rows): for c in range(cols): if grid[r][c] == ""1"": dfs(r, c) count += 1 return count",23,23 ,"public int trap(int[] height) { int l = 0, r = height.length - 1, lMax = 0, rMax = 0, trapped = 0; while (l < r) { if (height[l] < height[r]) { if (height[l] >= lMax) lMax = height[l]; else trapped += lMax - height[l++]; } else { if (height[r] >= rMax) rMax = height[r]; else trapped += rMax - height[r--]; } } return trapped; }",1.0,GEMINI,"write an effective java code for a Given elevation map (array), calculate how much water it can trap after raining. Use a two-pointer approach for $O(n)$ time and $O(1)$ space.",java,"public int trap(int[] height) { int l = 0, r = height.length - 1, lMax = 0, rMax = 0, trapped = 0; while (l < r) { if (height[l] < height[r]) { if (height[l] >= lMax) lMax = height[l]; else trapped += lMax - height[l++]; } else { if (height[r] >= rMax) rMax = height[r]; else trapped += rMax - height[r--]; } } return trapped; }",11,11 ,"# Define a function named 'multiply' that takes a list of numbers as input def multiply(numbers): # Initialize a variable 'total' to store the multiplication result, starting at 1 total = 1 # Iterate through each element 'x' in the 'numbers' list for x in numbers: # Multiply the current element 'x' with the 'total' total *= x # Return the final multiplication result stored in the 'total' variable return total # Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7) print(multiply((8, 2, 3, -1, 7))) ",0.0,W3RESOURCE,,python,"# Define a function named 'multiply' that takes a list of numbers as input def multiply(numbers): # Initialize a variable 'total' to store the multiplication result, starting at 1 total = 1 # Iterate through each element 'x' in the 'numbers' list for x in numbers: # Multiply the current element 'x' with the 'total' total *= x # Return the final multiplication result stored in the 'total' variable return total # Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7) print(multiply((8, 2, 3, -1, 7))) ",15,15 ,"class Solution { public String countOfAtoms(String formula) { int n = formula.length(); Map result_counter = new HashMap<>(); Deque> parenthesis_stack = new ArrayDeque<>(); int cur_ind = 0; while (cur_ind < n) { char cur_char = formula.charAt(cur_ind); if (cur_char == '(') { cur_ind++; parenthesis_stack.push(new HashMap<>()); continue; } if (cur_char == ')') { StringBuilder mult_str = new StringBuilder(); cur_ind++; while (cur_ind < n && Character.isDigit(formula.charAt(cur_ind))) { mult_str.append(formula.charAt(cur_ind)); cur_ind++; } int mult = mult_str.length() == 0 ? 1 : Integer.parseInt(mult_str.toString()); Map last_counter = parenthesis_stack.pop(); Map target = parenthesis_stack.isEmpty() ? result_counter : parenthesis_stack.peek(); for (Map.Entry entry : last_counter.entrySet()) { target.put(entry.getKey(), target.getOrDefault(entry.getKey(), 0) + entry.getValue() * mult); } continue; } StringBuilder cur_elem = new StringBuilder(); StringBuilder cur_counter_str = new StringBuilder(); Map target = parenthesis_stack.isEmpty() ? result_counter : parenthesis_stack.peek(); while (cur_ind < n && formula.charAt(cur_ind) != '(' && formula.charAt(cur_ind) != ')') { if (Character.isAlphabetic(formula.charAt(cur_ind))) { if (Character.isUpperCase(formula.charAt(cur_ind)) && cur_elem.length() > 0) { target.put(cur_elem.toString(), target.getOrDefault(cur_elem.toString(), 0) + (cur_counter_str.length() == 0 ? 1 : Integer.parseInt(cur_counter_str.toString()))); cur_elem = new StringBuilder(); cur_counter_str = new StringBuilder(); } cur_elem.append(formula.charAt(cur_ind)); } else { cur_counter_str.append(formula.charAt(cur_ind)); } cur_ind++; } target.put(cur_elem.toString(), target.getOrDefault(cur_elem.toString(), 0) + (cur_counter_str.length() == 0 ? 1 : Integer.parseInt(cur_counter_str.toString()))); } List parts = new ArrayList<>(); for (Map.Entry entry : result_counter.entrySet()) { parts.add(entry.getKey() + (entry.getValue() == 1 ? """" : entry.getValue())); } Collections.sort(parts); StringBuilder result = new StringBuilder(); for (String part : parts) { result.append(part); } return result.toString(); } }",0.0,leetcode,,java,"class Solution { public String countOfAtoms(String formula) { int n = formula.length(); Map result_counter = new HashMap<>(); Deque> parenthesis_stack = new ArrayDeque<>(); int cur_ind = 0; while (cur_ind < n) { char cur_char = formula.charAt(cur_ind); if (cur_char == '(') { cur_ind++; parenthesis_stack.push(new HashMap<>()); continue; } if (cur_char == ')') { StringBuilder mult_str = new StringBuilder(); cur_ind++; while (cur_ind < n && Character.isDigit(formula.charAt(cur_ind))) { mult_str.append(formula.charAt(cur_ind)); cur_ind++; } int mult = mult_str.length() == 0 ? 1 : Integer.parseInt(mult_str.toString()); Map last_counter = parenthesis_stack.pop(); Map target = parenthesis_stack.isEmpty() ? result_counter : parenthesis_stack.peek(); for (Map.Entry entry : last_counter.entrySet()) { target.put(entry.getKey(), target.getOrDefault(entry.getKey(), 0) + entry.getValue() * mult); } continue; } StringBuilder cur_elem = new StringBuilder(); StringBuilder cur_counter_str = new StringBuilder(); Map target = parenthesis_stack.isEmpty() ? result_counter : parenthesis_stack.peek(); while (cur_ind < n && formula.charAt(cur_ind) != '(' && formula.charAt(cur_ind) != ')') { if (Character.isAlphabetic(formula.charAt(cur_ind))) { if (Character.isUpperCase(formula.charAt(cur_ind)) && cur_elem.length() > 0) { target.put(cur_elem.toString(), target.getOrDefault(cur_elem.toString(), 0) + (cur_counter_str.length() == 0 ? 1 : Integer.parseInt(cur_counter_str.toString()))); cur_elem = new StringBuilder(); cur_counter_str = new StringBuilder(); } cur_elem.append(formula.charAt(cur_ind)); } else { cur_counter_str.append(formula.charAt(cur_ind)); } cur_ind++; } target.put(cur_elem.toString(), target.getOrDefault(cur_elem.toString(), 0) + (cur_counter_str.length() == 0 ? 1 : Integer.parseInt(cur_counter_str.toString()))); } List parts = new ArrayList<>(); for (Map.Entry entry : result_counter.entrySet()) { parts.add(entry.getKey() + (entry.getValue() == 1 ? """" : entry.getValue())); } Collections.sort(parts); StringBuilder result = new StringBuilder(); for (String part : parts) { result.append(part); } return result.toString(); } }",70,70 ,"class Solution: def isHappy(self, n: int) -> bool: slow, fast = n, self.sumOfSquares(n) power = lam = 1 while slow != fast: if power == lam: slow = fast power *= 2 lam = 0 fast = self.sumOfSquares(fast) lam += 1 return True if fast == 1 else False def sumOfSquares(self, n: int) -> int: output = 0 while n: digit = n % 10 digit = digit ** 2 output += digit n = n // 10 return output",0.0,GFG,,python,"class Solution: def isHappy(self, n: int) -> bool: slow, fast = n, self.sumOfSquares(n) power = lam = 1 while slow != fast: if power == lam: slow = fast power *= 2 lam = 0 fast = self.sumOfSquares(fast) lam += 1 return True if fast == 1 else False def sumOfSquares(self, n: int) -> int: output = 0 while n: digit = n % 10 digit = digit ** 2 output += digit n = n // 10 return output",23,23 ,"// 1. Binary Search (AI-generated for sorted array lookup) public class BinarySearch { public static int search(int[] arr, int target) { int left = 0, right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) left = mid + 1; else right = mid - 1; } return -1; } } ",1.0,PERPLEXITY,Write a Java method for binary search on a sorted integer array that returns the index or -1 if not found,java,"// 1. Binary Search (AI-generated for sorted array lookup) public class BinarySearch { public static int search(int[] arr, int target) { int left = 0, right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) left = mid + 1; else right = mid - 1; } return -1; } }",13,13 ,"def reorderList(head): if not head: return slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next prev, curr = None, slow.next slow.next = None while curr: nxt = curr.next curr.next = prev prev = curr curr = nxt first, second = head, prev while second: tmp1, tmp2 = first.next, second.next first.next = second second.next = tmp1 first, second = tmp1, tmp2 ",1.0,GPT,"Solve the problem ""Reorder Linked List"". Reorder the list as: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → … Do it in-place with O(1) extra space. ",python,"def reorderList(head): if not head: return slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next prev, curr = None, slow.next slow.next = None while curr: nxt = curr.next curr.next = prev prev = curr curr = nxt first, second = head, prev while second: tmp1, tmp2 = first.next, second.next first.next = second second.next = tmp1 first, second = tmp1, tmp2",24,24 ,"public int findKthLargest(int[] nums, int k) { PriorityQueue pq = new PriorityQueue<>(); for (int val : nums) { pq.offer(val); if (pq.size() > k) pq.poll(); } return pq.peek(); }",1.0,GEMINI,Find the kth largest element in an unsorted array.,java,"public int findKthLargest(int[] nums, int k) { PriorityQueue pq = new PriorityQueue<>(); for (int val : nums) { pq.offer(val); if (pq.size() > k) pq.poll(); } return pq.peek(); }",8,8 ,"# Import the queue module to use PriorityQueue import queue # Import the threading module to use threads and locks import threading # Define a class for a thread-safe priority queue class ThreadSafePriorityQueue: def __init__(self): # Initialize a PriorityQueue object to hold the items self._queue = queue.PriorityQueue() # Initialize a lock to ensure thread safety self._lock = threading.Lock() # Method to put an item into the priority queue def put(self, item, priority): # Acquire the lock to ensure thread safety with self._lock: # Put the item into the queue with its priority self._queue.put((priority, item)) # Method to get an item from the priority queue def get(self): # Acquire the lock to ensure thread safety with self._lock: # Check if the queue is not empty if not self._queue.empty(): # Get the item with the highest priority (lowest priority number) priority, item = self._queue.get() # Return the item return item else: # Return None if the queue is empty return None # Example usage to demonstrate the thread-safe priority queue if __name__ == ""__main__"": # Define a producer function to add items to the queue def producer(q): # Add 5 items to the queue with their priority as their value for i in range(5): q.put(i, i) # Define a consumer function to get items from the queue def consumer(q): # Continuously get items from the queue while True: # Get an item from the queue item = q.get() # If the item is None, break the loop (end of processing) if item is None: break # Print the consumed item print(""Consumed:"", item) # Create an instance of the thread-safe priority queue q = ThreadSafePriorityQueue() # Create a producer thread to add items to the queue producer_thread = threading.Thread(target=producer, args=(q,)) # Create a consumer thread to get items from the queue consumer_thread = threading.Thread(target=consumer, args=(q,)) # Start the producer thread producer_thread.start() # Start the consumer thread consumer_thread.start() # Wait for the producer thread to finish producer_thread.join() # Add a sentinel value to the queue to signal the consumer to stop q.put(None, None) # Wait for the consumer thread to finish consumer_thread.join()",0.0,W3RESOURCE,,python,"# Import the queue module to use PriorityQueue import queue # Import the threading module to use threads and locks import threading # Define a class for a thread-safe priority queue class ThreadSafePriorityQueue: def __init__(self): # Initialize a PriorityQueue object to hold the items self._queue = queue.PriorityQueue() # Initialize a lock to ensure thread safety self._lock = threading.Lock() # Method to put an item into the priority queue def put(self, item, priority): # Acquire the lock to ensure thread safety with self._lock: # Put the item into the queue with its priority self._queue.put((priority, item)) # Method to get an item from the priority queue def get(self): # Acquire the lock to ensure thread safety with self._lock: # Check if the queue is not empty if not self._queue.empty(): # Get the item with the highest priority (lowest priority number) priority, item = self._queue.get() # Return the item return item else: # Return None if the queue is empty return None # Example usage to demonstrate the thread-safe priority queue if __name__ == ""__main__"": # Define a producer function to add items to the queue def producer(q): # Add 5 items to the queue with their priority as their value for i in range(5): q.put(i, i) # Define a consumer function to get items from the queue def consumer(q): # Continuously get items from the queue while True: # Get an item from the queue item = q.get() # If the item is None, break the loop (end of processing) if item is None: break # Print the consumed item print(""Consumed:"", item) # Create an instance of the thread-safe priority queue q = ThreadSafePriorityQueue() # Create a producer thread to add items to the queue producer_thread = threading.Thread(target=producer, args=(q,)) # Create a consumer thread to get items from the queue consumer_thread = threading.Thread(target=consumer, args=(q,)) # Start the producer thread producer_thread.start() # Start the consumer thread consumer_thread.start() # Wait for the producer thread to finish producer_thread.join() # Add a sentinel value to the queue to signal the consumer to stop q.put(None, None) # Wait for the consumer thread to finish consumer_thread.join()",72,72 ,"class Solution { public int maxPoints(int[][] points) { int n = points.length; if (n <= 2) return n; int result = 0; for (int i = 0; i < n; i++) { Map map = new HashMap<>(); int max = 0; for (int j = i + 1; j < n; j++) { int dx = points[j][0] - points[i][0]; int dy = points[j][1] - points[i][1]; int g = gcd(dx, dy); dx /= g; dy /= g; String key = dx + "","" + dy; map.put(key, map.getOrDefault(key, 0) + 1); max = Math.max(max, map.get(key)); } result = Math.max(result, max + 1); // +1 for anchor point } return result; } private int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } }",0.0,leetcode,,java,"class Solution { public int maxPoints(int[][] points) { int n = points.length; if (n <= 2) return n; int result = 0; for (int i = 0; i < n; i++) { Map map = new HashMap<>(); int max = 0; for (int j = i + 1; j < n; j++) { int dx = points[j][0] - points[i][0]; int dy = points[j][1] - points[i][1]; int g = gcd(dx, dy); dx /= g; dy /= g; String key = dx + "","" + dy; map.put(key, map.getOrDefault(key, 0) + 1); max = Math.max(max, map.get(key)); } result = Math.max(result, max + 1); // +1 for anchor point } return result; } private int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } }",35,35 ,"import java.util.List; import java.nio.file.Files; import java.nio.file.Paths; public class FileReaderUtil { public static List readFile(String path) throws Exception { try (var lines = Files.newBufferedReader(Paths.get(path))) { return Files.readAllLines(Paths.get(path)); } } } ",1.0,PERPLEXITY,"Create a Java method to read all lines from a file using try-with-resources and return as List.""",java,"import java.util.List; import java.nio.file.Files; import java.nio.file.Paths; public class FileReaderUtil { public static List readFile(String path) throws Exception { try (var lines = Files.newBufferedReader(Paths.get(path))) { return Files.readAllLines(Paths.get(path)); } } }",10,10 ,"import asyncio class Scheduler: def __init__(self): self.tasks=[] def add(self, coro, *args): self.tasks.append(coro(*args)) async def run(self): await asyncio.gather(*self.tasks) async def task(name, t): print(f""Task {name} started ({t}s)"") await asyncio.sleep(t) print(f""Task {name} finished"") # ---------- INPUT ---------- async def main(): s = Scheduler() s.add(task, ""A"", 2) s.add(task, ""B"", 1) s.add(task, ""C"", 3) await s.run() # ---------- OUTPUT ---------- asyncio.run(main()) ",1.0,GPT,Write a Python program that builds a concurrent task scheduler using asyncio WITH I/O,python,"import asyncio class Scheduler: def __init__(self): self.tasks=[] def add(self, coro, *args): self.tasks.append(coro(*args)) async def run(self): await asyncio.gather(*self.tasks) async def task(name, t): print(f""Task {name} started ({t}s)"") await asyncio.sleep(t) print(f""Task {name} finished"") # ---------- INPUT ---------- async def main(): s = Scheduler() s.add(task, ""A"", 2) s.add(task, ""B"", 1) s.add(task, ""C"", 3) await s.run() # ---------- OUTPUT ---------- asyncio.run(main())",22,22 ,"class Solution { public int numRabbits(int[] answers) { Map mpp = new HashMap<>(); for (int i : answers) mpp.put(i, mpp.getOrDefault(i, 0) + 1); int total = 0; for (Map.Entry p : mpp.entrySet()) total += Math.ceil((double)p.getValue() / (p.getKey() + 1)) * (p.getKey() + 1); return total; } }",0.0,leetcode,,java,"class Solution { public int numRabbits(int[] answers) { Map mpp = new HashMap<>(); for (int i : answers) mpp.put(i, mpp.getOrDefault(i, 0) + 1); int total = 0; for (Map.Entry p : mpp.entrySet()) total += Math.ceil((double)p.getValue() / (p.getKey() + 1)) * (p.getKey() + 1); return total; } }",12,12 ,"import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); for (int i = 1; i <= 5; i++) { int taskId = i; executor.submit(() -> { System.out.println(""Task "" + taskId + "" executed by "" + Thread.currentThread().getName()); }); } executor.shutdown(); } } ",1.0,PERPLEXITY,Write Java code using ExecutorService to execute 5 tasks in a thread pool.,java,"import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); for (int i = 1; i <= 5; i++) { int taskId = i; executor.submit(() -> { System.out.println(""Task "" + taskId + "" executed by "" + Thread.currentThread().getName()); }); } executor.shutdown(); } }",15,15 ,"class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [1] * n for i in range(m - 2, -1, -1): for j in range(n - 2, -1, -1): dp[j] += dp[j + 1] return dp[0]",0.0,GFG,,python,"class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [1] * n for i in range(m - 2, -1, -1): for j in range(n - 2, -1, -1): dp[j] += dp[j + 1] return dp[0]",8,8 ,"import numpy as np arr = np.array([4, 2, 9, 7, 1]) indices = np.argsort(arr) print(""Indices of sorted elements:"", indices)",1.0,DEEPAI,Write a NumPy program to get the indices of the sorted elements of a given array.,python,"import numpy as np arr = np.array([4, 2, 9, 7, 1]) indices = np.argsort(arr) print(""Indices of sorted elements:"", indices)",5,5 ,"import numpy as np arr = np.random.randint(0, 10**6, size=10**7) # For loop def find_max(arr): m = arr[0] for num in arr: if num > m: m = num return m print(""Max with loop:"", find_max(arr)) print(""Max with np.max:"", np.max(arr))",1.0,DEEPAI,Write a NumPy program to generate a large NumPy array and write a function to find the maximum element using a for loop. Optimize it using NumPy's built-in functions.,python,"import numpy as np arr = np.random.randint(0, 10**6, size=10**7) # For loop def find_max(arr): m = arr[0] for num in arr: if num > m: m = num return m print(""Max with loop:"", find_max(arr)) print(""Max with np.max:"", np.max(arr))",14,14 ,"public class Solution { public void setZeroes(int[][] matrix) { boolean fr = false,fc = false; for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[0].length; j++) { if(matrix[i][j] == 0) { if(i == 0) fr = true; if(j == 0) fc = true; matrix[0][j] = 0; matrix[i][0] = 0; } } } for(int i = 1; i < matrix.length; i++) { for(int j = 1; j < matrix[0].length; j++) { if(matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; }} } if(fr) { for(int j = 0; j < matrix[0].length; j++) { matrix[0][j] = 0; } } if(fc) { for(int i = 0; i < matrix.length; i++) { matrix[i][0] = 0; } } }} ",0.0,leetcode,,java,"public class Solution { public void setZeroes(int[][] matrix) { boolean fr = false,fc = false; for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[0].length; j++) { if(matrix[i][j] == 0) { if(i == 0) fr = true; if(j == 0) fc = true; matrix[0][j] = 0; matrix[i][0] = 0; } } } for(int i = 1; i < matrix.length; i++) { for(int j = 1; j < matrix[0].length; j++) { if(matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; }} } if(fr) { for(int j = 0; j < matrix[0].length; j++) { matrix[0][j] = 0; } } if(fc) { for(int i = 0; i < matrix.length; i++) { matrix[i][0] = 0; } } }} ",30,30 ,"class Solution { public List topKFrequent(String[] words, int k) { Map map = new HashMap<>(); for(String ch:words){ map.put(ch,map.getOrDefault(ch,0)+1); } PriorityQueue pq = new PriorityQueue<>((a,b) -> { if(a.freq!=b.freq){ return b.freq - a.freq; } return a.ch.compareTo(b.ch); }); for (Map.Entry entry : map.entrySet()) { pq.add(new Pair(entry.getKey(), entry.getValue())); } List ans = new ArrayList<>(); while(!pq.isEmpty() && k >0){ Pair curr = pq.poll(); ans.add(curr.ch); k--; } return ans; } } class Pair{ String ch; int freq; Pair(String ch,int freq){ this.ch = ch; this.freq = freq; } }",0.0,leetcode,,java,"class Solution { public List topKFrequent(String[] words, int k) { Map map = new HashMap<>(); for(String ch:words){ map.put(ch,map.getOrDefault(ch,0)+1); } PriorityQueue pq = new PriorityQueue<>((a,b) -> { if(a.freq!=b.freq){ return b.freq - a.freq; } return a.ch.compareTo(b.ch); }); for (Map.Entry entry : map.entrySet()) { pq.add(new Pair(entry.getKey(), entry.getValue())); } List ans = new ArrayList<>(); while(!pq.isEmpty() && k >0){ Pair curr = pq.poll(); ans.add(curr.ch); k--; } return ans; } } class Pair{ String ch; int freq; Pair(String ch,int freq){ this.ch = ch; this.freq = freq; } }",38,38 ,"# Import the random module for generating random numbers import random # Import the numpy module for numerical operations import numpy as np # Problem definition: Example function to optimize (e.g., Rastrigin function) def rastrigin(x): # Define the constant A A = 10 # Compute the Rastrigin function value for the input x return A * len(x) + sum([(xi**2 - A * np.cos(2 * np.pi * xi)) for xi in x]) # GA Parameters # Set the population size population_size = 100 # Set the genome length (number of genes in a chromosome) genome_length = 10 # Set the crossover rate crossover_rate = 0.8 # Set the mutation rate mutation_rate = 0.01 # Set the number of generations num_generations = 100 # Define the bounds for the gene values bounds = [-5.12, 5.12] # Initialization def initialize_population(pop_size, genome_len, bounds): # Generate a population of random individuals within the given bounds return [np.random.uniform(bounds[0], bounds[1], genome_len) for _ in range(pop_size)] # Fitness function def evaluate_fitness(population): # Evaluate the fitness of each individual in the population using the Rastrigin function return [rastrigin(individual) for individual in population] # Selection (Tournament Selection) def tournament_selection(population, fitness, tournament_size=3): # Initialize the list of selected individuals selected = [] # Select individuals based on tournament selection for _ in range(len(population)): # Choose random aspirants for the tournament aspirants = [random.randint(0, len(population) - 1) for _ in range(tournament_size)] # Select the individual with the best fitness among the aspirants selected.append(min(aspirants, key=lambda aspirant: fitness[aspirant])) # Return the selected individuals return [population[i] for i in selected] # Crossover (Single Point Crossover) def single_point_crossover(parent1, parent2): # Perform crossover with a given probability if random.random() < crossover_rate: # Choose a random crossover point point = random.randint(1, len(parent1) - 1) # Create children by combining the parents at the crossover point child1 = np.concatenate([parent1[:point], parent2[point:]]) child2 = np.concatenate([parent2[:point], parent1[point:]]) # Return the children return child1, child2 # If no crossover, return the parents as is return parent1, parent2 # Mutation def mutate(individual, mutation_rate, bounds): # Mutate each gene with a given probability for i in range(len(individual)): if random.random() < mutation_rate: # Replace the gene with a random value within the bounds individual[i] = np.random.uniform(bounds[0], bounds[1]) # Return the mutated individual return individual # Genetic Algorithm def genetic_algorithm(): # Initialize the population population = initialize_population(population_size, genome_length, bounds) # Iterate over the number of generations for generation in range(num_generations): # Evaluate the fitness of the population fitness = evaluate_fitness(population) # Selection # Select individuals based on their fitness selected_population = tournament_selection(population, fitness) # Crossover # Create the next generation through crossover next_population = [] for i in range(0, len(selected_population), 2): parent1 = selected_population[i] parent2 = selected_population[min(i + 1, len(selected_population) - 1)] child1, child2 = single_point_crossover(parent1, parent2) next_population.extend([child1, child2]) # Mutation # Mutate the individuals in the next generation population = [mutate(individual, mutation_rate, bounds) for individual in next_population] # Evaluation # Re-evaluate the fitness of the new population fitness = evaluate_fitness(population) # Find the best fitness and corresponding individual best_fitness = min(fitness) best_individual = population[fitness.index(best_fitness)] # Print the best fitness of the current generation print(f'Generation {generation + 1}: Best Fitness = {best_fitness}') # Return the best individual found return best_individual # Uncomment the line below to run the genetic algorithm best_solution = genetic_algorithm() # Print the best solution found print(""Best solution found:"", best_solution)",0.0,W3RESOURCE,,python,"# Import the random module for generating random numbers import random # Import the numpy module for numerical operations import numpy as np # Problem definition: Example function to optimize (e.g., Rastrigin function) def rastrigin(x): # Define the constant A A = 10 # Compute the Rastrigin function value for the input x return A * len(x) + sum([(xi**2 - A * np.cos(2 * np.pi * xi)) for xi in x]) # GA Parameters # Set the population size population_size = 100 # Set the genome length (number of genes in a chromosome) genome_length = 10 # Set the crossover rate crossover_rate = 0.8 # Set the mutation rate mutation_rate = 0.01 # Set the number of generations num_generations = 100 # Define the bounds for the gene values bounds = [-5.12, 5.12] # Initialization def initialize_population(pop_size, genome_len, bounds): # Generate a population of random individuals within the given bounds return [np.random.uniform(bounds[0], bounds[1], genome_len) for _ in range(pop_size)] # Fitness function def evaluate_fitness(population): # Evaluate the fitness of each individual in the population using the Rastrigin function return [rastrigin(individual) for individual in population] # Selection (Tournament Selection) def tournament_selection(population, fitness, tournament_size=3): # Initialize the list of selected individuals selected = [] # Select individuals based on tournament selection for _ in range(len(population)): # Choose random aspirants for the tournament aspirants = [random.randint(0, len(population) - 1) for _ in range(tournament_size)] # Select the individual with the best fitness among the aspirants selected.append(min(aspirants, key=lambda aspirant: fitness[aspirant])) # Return the selected individuals return [population[i] for i in selected] # Crossover (Single Point Crossover) ... truncated ... if random.random() < mutation_rate: # Replace the gene with a random value within the bounds individual[i] = np.random.uniform(bounds[0], bounds[1]) # Return the mutated individual return individual # Genetic Algorithm def genetic_algorithm(): # Initialize the population population = initialize_population(population_size, genome_length, bounds) # Iterate over the number of generations for generation in range(num_generations): # Evaluate the fitness of the population fitness = evaluate_fitness(population) # Selection # Select individuals based on their fitness selected_population = tournament_selection(population, fitness) # Crossover # Create the next generation through crossover next_population = [] for i in range(0, len(selected_population), 2): parent1 = selected_population[i] parent2 = selected_population[min(i + 1, len(selected_population) - 1)] child1, child2 = single_point_crossover(parent1, parent2) next_population.extend([child1, child2]) # Mutation # Mutate the individuals in the next generation population = [mutate(individual, mutation_rate, bounds) for individual in next_population] # Evaluation # Re-evaluate the fitness of the new population fitness = evaluate_fitness(population) # Find the best fitness and corresponding individual best_fitness = min(fitness) best_individual = population[fitness.index(best_fitness)] # Print the best fitness of the current generation print(f'Generation {generation + 1}: Best Fitness = {best_fitness}') # Return the best individual found return best_individual # Uncomment the line below to run the genetic algorithm best_solution = genetic_algorithm() # Print the best solution found print(""Best solution found:"", best_solution)",117,101 ,"import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class TokenBucketRateLimiter { private final long capacity; private final long refillTokensPerSecond; private long availableTokens; private long lastRefillTimestamp; private final ReentrantLock lock; public TokenBucketRateLimiter(long capacity, long refillTokensPerSecond) { this.capacity = capacity; this.refillTokensPerSecond = refillTokensPerSecond; this.availableTokens = capacity; this.lastRefillTimestamp = System.currentTimeMillis(); this.lock = new ReentrantLock(); } public boolean tryAcquire() { return tryAcquire(1); } public boolean tryAcquire(long tokens) { if (tokens <= 0 || tokens > capacity) { throw new IllegalArgumentException(""Invalid token request""); } lock.lock(); try { refillTokens(); if (availableTokens >= tokens) { availableTokens -= tokens; return true; } return false; } finally { lock.unlock(); } } public boolean tryAcquireWithTimeout(long tokens, long timeout, TimeUnit unit) throws InterruptedException { long timeoutMillis = unit.toMillis(timeout); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < timeoutMillis) { if (tryAcquire(tokens)) { return true; } // Calculate wait time for next token lock.lock(); try { refillTokens(); if (availableTokens < tokens && refillTokensPerSecond > 0) { long tokensNeeded = tokens - availableTokens; long waitTimeMillis = (tokensNeeded * 1000) / refillTokensPerSecond; Thread.sleep(Math.min(waitTimeMillis, 100)); } } finally { lock.unlock(); } } return false; } private void refillTokens() { long now = System.currentTimeMillis(); long timeElapsed = now - lastRefillTimestamp; if (timeElapsed > 0) { long tokensToAdd = (timeElapsed * refillTokensPerSecond) / 1000; if (tokensToAdd > 0) { availableTokens = Math.min(capacity, availableTokens + tokensToAdd); lastRefillTimestamp = now; } } } public long getAvailableTokens() { lock.lock(); try { refillTokens(); return availableTokens; } finally { lock.unlock(); } } }",1.0,DEEPSEEK,Implement a thread-safe rate limiter using the token bucket algorithm that allows a maximum of N requests per second.,java,"import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class TokenBucketRateLimiter { private final long capacity; private final long refillTokensPerSecond; private long availableTokens; private long lastRefillTimestamp; private final ReentrantLock lock; public TokenBucketRateLimiter(long capacity, long refillTokensPerSecond) { this.capacity = capacity; this.refillTokensPerSecond = refillTokensPerSecond; this.availableTokens = capacity; this.lastRefillTimestamp = System.currentTimeMillis(); this.lock = new ReentrantLock(); } public boolean tryAcquire() { return tryAcquire(1); } public boolean tryAcquire(long tokens) { if (tokens <= 0 || tokens > capacity) { throw new IllegalArgumentException(""Invalid token request""); } lock.lock(); try { refillTokens(); if (availableTokens >= tokens) { availableTokens -= tokens; return true; } return false; } finally { lock.unlock(); } } public boolean tryAcquireWithTimeout(long tokens, long timeout, TimeUnit unit) throws InterruptedException { long timeoutMillis = unit.toMillis(timeout); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < timeoutMillis) { if (tryAcquire(tokens)) { return true; } // Calculate wait time for next token lock.lock(); try { refillTokens(); if (availableTokens < tokens && refillTokensPerSecond > 0) { long tokensNeeded = tokens - availableTokens; long waitTimeMillis = (tokensNeeded * 1000) / refillTokensPerSecond; Thread.sleep(Math.min(waitTimeMillis, 100)); } } finally { lock.unlock(); } } return false; } private void refillTokens() { long now = System.currentTimeMillis(); long timeElapsed = now - lastRefillTimestamp; if (timeElapsed > 0) { long tokensToAdd = (timeElapsed * refillTokensPerSecond) / 1000; if (tokensToAdd > 0) { availableTokens = Math.min(capacity, availableTokens + tokensToAdd); lastRefillTimestamp = now; } } } public long getAvailableTokens() { lock.lock(); try { refillTokens(); return availableTokens; } finally { lock.unlock(); } } }",91,91 ,"from collections import OrderedDict # Define a class for the caching system with LRU eviction policy class LRUCache: # Initialize the cache with a maximum capacity def __init__(self, capacity): self.capacity = capacity # Set the maximum capacity self.cache = OrderedDict() # Use OrderedDict for O(1) access and ordering # Get the value associated with the key from the cache def get(self, key): # If the key is not in the cache, return -1 if key not in self.cache: return -1 # Move the accessed key to the end to indicate recent use self.cache.move_to_end(key) # Return the value associated with the key return self.cache[key] # Put a key-value pair into the cache def put(self, key, value): # If the key is already in the cache, update its value and move it to the end if key in self.cache: self.cache[key] = value self.cache.move_to_end(key) else: # If the cache is at capacity, remove the least recently used item if len(self.cache) == self.capacity: self.cache.popitem(last=False) # Remove the first item (least recently used) # Add the new key-value pair to the cache self.cache[key] = value # Example usage if __name__ == ""__main__"": # Create a cache with a capacity of 2 cache = LRUCache(2) # Put key-value pairs into the cache cache.put(1, 1) cache.put(2, 2) # Retrieve and print the value associated with key 1 (should be 1) print(cache.get(1)) # Put a new key-value pair into the cache (evicting key 2) cache.put(3, 3) # Retrieve and print the value associated with key 2 (should be -1, as it was evicted) print(cache.get(2)) # Retrieve and print the value associated with key 3 (should be 3) print(cache.get(3))",0.0,W3RESOURCE,,python,"from collections import OrderedDict # Define a class for the caching system with LRU eviction policy class LRUCache: # Initialize the cache with a maximum capacity def __init__(self, capacity): self.capacity = capacity # Set the maximum capacity self.cache = OrderedDict() # Use OrderedDict for O(1) access and ordering # Get the value associated with the key from the cache def get(self, key): # If the key is not in the cache, return -1 if key not in self.cache: return -1 # Move the accessed key to the end to indicate recent use self.cache.move_to_end(key) # Return the value associated with the key return self.cache[key] # Put a key-value pair into the cache def put(self, key, value): # If the key is already in the cache, update its value and move it to the end if key in self.cache: self.cache[key] = value self.cache.move_to_end(key) else: # If the cache is at capacity, remove the least recently used item if len(self.cache) == self.capacity: self.cache.popitem(last=False) # Remove the first item (least recently used) # Add the new key-value pair to the cache self.cache[key] = value # Example usage if __name__ == ""__main__"": # Create a cache with a capacity of 2 cache = LRUCache(2) # Put key-value pairs into the cache cache.put(1, 1) cache.put(2, 2) # Retrieve and print the value associated with key 1 (should be 1) print(cache.get(1)) # Put a new key-value pair into the cache (evicting key 2) cache.put(3, 3) # Retrieve and print the value associated with key 2 (should be -1, as it was evicted) print(cache.get(2)) # Retrieve and print the value associated with key 3 (should be 3) print(cache.get(3))",47,47 ,"class Solution: def findDuplicate(self, nums: List[int]) -> int: slow, fast = 0, 0 while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break slow2 = 0 while True: slow = nums[slow] slow2 = nums[slow2] if slow == slow2: return slow",0.0,GFG,,python,"class Solution: def findDuplicate(self, nums: List[int]) -> int: slow, fast = 0, 0 while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break slow2 = 0 while True: slow = nums[slow] slow2 = nums[slow2] if slow == slow2: return slow",15,15 ,"public class ReverseNum { public static void main(String[] args) { int rev = 0; int num = 1234; int no=num; while (num > 0) { int rem = num % 10; rev = rem + (rev * 10); num = num / 10; } System.out.println(""Number = ""+no); System.out.println(""Reverse = ""+rev); } }",0.0,IPSGWALIOR.ORG,,java,"public class ReverseNum { public static void main(String[] args) { int rev = 0; int num = 1234; int no=num; while (num > 0) { int rem = num % 10; rev = rem + (rev * 10); num = num / 10; } System.out.println(""Number = ""+no); System.out.println(""Reverse = ""+rev); } }",18,18 ,"public class Codec { Map codeDB = new HashMap<>(), urlDB = new HashMap<>(); static final String chars = ""0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz""; private String getCode() { char[] code = new char[6]; for (int i = 0; i < 6; i++) code[i] = chars.charAt((int)(Math.random() * 62)); return ""http://tinyurl.com/"" + String.valueOf(code); } public String encode(String longUrl) { if (urlDB.containsKey(longUrl)) return urlDB.get(longUrl); String code = getCode(); while (codeDB.containsKey(code)) code = getCode(); codeDB.put(code, longUrl); urlDB.put(longUrl, code); return code; } public String decode(String shortUrl) { return codeDB.get(shortUrl); } }",0.0,leetcode,,java,"public class Codec { Map codeDB = new HashMap<>(), urlDB = new HashMap<>(); static final String chars = ""0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz""; private String getCode() { char[] code = new char[6]; for (int i = 0; i < 6; i++) code[i] = chars.charAt((int)(Math.random() * 62)); return ""http://tinyurl.com/"" + String.valueOf(code); } public String encode(String longUrl) { if (urlDB.containsKey(longUrl)) return urlDB.get(longUrl); String code = getCode(); while (codeDB.containsKey(code)) code = getCode(); codeDB.put(code, longUrl); urlDB.put(longUrl, code); return code; } public String decode(String shortUrl) { return codeDB.get(shortUrl); } }",24,24 ,"public class AsciiToCharacter { public static void main(String[] args) { char c; for(int i=65;i<=90;i++) { c =(char)i; System.out.println(i+"" = ""+c); } } }",0.0,IPSGWALIOR.ORG,,java,"public class AsciiToCharacter { public static void main(String[] args) { char c; for(int i=65;i<=90;i++) { c =(char)i; System.out.println(i+"" = ""+c); } } }",12,12 ,"import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; public class DistributedTaskScheduler { private final ExecutorService executor; private final List workerNodes; private final Map tasks; private final AtomicInteger taskIdCounter; private final ReentrantLock lock; private final ScheduledExecutorService healthCheckScheduler; public static class WorkerNode { private final String id; private final String host; private final int port; private volatile boolean healthy; private volatile long lastHeartbeat; public WorkerNode(String id, String host, int port) { this.id = id; this.host = host; this.port = port; this.healthy = true; this.lastHeartbeat = System.currentTimeMillis(); } // Getters and setters public String getId() { return id; } public String getHost() { return host; } public int getPort() { return port; } public boolean isHealthy() { return healthy; } public void setHealthy(boolean healthy) { this.healthy = healthy; } public long getLastHeartbeat() { return lastHeartbeat; } public void updateHeartbeat() { this.lastHeartbeat = System.currentTimeMillis(); } } public static class ScheduledTask { private final String id; private final Runnable task; private final long initialDelay; private final long period; private final TimeUnit timeUnit; private volatile TaskStatus status; private volatile String assignedWorker; private volatile Future future; public ScheduledTask(String id, Runnable task, long initialDelay, long period, TimeUnit timeUnit) { this.id = id; this.task = task; this.initialDelay = initialDelay; this.period = period; this.timeUnit = timeUnit; this.status = TaskStatus.PENDING; } public enum TaskStatus { PENDING, SCHEDULED, RUNNING, COMPLETED, FAILED, CANCELLED } // Getters and setters public String getId() { return id; } public Runnable getTask() { return task; } public long getInitialDelay() { return initialDelay; } public long getPeriod() { return period; } public TimeUnit getTimeUnit() { return timeUnit; } public TaskStatus getStatus() { return status; } public void setStatus(TaskStatus status) { this.status = status; } public String getAssignedWorker() { return assignedWorker; } public void setAssignedWorker(String workerId) { this.assignedWorker = workerId; } public Future getFuture() { return future; } public void setFuture(Future future) { this.future = future; } } public DistributedTaskScheduler(int corePoolSize) { this.executor = Executors.newFixedThreadPool(corePoolSize); this.workerNodes = new CopyOnWriteArrayList<>(); this.tasks = new ConcurrentHashMap<>(); this.taskIdCounter = new AtomicInteger(0); this.lock = new ReentrantLock(); this.healthCheckScheduler = Executors.newScheduledThreadPool(1); // Start health check startHealthCheck(); } private void startHealthCheck() { healthCheckScheduler.scheduleAtFixedRate(() -> { checkWorkerHealth(); reassignFailedTasks(); }, 30, 30, TimeUnit.SECONDS); } private void checkWorkerHealth() { long currentTime = System.currentTimeMillis(); long threshold = currentTime - 60000; // 1 minute timeout for (WorkerNode worker : workerNodes) { if (worker.getLastHeartbeat() < threshold) { worker.setHealthy(false); System.err.println(""Worker "" + worker.getId() + "" marked as unhealthy""); } } } private void reassignFailedTasks() { lock.lock(); try { for (ScheduledTask task : tasks.values()) { if (task.getStatus() == ScheduledTask.TaskStatus.RUNNING) { WorkerNode assignedWorker = findWorkerById(task.getAssignedWorker()); if (assignedWorker == null || !assignedWorker.isHealthy()) { // Task is running on failed worker, reschedule rescheduleTask(task); } } } } finally { lock.unlock(); } } private void rescheduleTask(ScheduledTask task) { task.setStatus(ScheduledTask.TaskStatus.PENDING); task.setAssignedWorker(null); if (task.getFuture() != null) { task.getFuture().cancel(false); } scheduleTask(task); } private WorkerNode findWorkerById(String workerId) { if (workerId == null) return null; for (WorkerNode worker : workerNodes) { if (worker.getId().equals(workerId)) { return worker; } } return null; } public void registerWorker(WorkerNode worker) { workerNodes.add(worker); System.out.println(""Registered worker: "" + worker.getId()); } public void unregisterWorker(String workerId) { workerNodes.removeIf(worker -> worker.getId().equals(workerId)); // Reassign tasks from removed worker reassignFailedTasks(); } public String scheduleTask(Runnable task, long initialDelay, long period, TimeUnit unit) { String taskId = ""task-"" + taskIdCounter.incrementAndGet(); ScheduledTask scheduledTask = new ScheduledTask(taskId, task, initialDelay, period, unit); tasks.put(taskId, scheduledTask); scheduleTask(scheduledTask); return taskId; } private void scheduleTask(ScheduledTask scheduledTask) { WorkerNode worker = selectWorker(); if (worker == null)",1.0,DEEPSEEK,Design a task scheduler that can distribute tasks across multiple worker nodes and handle failures.,java,"import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; public class DistributedTaskScheduler { private final ExecutorService executor; private final List workerNodes; private final Map tasks; private final AtomicInteger taskIdCounter; private final ReentrantLock lock; private final ScheduledExecutorService healthCheckScheduler; public static class WorkerNode { private final String id; private final String host; private final int port; private volatile boolean healthy; private volatile long lastHeartbeat; public WorkerNode(String id, String host, int port) { this.id = id; this.host = host; this.port = port; this.healthy = true; this.lastHeartbeat = System.currentTimeMillis(); } // Getters and setters public String getId() { return id; } public String getHost() { return host; } public int getPort() { return port; } public boolean isHealthy() { return healthy; } public void setHealthy(boolean healthy) { this.healthy = healthy; } public long getLastHeartbeat() { return lastHeartbeat; } public void updateHeartbeat() { this.lastHeartbeat = System.currentTimeMillis(); } } public static class ScheduledTask { private final String id; private final Runnable task; private final long initialDelay; private final long period; private final TimeUnit timeUnit; private volatile TaskStatus status; private volatile String assignedWorker; private volatile Future future; public ScheduledTask(String id, Runnable task, long initialDelay, long period, TimeUnit timeUnit) { ... truncated ... } private void rescheduleTask(ScheduledTask task) { task.setStatus(ScheduledTask.TaskStatus.PENDING); task.setAssignedWorker(null); if (task.getFuture() != null) { task.getFuture().cancel(false); } scheduleTask(task); } private WorkerNode findWorkerById(String workerId) { if (workerId == null) return null; for (WorkerNode worker : workerNodes) { if (worker.getId().equals(workerId)) { return worker; } } return null; } public void registerWorker(WorkerNode worker) { workerNodes.add(worker); System.out.println(""Registered worker: "" + worker.getId()); } public void unregisterWorker(String workerId) { workerNodes.removeIf(worker -> worker.getId().equals(workerId)); // Reassign tasks from removed worker reassignFailedTasks(); } public String scheduleTask(Runnable task, long initialDelay, long period, TimeUnit unit) { String taskId = ""task-"" + taskIdCounter.incrementAndGet(); ScheduledTask scheduledTask = new ScheduledTask(taskId, task, initialDelay, period, unit); tasks.put(taskId, scheduledTask); scheduleTask(scheduledTask); return taskId; } private void scheduleTask(ScheduledTask scheduledTask) { WorkerNode worker = selectWorker(); if (worker == null)",172,101 ,"class NoOfOccurenceOfCharacters { static final int MAX_CHAR = 256; static void getOccuringChar(String str) { int count[] = new int[MAX_CHAR]; int len = str.length(); for (int i = 0; i < len; i++) count[str.charAt(i)]++; char ch[] = new char[str.length()]; for (int i = 0; i < len; i++) { ch[i] = str.charAt(i); int find = 0; for (int j = 0; j <= i; j++) { if (str.charAt(i) == ch[j]) find++; } if (find == 1) System.out.println(""Number of Occurrence of "" + str.charAt(i) + "" is:"" + count[str.charAt(i)]); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = ""geeksforgeeks""; getOccuringChar(str); } }",0.0,IPSGWALIOR.ORG,,java,"class NoOfOccurenceOfCharacters { static final int MAX_CHAR = 256; static void getOccuringChar(String str) { int count[] = new int[MAX_CHAR]; int len = str.length(); for (int i = 0; i < len; i++) count[str.charAt(i)]++; char ch[] = new char[str.length()]; for (int i = 0; i < len; i++) { ch[i] = str.charAt(i); int find = 0; for (int j = 0; j <= i; j++) { if (str.charAt(i) == ch[j]) find++; } if (find == 1) System.out.println(""Number of Occurrence of "" + str.charAt(i) + "" is:"" + count[str.charAt(i)]); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = ""geeksforgeeks""; getOccuringChar(str); } }",30,30 ,"public List> threeSum(int[] nums) { Arrays.sort(nums); List> res = new ArrayList<>(); for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) { if (i > 0 && nums[i] == nums[i-1]) continue; int l = i + 1, r = nums.length - 1; while (l < r) { int sum = nums[i] + nums[l] + nums[r]; if (sum < 0) l++; else if (sum > 0) r--; else { res.add(Arrays.asList(nums[i], nums[l++], nums[r--])); while (l < r && nums[l] == nums[l-1]) l++; } } } return res; }",1.0,GEMINI,Find all unique triplets in an array that sum to zero. Avoid duplicate triplets in the output.,java,"public List> threeSum(int[] nums) { Arrays.sort(nums); List> res = new ArrayList<>(); for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) { if (i > 0 && nums[i] == nums[i-1]) continue; int l = i + 1, r = nums.length - 1; while (l < r) { int sum = nums[i] + nums[l] + nums[r]; if (sum < 0) l++; else if (sum > 0) r--; else { res.add(Arrays.asList(nums[i], nums[l++], nums[r--])); while (l < r && nums[l] == nums[l-1]) l++; } } } return res; }",18,18 ,"def dailyTemperatures(temperatures): res = [0] * len(temperatures) stack = [] for i, temp in enumerate(temperatures): while stack and temp > stack[-1][0]: stack_temp, idx = stack.pop() res[idx] = i - idx stack.append((temp, i)) return res ",1.0,GPT,"Given an array temperatures, return an array such that each index shows how many days until a warmer temperature. Use a monotonic stack.",python,"def dailyTemperatures(temperatures): res = [0] * len(temperatures) stack = [] for i, temp in enumerate(temperatures): while stack and temp > stack[-1][0]: stack_temp, idx = stack.pop() res[idx] = i - idx stack.append((temp, i)) return res",11,11 ,"import requests from bs4 import BeautifulSoup from concurrent.futures import ThreadPoolExecutor # Import ThreadPoolExecutor for multi-threading import urllib.robotparser from urllib.parse import urlparse, urljoin # Import urlparse and urljoin for URL manipulation def is_allowed(url, user_agent='*'): parsed_url = urlparse(url) base_url = f'{parsed_url.scheme}://{parsed_url.netloc}' robots_url = urljoin(base_url, 'robots.txt') rp = urllib.robotparser.RobotFileParser() rp.set_url(robots_url) rp.read() return rp.can_fetch(user_agent, url) def fetch_page(url): if not is_allowed(url): print(f'Scraping not allowed for {url}') return None try: response = requests.get(url) if response.status_code == 200: print(f'Successfully fetched {url}') soup = BeautifulSoup(response.content, 'html.parser') return soup else: print(f'Failed to fetch {url} with status code {response.status_code}') except Exception as e: print(f'Exception occurred while fetching {url}: {e}') return None def extract_links(soup, base_url): links = [] if soup: for link in soup.find_all('a', href=True): full_url = urljoin(base_url, link['href']) links.append(full_url) return links def scrape_urls(urls, max_workers=5): with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = {executor.submit(fetch_page, url): url for url in urls} results = [] for future in futures: result = future.result() if result: results.append(result) return results def main(): start_url = 'https://example.com' # Replace with the URL you want to start scraping from soup = fetch_page(start_url) if not soup: return links = extract_links(soup, start_url) pages = scrape_urls(links) for page in pages: if page: title = page.find('title').get_text() print(f'Page title: {title}') if __name__ == '__main__': main()",0.0,W3RESOURCE,,python,"import requests from bs4 import BeautifulSoup from concurrent.futures import ThreadPoolExecutor # Import ThreadPoolExecutor for multi-threading import urllib.robotparser from urllib.parse import urlparse, urljoin # Import urlparse and urljoin for URL manipulation def is_allowed(url, user_agent='*'): parsed_url = urlparse(url) base_url = f'{parsed_url.scheme}://{parsed_url.netloc}' robots_url = urljoin(base_url, 'robots.txt') rp = urllib.robotparser.RobotFileParser() rp.set_url(robots_url) rp.read() return rp.can_fetch(user_agent, url) def fetch_page(url): if not is_allowed(url): print(f'Scraping not allowed for {url}') return None try: response = requests.get(url) if response.status_code == 200: print(f'Successfully fetched {url}') soup = BeautifulSoup(response.content, 'html.parser') return soup else: print(f'Failed to fetch {url} with status code {response.status_code}') except Exception as e: print(f'Exception occurred while fetching {url}: {e}') return None def extract_links(soup, base_url): links = [] if soup: for link in soup.find_all('a', href=True): full_url = urljoin(base_url, link['href']) links.append(full_url) return links def scrape_urls(urls, max_workers=5): with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = {executor.submit(fetch_page, url): url for url in urls} results = [] for future in futures: result = future.result() if result: results.append(result) return results def main(): start_url = 'https://example.com' # Replace with the URL you want to start scraping from soup = fetch_page(start_url) if not soup: return links = extract_links(soup, start_url) pages = scrape_urls(links) for page in pages: if page: title = page.find('title').get_text() print(f'Page title: {title}') if __name__ == '__main__': main()",88,88 ,"def canCompleteCircuit(gas, cost): total = curr = start = 0 for i in range(len(gas)): total += gas[i] - cost[i] curr += gas[i] - cost[i] if curr < 0: start = i + 1 curr = 0 return start if total >= 0 else -1 ",1.0,GPT,"Solve the problem ""Gas Station"". Given gas and cost arrays, return the starting gas station index if you can travel around once. Otherwise return -1.",python,"def canCompleteCircuit(gas, cost): total = curr = start = 0 for i in range(len(gas)): total += gas[i] - cost[i] curr += gas[i] - cost[i] if curr < 0: start = i + 1 curr = 0 return start if total >= 0 else -1",11,11 ,"import java.util.List; public class GenericUtils { public static void printList(List list) { for (Object item : list) System.out.println(item); } public static void addNumbers(List list) { list.add(42); } public static double sum(List numbers) { double sum = 0; for (Number n : numbers) sum += n.doubleValue(); return sum; } } ",1.0,PERPLEXITY,Create generic methods using wildcards for super and extends in Java collections,java,"import java.util.List; public class GenericUtils { public static void printList(List list) { for (Object item : list) System.out.println(item); } public static void addNumbers(List list) { list.add(42); } public static double sum(List numbers) { double sum = 0; for (Number n : numbers) sum += n.doubleValue(); return sum; } }",14,14 ,"# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: Optional[ListNode]) -> None: slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next second = slow.next prev = slow.next = None while second: tmp = second.next second.next = prev prev = second second = tmp first, second = head, prev while second: tmp1, tmp2 = first.next, second.next first.next = second second.next = tmp1 first, second = tmp1, tmp2",0.0,GFG,,python,"# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: Optional[ListNode]) -> None: slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next second = slow.next prev = slow.next = None while second: tmp = second.next second.next = prev prev = second second = tmp first, second = head, prev while second: tmp1, tmp2 = first.next, second.next first.next = second second.next = tmp1 first, second = tmp1, tmp2",27,27 ,"def letterCombinations(digits): if not digits: return [] phone = { ""2"": ""abc"", ""3"": ""def"", ""4"": ""ghi"", ""5"": ""jkl"", ""6"": ""mno"", ""7"": ""pqrs"", ""8"": ""tuv"", ""9"": ""wxyz"" } res = [] def backtrack(i, cur): if i == len(digits): res.append(cur) return for ch in phone[digits[i]]: backtrack(i + 1, cur + ch) backtrack(0, """") return res ",1.0,GPT,"Solve the problem ""Letter Combinations of a Phone Number"". Given a string of digits from 2 to 9, return all possible letter combinations that the number could represent.",python,"def letterCombinations(digits): if not digits: return [] phone = { ""2"": ""abc"", ""3"": ""def"", ""4"": ""ghi"", ""5"": ""jkl"", ""6"": ""mno"", ""7"": ""pqrs"", ""8"": ""tuv"", ""9"": ""wxyz"" } res = [] def backtrack(i, cur): if i == len(digits): res.append(cur) return for ch in phone[digits[i]]: backtrack(i + 1, cur + ch) backtrack(0, """") return res",21,21 ,"class Node: def __init__(self, v, kids=None): self.v, self.kids = v, kids or [] def __iter__(self): stack = [self] while stack: n = stack.pop() yield n.v stack.extend(reversed(n.kids)) ",1.0,GPT,give me the shorter lines of python code for Custom Tree Iterator,python,"class Node: def __init__(self, v, kids=None): self.v, self.kids = v, kids or [] def __iter__(self): stack = [self] while stack: n = stack.pop() yield n.v stack.extend(reversed(n.kids))",10,10 ,"class Solution { public int numComponents(ListNode head, int[] nums) { Set set = new HashSet<>(); for (int x : nums) set.add(x); ListNode curr = head; int count = 0; while (curr != null) { // If current node is in set and (it's the last node OR next node is not in set) if (set.contains(curr.val) && (curr.next == null || !set.contains(curr.next.val))) { count++; } curr = curr.next; } return count; } }",0.0,leetcode,,java,"class Solution { public int numComponents(ListNode head, int[] nums) { Set set = new HashSet<>(); for (int x : nums) set.add(x); ListNode curr = head; int count = 0; while (curr != null) { // If current node is in set and (it's the last node OR next node is not in set) if (set.contains(curr.val) && (curr.next == null || !set.contains(curr.next.val))) { count++; } curr = curr.next; } return count; } }",18,18 ,"def printValues(): l = [i**2 for i in range(1, 31)] print(l) printValues() ",1.0,PERPLEXITY," Write a Python function to create and print a list where the values are the squares of numbers between 1 and 30 (both included).",python,"def printValues(): l = [i**2 for i in range(1, 31)] print(l) printValues()",5,5 ,"class Solution: def exist(self, board: List[List[str]], word: str) -> bool: ROWS, COLS = len(board), len(board[0]) def dfs(r, c, i): if i == len(word): return True if (r < 0 or c < 0 or r >= ROWS or c >= COLS or word[i] != board[r][c] or board[r][c] == '#'): return False board[r][c] = '#' res = (dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1)) board[r][c] = word[i] return res for r in range(ROWS): for c in range(COLS): if dfs(r, c, 0): return True return False",0.0,GFG,,python,"class Solution: def exist(self, board: List[List[str]], word: str) -> bool: ROWS, COLS = len(board), len(board[0]) def dfs(r, c, i): if i == len(word): return True if (r < 0 or c < 0 or r >= ROWS or c >= COLS or word[i] != board[r][c] or board[r][c] == '#'): return False board[r][c] = '#' res = (dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1)) board[r][c] = word[i] return res for r in range(ROWS): for c in range(COLS): if dfs(r, c, 0): return True return False",24,24 ,"# Importing the NumPy library import numpy as np # Displaying a message for addition operation print(""Add:"") # Performing addition print(np.add(1.0, 4.0)) # Displaying a message for subtraction operation print(""Subtract:"") # Performing subtraction print(np.subtract(1.0, 4.0)) # Displaying a message for multiplication operation print(""Multiply:"") # Performing multiplication print(np.multiply(1.0, 4.0)) # Displaying a message for division operation print(""Divide:"") # Performing division print(np.divide(1.0, 4.0))",0.0,W3RESOURCE,,python,"# Importing the NumPy library import numpy as np # Displaying a message for addition operation print(""Add:"") # Performing addition print(np.add(1.0, 4.0)) # Displaying a message for subtraction operation print(""Subtract:"") # Performing subtraction print(np.subtract(1.0, 4.0)) # Displaying a message for multiplication operation print(""Multiply:"") # Performing multiplication print(np.multiply(1.0, 4.0)) # Displaying a message for division operation print(""Divide:"") # Performing division print(np.divide(1.0, 4.0))",22,22 ,"class Solution: def maxProfit(self, prices: List[int]) -> int: maxP = 0 minBuy = prices[0] for sell in prices: maxP = max(maxP, sell - minBuy) minBuy = min(minBuy, sell) return maxP",0.0,GFG,,python,"class Solution: def maxProfit(self, prices: List[int]) -> int: maxP = 0 minBuy = prices[0] for sell in prices: maxP = max(maxP, sell - minBuy) minBuy = min(minBuy, sell) return maxP",9,9 ,"import json class Address: def __init__(s,st,ct,stt,z): s.street, s.city, s.state, s.zip = st,ct,stt,z class Person: def __init__(s,n,a,ad): s.name, s.age, s.address = n,a,ad class Encoder(json.JSONEncoder): def default(s,o): if hasattr(o,""__dict__""): return {""__t__"":o.__class__.__name__, **o.__dict__} return super().default(o) def decoder(d): if ""__t__"" in d: cls = {""Address"":Address,""Person"":Person}[d.pop(""__t__"")] return cls(**d) return d ",1.0,GPT,GIVE me a python code for Custom JSON Encoder/Decoder,python,"import json class Address: def __init__(s,st,ct,stt,z): s.street, s.city, s.state, s.zip = st,ct,stt,z class Person: def __init__(s,n,a,ad): s.name, s.age, s.address = n,a,ad class Encoder(json.JSONEncoder): def default(s,o): if hasattr(o,""__dict__""): return {""__t__"":o.__class__.__name__, **o.__dict__} return super().default(o) def decoder(d): if ""__t__"" in d: cls = {""Address"":Address,""Person"":Person}[d.pop(""__t__"")] return cls(**d) return d",19,19 ,"import os # Import the os module for interacting with the operating system import shutil # Import the shutil module for file operations import argparse # Import the argparse module for command-line argument parsing def synchronize(source_dir, destination_dir): # Ensure both directories exist if not os.path.exists(source_dir): print(f""Source directory '{source_dir}' does not exist."") return if not os.path.exists(destination_dir): print(f""Destination directory '{destination_dir}' does not exist."") return # Iterate over files in source directory for root, dirs, files in os.walk(source_dir): # Get corresponding path in destination directory relative_path = os.path.relpath(root, source_dir) dest_path = os.path.join(destination_dir, relative_path) # Ensure corresponding directory structure exists in destination if not os.path.exists(dest_path): os.makedirs(dest_path) # Copy files from source to destination for file in files: source_file = os.path.join(root, file) dest_file = os.path.join(dest_path, file) shutil.copy2(source_file, dest_file) print(f""Copied: {source_file} -> {dest_file}"") print(""Synchronization complete."") if __name__ == ""__main__"": # Create argument parser parser = argparse.ArgumentParser(description=""Synchronize files between two directories."") # Add argument for source directory parser.add_argument(""source"", help=""Source directory"") # Add argument for destination directory parser.add_argument(""destination"", help=""Destination directory"") # Parse the command-line arguments args = parser.parse_args() # Call the synchronize function with the provided arguments synchronize(args.source, args.destination)",0.0,W3RESOURCE,,python,"import os # Import the os module for interacting with the operating system import shutil # Import the shutil module for file operations import argparse # Import the argparse module for command-line argument parsing def synchronize(source_dir, destination_dir): # Ensure both directories exist if not os.path.exists(source_dir): print(f""Source directory '{source_dir}' does not exist."") return if not os.path.exists(destination_dir): print(f""Destination directory '{destination_dir}' does not exist."") return # Iterate over files in source directory for root, dirs, files in os.walk(source_dir): # Get corresponding path in destination directory relative_path = os.path.relpath(root, source_dir) dest_path = os.path.join(destination_dir, relative_path) # Ensure corresponding directory structure exists in destination if not os.path.exists(dest_path): os.makedirs(dest_path) # Copy files from source to destination for file in files: source_file = os.path.join(root, file) dest_file = os.path.join(dest_path, file) shutil.copy2(source_file, dest_file) print(f""Copied: {source_file} -> {dest_file}"") print(""Synchronization complete."") if __name__ == ""__main__"": # Create argument parser parser = argparse.ArgumentParser(description=""Synchronize files between two directories."") # Add argument for source directory parser.add_argument(""source"", help=""Source directory"") # Add argument for destination directory parser.add_argument(""destination"", help=""Destination directory"") # Parse the command-line arguments args = parser.parse_args() # Call the synchronize function with the provided arguments synchronize(args.source, args.destination)",44,44 ,"class Solution { public int numJewelsInStones(String jewels, String stones) { int cnt=0; for(int i=0;i map=new HashMap<>(); for (int i=0; i map=new HashMap<>(); for (int i=0; i dividedRange; int numberOfDivisions = 0; Random rand; public Solution(int n, int[] arr) { Arrays.sort(arr); rand = new Random(); dividedRange = new ArrayList <>(); int start = 0, end = 0; for (int i = 0; i < arr.length; i++) { end = arr[i] - 1; if (start > end) { start = arr[i] + 1; continue; } dividedRange.add(new int[]{start, end}); start = arr[i] + 1; } if (start < n) { dividedRange.add(new int[]{start, n-1}); } numberOfDivisions = dividedRange.size(); } public int pick() { int pickedDivision = rand.nextInt(numberOfDivisions); int start = dividedRange.get(pickedDivision)[0]; int end = dividedRange.get(pickedDivision)[1]; return rand.nextInt(end - start + 1) + start; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(n, blacklist); * int param_1 = obj.pick(); */",0.0,leetcode,,java,"class Solution { List dividedRange; int numberOfDivisions = 0; Random rand; public Solution(int n, int[] arr) { Arrays.sort(arr); rand = new Random(); dividedRange = new ArrayList <>(); int start = 0, end = 0; for (int i = 0; i < arr.length; i++) { end = arr[i] - 1; if (start > end) { start = arr[i] + 1; continue; } dividedRange.add(new int[]{start, end}); start = arr[i] + 1; } if (start < n) { dividedRange.add(new int[]{start, n-1}); } numberOfDivisions = dividedRange.size(); } public int pick() { int pickedDivision = rand.nextInt(numberOfDivisions); int start = dividedRange.get(pickedDivision)[0]; int end = dividedRange.get(pickedDivision)[1]; return rand.nextInt(end - start + 1) + start; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(n, blacklist); * int param_1 = obj.pick(); */",38,38 ,"interface SortStrategy { void sort(int[] arr); } class BubbleSortStrategy implements SortStrategy { public void sort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } } public class Sorter { private SortStrategy strategy; public void setStrategy(SortStrategy strategy) { this.strategy = strategy; } public void sort(int[] arr) { strategy.sort(arr); } } ",1.0,PERPLEXITY,Create strategy pattern in Java for different sorting algorithms.,java,"interface SortStrategy { void sort(int[] arr); } class BubbleSortStrategy implements SortStrategy { public void sort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } } public class Sorter { private SortStrategy strategy; public void setStrategy(SortStrategy strategy) { this.strategy = strategy; } public void sort(int[] arr) { strategy.sort(arr); } }",17,17 ,"def isHappy(n): seen = set() while n != 1 and n not in seen: seen.add(n) n = sum(int(c) ** 2 for c in str(n)) return n == 1 ",1.0,GPT,"Solve the problem ""Happy Number"". Determine if a number is happy. Use cycle detection or a set. Provide Python solution. ",python,"def isHappy(n): seen = set() while n != 1 and n not in seen: seen.add(n) n = sum(int(c) ** 2 for c in str(n)) return n == 1",8,8 ,"import java.util.regex.Pattern; public class EmailValidator { private static final Pattern EMAIL_PATTERN = Pattern.compile(""^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$""); public static boolean isValid(String email) { return EMAIL_PATTERN.matcher(email).matches(); } } ",1.0,PERPLEXITY,Write a Java method with regex pattern to validate email addresses comprehensively,java,"import java.util.regex.Pattern; public class EmailValidator { private static final Pattern EMAIL_PATTERN = Pattern.compile(""^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$""); public static boolean isValid(String email) { return EMAIL_PATTERN.matcher(email).matches(); } }",8,8 ,"import java.util.LinkedList; public class Queue { private LinkedList list = new LinkedList<>(); public void enqueue(T item) { list.addLast(item); } public T dequeue() { return list.pollFirst(); } public T peek() { return list.peekFirst(); } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } } ",1.0,PERPLEXITY,"Implement a generic Queue class in Java using LinkedList with enqueue, dequeue, and size methods.",java,"import java.util.LinkedList; public class Queue { private LinkedList list = new LinkedList<>(); public void enqueue(T item) { list.addLast(item); } public T dequeue() { return list.pollFirst(); } public T peek() { return list.peekFirst(); } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } }",9,9 ,"import numpy as np x = np.arange(10) print(""Original:"", x) print(""True division by 3:"", x / 3) ",1.0,PERPLEXITY," Write a NumPy program to get true division of the element-wise array inputs.",python,"import numpy as np x = np.arange(10) print(""Original:"", x) print(""True division by 3:"", x / 3)",5,5 ,"def numDecodings(s): if not s or s[0] == ""0"": return 0 dp1, dp2 = 1, 1 for i in range(1, len(s)): cur = 0 if s[i] != ""0"": cur += dp2 if 10 <= int(s[i - 1:i + 1]) <= 26: cur += dp1 dp1, dp2 = dp2, cur return dp2 ",1.0,GPT,"Solve the problem ""Decode Ways"". Given a string s containing digits, return the number of ways to decode it.",python,"def numDecodings(s): if not s or s[0] == ""0"": return 0 dp1, dp2 = 1, 1 for i in range(1, len(s)): cur = 0 if s[i] != ""0"": cur += dp2 if 10 <= int(s[i - 1:i + 1]) <= 26: cur += dp1 dp1, dp2 = dp2, cur return dp2",15,15 ,"def pascal_triangle(n): for i in range(n): row = [1] for j in range(1, i): row.append(row[j-1] + row[j]) row.append(1) if i > 0 else None print(row) # Test pascal_triangle(6) ",1.0,PERPLEXITY,Write a Python function that prints out the first n rows of Pascal's triangle.,python,"def pascal_triangle(n): for i in range(n): row = [1] for j in range(1, i): row.append(row[j-1] + row[j]) row.append(1) if i > 0 else None print(row) # Test pascal_triangle(6)",10,10 ,"class Solution { public String frequencySort(String s) { Map freqMap = new HashMap<>(); for (char c : s.toCharArray()) { freqMap.put(c, freqMap.getOrDefault(c, 0) + 1); } List> list = new ArrayList<>(freqMap.entrySet()); list.sort((a, b) -> b.getValue() - a.getValue()); StringBuilder sb = new StringBuilder(); for (Map.Entry entry : list) { char ch = entry.getKey(); int count = entry.getValue(); for (int i = 0; i < count; i++) { sb.append(ch); } } return sb.toString(); } } ",0.0,leetcode,,java,"class Solution { public String frequencySort(String s) { Map freqMap = new HashMap<>(); for (char c : s.toCharArray()) { freqMap.put(c, freqMap.getOrDefault(c, 0) + 1); } List> list = new ArrayList<>(freqMap.entrySet()); list.sort((a, b) -> b.getValue() - a.getValue()); StringBuilder sb = new StringBuilder(); for (Map.Entry entry : list) { char ch = entry.getKey(); int count = entry.getValue(); for (int i = 0; i < count; i++) { sb.append(ch); } } return sb.toString(); } }",27,27 ,"def reverseList(head): prev = None curr = head while curr: nxt = curr.next curr.next = prev prev = curr curr = nxt return prev ",1.0,GPT,"Solve the problem ""Reverse a Linked List"". Given the head of a singly linked list, reverse the list and return the new head.",python,"def reverseList(head): prev = None curr = head while curr: nxt = curr.next curr.next = prev prev = curr curr = nxt return prev",11,11 ,"class Solution { public boolean isRectangleCover(int[][] rectangles) { TreeSet set = new TreeSet((a, b) -> { if (a[3] <= b[1]) return -1; else if (a[1] >= b[3]) return 1; else if (a[2] <= b[0]) return -1; else if (a[0] >= b[2]) return 1; else return 0; }); int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE; int maxA = Integer.MIN_VALUE, maxB = Integer.MIN_VALUE; int totalArea = 0; for (int[] i : rectangles) { if (i[0] < minX) { minX = i[0]; } if (i[1] < minY) { minY = i[1]; } if (i[2] > maxA) { maxA = i[2]; } if (i[3] > maxB) { maxB = i[3]; } totalArea += (i[2] - i[0]) * (i[3] - i[1]); if (!set.add(i)) return false; } return totalArea == (maxA - minX) * (maxB - minY); } }",0.0,leetcode,,java,"class Solution { public boolean isRectangleCover(int[][] rectangles) { TreeSet set = new TreeSet((a, b) -> { if (a[3] <= b[1]) return -1; else if (a[1] >= b[3]) return 1; else if (a[2] <= b[0]) return -1; else if (a[0] >= b[2]) return 1; else return 0; }); int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE; int maxA = Integer.MIN_VALUE, maxB = Integer.MIN_VALUE; int totalArea = 0; for (int[] i : rectangles) { if (i[0] < minX) { minX = i[0]; } if (i[1] < minY) { minY = i[1]; } if (i[2] > maxA) { maxA = i[2]; } if (i[3] > maxB) { maxB = i[3]; } totalArea += (i[2] - i[0]) * (i[3] - i[1]); if (!set.add(i)) return false; } return totalArea == (maxA - minX) * (maxB - minY); } }",28,28 ,"# Define a function named 'abc' def abc(): # Define and assign values to local variables 'x', 'y', and 'str1' inside the function 'abc' x = 1 y = 2 str1 = ""w3resource"" # Print the string ""Python Exercises"" print(""Python Exercises"") # Access the number of local variables in the function 'abc' using the __code__.co_nlocals attribute print(abc.__code__.co_nlocals) ",0.0,W3RESOURCE,,python,"# Define a function named 'abc' def abc(): # Define and assign values to local variables 'x', 'y', and 'str1' inside the function 'abc' x = 1 y = 2 str1 = ""w3resource"" # Print the string ""Python Exercises"" print(""Python Exercises"") # Access the number of local variables in the function 'abc' using the __code__.co_nlocals attribute print(abc.__code__.co_nlocals) ",12,12 ,"class Solution { public double[] medianSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0) return new double[0]; Node root = null; for (int i = 0; i < k; i++) { root = insert(root, nums[i]); } double[] r = new double[nums.length - k + 1]; boolean even = k % 2 == 0; int j = 0; for (int i = k; i <= nums.length; i++) { double sum = 0.0; if (even) sum = (findSmallest(root, k/2).val + findSmallest(root, k/2 + 1).val) / 2.0; else sum = findSmallest(root, k/2 + 1).val; r[j++] = sum; if (i < nums.length) { root = insert(root, nums[i]); root = delete(root, nums[i - k]); } } return r; } private Node findSmallest(Node root, int k) { int s = countWith(root.left) + 1; if (s == k) return root; if (s > k) { return findSmallest(root.left, k); } return findSmallest(root.right, k - s); } private Node delete(Node root, long val) { if (root == null) return null; else if (val > root.val) root.right = delete(root.right, val); else if (val < root.val) root.left = delete(root.left, val); else { if (root.left == null) root = root.right; else if (root.right == null) root = root.left; else { Node t = findMin(root.right); root.val = t.val; root.right = delete(root.right, t.val); } } return updateNode(root); } private Node findMin(Node root) { if (root.left != null) return findMin(root.left); return root; } private Node insert(Node root, long val) { if (root == null) { return new Node(val); } if (val >= root.val) { root.right = insert(root.right, val); } else { root.left = insert(root.left, val); } return updateNode(root); } private Node updateNode(Node root) { int b = balance(root); if (b == 2 && balance(root.left) < 0) { root.left = leftRotate(root.left); root = rightRotate(root); } else if (b == -2 && balance(root.right) > 0) { root.right = rightRotate(root.right); root = leftRotate(root); } else if (b == 2) { root = rightRotate(root); } else if (b == -2) { root = leftRotate(root); } update(root); return root; } private Node leftRotate(Node n) { Node r = n.right; n.right = r.left; r.left = n; update(n); update(r); return r; } private Node rightRotate(Node n) { Node l = n.left; n.left = l.right; l.right = n; update(n); update(l); return l; } private int balance(Node n) { if (n==null)return 0; return height(n.left) - height(n.right); } private void update(Node n) { if (n==null)return; n.height = Math.max(height(n.left), height(n.right)) + 1; n.count = n.left != null ? n.left.count + 1 : 0; n.count += n.right != null ? n.right.count + 1 : 0; } private int height(Node n) { return n != null ? n.height : 0; } private int countWith(Node n) { return n != null ? n.count + 1 : 0; } static class Node { Node left; Node right; long val; int count; int height; Node(long val) { this.val = val; } } }",0.0,leetcode,,java,"class Solution { public double[] medianSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0) return new double[0]; Node root = null; for (int i = 0; i < k; i++) { root = insert(root, nums[i]); } double[] r = new double[nums.length - k + 1]; boolean even = k % 2 == 0; int j = 0; for (int i = k; i <= nums.length; i++) { double sum = 0.0; if (even) sum = (findSmallest(root, k/2).val + findSmallest(root, k/2 + 1).val) / 2.0; else sum = findSmallest(root, k/2 + 1).val; r[j++] = sum; if (i < nums.length) { root = insert(root, nums[i]); root = delete(root, nums[i - k]); } } return r; } private Node findSmallest(Node root, int k) { int s = countWith(root.left) + 1; if (s == k) return root; if (s > k) { return findSmallest(root.left, k); } return findSmallest(root.right, k - s); } private Node delete(Node root, long val) { if (root == null) return null; else if (val > root.val) root.right = delete(root.right, val); else if (val < root.val) root.left = delete(root.left, val); else { if (root.left == null) root = root.right; else if (root.right == null) ... truncated ... } private Node rightRotate(Node n) { Node l = n.left; n.left = l.right; l.right = n; update(n); update(l); return l; } private int balance(Node n) { if (n==null)return 0; return height(n.left) - height(n.right); } private void update(Node n) { if (n==null)return; n.height = Math.max(height(n.left), height(n.right)) + 1; n.count = n.left != null ? n.left.count + 1 : 0; n.count += n.right != null ? n.right.count + 1 : 0; } private int height(Node n) { return n != null ? n.height : 0; } private int countWith(Node n) { return n != null ? n.count + 1 : 0; } static class Node { Node left; Node right; long val; int count; int height; Node(long val) { this.val = val; } } }",167,101 ,"class Solution: def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] res = [""""] digitToChar = { ""2"": ""abc"", ""3"": ""def"", ""4"": ""ghi"", ""5"": ""jkl"", ""6"": ""mno"", ""7"": ""qprs"", ""8"": ""tuv"", ""9"": ""wxyz"", } for digit in digits: tmp = [] for curStr in res: for c in digitToChar[digit]: tmp.append(curStr + c) res = tmp return res",0.0,GFG,,python,"class Solution: def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] res = [""""] digitToChar = { ""2"": ""abc"", ""3"": ""def"", ""4"": ""ghi"", ""5"": ""jkl"", ""6"": ""mno"", ""7"": ""qprs"", ""8"": ""tuv"", ""9"": ""wxyz"", } for digit in digits: tmp = [] for curStr in res: for c in digitToChar[digit]: tmp.append(curStr + c) res = tmp return res",24,24 ,"import java.util.concurrent.Exchanger; public class ExchangerExercise { public static void main(String[] args) { Exchanger < String > exchanger = new Exchanger < > (); // Create and start two worker threads Thread thread1 = new Thread(new Worker(exchanger, ""Data from Thread 1"")); Thread thread2 = new Thread(new Worker(exchanger, ""Data from Thread 2"")); thread1.start(); thread2.start(); } static class Worker implements Runnable { private final Exchanger < String > exchanger; private final String data; public Worker(Exchanger < String > exchanger, String data) { this.exchanger = exchanger; this.data = data; } @Override public void run() { try { System.out.println(Thread.currentThread().getName() + "" sending data: "" + data); String receivedData = exchanger.exchange(data); // Exchange data with the other thread System.out.println(Thread.currentThread().getName() + "" received data: "" + receivedData); } catch (InterruptedException e) { e.printStackTrace(); } } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.Exchanger; public class ExchangerExercise { public static void main(String[] args) { Exchanger < String > exchanger = new Exchanger < > (); // Create and start two worker threads Thread thread1 = new Thread(new Worker(exchanger, ""Data from Thread 1"")); Thread thread2 = new Thread(new Worker(exchanger, ""Data from Thread 2"")); thread1.start(); thread2.start(); } static class Worker implements Runnable { private final Exchanger < String > exchanger; private final String data; public Worker(Exchanger < String > exchanger, String data) { this.exchanger = exchanger; this.data = data; } @Override public void run() { try { System.out.println(Thread.currentThread().getName() + "" sending data: "" + data); String receivedData = exchanger.exchange(data); // Exchange data with the other thread System.out.println(Thread.currentThread().getName() + "" received data: "" + receivedData); } catch (InterruptedException e) { e.printStackTrace(); } } } }",36,36 ,"def Sequential_Search(dlist, item): pos = 0 found = False while pos < len(dlist) and not found: if dlist[pos] == item: found = True else: pos = pos + 1 return found, pos print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))",0.0,W3RESOURCE,,python,"def Sequential_Search(dlist, item): pos = 0 found = False while pos < len(dlist) and not found: if dlist[pos] == item: found = True else: pos = pos + 1 return found, pos print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))",14,14 ,"class Solution { private TreeNode root; private String result = """"; public String longestWord(String[] words) { root = new TreeNode(); for (String w : words) insert(w); dfs(root); return result; } private void dfs(TreeNode node) { if (node == null) return; if (node.word != null) { if (node.word.length() > result.length()) result = node.word; else if (node.word.length() == result.length() && node.word.compareTo(result) < 0) result = node.word; } for (TreeNode child : node.children) if (child != null && child.word != null) dfs(child); } private void insert(String word) { TreeNode current = root; for (char c : word.toCharArray()) { if (current.children[c - 'a'] == null) current.children[c - 'a'] = new TreeNode(); current = current.children[c - 'a']; } current.word = word; } } class TreeNode { TreeNode[] children = new TreeNode[26]; String word; TreeNode () {} }",0.0,leetcode,,java,"class Solution { private TreeNode root; private String result = """"; public String longestWord(String[] words) { root = new TreeNode(); for (String w : words) insert(w); dfs(root); return result; } private void dfs(TreeNode node) { if (node == null) return; if (node.word != null) { if (node.word.length() > result.length()) result = node.word; else if (node.word.length() == result.length() && node.word.compareTo(result) < 0) result = node.word; } for (TreeNode child : node.children) if (child != null && child.word != null) dfs(child); } private void insert(String word) { TreeNode current = root; for (char c : word.toCharArray()) { if (current.children[c - 'a'] == null) current.children[c - 'a'] = new TreeNode(); current = current.children[c - 'a']; } current.word = word; } } class TreeNode { TreeNode[] children = new TreeNode[26]; String word; TreeNode () {} }",49,49 ,"# Define a function named 'string_test' that counts the number of upper and lower case characters in a string 's' def string_test(s): # Create a dictionary 'd' to store the count of upper and lower case characters d = {""UPPER_CASE"": 0, ""LOWER_CASE"": 0} # Iterate through each character 'c' in the string 's' for c in s: # Check if the character 'c' is in upper case if c.isupper(): # If 'c' is upper case, increment the count of upper case characters in the dictionary d[""UPPER_CASE""] += 1 # Check if the character 'c' is in lower case elif c.islower(): # If 'c' is lower case, increment the count of lower case characters in the dictionary d[""LOWER_CASE""] += 1 else: # If 'c' is neither upper nor lower case (e.g., punctuation, spaces), do nothing pass # Print the original string 's' print(""Original String: "", s) # Print the count of upper case characters print(""No. of Upper case characters: "", d[""UPPER_CASE""]) # Print the count of lower case characters print(""No. of Lower case Characters: "", d[""LOWER_CASE""]) # Call the 'string_test' function with the input string 'The quick Brown Fox' string_test('The quick Brown Fox')",0.0,W3RESOURCE,,python,"# Define a function named 'string_test' that counts the number of upper and lower case characters in a string 's' def string_test(s): # Create a dictionary 'd' to store the count of upper and lower case characters d = {""UPPER_CASE"": 0, ""LOWER_CASE"": 0} # Iterate through each character 'c' in the string 's' for c in s: # Check if the character 'c' is in upper case if c.isupper(): # If 'c' is upper case, increment the count of upper case characters in the dictionary d[""UPPER_CASE""] += 1 # Check if the character 'c' is in lower case elif c.islower(): # If 'c' is lower case, increment the count of lower case characters in the dictionary d[""LOWER_CASE""] += 1 else: # If 'c' is neither upper nor lower case (e.g., punctuation, spaces), do nothing pass # Print the original string 's' print(""Original String: "", s) # Print the count of upper case characters print(""No. of Upper case characters: "", d[""UPPER_CASE""]) # Print the count of lower case characters print(""No. of Lower case Characters: "", d[""LOWER_CASE""]) # Call the 'string_test' function with the input string 'The quick Brown Fox' string_test('The quick Brown Fox')",30,30 ,"public class OddEvenArray { public static void main(String args[]) { int s, i; int[] a = { 33, 2, 4, 71, 88, 92, 9, 1 }; for (i = 0; i < a.length; i++) { for (int j = i + 1; j < a.length; j++) { if (a[i] > a[j]) { s = a[i]; a[i] = a[j]; a[j] = s; } } } System.out.print(""Input numbers :""); for (i = 0; i < a.length; i++) { System.out.print("" "" + a[i]); } System.out.print(""\nOdd numbers :""); for (i = 0; i <= a.length - 1; i++) { if (a[i] % 2 != 0) { System.out.print("" "" + a[i]); } } System.out.print(""\nEven numbers :""); for (i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { System.out.print("" "" + a[i]); } } } } ",0.0,IPSGWALIOR.ORG,,java,"public class OddEvenArray { public static void main(String args[]) { int s, i; int[] a = { 33, 2, 4, 71, 88, 92, 9, 1 }; for (i = 0; i < a.length; i++) { for (int j = i + 1; j < a.length; j++) { if (a[i] > a[j]) { s = a[i]; a[i] = a[j]; a[j] = s; } } } System.out.print(""Input numbers :""); for (i = 0; i < a.length; i++) { System.out.print("" "" + a[i]); } System.out.print(""\nOdd numbers :""); for (i = 0; i <= a.length - 1; i++) { if (a[i] % 2 != 0) { System.out.print("" "" + a[i]); } } System.out.print(""\nEven numbers :""); for (i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { System.out.print("" "" + a[i]); } } } }",42,42 ,"import java.util.*; class AllOne { // Bucket node for doubly linked list private static class Bucket { int count; Set keys; Bucket prev, next; Bucket(int count) { this.count = count; this.keys = new HashSet<>(); } } private Bucket head, tail; private Map keyToBucket; public AllOne() { head = new Bucket(0); // dummy head tail = new Bucket(0); // dummy tail head.next = tail; tail.prev = head; keyToBucket = new HashMap<>(); } public void inc(String key) { if (!keyToBucket.containsKey(key)) { // insert new key with count = 1 Bucket first = head.next; if (first != tail && first.count == 1) { first.keys.add(key); keyToBucket.put(key, first); } else { Bucket newBucket = new Bucket(1); newBucket.keys.add(key); insertAfter(head, newBucket); keyToBucket.put(key, newBucket); } } else { Bucket curr = keyToBucket.get(key); Bucket next = curr.next; if (next != tail && next.count == curr.count + 1) { next.keys.add(key); keyToBucket.put(key, next); } else { Bucket newBucket = new Bucket(curr.count + 1); newBucket.keys.add(key); insertAfter(curr, newBucket); keyToBucket.put(key, newBucket); } curr.keys.remove(key); if (curr.keys.isEmpty()) { remove(curr); } } } public void dec(String key) { Bucket curr = keyToBucket.get(key); if (curr.count == 1) { // remove key completely curr.keys.remove(key); keyToBucket.remove(key); if (curr.keys.isEmpty()) { remove(curr); } } else { Bucket prev = curr.prev; if (prev != head && prev.count == curr.count - 1) { prev.keys.add(key); keyToBucket.put(key, prev); } else { Bucket newBucket = new Bucket(curr.count - 1); newBucket.keys.add(key); insertAfter(curr.prev, newBucket); keyToBucket.put(key, newBucket); } curr.keys.remove(key); if (curr.keys.isEmpty()) { remove(curr); } } } public String getMaxKey() { if (tail.prev == head) return """"; return tail.prev.keys.iterator().next(); } public String getMinKey() { if (head.next == tail) return """"; return head.next.keys.iterator().next(); } // Doubly linked list helpers private void insertAfter(Bucket prev, Bucket node) { node.prev = prev; node.next = prev.next; prev.next.prev = node; prev.next = node; } private void remove(Bucket node) { node.prev.next = node.next; node.next.prev = node.prev; } } /** * Your AllOne object will be instantiated and called as such: * AllOne obj = new AllOne(); * obj.inc(key); * obj.dec(key); * String param_3 = obj.getMaxKey(); * String param_4 = obj.getMinKey(); */",0.0,leetcode,,java,"import java.util.*; class AllOne { // Bucket node for doubly linked list private static class Bucket { int count; Set keys; Bucket prev, next; Bucket(int count) { this.count = count; this.keys = new HashSet<>(); } } private Bucket head, tail; private Map keyToBucket; public AllOne() { head = new Bucket(0); // dummy head tail = new Bucket(0); // dummy tail head.next = tail; tail.prev = head; keyToBucket = new HashMap<>(); } public void inc(String key) { if (!keyToBucket.containsKey(key)) { // insert new key with count = 1 Bucket first = head.next; if (first != tail && first.count == 1) { first.keys.add(key); keyToBucket.put(key, first); } else { Bucket newBucket = new Bucket(1); newBucket.keys.add(key); insertAfter(head, newBucket); keyToBucket.put(key, newBucket); } } else { Bucket curr = keyToBucket.get(key); Bucket next = curr.next; if (next != tail && next.count == curr.count + 1) { next.keys.add(key); keyToBucket.put(key, next); } else { Bucket newBucket = new Bucket(curr.count + 1); newBucket.keys.add(key); ... truncated ... if (prev != head && prev.count == curr.count - 1) { prev.keys.add(key); keyToBucket.put(key, prev); } else { Bucket newBucket = new Bucket(curr.count - 1); newBucket.keys.add(key); insertAfter(curr.prev, newBucket); keyToBucket.put(key, newBucket); } curr.keys.remove(key); if (curr.keys.isEmpty()) { remove(curr); } } } public String getMaxKey() { if (tail.prev == head) return """"; return tail.prev.keys.iterator().next(); } public String getMinKey() { if (head.next == tail) return """"; return head.next.keys.iterator().next(); } // Doubly linked list helpers private void insertAfter(Bucket prev, Bucket node) { node.prev = prev; node.next = prev.next; prev.next.prev = node; prev.next = node; } private void remove(Bucket node) { node.prev.next = node.next; node.next.prev = node.prev; } } /** * Your AllOne object will be instantiated and called as such: * AllOne obj = new AllOne(); * obj.inc(key); * obj.dec(key); * String param_3 = obj.getMaxKey(); * String param_4 = obj.getMinKey(); */",124,101 ,"class Solution { public List findDuplicateSubtrees(TreeNode root) { List res=new ArrayList<>(); HashMap hm=new HashMap<>(); helper(res,root,hm); return res; } public String helper(List res,TreeNode root,HashMap hm){ if(root==null) return """"; String left=helper(res,root.left,hm); String right=helper(res,root.right,hm); int currroot=root.val; String stringformed=currroot+""$""+left+""$""+right; if(hm.getOrDefault(stringformed,0)==1){ res.add(root); } hm.put(stringformed,hm.getOrDefault(stringformed,0)+1); return stringformed; } }",0.0,leetcode,,java,"class Solution { public List findDuplicateSubtrees(TreeNode root) { List res=new ArrayList<>(); HashMap hm=new HashMap<>(); helper(res,root,hm); return res; } public String helper(List res,TreeNode root,HashMap hm){ if(root==null) return """"; String left=helper(res,root.left,hm); String right=helper(res,root.right,hm); int currroot=root.val; String stringformed=currroot+""$""+left+""$""+right; if(hm.getOrDefault(stringformed,0)==1){ res.add(root); } hm.put(stringformed,hm.getOrDefault(stringformed,0)+1); return stringformed; } }",21,21 ,"import json def encode_complex(object): # check using isinstance method if isinstance(object, complex): return [object.real, object.imag] # raised error if object is not complex raise TypeError(repr(object) + "" is not JSON serialized"") complex_obj = json.dumps(2 + 3j, default=encode_complex) print(complex_obj) ",0.0,WE3RESOURCE,,python,"import json def encode_complex(object): # check using isinstance method if isinstance(object, complex): return [object.real, object.imag] # raised error if object is not complex raise TypeError(repr(object) + "" is not JSON serialized"") complex_obj = json.dumps(2 + 3j, default=encode_complex) print(complex_obj) ",11,11 ,"# Import the 'string' and 'sys' modules import string import sys # Define a function named 'ispangram' that checks if a string is a pangram def ispangram(str1, alphabet=string.ascii_lowercase): # Create a set 'alphaset' containing all lowercase letters from the provided alphabet alphaset = set(alphabet) # Convert the input string to lowercase and create a set from it str_set = set(str1.lower()) # Check if the set of lowercase characters in the input string covers all characters in 'alphaset' return alphaset <= str_set # Print the result of checking if the string is a pangram by calling the 'ispangram' function print(ispangram('The quick brown fox jumps over the lazy dog')) ",0.0,W3RESOURCE,,python,"# Import the 'string' and 'sys' modules import string import sys # Define a function named 'ispangram' that checks if a string is a pangram def ispangram(str1, alphabet=string.ascii_lowercase): # Create a set 'alphaset' containing all lowercase letters from the provided alphabet alphaset = set(alphabet) # Convert the input string to lowercase and create a set from it str_set = set(str1.lower()) # Check if the set of lowercase characters in the input string covers all characters in 'alphaset' return alphaset <= str_set # Print the result of checking if the string is a pangram by calling the 'ispangram' function print(ispangram('The quick brown fox jumps over the lazy dog')) ",17,17 ,"#https://bit.ly/2lVhlLX import requests from lxml import html url = 'http://www.state.gov/r/pa/ode/socialmedia/' doc = html.fromstring(requests.get(url).text) pinlinks = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))] print(""The number of Pinterest accounts maintained by U.S. State Department embassies and missions:"") print(len(pinlinks)) ",0.0,WE3RESOURCE,,python,"#https://bit.ly/2lVhlLX import requests from lxml import html url = 'http://www.state.gov/r/pa/ode/socialmedia/' doc = html.fromstring(requests.get(url).text) pinlinks = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))] print(""The number of Pinterest accounts maintained by U.S. State Department embassies and missions:"") print(len(pinlinks))",8,8 ,"def reverseKGroup(head, k): dummy = ListNode(0) dummy.next = head prev = dummy while True: kth = prev for _ in range(k): kth = kth.next if not kth: return dummy.next nxt = kth.next curr = prev.next for _ in range(k): tmp = curr.next curr.next = nxt nxt = curr curr = tmp tmp = prev.next prev.next = kth prev = tmp ",1.0,GPT,"Solve the problem ""Reverse Nodes in K-Group"". Given a linked list, reverse the nodes of the list k at a time. If the number of nodes is not a multiple of k, leave them as is. Provide Python solution. ",python,"def reverseKGroup(head, k): dummy = ListNode(0) dummy.next = head prev = dummy while True: kth = prev for _ in range(k): kth = kth.next if not kth: return dummy.next nxt = kth.next curr = prev.next for _ in range(k): tmp = curr.next curr.next = nxt nxt = curr curr = tmp tmp = prev.next prev.next = kth prev = tmp",24,24 ,"import json # a Python object (dict): python_obj = { ""name"": ""David"", ""class"":""I"", ""age"": 6 } print(type(python_obj)) # convert into JSON: j_data = json.dumps(python_obj) # result is a JSON string: print(j_data) ",0.0,WE3RESOURCE,,python,"import json # a Python object (dict): python_obj = { ""name"": ""David"", ""class"":""I"", ""age"": 6 } print(type(python_obj)) # convert into JSON: j_data = json.dumps(python_obj) # result is a JSON string: print(j_data)",13,13 ,"class Solution { private Map digitToLetters = new HashMap<>(); private List resultList = new ArrayList<>(); public List letterCombinations(String digits) { if (digits == null || digits.length() == 0) { return resultList; } digitToLetters.put('2', ""abc""); digitToLetters.put('3', ""def""); digitToLetters.put('4', ""ghi""); digitToLetters.put('5', ""jkl""); digitToLetters.put('6', ""mno""); digitToLetters.put('7', ""pqrs""); digitToLetters.put('8', ""tuv""); digitToLetters.put('9', ""wxyz""); generateCombinations(digits, 0, new StringBuilder()); return resultList; } private void generateCombinations(String digits, int currentIndex, StringBuilder currentCombination) { if (currentIndex == digits.length()) { resultList.add(currentCombination.toString()); return; } char currentDigit = digits.charAt(currentIndex); String letterOptions = digitToLetters.get(currentDigit); if (letterOptions != null) { for (int i = 0; i < letterOptions.length(); i++) { char letter = letterOptions.charAt(i); currentCombination.append(letter); generateCombinations(digits, currentIndex + 1, currentCombination); currentCombination.deleteCharAt(currentCombination.length() - 1); } } } }",0.0,leetcode,,java,"class Solution { private Map digitToLetters = new HashMap<>(); private List resultList = new ArrayList<>(); public List letterCombinations(String digits) { if (digits == null || digits.length() == 0) { return resultList; } digitToLetters.put('2', ""abc""); digitToLetters.put('3', ""def""); digitToLetters.put('4', ""ghi""); digitToLetters.put('5', ""jkl""); digitToLetters.put('6', ""mno""); digitToLetters.put('7', ""pqrs""); digitToLetters.put('8', ""tuv""); digitToLetters.put('9', ""wxyz""); generateCombinations(digits, 0, new StringBuilder()); return resultList; } private void generateCombinations(String digits, int currentIndex, StringBuilder currentCombination) { if (currentIndex == digits.length()) { resultList.add(currentCombination.toString()); return; } char currentDigit = digits.charAt(currentIndex); String letterOptions = digitToLetters.get(currentDigit); if (letterOptions != null) { for (int i = 0; i < letterOptions.length(); i++) { char letter = letterOptions.charAt(i); currentCombination.append(letter); generateCombinations(digits, currentIndex + 1, currentCombination); currentCombination.deleteCharAt(currentCombination.length() - 1); } } } }",45,45 ,"def mergeSort(nlist): print(""Splitting "",nlist) if len(nlist)>1: mid = len(nlist)//2 lefthalf = nlist[:mid] righthalf = nlist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=j=k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: nlist[k]=lefthalf[i] i=i+1 else: nlist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): nlist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): nlist[k]=righthalf[j] j=j+1 k=k+1 print(""Merging "",nlist) nlist = [14,46,43,27,57,41,45,21,70] mergeSort(nlist) print(nlist) ",0.0,W3RESOURCE,,python,"def mergeSort(nlist): print(""Splitting "",nlist) if len(nlist)>1: mid = len(nlist)//2 lefthalf = nlist[:mid] righthalf = nlist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=j=k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: nlist[k]=lefthalf[i] i=i+1 else: nlist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): nlist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): nlist[k]=righthalf[j] j=j+1 k=k+1 print(""Merging "",nlist) nlist = [14,46,43,27,57,41,45,21,70] mergeSort(nlist) print(nlist)",33,33 ,"import java.time.Instant; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; public class EventStore { private final ConcurrentHashMap> streams; private final ConcurrentHashMap streamVersions; public EventStore() { this.streams = new ConcurrentHashMap<>(); this.streamVersions = new ConcurrentHashMap<>(); } public static class Event { private final String eventId; private final String streamId; private final String eventType; private final Map data; private final Map metadata; private final Instant timestamp; private final long version; public Event(String streamId, String eventType, Map data, long version) { this.eventId = UUID.randomUUID().toString(); this.streamId = streamId; this.eventType = eventType; this.data = Collections.unmodifiableMap(new HashMap<>(data)); this.metadata = new HashMap<>(); this.timestamp = Instant.now(); this.version = version; } // Getters public String getEventId() { return eventId; } public String getStreamId() { return streamId; } public String getEventType() { return eventType; } public Map getData() { return data; } public Map getMetadata() { return metadata; } public Instant getTimestamp() { return timestamp; } public long getVersion() { return version; } public void addMetadata(String key, Object value) { metadata.put(key, value); } } public AppendResult appendToStream(String streamId, List events, long expectedVersion) { if (events == null || events.isEmpty()) { throw new IllegalArgumentException(""Events cannot be empty""); } streams.compute(streamId, (key, existingEvents) -> { long currentVersion = streamVersions .computeIfAbsent(streamId, k -> new AtomicLong(0)) .get(); // Optimistic concurrency check if (expectedVersion != -1 && currentVersion != expectedVersion) { throw new ConcurrencyException( String.format(""Expected version %d but was %d"", expectedVersion, currentVersion) ); } List streamEvents = existingEvents != null ? new ArrayList<>(existingEvents) : new ArrayList<>(); // Assign versions to events for (int i = 0; i < events.size(); i++) { Event event = events.get(i); Event versionedEvent = new Event( streamId, event.eventType, event.data, currentVersion + i + 1 ); event.metadata.forEach(versionedEvent::addMetadata); streamEvents.add(versionedEvent); } // Update version streamVersions.get(streamId).addAndGet(events.size()); return Collections.unmodifiableList(streamEvents); }); return new AppendResult(streamId, streamVersions.get(streamId).get(), events.size() ); } public List readStream(String streamId) { List events = streams.get(streamId); return events != null ? new ArrayList<>(events) : new ArrayList<>(); } public List readStream(String streamId, long fromVersion) { List events = streams.get(streamId); if (events == null) { return new ArrayList<>(); } return events.stream() .filter(e -> e.getVersion() >= fromVersion) .collect(Collectors.toList()); } public List readAllEvents() { return streams.values().stream() .flatMap(List::stream) .sorted(Comparator.comparing(Event::getTimestamp) .thenComparing(Event::getVersion)) .collect(Collectors.toList()); } public long getStreamVersion(String streamId) { AtomicLong version = streamVersions.get(streamId); return version != null ? version.get() : 0; } public void subscribe(EventSubscriber subscriber) { // Implementation for event subscription } public static class AppendResult { private final String streamId; private final long newVersion; private final int eventsAppended; AppendResult(String streamId, long newVersion, int eventsAppended) { this.streamId = streamId; this.newVersion = newVersion; this.eventsAppended = eventsAppended; } public String getStreamId() { return streamId; } public long getNewVersion() { return newVersion; } public int getEventsAppended() { return eventsAppended; } } public interface EventSubscriber { void handle(Event event); } public static class ConcurrencyException extends RuntimeException { public ConcurrencyException(String message) { super(message); } } }",1.0,DEEPSEEK,Create an event store for CQRS pattern with optimistic concurrency control.,java,"import java.time.Instant; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; public class EventStore { private final ConcurrentHashMap> streams; private final ConcurrentHashMap streamVersions; public EventStore() { this.streams = new ConcurrentHashMap<>(); this.streamVersions = new ConcurrentHashMap<>(); } public static class Event { private final String eventId; private final String streamId; private final String eventType; private final Map data; private final Map metadata; private final Instant timestamp; private final long version; public Event(String streamId, String eventType, Map data, long version) { this.eventId = UUID.randomUUID().toString(); this.streamId = streamId; this.eventType = eventType; this.data = Collections.unmodifiableMap(new HashMap<>(data)); this.metadata = new HashMap<>(); this.timestamp = Instant.now(); this.version = version; } // Getters public String getEventId() { return eventId; } public String getStreamId() { return streamId; } public String getEventType() { return eventType; } public Map getData() { return data; } public Map getMetadata() { return metadata; } public Instant getTimestamp() { return timestamp; } public long getVersion() { return version; } public void addMetadata(String key, Object value) { metadata.put(key, value); } } public AppendResult appendToStream(String streamId, List events, ... truncated ... } return events.stream() .filter(e -> e.getVersion() >= fromVersion) .collect(Collectors.toList()); } public List readAllEvents() { return streams.values().stream() .flatMap(List::stream) .sorted(Comparator.comparing(Event::getTimestamp) .thenComparing(Event::getVersion)) .collect(Collectors.toList()); } public long getStreamVersion(String streamId) { AtomicLong version = streamVersions.get(streamId); return version != null ? version.get() : 0; } public void subscribe(EventSubscriber subscriber) { // Implementation for event subscription } public static class AppendResult { private final String streamId; private final long newVersion; private final int eventsAppended; AppendResult(String streamId, long newVersion, int eventsAppended) { this.streamId = streamId; this.newVersion = newVersion; this.eventsAppended = eventsAppended; } public String getStreamId() { return streamId; } public long getNewVersion() { return newVersion; } public int getEventsAppended() { return eventsAppended; } } public interface EventSubscriber { void handle(Event event); } public static class ConcurrencyException extends RuntimeException { public ConcurrencyException(String message) { super(message); } } }",155,101 ,"def solve(board): if not board: return rows, cols = len(board), len(board[0]) def dfs(r, c): if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != ""O"": return board[r][c] = ""T"" dfs(r+1, c) dfs(r-1, c) dfs(r, c+1) dfs(r, c-1) for r in range(rows): dfs(r, 0) dfs(r, cols - 1) for c in range(cols): dfs(0, c) dfs(rows - 1, c) for r in range(rows): for c in range(cols): if board[r][c] == ""O"": board[r][c] = ""X"" elif board[r][c] == ""T"": board[r][c] = ""O"" ",1.0,GPT,"Solve the problem ""Surrounded Regions"". Given a board of 'X' and 'O', capture all regions surrounded by 'X'.",python,"def solve(board): if not board: return rows, cols = len(board), len(board[0]) def dfs(r, c): if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != ""O"": return board[r][c] = ""T"" dfs(r+1, c) dfs(r-1, c) dfs(r, c+1) dfs(r, c-1) for r in range(rows): dfs(r, 0) dfs(r, cols - 1) for c in range(cols): dfs(0, c) dfs(rows - 1, c) for r in range(rows): for c in range(cols): if board[r][c] == ""O"": board[r][c] = ""X"" elif board[r][c] == ""T"": board[r][c] = ""O""",28,28 ,"import numpy as np # Example 2D array arr = np.array([[3, 2, 5], [1, 4, 6], [2, 1, 7]]) n = 1 # The column index to sort by (0-based) # Get the indices that would sort the array by column n sorted_indices = np.argsort(arr[:, n]) # Sort the array by the specified column sorted_arr = arr[sorted_indices] print(""Array sorted by column"", n, "":\n"", sorted_arr)",1.0,DEEPAI,Write a NumPy program to sort an given array by the nth column.,python,"import numpy as np # Example 2D array arr = np.array([[3, 2, 5], [1, 4, 6], [2, 1, 7]]) n = 1 # The column index to sort by (0-based) # Get the indices that would sort the array by column n sorted_indices = np.argsort(arr[:, n]) # Sort the array by the specified column sorted_arr = arr[sorted_indices] print(""Array sorted by column"", n, "":\n"", sorted_arr)",16,16 ,"def subsetsWithDup(nums): nums.sort() res = [] def backtrack(i, cur): res.append(cur[:]) for j in range(i, len(nums)): if j > i and nums[j] == nums[j - 1]: continue cur.append(nums[j]) backtrack(j + 1, cur) cur.pop() backtrack(0, []) return res ",1.0,GPT,"Solve the problem ""Subsets II"". Given an integer array nums that may contain duplicates, return all possible subsets without duplicate subsets.",python,"def subsetsWithDup(nums): nums.sort() res = [] def backtrack(i, cur): res.append(cur[:]) for j in range(i, len(nums)): if j > i and nums[j] == nums[j - 1]: continue cur.append(nums[j]) backtrack(j + 1, cur) cur.pop() backtrack(0, []) return res",15,15 ,"import json # JSON encoded data (often received from an API or web request) json_data = ''' { ""company"": ""TechFlow"", ""location"": ""San Francisco"", ""employees"": 150, ""is_hiring"": true, ""tech_stack"": [""Python"", ""React"", ""PostgreSQL""], ""revenue"": null } ''' def decode_json(json_string): try: # Convert JSON string to Python object (Dictionary) python_obj = json.loads(json_string) print(""Successfully converted JSON to Python Object:"") print(f""Type: {type(python_obj)}"") print(""-"" * 30) # Accessing the data using Python keys print(f""Company Name: {python_obj['company']}"") print(f""Main Language: {python_obj['tech_stack'][0]}"") print(f""Hiring Status: {python_obj['is_hiring']}"") return python_obj except json.JSONDecodeError as e: print(f""Failed to decode JSON: {e}"") # Execute the conversion decoded_data = decode_json(json_data)",1.0,GEMINI,Write a Python program to convert JSON encoded data into Python objects.,python,"import json # JSON encoded data (often received from an API or web request) json_data = ''' { ""company"": ""TechFlow"", ""location"": ""San Francisco"", ""employees"": 150, ""is_hiring"": true, ""tech_stack"": [""Python"", ""React"", ""PostgreSQL""], ""revenue"": null } ''' def decode_json(json_string): try: # Convert JSON string to Python object (Dictionary) python_obj = json.loads(json_string) print(""Successfully converted JSON to Python Object:"") print(f""Type: {type(python_obj)}"") print(""-"" * 30) # Accessing the data using Python keys print(f""Company Name: {python_obj['company']}"") print(f""Main Language: {python_obj['tech_stack'][0]}"") print(f""Hiring Status: {python_obj['is_hiring']}"") return python_obj except json.JSONDecodeError as e: print(f""Failed to decode JSON: {e}"") # Execute the conversion decoded_data = decode_json(json_data)",35,35 ,"import java.util.concurrent.Phaser; public class PhaserExercise { public static void main(String[] args) { // Create a Phaser with 4 registered parties Phaser phaser = new Phaser(4); // Create and start three worker threads Thread thread1 = new Thread(new Worker(phaser, ""Thread 1"")); Thread thread2 = new Thread(new Worker(phaser, ""Thread 2"")); Thread thread3 = new Thread(new Worker(phaser, ""Thread 3"")); Thread thread4 = new Thread(new Worker(phaser, ""Thread 4"")); thread1.start(); thread2.start(); thread3.start(); thread4.start(); // Wait for all threads to complete phaser.awaitAdvance(phaser.getPhase()); System.out.println(""All threads have completed their tasks.""); } static class Worker implements Runnable { private final Phaser phaser; private final String name; public Worker(Phaser phaser, String name) { this.phaser = phaser; this.name = name; } @Override public void run() { System.out.println(name + "" starting phase 1""); phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point // Perform phase 1 tasks System.out.println(name + "" performing phase 1 tasks""); // Wait for all threads to complete phase 1 phaser.arriveAndAwaitAdvance(); System.out.println(name + "" starting phase 2""); phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point // Perform phase 2 tasks System.out.println(name + "" performing phase 2 tasks""); // Wait for all threads to complete phase 2 phaser.arriveAndAwaitAdvance(); System.out.println(name + "" completed all phases""); phaser.arriveAndDeregister(); // Deregister from the Phaser } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.Phaser; public class PhaserExercise { public static void main(String[] args) { // Create a Phaser with 4 registered parties Phaser phaser = new Phaser(4); // Create and start three worker threads Thread thread1 = new Thread(new Worker(phaser, ""Thread 1"")); Thread thread2 = new Thread(new Worker(phaser, ""Thread 2"")); Thread thread3 = new Thread(new Worker(phaser, ""Thread 3"")); Thread thread4 = new Thread(new Worker(phaser, ""Thread 4"")); thread1.start(); thread2.start(); thread3.start(); thread4.start(); // Wait for all threads to complete phaser.awaitAdvance(phaser.getPhase()); System.out.println(""All threads have completed their tasks.""); } static class Worker implements Runnable { private final Phaser phaser; private final String name; public Worker(Phaser phaser, String name) { this.phaser = phaser; this.name = name; } @Override public void run() { System.out.println(name + "" starting phase 1""); phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point // Perform phase 1 tasks System.out.println(name + "" performing phase 1 tasks""); // Wait for all threads to complete phase 1 phaser.arriveAndAwaitAdvance(); System.out.println(name + "" starting phase 2""); phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point // Perform phase 2 tasks System.out.println(name + "" performing phase 2 tasks""); // Wait for all threads to complete phase 2 phaser.arriveAndAwaitAdvance(); System.out.println(name + "" completed all phases""); phaser.arriveAndDeregister(); // Deregister from the Phaser } } }",58,58 ,"def twoSum(numbers, target): l, r = 0, len(numbers) - 1 while l < r: s = numbers[l] + numbers[r] if s == target: return [l + 1, r + 1] elif s < target: l += 1 else: r -= 1 ",1.0,GPT,"Given a sorted array of integers and a target, return the 1-based indices of the two numbers such that they add up to the target. Use only constant extra space.",python,"def twoSum(numbers, target): l, r = 0, len(numbers) - 1 while l < r: s = numbers[l] + numbers[r] if s == target: return [l + 1, r + 1] elif s < target: l += 1 else: r -= 1",11,11 ,"//SemaphoreExercise.java import java.util.concurrent.Semaphore; public class SemaphoreExercise { private static final int NUM_THREADS = 5; private static final int NUM_PERMITS = 2; public static void main(String[] args) { Semaphore semaphore = new Semaphore(NUM_PERMITS); Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Worker(semaphore)); threads[i].start(); } try { for (Thread thread: threads) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } } static class Worker implements Runnable { private Semaphore semaphore; public Worker(Semaphore semaphore) { this.semaphore = semaphore; } public void run() { try { semaphore.acquire(); // Perform work that requires the semaphore System.out.println(""Thread "" + Thread.currentThread().getName() + "" acquired the semaphore.""); Thread.sleep(2000); // Simulating work System.out.println(""Thread "" + Thread.currentThread().getName() + "" released the semaphore.""); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } } } ",0.0,WE3RESOURCE,,java,"//SemaphoreExercise.java import java.util.concurrent.Semaphore; public class SemaphoreExercise { private static final int NUM_THREADS = 5; private static final int NUM_PERMITS = 2; public static void main(String[] args) { Semaphore semaphore = new Semaphore(NUM_PERMITS); Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Worker(semaphore)); threads[i].start(); } try { for (Thread thread: threads) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } } static class Worker implements Runnable { private Semaphore semaphore; public Worker(Semaphore semaphore) { this.semaphore = semaphore; } public void run() { try { semaphore.acquire(); // Perform work that requires the semaphore System.out.println(""Thread "" + Thread.currentThread().getName() + "" acquired the semaphore.""); Thread.sleep(2000); // Simulating work System.out.println(""Thread "" + Thread.currentThread().getName() + "" released the semaphore.""); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } } }",48,48 ,"public int trap(int[] height) { int l = 0, r = height.length - 1, lMax = 0, rMax = 0, ans = 0; while (l < r) { if (height[l] < height[r]) { if (height[l] >= lMax) lMax = height[l]; else ans += lMax - height[l]; l++; } else { if (height[r] >= rMax) rMax = height[r]; else ans += rMax - height[r]; r--; } } return ans; }",1.0,GEMINI,"write a java progrom for Given n non-negative integers representing an elevation map, compute how much water it can trap.",java,"public int trap(int[] height) { int l = 0, r = height.length - 1, lMax = 0, rMax = 0, ans = 0; while (l < r) { if (height[l] < height[r]) { if (height[l] >= lMax) lMax = height[l]; else ans += lMax - height[l]; l++; } else { if (height[r] >= rMax) rMax = height[r]; else ans += rMax - height[r]; r--; } } return ans; }",13,13 ,"from collections import deque def orangesRotting(grid): rows, cols = len(grid), len(grid[0]) q = deque() fresh = 0 for r in range(rows): for c in range(cols): if grid[r][c] == 2: q.append((r, c)) elif grid[r][c] == 1: fresh += 1 time = 0 directions = [(1,0), (-1,0), (0,1), (0,-1)] while q and fresh: for _ in range(len(q)): r, c = q.popleft() for dr, dc in directions: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1: grid[nr][nc] = 2 fresh -= 1 q.append((nr, nc)) time += 1 return time if fresh == 0 else -1 ",1.0,GPT,"Solve the problem ""Rotting Oranges"". Given a grid where: 0 = empty, 1 = fresh, 2 = rotten, return the minimum minutes to rot all fresh oranges. If impossible, return -1. ",python,"from collections import deque def orangesRotting(grid): rows, cols = len(grid), len(grid[0]) q = deque() fresh = 0 for r in range(rows): for c in range(cols): if grid[r][c] == 2: q.append((r, c)) elif grid[r][c] == 1: fresh += 1 time = 0 directions = [(1,0), (-1,0), (0,1), (0,-1)] while q and fresh: for _ in range(len(q)): r, c = q.popleft() for dr, dc in directions: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1: grid[nr][nc] = 2 fresh -= 1 q.append((nr, nc)) time += 1 return time if fresh == 0 else -1",29,29 ,"def bubbleSort(nlist): for passnum in range(len(nlist)-1,0,-1): for i in range(passnum): if nlist[i]>nlist[i+1]: temp = nlist[i] nlist[i] = nlist[i+1] nlist[i+1] = temp nlist = [14,46,43,27,57,41,45,21,70] bubbleSort(nlist) print(nlist)",0.0,W3RESOURCE,,python,"def bubbleSort(nlist): for passnum in range(len(nlist)-1,0,-1): for i in range(passnum): if nlist[i]>nlist[i+1]: temp = nlist[i] nlist[i] = nlist[i+1] nlist[i+1] = temp nlist = [14,46,43,27,57,41,45,21,70] bubbleSort(nlist) print(nlist)",11,11 ,"import java.util.Scanner; public class BinarySearch { public static void main(String args[]) { int counter, num, item, array[], first, last, middle; Scanner input = new Scanner(System.in); System.out.println(""Enter number of elements:""); num = input.nextInt(); array = new int[num]; System.out.println(""Enter "" + num + "" integers""); for (counter = 0; counter < num; counter++) array[counter] = input.nextInt(); System.out.println(""Enter the search value:""); item = input.nextInt(); first = 0; last = num - 1; middle = (first + last) / 2; while (first <= last) { if (array[middle] < item) first = middle + 1; else if (array[middle] == item) { System.out.println(item + "" found at location "" + (middle + 1) + "".""); break; } else { last = middle - 1; } middle = (first + last) / 2; } if (first > last) System.out.println(item + "" is not found.\n""); } } ",0.0,IPSGWALIOR.ORG,,java,"import java.util.Scanner; public class BinarySearch { public static void main(String args[]) { int counter, num, item, array[], first, last, middle; Scanner input = new Scanner(System.in); System.out.println(""Enter number of elements:""); num = input.nextInt(); array = new int[num]; System.out.println(""Enter "" + num + "" integers""); for (counter = 0; counter < num; counter++) array[counter] = input.nextInt(); System.out.println(""Enter the search value:""); item = input.nextInt(); first = 0; last = num - 1; middle = (first + last) / 2; while (first <= last) { if (array[middle] < item) first = middle + 1; else if (array[middle] == item) { System.out.println(item + "" found at location "" + (middle + 1) + "".""); break; } else { last = middle - 1; } middle = (first + last) / 2; } if (first > last) System.out.println(item + "" is not found.\n""); } }",38,38 ,"import string def ispangram(str1, alphabet=string.ascii_lowercase): alphaset = set(alphabet) str_set = set(str1.lower()) return alphaset <= str_set # Test print(ispangram('The quick brown fox jumps over the lazy dog')) # True ",1.0,PERPLEXITY,Write a Python function to check whether a string is a pangram or not.,python,"import string def ispangram(str1, alphabet=string.ascii_lowercase): alphaset = set(alphabet) str_set = set(str1.lower()) return alphaset <= str_set # Test print(ispangram('The quick brown fox jumps over the lazy dog')) # True",9,9 ,"class MinStack { private Stack st = new Stack<>(), minSt = new Stack<>(); public void push(int x) { st.push(x); if (minSt.isEmpty() || x <= minSt.peek()) minSt.push(x); } public void pop() { if (st.pop().equals(minSt.peek())) minSt.pop(); } public int getMin() { return minSt.peek(); } }",1.0,GEMINI,"Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.",java,"class MinStack { private Stack st = new Stack<>(), minSt = new Stack<>(); public void push(int x) { st.push(x); if (minSt.isEmpty() || x <= minSt.peek()) minSt.push(x); } public void pop() { if (st.pop().equals(minSt.peek())) minSt.pop(); } public int getMin() { return minSt.peek(); } }",11,11 ,"class Solution { int i=0,j=0; int m=0;int n=0; public Solution(int m, int n) { this.m=m; this.n=n; } public int[] flip() { j++; if(j==n){ j=0; i++; } if(i==m){ i=0; j=0; } return new int[]{i,j}; } public void reset() { } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(m, n); * int[] param_1 = obj.flip(); * obj.reset(); */",0.0,leetcode,,java,"class Solution { int i=0,j=0; int m=0;int n=0; public Solution(int m, int n) { this.m=m; this.n=n; } public int[] flip() { j++; if(j==n){ j=0; i++; } if(i==m){ i=0; j=0; } return new int[]{i,j}; } public void reset() { } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(m, n); * int[] param_1 = obj.flip(); * obj.reset(); */",39,39 ,"class Trie { Node root; public Trie() { root = new Node(); } public void insert(String word) { root.insert(word, 0); } public boolean search(String word) { return root.search(word, 0); } public boolean startsWith(String prefix) { return root.startsWith(prefix, 0); } class Node { Node[] nodes; boolean isEnd; Node() { nodes = new Node[26]; } private void insert(String word, int idx) { if (idx >= word.length()) return; int i = word.charAt(idx) - 'a'; if (nodes[i] == null) { nodes[i] = new Node(); } if (idx == word.length()-1) nodes[i].isEnd = true; nodes[i].insert(word, idx+1); } private boolean search(String word, int idx) { if (idx >= word.length()) return false; Node node = nodes[word.charAt(idx) - 'a']; if (node == null) return false; if (idx == word.length() - 1 && node.isEnd) return true; return node.search(word, idx+1); } private boolean startsWith(String prefix, int idx) { if (idx >= prefix.length()) return false; Node node = nodes[prefix.charAt(idx) - 'a']; if (node == null) return false; if (idx == prefix.length() - 1) return true; return node.startsWith(prefix, idx+1); } } }",0.0,leetcode,,java,"class Trie { Node root; public Trie() { root = new Node(); } public void insert(String word) { root.insert(word, 0); } public boolean search(String word) { return root.search(word, 0); } public boolean startsWith(String prefix) { return root.startsWith(prefix, 0); } class Node { Node[] nodes; boolean isEnd; Node() { nodes = new Node[26]; } private void insert(String word, int idx) { if (idx >= word.length()) return; int i = word.charAt(idx) - 'a'; if (nodes[i] == null) { nodes[i] = new Node(); } if (idx == word.length()-1) nodes[i].isEnd = true; nodes[i].insert(word, idx+1); } private boolean search(String word, int idx) { if (idx >= word.length()) return false; Node node = nodes[word.charAt(idx) - 'a']; if (node == null) return false; if (idx == word.length() - 1 && node.isEnd) return true; return node.search(word, idx+1); } private boolean startsWith(String prefix, int idx) { if (idx >= prefix.length()) return false; Node node = nodes[prefix.charAt(idx) - 'a']; if (node == null) return false; if (idx == prefix.length() - 1) return true; return node.startsWith(prefix, idx+1); } } }",58,58 ,"# Define a function named 'test_range' that checks if a number 'n' is within the range 3 to 8 (inclusive) def test_range(n): # Check if 'n' is within the range from 3 to 8 (inclusive) using the 'in range()' statement if n in range(3, 9): # If 'n' is within the range, print that 'n' is within the given range print(""%s is in the range"" % str(n)) else: # If 'n' is outside the range, print that the number is outside the given range print(""The number is outside the given range."") # Call the 'test_range' function with the argument 5 test_range(5)",0.0,W3RESOURCE,,python,"# Define a function named 'test_range' that checks if a number 'n' is within the range 3 to 8 (inclusive) def test_range(n): # Check if 'n' is within the range from 3 to 8 (inclusive) using the 'in range()' statement if n in range(3, 9): # If 'n' is within the range, print that 'n' is within the given range print(""%s is in the range"" % str(n)) else: # If 'n' is outside the range, print that the number is outside the given range print(""The number is outside the given range."") # Call the 'test_range' function with the argument 5 test_range(5)",12,12 ,"import java.util.Base64; public class Base64Util { public static String encode(String input) { byte[] encoded = Base64.getEncoder().encode(input.getBytes()); return new String(encoded); } public static String decode(String encoded) { byte[] decoded = Base64.getDecoder().decode(encoded.getBytes()); return new String(decoded); } } ",1.0,PERPLEXITY,Create a Java utility class with static methods to encode and decode strings using Base64.,java,"import java.util.Base64; public class Base64Util { public static String encode(String input) { byte[] encoded = Base64.getEncoder().encode(input.getBytes()); return new String(encoded); } public static String decode(String encoded) { byte[] decoded = Base64.getDecoder().decode(encoded.getBytes()); return new String(decoded); } }",11,11 ,"import json python_obj = '{""a"": 1, ""a"": 2, ""a"": 3, ""a"": 4, ""b"": 1, ""b"": 2}' print(""Original Python object:"") print(python_obj) json_obj = json.loads(python_obj) print(""\nUnique Key in a JSON object:"") print(json_obj) ",0.0,WE3RESOURCE,,python,"import json python_obj = '{""a"": 1, ""a"": 2, ""a"": 3, ""a"": 4, ""b"": 1, ""b"": 2}' print(""Original Python object:"") print(python_obj) json_obj = json.loads(python_obj) print(""\nUnique Key in a JSON object:"") print(json_obj) ",7,7 ,"class Solution: def islandsAndTreasure(self, grid: List[List[int]]) -> None: ROWS, COLS = len(grid), len(grid[0]) visit = set() q = deque() def addCell(r, c): if (min(r, c) < 0 or r == ROWS or c == COLS or (r, c) in visit or grid[r][c] == -1 ): return visit.add((r, c)) q.append([r, c]) for r in range(ROWS): for c in range(COLS): if grid[r][c] == 0: q.append([r, c]) visit.add((r, c)) dist = 0 while q: for i in range(len(q)): r, c = q.popleft() grid[r][c] = dist addCell(r + 1, c) addCell(r - 1, c) addCell(r, c + 1) addCell(r, c - 1) dist += 1",0.0,GFG,,python,"class Solution: def islandsAndTreasure(self, grid: List[List[int]]) -> None: ROWS, COLS = len(grid), len(grid[0]) visit = set() q = deque() def addCell(r, c): if (min(r, c) < 0 or r == ROWS or c == COLS or (r, c) in visit or grid[r][c] == -1 ): return visit.add((r, c)) q.append([r, c]) for r in range(ROWS): for c in range(COLS): if grid[r][c] == 0: q.append([r, c]) visit.add((r, c)) dist = 0 while q: for i in range(len(q)): r, c = q.popleft() grid[r][c] = dist addCell(r + 1, c) addCell(r - 1, c) addCell(r, c + 1) addCell(r, c - 1) dist += 1",30,30 ,"// O(n) Time Solution class Solution { public int findPairs(int[] nums, int k) { Map map = new HashMap(); for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); int result = 0; for (int i : map.keySet()) if (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1) result++; return result; } }",0.0,leetcode,,java,"// O(n) Time Solution class Solution { public int findPairs(int[] nums, int k) { Map map = new HashMap(); for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); int result = 0; for (int i : map.keySet()) if (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1) result++; return result; } }",15,15 ,"from collections import deque def ladderLength(beginWord, endWord, wordList): wordSet = set(wordList) if endWord not in wordSet: return 0 q = deque([(beginWord, 1)]) while q: word, steps = q.popleft() if word == endWord: return steps for i in range(len(word)): for c in ""abcdefghijklmnopqrstuvwxyz"": new = word[:i] + c + word[i+1:] if new in wordSet: wordSet.remove(new) q.append((new, steps + 1)) return 0 ",1.0,GPT,"Solve the problem ""Word Ladder"". Given beginWord, endWord, and a wordList, return the length of the shortest transformation sequence.",python,"from collections import deque def ladderLength(beginWord, endWord, wordList): wordSet = set(wordList) if endWord not in wordSet: return 0 q = deque([(beginWord, 1)]) while q: word, steps = q.popleft() if word == endWord: return steps for i in range(len(word)): for c in ""abcdefghijklmnopqrstuvwxyz"": new = word[:i] + c + word[i+1:] if new in wordSet: wordSet.remove(new) q.append((new, steps + 1)) return 0",21,21 ,"def solveNQueens(n): res = [] cols, diag1, diag2 = set(), set(), set() board = [["".""] * n for _ in range(n)] def backtrack(r): if r == n: res.append(["""".join(row) for row in board]) return for c in range(n): if c in cols or (r - c) in diag1 or (r + c) in diag2: continue cols.add(c) diag1.add(r - c) diag2.add(r + c) board[r][c] = ""Q"" backtrack(r + 1) cols.remove(c) diag1.remove(r - c) diag2.remove(r + c) board[r][c] = ""."" backtrack(0) return res ",1.0,GPT,"Solve the problem ""N-Queens"". Given an integer n, return all distinct solutions to the n-queens puzzle.",python,"def solveNQueens(n): res = [] cols, diag1, diag2 = set(), set(), set() board = [["".""] * n for _ in range(n)] def backtrack(r): if r == n: res.append(["""".join(row) for row in board]) return for c in range(n): if c in cols or (r - c) in diag1 or (r + c) in diag2: continue cols.add(c) diag1.add(r - c) diag2.add(r + c) board[r][c] = ""Q"" backtrack(r + 1) cols.remove(c) diag1.remove(r - c) diag2.remove(r + c) board[r][c] = ""."" backtrack(0) return res",26,26 ,"class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: m, n = len(s1), len(s2) if m + n != len(s3): return False if n < m: s1, s2 = s2, s1 m, n = n, m dp = [False for _ in range(n + 1)] dp[n] = True for i in range(m, -1, -1): nextDp = True if i == m else False for j in range(n, -1, -1): res = False if j < n else nextDp if i < m and s1[i] == s3[i + j] and dp[j]: res = True if j < n and s2[j] == s3[i + j] and nextDp: res = True dp[j] = res nextDp = dp[j] return dp[0]",0.0,GFG,,python,"class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: m, n = len(s1), len(s2) if m + n != len(s3): return False if n < m: s1, s2 = s2, s1 m, n = n, m dp = [False for _ in range(n + 1)] dp[n] = True for i in range(m, -1, -1): nextDp = True if i == m else False for j in range(n, -1, -1): res = False if j < n else nextDp if i < m and s1[i] == s3[i + j] and dp[j]: res = True if j < n and s2[j] == s3[i + j] and nextDp: res = True dp[j] = res nextDp = dp[j] return dp[0]",22,22 ,"class Solution { public int leastInterval(char[] tasks, int n) { int[] freq = new int[26]; for (char task : tasks) { freq[task - 'A']++; } Arrays.sort(freq); int chunk = freq[25] - 1; int idle = chunk * n; for (int i = 24; i >= 0; i--) { idle -= Math.min(chunk, freq[i]); } return idle < 0 ? tasks.length : tasks.length + idle; } }",0.0,leetcode,,java,"class Solution { public int leastInterval(char[] tasks, int n) { int[] freq = new int[26]; for (char task : tasks) { freq[task - 'A']++; } Arrays.sort(freq); int chunk = freq[25] - 1; int idle = chunk * n; for (int i = 24; i >= 0; i--) { idle -= Math.min(chunk, freq[i]); } return idle < 0 ? tasks.length : tasks.length + idle; } }",17,17 ,"import java.util.HashMap; class Solution { public String customSortString(String order, String s) { StringBuilder result = new StringBuilder(); HashMap mp = new HashMap<>(); for (char c : s.toCharArray()) { mp.put(c, mp.getOrDefault(c, 0) + 1); } for (char c : order.toCharArray()) { if (mp.containsKey(c)) { result.append(String.valueOf(c).repeat(Math.max(0, mp.get(c)))); mp.remove(c); } } for (char c : mp.keySet()) { result.append(String.valueOf(c).repeat(Math.max(0, mp.get(c)))); } return result.toString(); } }",0.0,leetcode,,java,"import java.util.HashMap; class Solution { public String customSortString(String order, String s) { StringBuilder result = new StringBuilder(); HashMap mp = new HashMap<>(); for (char c : s.toCharArray()) { mp.put(c, mp.getOrDefault(c, 0) + 1); } for (char c : order.toCharArray()) { if (mp.containsKey(c)) { result.append(String.valueOf(c).repeat(Math.max(0, mp.get(c)))); mp.remove(c); } } for (char c : mp.keySet()) { result.append(String.valueOf(c).repeat(Math.max(0, mp.get(c)))); } return result.toString(); } }",21,21 ,"# Import necessary modules from dataclasses import dataclass, field, fields, Field from typing import Any, Callable, List, get_type_hints # Custom exception for validation errors class ValidationError(Exception): pass # Function to validate dataclass fields def validate(instance): cls = instance.__class__ hints = get_type_hints(cls) # Iterate through fields and type hints for name, type_hint in hints.items(): value = getattr(instance, name) # Check if value matches type hint if not isinstance(value, type_hint): raise ValidationError(f""Field '{name}' expects {type_hint}, got {type(value)}"") # Check for custom validators field: Field = next(f for f in fields(cls) if f.name == name) if 'validators' in field.metadata: for validator in field.metadata['validators']: validator(instance, value) # Decorator to define a validator function def validator(func: Callable[[Any, Any], None]): if not callable(func): raise ValueError(""Validator must be callable"") func._is_validator = True return func # Function to define a field with validation def field_with_validation(*, default: Any = None, default_factory: Callable[[], Any] = None, validators: List[Callable[[Any, Any], None]] = None) -> Field: # Ensure only one of default or default_factory is provided if default is not None and default_factory is not None: raise ValueError('cannot specify both default and default_factory') metadata = {} # Attach validators to metadata if validators: metadata['validators'] = validators # Define field with appropriate parameters if default is not None: return field(default=default, metadata=metadata) elif default_factory is not None: return field(default_factory=default_factory, metadata=metadata) else: return field(metadata=metadata) # Dataclass representing a User with validation @dataclass class User: # Define fields with validation name: str age: int = field_with_validation(default=0, validators=[ validator(lambda instance, value: value >= 0 or ValidationError(""Age must be non-negative"")), validator(lambda instance, value: value <= 150 or ValidationError(""Age must be 150 or less"")) ]) email: str = field_with_validation(default="""", validators=[ validator(lambda instance, value: ""@"" in value or ValidationError(""Invalid email address"")) ]) # Example usage try: user = User(name=""Arsen"", age=30, email=""arsen@example.com"") validate(user) print(""User is valid"") except ValidationError as e: print(f""Validation error: {e}"")",0.0,W3RESOURCE,,python,"# Import necessary modules from dataclasses import dataclass, field, fields, Field from typing import Any, Callable, List, get_type_hints # Custom exception for validation errors class ValidationError(Exception): pass # Function to validate dataclass fields def validate(instance): cls = instance.__class__ hints = get_type_hints(cls) # Iterate through fields and type hints for name, type_hint in hints.items(): value = getattr(instance, name) # Check if value matches type hint if not isinstance(value, type_hint): raise ValidationError(f""Field '{name}' expects {type_hint}, got {type(value)}"") # Check for custom validators field: Field = next(f for f in fields(cls) if f.name == name) if 'validators' in field.metadata: for validator in field.metadata['validators']: validator(instance, value) # Decorator to define a validator function def validator(func: Callable[[Any, Any], None]): if not callable(func): raise ValueError(""Validator must be callable"") func._is_validator = True return func # Function to define a field with validation def field_with_validation(*, default: Any = None, default_factory: Callable[[], Any] = None, validators: List[Callable[[Any, Any], None]] = None) -> Field: # Ensure only one of default or default_factory is provided if default is not None and default_factory is not None: raise ValueError('cannot specify both default and default_factory') metadata = {} # Attach validators to metadata if validators: metadata['validators'] = validators # Define field with appropriate parameters if default is not None: return field(default=default, metadata=metadata) elif default_factory is not None: return field(default_factory=default_factory, metadata=metadata) else: return field(metadata=metadata) # Dataclass representing a User with validation @dataclass class User: # Define fields with validation name: str age: int = field_with_validation(default=0, validators=[ validator(lambda instance, value: value >= 0 or ValidationError(""Age must be non-negative"")), validator(lambda instance, value: value <= 150 or ValidationError(""Age must be 150 or less"")) ]) email: str = field_with_validation(default="""", validators=[ validator(lambda instance, value: ""@"" in value or ValidationError(""Invalid email address"")) ]) # Example usage try: user = User(name=""Arsen"", age=30, email=""arsen@example.com"") validate(user) print(""User is valid"") except ValidationError as e: print(f""Validation error: {e}"")",70,70 ,"# Define a function to perform matrix multiplication of matrices A and B def matrix_multiplication(A, B): """""" Perform matrix multiplication of matrices A and B. Args: A: First matrix (list of lists). B: Second matrix (list of lists). Returns: Result of matrix multiplication (list of lists). """""" if len(A[0]) != len(B): raise ValueError(""Number of columns in A must equal number of rows in B"") # Number of rows and columns in resulting matrix num_rows_A = len(A) num_cols_B = len(B[0]) # Perform matrix multiplication using list comprehension result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(num_cols_B)] for i in range(num_rows_A)] return result # Example usage: if __name__ == ""__main__"": # Example matrices A and B A = [[1, 2, 3], [4, 5, 6]] B = [[7, 8], [9, 10], [11, 12]] # Print the result of matrix multiplication print(matrix_multiplication(A, B)) Output:",0.0,W3RESOURCE,,python,"# Define a function to perform matrix multiplication of matrices A and B def matrix_multiplication(A, B): """""" Perform matrix multiplication of matrices A and B. Args: A: First matrix (list of lists). B: Second matrix (list of lists). Returns: Result of matrix multiplication (list of lists). """""" if len(A[0]) != len(B): raise ValueError(""Number of columns in A must equal number of rows in B"") # Number of rows and columns in resulting matrix num_rows_A = len(A) num_cols_B = len(B[0]) # Perform matrix multiplication using list comprehension result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(num_cols_B)] for i in range(num_rows_A)] return result # Example usage: if __name__ == ""__main__"": # Example matrices A and B A = [[1, 2, 3], [4, 5, 6]] B = [[7, 8], [9, 10], [11, 12]] # Print the result of matrix multiplication print(matrix_multiplication(A, B)) Output:",37,37 ,"def coinChange(coins, amount): dp = [amount + 1] * (amount + 1) dp[0] = 0 for a in range(1, amount + 1): for c in coins: if a - c >= 0: dp[a] = min(dp[a], dp[a - c] + 1) return dp[amount] if dp[amount] != amount + 1 else -1 ",1.0,GPT,"Solve the problem ""Coin Change"". Given an array coins and an integer amount, return the fewest number of coins needed to make up that amount. If not possible, return -1.",python,"def coinChange(coins, amount): dp = [amount + 1] * (amount + 1) dp[0] = 0 for a in range(1, amount + 1): for c in coins: if a - c >= 0: dp[a] = min(dp[a], dp[a - c] + 1) return dp[amount] if dp[amount] != amount + 1 else -1",10,10 ,"def generateParenthesis(n): res = [] def backtrack(opened, closed, cur): if opened == closed == n: res.append(cur) return if opened < n: backtrack(opened + 1, closed, cur + ""("") if closed < opened: backtrack(opened, closed + 1, cur + "")"") backtrack(0, 0, """") return res ",1.0,GPT,"Solve the problem ""Generate Parentheses"". Given n pairs of parentheses, generate all combinations of well-formed parentheses. Provide Python backtracking solution. ",python,"def generateParenthesis(n): res = [] def backtrack(opened, closed, cur): if opened == closed == n: res.append(cur) return if opened < n: backtrack(opened + 1, closed, cur + ""("") if closed < opened: backtrack(opened, closed + 1, cur + "")"") backtrack(0, 0, """") return res",14,14 ,"import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierExercise { private static final int NUM_THREADS = 3; private static final CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS, new BarrierAction()); public static void main(String[] args) { Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Worker()); threads[i].start(); } try { for (Thread thread: threads) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } } static class Worker implements Runnable { public void run() { try { System.out.println(""Thread "" + Thread.currentThread().getName() + "" is waiting at the barrier.""); barrier.await(); // Perform work after reaching the barrier System.out.println(""Thread "" + Thread.currentThread().getName() + "" has crossed the barrier and continued execution.""); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } } static class BarrierAction implements Runnable { public void run() { System.out.println(""Barrier reached! All threads have arrived at the barrier.""); } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierExercise { private static final int NUM_THREADS = 3; private static final CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS, new BarrierAction()); public static void main(String[] args) { Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Worker()); threads[i].start(); } try { for (Thread thread: threads) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } } static class Worker implements Runnable { public void run() { try { System.out.println(""Thread "" + Thread.currentThread().getName() + "" is waiting at the barrier.""); barrier.await(); // Perform work after reaching the barrier System.out.println(""Thread "" + Thread.currentThread().getName() + "" has crossed the barrier and continued execution.""); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } } static class BarrierAction implements Runnable { public void run() { System.out.println(""Barrier reached! All threads have arrived at the barrier.""); } } }",44,44 ,"// Define the Account class public class Account { // Private instance variables private String accountNumber; private double balance; // Parameterized constructor with validation public Account(String accountNumber, double balance) { // Validate accountNumber if (accountNumber == null || accountNumber.isEmpty()) { // Print error message if accountNumber is null or empty System.err.println(""Error: Account number cannot be null or empty.""); return; } // Validate balance if (balance < 0) { // Print error message if balance is negative System.err.println(""Error: Balance cannot be negative.""); return; } // Initialize accountNumber with the provided parameter this.accountNumber = accountNumber; // Initialize balance with the provided parameter this.balance = balance; } // Main method to test the Account class public static void main(String[] args) { // Test with valid data Account account1 = new Account(""12340009"", 1000.00); System.out.println(""Account 1 Number: "" + account1.accountNumber); System.out.println(""Account 1 Balance: "" + account1.balance); // Test with invalid accountNumber Account account2 = new Account("""", 400.00); // Test with invalid balance Account account3 = new Account(""1230000873"", -200.00); } } ",0.0,WE3RESOURCE,,java,"// Define the Account class public class Account { // Private instance variables private String accountNumber; private double balance; // Parameterized constructor with validation public Account(String accountNumber, double balance) { // Validate accountNumber if (accountNumber == null || accountNumber.isEmpty()) { // Print error message if accountNumber is null or empty System.err.println(""Error: Account number cannot be null or empty.""); return; } // Validate balance if (balance < 0) { // Print error message if balance is negative System.err.println(""Error: Balance cannot be negative.""); return; } // Initialize accountNumber with the provided parameter this.accountNumber = accountNumber; // Initialize balance with the provided parameter this.balance = balance; } // Main method to test the Account class public static void main(String[] args) { // Test with valid data Account account1 = new Account(""12340009"", 1000.00); System.out.println(""Account 1 Number: "" + account1.accountNumber); System.out.println(""Account 1 Balance: "" + account1.balance); // Test with invalid accountNumber Account account2 = new Account("""", 400.00); // Test with invalid balance Account account3 = new Account(""1230000873"", -200.00); } }",40,40 ,"def multiply_numbers(numbers): return 1 if not numbers else numbers[0] * multiply_numbers(numbers[1:]) # Or using reduce (from functools) from functools import reduce def multiply_numbers(numbers): return reduce(lambda x, y: x * y, numbers, 1) print(multiply_numbers([8, 2, 3, -1, 7])) # Output: -336 ",1.0,PERPLEXITY,"Write a Python function to multiply all the numbers in a list. Sample List : (8, 2, 3, -1, 7) Expected Output : -336",python,"def multiply_numbers(numbers): return 1 if not numbers else numbers[0] * multiply_numbers(numbers[1:]) # Or using reduce (from functools) from functools import reduce def multiply_numbers(numbers): return reduce(lambda x, y: x * y, numbers, 1) print(multiply_numbers([8, 2, 3, -1, 7])) # Output: -336",9,9 ,"class Solution { public boolean pyramidTransition(String bottom, List allowed) { List[][] map = new List[6][6]; Map memo = new HashMap<>(); for (String al : allowed) { int a = al.charAt(0) - 'A'; int b = al.charAt(1) - 'A'; if (map[a][b] == null) map[a][b] = new ArrayList<>(); map[a][b].add(al.charAt(2)); } return dfs(bottom.toCharArray(), map, memo); } private boolean dfs(char[] row, List[][] map, Map memo) { int n = row.length; if (n == 1) return true; String key = new String(row); if (memo.containsKey(key)) return memo.get(key); List nextRows = new ArrayList<>(); getNextRows(row, map, 0, new char[n-1], nextRows); for (char[] next : nextRows) { if (dfs(next, map, memo)) { memo.put(key, true); return true; } } memo.put(key, false); return false; } private void getNextRows(char[] row, List[][] map, int idx, char[] current, List result) { if (idx == row.length - 1) { result.add(current.clone()); return; } int a = row[idx] - 'A'; int b = row[idx + 1] - 'A'; if (map[a][b] == null) return; for (char c : map[a][b]) { current[idx] = c; getNextRows(row, map, idx + 1, current, result); } } }",0.0,leetcode,,java,"class Solution { public boolean pyramidTransition(String bottom, List allowed) { List[][] map = new List[6][6]; Map memo = new HashMap<>(); for (String al : allowed) { int a = al.charAt(0) - 'A'; int b = al.charAt(1) - 'A'; if (map[a][b] == null) map[a][b] = new ArrayList<>(); map[a][b].add(al.charAt(2)); } return dfs(bottom.toCharArray(), map, memo); } private boolean dfs(char[] row, List[][] map, Map memo) { int n = row.length; if (n == 1) return true; String key = new String(row); if (memo.containsKey(key)) return memo.get(key); List nextRows = new ArrayList<>(); getNextRows(row, map, 0, new char[n-1], nextRows); for (char[] next : nextRows) { if (dfs(next, map, memo)) { memo.put(key, true); return true; } } memo.put(key, false); return false; } private void getNextRows(char[] row, List[][] map, int idx, char[] current, List result) { if (idx == row.length - 1) { result.add(current.clone()); return; } int a = row[idx] - 'A'; int b = row[idx + 1] - 'A'; if (map[a][b] == null) return; for (char c : map[a][b]) { current[idx] = c; getNextRows(row, map, idx + 1, current, result); } } }",54,54 ,"public List wordBreak(String s, Set wordDict) { return DFS(s, wordDict, new HashMap>()); } // DFS function returns an array including all substrings derived from s. List DFS(String s, Set wordDict, HashMap>map) { if (map.containsKey(s)) return map.get(s); LinkedListres = new LinkedList(); if (s.length() == 0) { res.add(""""); return res; } for (String word : wordDict) { if (s.startsWith(word)) { Listsublist = DFS(s.substring(word.length()), wordDict, map); for (String sub : sublist) res.add(word + (sub.isEmpty() ? """" : "" "") + sub); } } map.put(s, res); return res; }",0.0,leetcode,,java,"public List wordBreak(String s, Set wordDict) { return DFS(s, wordDict, new HashMap>()); } // DFS function returns an array including all substrings derived from s. List DFS(String s, Set wordDict, HashMap>map) { if (map.containsKey(s)) return map.get(s); LinkedListres = new LinkedList(); if (s.length() == 0) { res.add(""""); return res; } for (String word : wordDict) { if (s.startsWith(word)) { Listsublist = DFS(s.substring(word.length()), wordDict, map); for (String sub : sublist) res.add(word + (sub.isEmpty() ? """" : "" "") + sub); } } map.put(s, res); return res; }",24,24 ,"import java.util.concurrent.CountDownLatch; public class CountDownLatchExercise { private static final int NUM_THREADS = 3; private static final CountDownLatch startLatch = new CountDownLatch(1); private static final CountDownLatch finishLatch = new CountDownLatch(NUM_THREADS); public static void main(String[] args) { Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Worker()); threads[i].start(); } // Allow threads to start simultaneously startLatch.countDown(); try { finishLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(""All threads have finished their work.""); } static class Worker implements Runnable { public void run() { try { startLatch.await(); // Perform work System.out.println(""Thread "" + Thread.currentThread().getName() + "" has finished its work.""); } catch (InterruptedException e) { e.printStackTrace(); } finally { finishLatch.countDown(); } } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.CountDownLatch; public class CountDownLatchExercise { private static final int NUM_THREADS = 3; private static final CountDownLatch startLatch = new CountDownLatch(1); private static final CountDownLatch finishLatch = new CountDownLatch(NUM_THREADS); public static void main(String[] args) { Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Worker()); threads[i].start(); } // Allow threads to start simultaneously startLatch.countDown(); try { finishLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(""All threads have finished their work.""); } static class Worker implements Runnable { public void run() { try { startLatch.await(); // Perform work System.out.println(""Thread "" + Thread.currentThread().getName() + "" has finished its work.""); } catch (InterruptedException e) { e.printStackTrace(); } finally { finishLatch.countDown(); } } } }",42,42 ,"import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockExercise { private static final int NUM_READERS = 3; private static final int NUM_WRITERS = 2; public static void main(String[] args) { ReadWriteLock lock = new ReentrantReadWriteLock(); SharedResource sharedResource = new SharedResource(); // Create and start the reader threads for (int i = 0; i < NUM_READERS; i++) { Thread readerThread = new Thread(new Reader(lock, sharedResource)); readerThread.start(); } // Create and start the writer threads for (int i = 0; i < NUM_WRITERS; i++) { Thread writerThread = new Thread(new Writer(lock, sharedResource)); writerThread.start(); } } static class Reader implements Runnable { private ReadWriteLock lock; private SharedResource sharedResource; public Reader(ReadWriteLock lock, SharedResource sharedResource) { this.lock = lock; this.sharedResource = sharedResource; } public void run() { while (true) { lock.readLock().lock(); // Read from the shared resource System.out.println(""Reader "" + Thread.currentThread().getName() + "" reads: "" + sharedResource.read()); lock.readLock().unlock(); // Delay between consecutive reads try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class Writer implements Runnable { private ReadWriteLock lock; private SharedResource sharedResource; private int counter = 0; public Writer(ReadWriteLock lock, SharedResource sharedResource) { this.lock = lock; this.sharedResource = sharedResource; } public void run() { while (true) { lock.writeLock().lock(); // Write to the shared resource sharedResource.write(""Writer "" + Thread.currentThread().getName() + "" writes: "" + counter++); lock.writeLock().unlock(); // Delay between consecutive writes try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class SharedResource { private String data; public String read() { return data; } public void write(String data) { this.data = data; } } } ",0.0,WE3RESOURCE,,java,"import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockExercise { private static final int NUM_READERS = 3; private static final int NUM_WRITERS = 2; public static void main(String[] args) { ReadWriteLock lock = new ReentrantReadWriteLock(); SharedResource sharedResource = new SharedResource(); // Create and start the reader threads for (int i = 0; i < NUM_READERS; i++) { Thread readerThread = new Thread(new Reader(lock, sharedResource)); readerThread.start(); } // Create and start the writer threads for (int i = 0; i < NUM_WRITERS; i++) { Thread writerThread = new Thread(new Writer(lock, sharedResource)); writerThread.start(); } } static class Reader implements Runnable { private ReadWriteLock lock; private SharedResource sharedResource; public Reader(ReadWriteLock lock, SharedResource sharedResource) { this.lock = lock; this.sharedResource = sharedResource; } public void run() { while (true) { lock.readLock().lock(); // Read from the shared resource System.out.println(""Reader "" + Thread.currentThread().getName() + "" reads: "" + sharedResource.read()); lock.readLock().unlock(); // Delay between consecutive reads try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class Writer implements Runnable { private ReadWriteLock lock; private SharedResource sharedResource; private int counter = 0; public Writer(ReadWriteLock lock, SharedResource sharedResource) { this.lock = lock; this.sharedResource = sharedResource; } public void run() { while (true) { lock.writeLock().lock(); // Write to the shared resource sharedResource.write(""Writer "" + Thread.currentThread().getName() + "" writes: "" + counter++); lock.writeLock().unlock(); // Delay between consecutive writes try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class SharedResource { private String data; public String read() { return data; } public void write(String data) { this.data = data; } } }",93,93 ,"class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: pair = [(p, s) for p, s in zip(position, speed)] pair.sort(reverse=True) fleets = 1 prevTime = (target - pair[0][0]) / pair[0][1] for i in range(1, len(pair)): currCar = pair[i] currTime = (target - currCar[0]) / currCar[1] if currTime > prevTime: fleets += 1 prevTime = currTime return fleets",0.0,GFG,,python,"class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: pair = [(p, s) for p, s in zip(position, speed)] pair.sort(reverse=True) fleets = 1 prevTime = (target - pair[0][0]) / pair[0][1] for i in range(1, len(pair)): currCar = pair[i] currTime = (target - currCar[0]) / currCar[1] if currTime > prevTime: fleets += 1 prevTime = currTime return fleets",14,14 ,"# Importing the NumPy library import numpy as np # Creating an array from 0 to 6 x = np.arange(7) # Displaying the original array print(""Original array:"") print(x) # Raising the elements of the array to the power of 3 and displaying the result print(""First array elements raised to powers from second array, element-wise:"") print(np.power(x, 3)) ",0.0,W3RESOURCE,,python,"# Importing the NumPy library import numpy as np # Creating an array from 0 to 6 x = np.arange(7) # Displaying the original array print(""Original array:"") print(x) # Raising the elements of the array to the power of 3 and displaying the result print(""First array elements raised to powers from second array, element-wise:"") print(np.power(x, 3)) ",13,13 ,"class Solution { public int subarraySum(int[] nums, int k) { HashMap subNum = new HashMap<>(); subNum.put(0, 1); int total = 0, count = 0; for (int n : nums) { total += n; if (subNum.containsKey(total - k)) { count += subNum.get(total - k); } subNum.put(total, subNum.getOrDefault(total, 0) + 1); } return count; } }",0.0,leetcode,,java,"class Solution { public int subarraySum(int[] nums, int k) { HashMap subNum = new HashMap<>(); subNum.put(0, 1); int total = 0, count = 0; for (int n : nums) { total += n; if (subNum.containsKey(total - k)) { count += subNum.get(total - k); } subNum.put(total, subNum.getOrDefault(total, 0) + 1); } return count; } }",19,19 ,"import java.lang.reflect.Field; public class ReflectionUtil { public static void setPrivateField(Object obj, String fieldName, Object value) throws Exception { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(obj, value); } public static Object getPrivateField(Object obj, String fieldName) throws Exception { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); return field.get(obj); } } ",1.0,PERPLEXITY,Write Java reflection code to access and modify private fields dynamically.,java,"import java.lang.reflect.Field; public class ReflectionUtil { public static void setPrivateField(Object obj, String fieldName, Object value) throws Exception { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(obj, value); } public static Object getPrivateField(Object obj, String fieldName) throws Exception { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); return field.get(obj); } }",13,13 ,"class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; } } public class BSTInsert { public TreeNode insert(TreeNode root, int val) { if (root == null) return new TreeNode(val); TreeNode curr = root; while (true) { if (val < curr.val) { if (curr.left == null) { curr.left = new TreeNode(val); break; } curr = curr.left; } else { if (curr.right == null) { curr.right = new TreeNode(val); break; } curr = curr.right; } } return root; } } ",1.0,PERPLEXITY,Write Java code for inserting a node into a Binary Search Tree iteratively,java,"class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; } } public class BSTInsert { public TreeNode insert(TreeNode root, int val) { if (root == null) return new TreeNode(val); TreeNode curr = root; while (true) { if (val < curr.val) { if (curr.left == null) { curr.left = new TreeNode(val); break; } curr = curr.left; } else { if (curr.right == null) { curr.right = new TreeNode(val); break; } curr = curr.right; } } return root; } }",20,20 ,"import java.net.http.*; import java.net.URI; import com.fasterxml.jackson.databind.ObjectMapper; public class RestClient { public static T getJson(String url, Class clazz) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build(); HttpResponse resp = client.send(req, HttpResponse.BodyHandlers.ofString()); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(resp.body(), clazz); } } ",1.0,PERPLEXITY,Write Java code using HttpClient to call REST API and parse JSON response.,java,"import java.net.http.*; import java.net.URI; import com.fasterxml.jackson.databind.ObjectMapper; public class RestClient { public static T getJson(String url, Class clazz) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build(); HttpResponse resp = client.send(req, HttpResponse.BodyHandlers.ofString()); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(resp.body(), clazz); } }",12,12 ,"import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ThreadSafeLRUCache { private final int capacity; private final ConcurrentHashMap> cache; private final DoublyLinkedList dll; private final ReentrantReadWriteLock lock; private static class Node { K key; V value; Node prev; Node next; Node(K key, V value) { this.key = key; this.value = value; } } private static class DoublyLinkedList { private Node head; private Node tail; void addToFront(Node node) { if (head == null) { head = tail = node; } else { node.next = head; head.prev = node; head = node; } } void remove(Node node) { if (node.prev != null) { node.prev.next = node.next; } else { head = node.next; } if (node.next != null) { node.next.prev = node.prev; } else { tail = node.prev; } node.prev = node.next = null; } Node removeLast() { if (tail == null) return null; Node last = tail; remove(last); return last; } void moveToFront(Node node) { remove(node); addToFront(node); } } public ThreadSafeLRUCache(int capacity) { this.capacity = capacity; this.cache = new ConcurrentHashMap<>(); this.dll = new DoublyLinkedList<>(); this.lock = new ReentrantReadWriteLock(); } public V get(K key) { lock.readLock().lock(); try { Node node = cache.get(key); if (node == null) return null; lock.readLock().unlock(); lock.writeLock().lock(); try { dll.moveToFront(node); return node.value; } finally { lock.readLock().lock(); lock.writeLock().unlock(); } } finally { lock.readLock().unlock(); } } public void put(K key, V value) { lock.writeLock().lock(); try { Node node = cache.get(key); if (node != null) { node.value = value; dll.moveToFront(node); } else { node = new Node<>(key, value); if (cache.size() >= capacity) { Node removed = dll.removeLast(); if (removed != null) { cache.remove(removed.key); } } cache.put(key, node); dll.addToFront(node); } } finally { lock.writeLock().unlock(); } } public int size() { lock.readLock().lock(); try { return cache.size(); } finally { lock.readLock().unlock(); } } }",1.0,DEEPSEEK,Design and implement a thread-safe Least Recently Used (LRU) cache with O(1) average time complexity for get and put operations. The cache should have a fixed capacity and evict the least recently used item when capacity is reached.,java,"import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ThreadSafeLRUCache { private final int capacity; private final ConcurrentHashMap> cache; private final DoublyLinkedList dll; private final ReentrantReadWriteLock lock; private static class Node { K key; V value; Node prev; Node next; Node(K key, V value) { this.key = key; this.value = value; } } private static class DoublyLinkedList { private Node head; private Node tail; void addToFront(Node node) { if (head == null) { head = tail = node; } else { node.next = head; head.prev = node; head = node; } } void remove(Node node) { if (node.prev != null) { node.prev.next = node.next; } else { head = node.next; } if (node.next != null) { node.next.prev = node.prev; } else { tail = node.prev; } node.prev = node.next = null; } ... truncated ... lock.readLock().unlock(); lock.writeLock().lock(); try { dll.moveToFront(node); return node.value; } finally { lock.readLock().lock(); lock.writeLock().unlock(); } } finally { lock.readLock().unlock(); } } public void put(K key, V value) { lock.writeLock().lock(); try { Node node = cache.get(key); if (node != null) { node.value = value; dll.moveToFront(node); } else { node = new Node<>(key, value); if (cache.size() >= capacity) { Node removed = dll.removeLast(); if (removed != null) { cache.remove(removed.key); } } cache.put(key, node); dll.addToFront(node); } } finally { lock.writeLock().unlock(); } } public int size() { lock.readLock().lock(); try { return cache.size(); } finally { lock.readLock().unlock(); } } }",126,101 ,"public int lengthOfLongestSubstring(String s) { int max = 0; Map map = new HashMap<>(); for (int j = 0, i = 0; j < s.length(); j++) { if (map.containsKey(s.charAt(j))) i = Math.max(map.get(s.charAt(j)), i); max = Math.max(max, j - i + 1); map.put(s.charAt(j), j + 1); } return max; }",1.0,GEMINI,Find the length of the longest substring without repeating characters.,java,"public int lengthOfLongestSubstring(String s) { int max = 0; Map map = new HashMap<>(); for (int j = 0, i = 0; j < s.length(); j++) { if (map.containsKey(s.charAt(j))) i = Math.max(map.get(s.charAt(j)), i); max = Math.max(max, j - i + 1); map.put(s.charAt(j), j + 1); } return max; }",10,10 ,"// Define the Dog class public class Dog { // Private instance variables private String name; private String color; // Parameterized constructor public Dog(String name, String color) { // Initialize name with the provided parameter this.name = name; // Initialize color with the provided parameter this.color = color; } // Main method to test the Dog class public static void main(String[] args) { // Create a new Dog object using the parameterized constructor Dog myDog = new Dog(""Bailey"", ""Black""); // Print the values of the instance variables System.out.println(""Dog's Name: "" + myDog.name); System.out.println(""Dog's Color: "" + myDog.color); } } ",0.0,WE3RESOURCE,,java,"// Define the Dog class public class Dog { // Private instance variables private String name; private String color; // Parameterized constructor public Dog(String name, String color) { // Initialize name with the provided parameter this.name = name; // Initialize color with the provided parameter this.color = color; } // Main method to test the Dog class public static void main(String[] args) { // Create a new Dog object using the parameterized constructor Dog myDog = new Dog(""Bailey"", ""Black""); // Print the values of the instance variables System.out.println(""Dog's Name: "" + myDog.name); System.out.println(""Dog's Color: "" + myDog.color); } }",23,23 ,"// ProducerConsumer.java import java.util.LinkedList; import java.util.Queue; public class ProducerConsumer { private static final int BUFFER_SIZE = 5; private static final Queue < Integer > buffer = new LinkedList < > (); public static void main(String[] args) { Thread producerThread = new Thread(new Producer()); Thread consumerThread = new Thread(new Consumer()); producerThread.start(); consumerThread.start(); } static class Producer implements Runnable { public void run() { int value = 0; while (true) { synchronized(buffer) { // Wait if the buffer is full while (buffer.size() == BUFFER_SIZE) { try { buffer.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(""Producer produced: "" + value); buffer.add(value++); // Notify the consumer that an item is produced buffer.notify(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } static class Consumer implements Runnable { public void run() { while (true) { synchronized(buffer) { // Wait if the buffer is empty while (buffer.isEmpty()) { try { buffer.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int value = buffer.poll(); System.out.println(""Consumer consumed: "" + value); // Notify the producer that an item is consumed buffer.notify(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } ",0.0,WE3RESOURCE,,java,"// ProducerConsumer.java import java.util.LinkedList; import java.util.Queue; public class ProducerConsumer { private static final int BUFFER_SIZE = 5; private static final Queue < Integer > buffer = new LinkedList < > (); public static void main(String[] args) { Thread producerThread = new Thread(new Producer()); Thread consumerThread = new Thread(new Consumer()); producerThread.start(); consumerThread.start(); } static class Producer implements Runnable { public void run() { int value = 0; while (true) { synchronized(buffer) { // Wait if the buffer is full while (buffer.size() == BUFFER_SIZE) { try { buffer.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(""Producer produced: "" + value); buffer.add(value++); // Notify the consumer that an item is produced buffer.notify(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } static class Consumer implements Runnable { public void run() { while (true) { synchronized(buffer) { // Wait if the buffer is empty while (buffer.isEmpty()) { try { buffer.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int value = buffer.poll(); System.out.println(""Consumer consumed: "" + value); // Notify the producer that an item is consumed buffer.notify(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }",75,75 ,"static int[] redundant(int[][] e){ int[] p=new int[1001]; for(int i=1;i bool: if len(s1) > len(s2): return False s1Count, s2Count = [0] * 26, [0] * 26 for i in range(len(s1)): s1Count[ord(s1[i]) - ord('a')] += 1 s2Count[ord(s2[i]) - ord('a')] += 1 matches = 0 for i in range(26): matches += (1 if s1Count[i] == s2Count[i] else 0) l = 0 for r in range(len(s1), len(s2)): if matches == 26: return True index = ord(s2[r]) - ord('a') s2Count[index] += 1 if s1Count[index] == s2Count[index]: matches += 1 elif s1Count[index] + 1 == s2Count[index]: matches -= 1 index = ord(s2[l]) - ord('a') s2Count[index] -= 1 if s1Count[index] == s2Count[index]: matches += 1 elif s1Count[index] - 1 == s2Count[index]: matches -= 1 l += 1 return matches == 26",0.0,GFG,,python,"class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: if len(s1) > len(s2): return False s1Count, s2Count = [0] * 26, [0] * 26 for i in range(len(s1)): s1Count[ord(s1[i]) - ord('a')] += 1 s2Count[ord(s2[i]) - ord('a')] += 1 matches = 0 for i in range(26): matches += (1 if s1Count[i] == s2Count[i] else 0) l = 0 for r in range(len(s1), len(s2)): if matches == 26: return True index = ord(s2[r]) - ord('a') s2Count[index] += 1 if s1Count[index] == s2Count[index]: matches += 1 elif s1Count[index] + 1 == s2Count[index]: matches -= 1 index = ord(s2[l]) - ord('a') s2Count[index] -= 1 if s1Count[index] == s2Count[index]: matches += 1 elif s1Count[index] - 1 == s2Count[index]: matches -= 1 l += 1 return matches == 26",34,34 ,"import snscrape.modules.twitter as sntwitter username = input(""Enter Twitter username: "") count = 0 for i, _ in enumerate(sntwitter.TwitterUserScraper(username).get_items()): if i == 1000: break count += 1 print(f""Tweets counted (latest 1000 max): {count}"") ",1.0,GPT,Write a Python program to scrap number of tweets of a given Twitter account. ASK THE USER TO INPUT THIER ACCOUNT ,python,"import snscrape.modules.twitter as sntwitter username = input(""Enter Twitter username: "") count = 0 for i, _ in enumerate(sntwitter.TwitterUserScraper(username).get_items()): if i == 1000: break count += 1 print(f""Tweets counted (latest 1000 max): {count}"")",10,10 ,"import java.time.Instant; import java.util.concurrent.atomic.AtomicLong; public class SnowflakeIdGenerator { private static final long EPOCH = 1609459200000L; // 2021-01-01 private static final long WORKER_ID_BITS = 5L; private static final long DATACENTER_ID_BITS = 5L; private static final long SEQUENCE_BITS = 12L; private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1; private static final long MAX_DATACENTER_ID = (1L << DATACENTER_ID_BITS) - 1; private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1; private static final long WORKER_ID_SHIFT = SEQUENCE_BITS; private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS; private final long workerId; private final long datacenterId; private final AtomicLong sequence = new AtomicLong(0); private volatile long lastTimestamp = -1L; public SnowflakeIdGenerator(long workerId, long datacenterId) { if (workerId > MAX_WORKER_ID || workerId < 0) { throw new IllegalArgumentException( String.format(""Worker ID must be between 0 and %d"", MAX_WORKER_ID) ); } if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) { throw new IllegalArgumentException( String.format(""Datacenter ID must be between 0 and %d"", MAX_DATACENTER_ID) ); } this.workerId = workerId; this.datacenterId = datacenterId; } public synchronized long nextId() { long timestamp = currentTimestamp(); if (timestamp < lastTimestamp) { throw new IllegalStateException( String.format(""Clock moved backwards. Refusing to generate ID for %d milliseconds"", lastTimestamp - timestamp) ); } if (timestamp == lastTimestamp) { long currentSequence = (sequence.incrementAndGet() & MAX_SEQUENCE); if (currentSequence == 0) { // Sequence overflow, wait for next millisecond timestamp = waitNextMillis(lastTimestamp); } } else { sequence.set(0); } lastTimestamp = timestamp; return ((timestamp - EPOCH) << TIMESTAMP_SHIFT) | (datacenterId << DATACENTER_ID_SHIFT) | (workerId << WORKER_ID_SHIFT) | sequence.get(); } public String nextIdAsString() { return Long.toString(nextId()); } public Instant getTimestampFromId(long id) { long timestamp = (id >> TIMESTAMP_SHIFT) + EPOCH; return Instant.ofEpochMilli(timestamp); } public long getWorkerIdFromId(long id) { return (id >> WORKER_ID_SHIFT) & MAX_WORKER_ID; } public long getDatacenterIdFromId(long id) { return (id >> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID; } public long getSequenceFromId(long id) { return id & MAX_SEQUENCE; } private long waitNextMillis(long lastTimestamp) { long timestamp = currentTimestamp(); while (timestamp <= lastTimestamp) { timestamp = currentTimestamp(); } return timestamp; } private long currentTimestamp() { return System.currentTimeMillis(); } public static class IdMetadata { private final long id; private final Instant timestamp; private final long workerId; private final long datacenterId; private final long sequence; public IdMetadata(long id) { this.id = id; SnowflakeIdGenerator generator = new SnowflakeIdGenerator(0, 0); this.timestamp = generator.getTimestampFromId(id); this.workerId = generator.getWorkerIdFromId(id); this.datacenterId = generator.getDatacenterIdFromId(id); this.sequence = generator.getSequenceFromId(id); } // Getters public long getId() { return id; } public Instant getTimestamp() { return timestamp; } public long getWorkerId() { return workerId; } public long getDatacenterId() { return datacenterId; } public long getSequence() { return sequence; } @Override public String toString() { return String.format( ""ID: %d, Timestamp: %s, Worker: %d, Datacenter: %d, Sequence: %d"", id, timestamp, workerId, datacenterId, sequence ); } } }",1.0,DEEPSEEK,Create a distributed unique ID generator similar to Twitter's Snowflake.,java,"import java.time.Instant; import java.util.concurrent.atomic.AtomicLong; public class SnowflakeIdGenerator { private static final long EPOCH = 1609459200000L; // 2021-01-01 private static final long WORKER_ID_BITS = 5L; private static final long DATACENTER_ID_BITS = 5L; private static final long SEQUENCE_BITS = 12L; private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1; private static final long MAX_DATACENTER_ID = (1L << DATACENTER_ID_BITS) - 1; private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1; private static final long WORKER_ID_SHIFT = SEQUENCE_BITS; private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS; private final long workerId; private final long datacenterId; private final AtomicLong sequence = new AtomicLong(0); private volatile long lastTimestamp = -1L; public SnowflakeIdGenerator(long workerId, long datacenterId) { if (workerId > MAX_WORKER_ID || workerId < 0) { throw new IllegalArgumentException( String.format(""Worker ID must be between 0 and %d"", MAX_WORKER_ID) ); } if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) { throw new IllegalArgumentException( String.format(""Datacenter ID must be between 0 and %d"", MAX_DATACENTER_ID) ); } this.workerId = workerId; this.datacenterId = datacenterId; } public synchronized long nextId() { long timestamp = currentTimestamp(); if (timestamp < lastTimestamp) { throw new IllegalStateException( String.format(""Clock moved backwards. Refusing to generate ID for %d milliseconds"", lastTimestamp - timestamp) ); } if (timestamp == lastTimestamp) { long currentSequence = (sequence.incrementAndGet() & MAX_SEQUENCE); ... truncated ... } public long getSequenceFromId(long id) { return id & MAX_SEQUENCE; } private long waitNextMillis(long lastTimestamp) { long timestamp = currentTimestamp(); while (timestamp <= lastTimestamp) { timestamp = currentTimestamp(); } return timestamp; } private long currentTimestamp() { return System.currentTimeMillis(); } public static class IdMetadata { private final long id; private final Instant timestamp; private final long workerId; private final long datacenterId; private final long sequence; public IdMetadata(long id) { this.id = id; SnowflakeIdGenerator generator = new SnowflakeIdGenerator(0, 0); this.timestamp = generator.getTimestampFromId(id); this.workerId = generator.getWorkerIdFromId(id); this.datacenterId = generator.getDatacenterIdFromId(id); this.sequence = generator.getSequenceFromId(id); } // Getters public long getId() { return id; } public Instant getTimestamp() { return timestamp; } public long getWorkerId() { return workerId; } public long getDatacenterId() { return datacenterId; } public long getSequence() { return sequence; } @Override public String toString() { return String.format( ""ID: %d, Timestamp: %s, Worker: %d, Datacenter: %d, Sequence: %d"", id, timestamp, workerId, datacenterId, sequence ); } } }",131,101 ,"class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: l, r = 0, len(numbers) - 1 while l < r: curSum = numbers[l] + numbers[r] if curSum > target: r -= 1 elif curSum < target: l += 1 else: return [l + 1, r + 1] return []",0.0,GFG,,python,"class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: l, r = 0, len(numbers) - 1 while l < r: curSum = numbers[l] + numbers[r] if curSum > target: r -= 1 elif curSum < target: l += 1 else: return [l + 1, r + 1] return []",14,14 ,"import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicInteger; public class NonBlockingStack { private static class Node { final T value; Node next; Node(T value) { this.value = value; } } private final AtomicReference> top = new AtomicReference<>(); private final AtomicInteger size = new AtomicInteger(0); private final AtomicInteger operationCount = new AtomicInteger(0); public void push(T value) { Node newHead = new Node<>(value); Node oldHead; do { oldHead = top.get(); newHead.next = oldHead; } while (!top.compareAndSet(oldHead, newHead)); size.incrementAndGet(); operationCount.incrementAndGet(); } public T pop() { Node oldHead; Node newHead; do { oldHead = top.get(); if (oldHead == null) { return null; } newHead = oldHead.next; } while (!top.compareAndSet(oldHead, newHead)); size.decrementAndGet(); operationCount.incrementAndGet(); return oldHead.value; } public T peek() { Node currentTop = top.get(); return currentTop != null ? currentTop.value : null; } public boolean isEmpty() { return top.get() == null; } public int size() { return size.get(); } public int getOperationCount() { return operationCount.get(); } // Optimistic traversal for size (not thread-safe for exact count) public int optimisticSize() { int count = 0; Node current = top.get(); while (current != null) { count++; current = current.next; } return count; } }",1.0,DEEPSEEK,Implement a thread-safe non-blocking stack using atomic operations (Treiber's algorithm).,java,"import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicInteger; public class NonBlockingStack { private static class Node { final T value; Node next; Node(T value) { this.value = value; } } private final AtomicReference> top = new AtomicReference<>(); private final AtomicInteger size = new AtomicInteger(0); private final AtomicInteger operationCount = new AtomicInteger(0); public void push(T value) { Node newHead = new Node<>(value); Node oldHead; do { oldHead = top.get(); newHead.next = oldHead; } while (!top.compareAndSet(oldHead, newHead)); size.incrementAndGet(); operationCount.incrementAndGet(); } public T pop() { Node oldHead; Node newHead; do { oldHead = top.get(); if (oldHead == null) { return null; } newHead = oldHead.next; } while (!top.compareAndSet(oldHead, newHead)); size.decrementAndGet(); operationCount.incrementAndGet(); return oldHead.value; } public T peek() { Node currentTop = top.get(); return currentTop != null ? currentTop.value : null; } public boolean isEmpty() { return top.get() == null; } public int size() { return size.get(); } public int getOperationCount() { return operationCount.get(); } // Optimistic traversal for size (not thread-safe for exact count) public int optimisticSize() { int count = 0; Node current = top.get(); while (current != null) { count++; current = current.next; } return count; } }",75,75