First 19 rows of js
| uuidstring | contentstring | content_formatstring | raw_contentstring | taskstring | analysisstring | solutionstring | teststring | full_contentstring | full_content_formatstring |
|---|---|---|---|---|---|---|---|---|---|
| 23633968-4e2f-4670-99af-e51034695601 | /* Write a JavaScript function called `reverseCharacters` that takes a string as input and returns a new string with all characters in reverse order. The function should handle empty strings by returning an empty string, and should work with any Unicode characters including space… | code comment | console.log("Problem Solving Q: 3 "); /* First Reverse */ /* Have the function FirstReverse(str) take the str parameter being passed and return the string in reversed order. For example: if the input string is "Hello World and Coders" then your program should return the strin… |
| Write a JavaScript function called `reverseCharacters` that takes a string as input and returns a new string with all characters in reverse order. The function should handle empty strings by returning an empty string, and should work with any Unicode characters including spaces, … |
| The solution uses a simple iterative approach: create an empty result string, then loop through the input string starting from its last index (using `str.length - 1`) and going backwards to index 0, appending each character to the result. This works because string indexing in Jav… |
| "use strict"; // Reverse a string by building a new string from characters in reverse order. function reverseCharacters(str) { let reversed = ""; for (let i = str.length - 1; i >= 0; i--) { reversed += str[i]; } return reversed; } |
| const assert = require("assert"); assert.strictEqual(reverseCharacters("Hello World and Coders"), "sredoC dna dlroW olleH"); assert.strictEqual(reverseCharacters("I Love Code"), "edoC evoL I"); assert.strictEqual(reverseCharacters("Hello World"), "dlroW olleH"); assert.strictEqu… |
| /* Write a JavaScript function called `reverseCharacters` that takes a string as input and returns a new string with all characters in reverse order. The function should handle empty strings by returning an empty string, and should work with any Unicode characters including space… |
| solution-first order |
| ce923cd1-8704-443a-9a74-9bdef906678a | /* Write a JavaScript function that takes an array of strings (animal names, all lowercase) and returns a two-dimensional array where the inner arrays group the strings by their first letter, with the groups sorted alphabetically by first letter and each group's contents having o… | code comment | function groupAnimals(animals) { var hasil = [[]]; var kelompok = 0; animals.sort(); hasil[0].push(animals[0]) for (var i = 1; i < animals.length; i++) { if (animals[i][0] === hasil[kelompok][0][0]) { hasil[kelompok].push(animals[i]) }… | Write a JavaScript function that takes an array of strings (animal names, all lowercase) and returns a two-dimensional array where the inner arrays group the strings by their first letter, with the groups sorted alphabetically by first letter and each group's contents having orig… | The solution must first create a shallow copy of the input array and sort it lexicographically using the default string sort (which is case-sensitive but the input is all lowercase, so it's fine). After sorting, the first element initializes the first group. Then iterate from ind… | "use strict"; // Group an array of animal names by their first letter, sorted by name. function groupAnimalsByFirstLetter(animals) { const sorted = animals.slice().sort(); const groups = [[sorted[0]]]; let groupIndex = 0; for (let i = 1; i < sorted.length; i++) … | const assert = require("assert"); // Test case 1: basic example from problem assert.deepStrictEqual( groupAnimalsByFirstLetter(['cacing', 'ayam', 'kuda', 'anoa', 'kancil']), [['ayam', 'anoa'], ['cacing'], ['kuda', 'kancil']] ); // Test case 2: more animals with duplicat… | /* Write a JavaScript function that takes an array of strings (animal names, all lowercase) and returns a two-dimensional array where the inner arrays group the strings by their first letter, with the groups sorted alphabetically by first letter and each group's contents having o… | solution-first order |
| 847919f3-2455-4e38-81e4-31e502af7e96 | Write a JavaScript function that determines whether a given word can be formed by tracing a path through a 2D grid of characters, where each cell can be used only once per path and movement is allowed only in four orthogonal directions (up, down, left, right). The function should… | markdown | const exists = (board, word) => { const NUM_ROWS = board.length const NUM_COLS = board[0].length const seen = new Set() const dfs = (row, column, currentWordIndex) => { const seenKey = `${row},${column}` if (currentWordIndex === word.length) return true //… | Write a JavaScript function that determines whether a given word can be formed by tracing a path through a 2D grid of characters, where each cell can be used only once per path and movement is allowed only in four orthogonal directions (up, down, left, right). The function should… | This is a classic Depth-First Search (DFS) problem on a grid with backtracking. The main algorithm is to iterate over every cell in the grid as a potential starting point, and from each cell, perform a DFS that explores all four orthogonally adjacent neighbors. During the DFS, we… | "use strict"; // Check if a word can be formed by traversing orthogonal adjacent cells in a 2D board. function wordExists(board, word) { const numRows = board.length; if (numRows === 0) { return word.length === 0; } const numCols = board[0].length; f… | const assert = require("assert"); // Test basic case const board1 = [ ["A","B","C","E"], ["S","F","C","S"], ["A","D","E","E"] ]; assert.strictEqual(wordExists(board1, "ABCCED"), true, "Should find word horizontally and vertically"); assert.strictEqual(wordExists(boar… | Write a JavaScript function that determines whether a given word can be formed by tracing a path through a 2D grid of characters, where each cell can be used only once per path and movement is allowed only in four orthogonal directions (up, down, left, right). The function should… | commented standard order |
| 82e8bc2c-3fff-46da-bab3-1da08e69879d | /* Write a JavaScript function that takes an array of strings and returns a new array with the strings sorted by their length in ascending order (shortest first). If two or more strings have the same length, their original relative order must be preserved (stable sort). The input… | code comment | function sortByLength(array) { return [...array].sort((a, b) => a.length - b.length); } | Write a JavaScript function that takes an array of strings and returns a new array with the strings sorted by their length in ascending order (shortest first). If two or more strings have the same length, their original relative order must be preserved (stable sort). The input ar… | The main algorithm uses the built-in `Array.prototype.sort()` method with a custom comparator that compares two elements `a` and `b` by their `.length` property, subtracting one from the other (`a.length - b.length`) to produce a negative, zero, or positive value. Crucially, to a… | "use strict"; // Return a new array sorted by string length in ascending order, preserving original order for equal lengths. function sortStringsByLength(strings) { return [...strings].sort((a, b) => a.length - b.length); } | const assert = require("assert"); // Basic sorting assert.deepStrictEqual(sortStringsByLength(["longer", "short", "tiny"]), ["tiny", "short", "longer"]); // Empty array assert.deepStrictEqual(sortStringsByLength([]), []); // Single element assert.deepStrictEqual(sortStringsByL… | // Write a JavaScript function that takes an array of strings and returns a new array with the strings sorted by their length in ascending order (shortest first). If two or more strings have the same length, their original relative order must be preserved (stable sort). The input… | commented standard order |
| e72f02a3-55df-4359-b1e4-9e61693519df | /* Write a JavaScript function that reshapes a 2D matrix (array of arrays) into a new matrix with the specified number of rows `r` and columns `c`, while preserving the original row-major order of elements. The function should return the original matrix unchanged if the total num… | code comment | // // // in: [[1,2], [3,4]] , 1, 4 // out: [[1,2,3,4]] == 1row, 4cols // // in: [[1,2], [3,4]] , 2, 4 // out: [[1,2],[3,4]] == original array because // org size M*N 2*2 // expected out 2*4 not possible // // solution one // flatten array then build result // // solution two // c… | Write a JavaScript function that reshapes a 2D matrix (array of arrays) into a new matrix with the specified number of rows `r` and columns `c`, while preserving the original row-major order of elements. The function should return the original matrix unchanged if the total number… | The core algorithm flattens the input matrix in row-major order by iterating through each element and accumulating values into a buffer. When the buffer reaches the target column count `c`, it is pushed as a complete row into the result array and reset. This avoids creating a sep… | "use strict"; // Reshape a 2D matrix to new dimensions while preserving row-major order. function reshapeMatrix(matrix, rows, cols) { const originalRows = matrix.length; const originalCols = matrix[0].length; const totalElements = originalRows * originalCols; //… | const assert = require("assert"); // Test valid reshape assert.deepStrictEqual(reshapeMatrix([[1,2],[3,4]], 1, 4), [[1,2,3,4]]); assert.deepStrictEqual(reshapeMatrix([[1,2],[3,4]], 2, 2), [[1,2],[3,4]]); assert.deepStrictEqual(reshapeMatrix([[1,2,3],[4,5,6]], 3, 2), [[1,2],[3,4]… | /* Write a JavaScript function that reshapes a 2D matrix (array of arrays) into a new matrix with the specified number of rows `r` and columns `c`, while preserving the original row-major order of elements. The function should return the original matrix unchanged if the total num… | solution-first order |
| 6787c451-20e4-402b-9780-8b2adfa54414 | /* Write a JavaScript function called `findNearestPoint` that takes two arguments: an array of 2D points (each point is an array of two numbers `[x, y]`), and a query point `[x, y]`. The function should return the index of the point in the array that is closest (by Euclidean dist… | code comment | // From https://github.com/d3/d3-delaunay/blob/master/src/delaunay.js import Delaunator from "delaunator/delaunator.js"; function pointX(p) { return p[0]; } function pointY(p) { return p[1]; } // A triangulation is collinear if all its triangles have a non-null area functi… | Write a JavaScript function called `findNearestPoint` that takes two arguments: an array of 2D points (each point is an array of two numbers `[x, y]`), and a query point `[x, y]`. The function should return the index of the point in the array that is closest (by Euclidean distanc… | The approach is straightforward brute-force: iterate through all points in the array, compute the squared Euclidean distance from the query point to each point, and track the minimum distance and the index of the point that achieves that minimum. Using squared distance avoids the… | "use strict"; // Find the index of the closest point in an array of 2D points to a query point. function findNearestPoint(points, query) { if (points.length === 0) { return -1; } const qx = query[0]; const qy = query[1]; let bestIndex = 0; let be… | const assert = require("assert"); // Basic test assert.strictEqual(findNearestPoint([[0, 0], [1, 1], [2, 2]], [1, 1]), 1); // Empty array assert.strictEqual(findNearestPoint([], [0, 0]), -1); // Single point assert.strictEqual(findNearestPoint([[5, 5]], [0, 0]), 0); // Negati… | // Write a JavaScript function called `findNearestPoint` that takes two arguments: an array of 2D points (each point is an array of two numbers `[x, y]`), and a query point `[x, y]`. The function should return the index of the point in the array that is closest (by Euclidean dist… | test-first order |
| 992b2383-a6c5-4c1b-9e0e-17881011c811 | /* Create a JavaScript function that takes an array and a callback function, and returns a new array where each element is the result of calling the callback with the corresponding element and its index from the original array. The function should work with arrays of any length, … | code comment | export default function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } | Create a JavaScript function that takes an array and a callback function, and returns a new array where each element is the result of calling the callback with the corresponding element and its index from the original array. The function should work with arrays of any length, inc… | The solution implements a manual mapping operation without using the built-in `Array.prototype.map`. The algorithm iterates through the input array using a standard for loop, pushing the callback's return value into a new result array for each iteration. The callback is invoked w… | "use strict"; // Apply a callback to each element and its index, returning a new mapped array. function arrayMapper(array, callback) { const result = []; for (let index = 0; index < array.length; index++) { result.push(callback(array[index], index)); } re… | const assert = require("assert"); // Basic numeric transformation assert.deepStrictEqual(arrayMapper([1, 2, 3], (num) => num * 2), [2, 4, 6]); // Using both element and index assert.deepStrictEqual(arrayMapper(["a", "b", "c"], (value, idx) => `${idx}:${value}`), ["0:a", "1:b", … | /* Create a JavaScript function that takes an array and a callback function, and returns a new array where each element is the result of calling the callback with the corresponding element and its index from the original array. The function should work with arrays of any length, … | solution-first order |
| bad0e5de-9557-4aa3-865c-f114a8c5f931 | /* Write a JavaScript function named `printRightTriangle` that takes a positive integer `n` as input and returns a string containing `n` lines that form a right-aligned triangle pattern. Each line `i` (where `i` ranges from 1 to `n`) should consist of exactly `(i - 1)` spaces fol… | code comment | let input = require('fs').readFileSync('/dev/stdin').toString().split('\n'); let testCase = Number(input[0]); for(let i = 0; i<testCase; i++){ console.log(' '.repeat(i)+'*'.repeat(testCase-i)); } | Write a JavaScript function named `printRightTriangle` that takes a positive integer `n` as input and returns a string containing `n` lines that form a right-aligned triangle pattern. Each line `i` (where `i` ranges from 1 to `n`) should consist of exactly `(i - 1)` spaces follow… | The solution involves generating each line of the triangle by concatenating a number of spaces and asterisks determined by the current line index. The algorithm iterates from `i = 1` to `n` (inclusive). For each line, calculate `spaces = i - 1` and `asterisks = n - i + 1`. Use th… | "use strict"; // Generate a right-aligned triangle pattern with the given number of lines. function printRightTriangle(n) { if (n <= 0) { return ""; } let result = ""; for (let i = 1; i <= n; i++) { const spaces = i - 1; const asterisks =… | const assert = require("assert"); assert.strictEqual(printRightTriangle(1), "*\n"); assert.strictEqual(printRightTriangle(2), "**\n *\n"); assert.strictEqual(printRightTriangle(3), "***\n **\n *\n"); assert.strictEqual(printRightTriangle(4), "****\n ***\n **\n *\n"); assert.… | /* Write a JavaScript function named `printRightTriangle` that takes a positive integer `n` as input and returns a string containing `n` lines that form a right-aligned triangle pattern. Each line `i` (where `i` ranges from 1 to `n`) should consist of exactly `(i - 1)` spaces fol… | solution-first order |
| d15d5dae-4c48-423c-ac02-abd66cdcd7b2 | Write a JavaScript function that, given a sorted array of distinct integers and a target value, returns the index where the target is found, or the index where it would be inserted to maintain the sorted order. The array is sorted in ascending order, and the function must use an … | no fence | var searchInsert = function(nums, target) { let left =0, right = nums.length - 1 while(left <= right) { // <= 等于时也要比较一次 let mid = Math.floor((left + right) / 2) if(nums[mid] === target) return mid else if(nums[mid] < target) left = mid + 1 else right = mid - 1… | Write a JavaScript function that, given a sorted array of distinct integers and a target value, returns the index where the target is found, or the index where it would be inserted to maintain the sorted order. The array is sorted in ascending order, and the function must use an … | The problem reduces to finding the leftmost position where the target fits into the sorted array. A standard binary search can be adapted: maintain `left` and `right` pointers representing the current search range. At each step, compute `mid` as the floor of the average. If `nums… | "use strict"; // Return the index of target in sorted array, or the index where it would be inserted. function searchInsert(nums, target) { let left = 0; let right = nums.length - 1; while (left <= right) { const mid = Math.floor((left + right) / 2); … | const assert = require("assert"); // Test 1: Target present in the middle assert.strictEqual(searchInsert([1, 3, 5, 6], 5), 2); // Test 2: Target not present, should be inserted in the middle assert.strictEqual(searchInsert([1, 3, 5, 6], 2), 1); // Test 3: Target not present, … | Write a JavaScript function that, given a sorted array of distinct integers and a target value, returns the index where the target is found, or the index where it would be inserted to maintain the sorted order. The array is sorted in ascending order, and the function must use an … | test-first order |
| 0bed6ae1-1c45-4cb5-ba96-4c9055db531e | Create a JavaScript function that takes an array of names and returns a new array of personalized birthday message strings in the format `'kal kiski birthday ha: <name>'` for each name in the input array. The function should preserve the original order of names, handle an empty a… | markdown | "use strict"; let members = ['Ayan', 'Adeel', 'Affan', 'Anas', 'Ali']; let message = 'kal kiski birthday ha:'; for (let i = 0; i < members.length; i++) { console.log(message + members[i]); } | Create a JavaScript function that takes an array of names and returns a new array of personalized birthday message strings in the format `'kal kiski birthday ha: <name>'` for each name in the input array. The function should preserve the original order of names, handle an empty a… | The solution is straightforward: iterate over each element in the input array, construct the message string by concatenating the fixed prefix `'kal kiski birthday ha:'` with a single space and the current name, and collect these strings into a new result array. We use a simple `f… | "use strict"; // Create personalized birthday message strings for each name in the array. function birthdayMessages(names) { const messages = []; for (const name of names) { messages.push(`kal kiski birthday ha: ${name}`); } return messages; } | const assert = require("assert"); // Normal case with multiple names assert.deepStrictEqual( birthdayMessages(['Ayan', 'Adeel', 'Affan', 'Anas', 'Ali']), [ 'kal kiski birthday ha: Ayan', 'kal kiski birthday ha: Adeel', 'kal kiski birthday ha: Affa… | // Create a JavaScript function that takes an array of names and returns a new array of personalized birthday message strings in the format `'kal kiski birthday ha: <name>'` for each name in the input array. The function should preserve the original order of names, handle an empt… | test-first order |
| 95f986a1-79fb-4c9c-b5b3-c81bdd46a4db | /* Write a JavaScript function that takes a paragraph string and a positive integer `skipNum`, splits the paragraph into sentences, and for each sentence with more words than `skipNum`, reverses the order of all words in that sentence while preserving the original word order in s… | code comment | const swaping = () => { const inputStr = "Hi there. My name is Sam. This is my lucky day. I like coding so much. This is it."; const skipNum = 2; const sentences = inputStr.split('. '); let output = ''; for (const sentence of sentences) { const w… | Write a JavaScript function that takes a paragraph string and a positive integer `skipNum`, splits the paragraph into sentences, and for each sentence with more words than `skipNum`, reverses the order of all words in that sentence while preserving the original word order in shor… | The core approach is to split the input string into sentences using `.split(". ")`, then for each sentence, split it into words using `.split(" ")`. If the word count exceeds the threshold `skipNum`, reverse the words array in place using `.reverse()`. Finally, join the words bac… | "use strict"; // Transform a paragraph by reversing words in sentences longer than a threshold. function reverseLongSentenceWords(paragraph, skipNum) { const sentences = paragraph.split(". "); let output = ""; for (const sentence of sentences) { const words … | const assert = require("assert"); // Basic case with mixed sentence lengths assert.strictEqual( reverseLongSentenceWords("The cat sat. A quick brown fox jumps.", 3), "The cat sat. jumps fox brown quick A. " ); // All sentences shorter than threshold assert.strictEqual( … | /* Write a JavaScript function that takes a paragraph string and a positive integer `skipNum`, splits the paragraph into sentences, and for each sentence with more words than `skipNum`, reverses the order of all words in that sentence while preserving the original word order in s… | solution-first order |
| 092138ad-c943-43c2-8708-97fc12f81b39 | Write a JavaScript function called `findChampion` that takes a non-empty array of positive integers (e.g., `[3, 5, 15, 8, 333, 4, 9, 6, 7, 10]`) and returns the smallest number in that array. The function must not use built-in array methods like `Math.min`, `sort`, or `reduce`; i… | no fence | let numArr = [3, 5, 15, 8, 333, 4, 9, 6, 7, 10]; function lowestNum(arr) { let lowest = arr[0]; for (let i = 0; i < arr.length; i++) { if (arr[i] < lowest) { lowest = arr[i]; } } return console.log(lowest); } lowestNum(numArr); | Write a JavaScript function called `findChampion` that takes a non-empty array of positive integers (e.g., `[3, 5, 15, 8, 333, 4, 9, 6, 7, 10]`) and returns the smallest number in that array. The function must not use built-in array methods like `Math.min`, `sort`, or `reduce`; i… | The core algorithm is a linear scan: initialize a variable (e.g., `champion`) to the first element of the array, then iterate through the remaining elements, updating this variable whenever a smaller value is encountered. Because we assume positive integers and no duplicates, edg… | "use strict"; // Find and return the smallest number in a non-empty array of positive integers. function findChampion(numbers) { let champion = numbers[0]; for (let i = 1; i < numbers.length; i++) { if (numbers[i] < champion) { champion = numbers[i];… | const assert = require("assert"); assert.strictEqual(findChampion([3, 5, 15, 8, 333, 4, 9, 6, 7, 10]), 3); assert.strictEqual(findChampion([42]), 42); assert.strictEqual(findChampion([10, 20, 30, 5]), 5); assert.strictEqual(findChampion([100, 99, 98, 97]), 97); assert.strictEqua… | Write a JavaScript function called `findChampion` that takes a non-empty array of positive integers (e.g., `[3, 5, 15, 8, 333, 4, 9, 6, 7, 10]`) and returns the smallest number in that array. The function must not use built-in array methods like `Math.min`, `sort`, or `reduce`; i… | commented standard order |
| 5922d068-0d42-493a-84ba-75d6fab58db2 | Create a JavaScript function named `calculateAverage` that takes an array of numbers and returns the average of its elements as a number. The function must handle arrays of any length (including empty arrays, which should return 0) and must work correctly with positive numbers, n… | no fence | // 3) Challenging: Write a function called make_avg() which will take an array of integers and the size of that array and return the average of those values. function make_avg(intArray, arraySize) { let average = 0; for (var i = 0; i < arraySize; i++) { average =… | Create a JavaScript function named `calculateAverage` that takes an array of numbers and returns the average of its elements as a number. The function must handle arrays of any length (including empty arrays, which should return 0) and must work correctly with positive numbers, n… | The solution involves iterating through the entire array once, accumulating the sum of all elements, and then dividing by the array's length. The main algorithm is a simple linear scan: initialize a sum variable to 0, loop through each element using a `for` loop or `reduce` metho… | "use strict"; // Calculate and return the average of all numbers in the given array. function calculateAverage(numbers) { if (numbers.length === 0) { return 0; } let total = 0; for (const number of numbers) { total += number; } return tota… | const assert = require("assert"); // Test with positive integers assert.strictEqual(calculateAverage([1, 2, 3, 4]), 2.5); // Test with decimals assert.strictEqual(calculateAverage([1.5, 2.5, 3.0]), 7.0 / 3); // Test with negative numbers assert.strictEqual(calculateAverage([-5… | Create a JavaScript function named `calculateAverage` that takes an array of numbers and returns the average of its elements as a number. The function must handle arrays of any length (including empty arrays, which should return 0) and must work correctly with positive numbers, n… | standard order |
| 1ca1083c-26a0-459c-ab87-c26219868f9a | Create a JavaScript function that takes an array of integers and returns the maximum number of points you can collect by repeatedly selecting any number `x` from the array, gaining `x` points, and then deleting all occurrences of `x-1` and `x+1` from the array (along with all cop… | no fence | /** * @param {number[]} nums * @return {number} */ var deleteAndEarn = function(nums) { var n = 10001; sum = new Array(n).fill(0); arr = new Array(n).fill(0); for(var i of nums){ sum[i] += i; } arr[0] = 0; arr[1] = s… | Create a JavaScript function that takes an array of integers and returns the maximum number of points you can collect by repeatedly selecting any number `x` from the array, gaining `x` points, and then deleting all occurrences of `x-1` and `x+1` from the array (along with all cop… | The core insight is that choosing a number `x` prevents choosing `x-1` and `x+1`, while all copies of `x` can be taken together for multiplied reward. Since the values are bounded up to 10,000, we can use a counting array where `sum[i]` stores the total points available from all … | "use strict"; // Calculate maximum points from deleting numbers where adjacent values are removed. function deleteAndEarn(nums) { const MAX_VALUE = 10000; const totalPoints = new Array(MAX_VALUE + 1).fill(0); for (const num of nums) { if (num >= 0 && num… | const assert = require("assert"); assert.strictEqual(deleteAndEarn([3, 4, 2]), 6); assert.strictEqual(deleteAndEarn([2, 2, 3, 3, 3, 4]), 9); assert.strictEqual(deleteAndEarn([1, 1, 1, 2, 2, 3]), 5); assert.strictEqual(deleteAndEarn([]), 0); assert.strictEqual(deleteAndEarn([0]),… | Create a JavaScript function that takes an array of integers and returns the maximum number of points you can collect by repeatedly selecting any number `x` from the array, gaining `x` points, and then deleting all occurrences of `x-1` and `x+1` from the array (along with all cop… | standard order |
| f8813416-acb7-45d9-a4fe-783dced471c6 | /* Write a JavaScript function `extractLongestStrings` that takes a non-empty array of strings as input and returns a new array containing only the strings that have the maximum length among all strings in the input. The returned array must preserve the original relative order of… | code comment | /* All Longest Strings | CODEFIGHTS ARCADE | Level 3 # RESULTS: I prefer my answer to the top voted one. I thought of using Math.max() but, the top voted solution uses multiple loops (Math.max, inputArray.map, inputArray.filter), while my solution only uses 1 loop. */ /* … | Write a JavaScript function `extractLongestStrings` that takes a non-empty array of strings as input and returns a new array containing only the strings that have the maximum length among all strings in the input. The returned array must preserve the original relative order of th… | The solution requires a single pass through the array to track the current maximum string length and collect the strings that match it. The algorithm starts by initializing an empty result array and a variable `maxLength` set to 0 (since all strings have length at least 1). For e… | "use strict"; // Extract all strings that have the maximum length from a non-empty array of strings. function extractLongestStrings(inputArray) { const result = []; let maxLength = 0; for (const str of inputArray) { const currentLength = str.length; … | const assert = require("assert"); assert.deepStrictEqual(extractLongestStrings(["aba", "aa", "ad", "vcd", "aba"]), ["aba", "vcd", "aba"]); assert.deepStrictEqual(extractLongestStrings(["one"]), ["one"]); assert.deepStrictEqual(extractLongestStrings(["a", "b", "c"]), ["a", "b", "… | // Write a JavaScript function `extractLongestStrings` that takes a non-empty array of strings as input and returns a new array containing only the strings that have the maximum length among all strings in the input. The returned array must preserve the original relative order of… | standard order |
| 4f19d365-cabe-456c-8a01-295a5406e978 | /* Write a JavaScript function named `factorial` that takes a non-negative integer as input and returns its factorial. The function must handle edge cases where the input is 0 or 1 (both return 1). Additionally, if the input is negative, the function should throw an error with a … | code comment | //Find factorial in normal way function factorial(number){ let multiplication = 1; for(let i = 1; i<=number; i++){ multiplication = multiplication * i; } return multiplication; } const inNumber = factorial(10) console.log(inNumber) // Reverse Way Find Factorial … | Write a JavaScript function named `factorial` that takes a non-negative integer as input and returns its factorial. The function must handle edge cases where the input is 0 or 1 (both return 1). Additionally, if the input is negative, the function should throw an error with a des… | The factorial function computes \( n! \) by multiplying all integers from 1 to \( n \) together. The main algorithm initializes a result variable (using `let`) to 1 and then iterates from 1 up to \( n \), multiplying the result by each integer. Edge cases: - For \( n = 0 \), the… | "use strict"; // Compute the factorial of a non-negative integer n using a loop. function factorial(n) { if (typeof n !== 'number' || !Number.isInteger(n)) { throw new Error("Input must be an integer."); } if (n < 0) { throw new Error("Factorial is no… | const assert = require("assert"); assert.strictEqual(factorial(0), 1, "0! should be 1"); assert.strictEqual(factorial(1), 1, "1! should be 1"); assert.strictEqual(factorial(2), 2, "2! should be 2"); assert.strictEqual(factorial(5), 120, "5! should be 120"); assert.strictEqual(fa… | Write a JavaScript function named `factorial` that takes a non-negative integer as input and returns its factorial. The function must handle edge cases where the input is 0 or 1 (both return 1). Additionally, if the input is negative, the function should throw an error with a des… | standard order |
| 0cfefee2-73a8-4398-9c39-4520b3b49034 | Write a JavaScript function that reads a single line of input from standard input (using Node.js `fs.readFileSync(0, "utf8")`), trims any leading/trailing whitespace, and returns the length (number of characters) of the resulting string. The input is guaranteed to be a single lin… | markdown | // 단어 길이 재기 const fs = require("fs"); const word = fs.readFileSync(0).toString().trim(); console.log(word.length); | Write a JavaScript function that reads a single line of input from standard input (using Node.js `fs.readFileSync(0, "utf8")`), trims any leading/trailing whitespace, and returns the length (number of characters) of the resulting string. The input is guaranteed to be a single lin… | The solution reads the entire standard input synchronously using `fs.readFileSync(0, "utf8")`, which returns a string including any trailing newline. We then apply `.trim()` to remove all leading and trailing whitespace characters (spaces, tabs, newlines, etc.). The length of the… | "use strict"; const fs = require("fs"); // Read a trimmed line from standard input and return its character length. function wordLength() { const input = fs.readFileSync(0, "utf8"); const trimmed = input.trim(); return trimmed.length; } | const assert = require("assert"); // Simulate reading from stdin by redirecting file descriptor 0. const originalRead = fs.readSync; // We won't mock stdin; instead we'll test the function indirectly by verifying behavior. // But the function directly reads from fd 0, which is h… | /* Write a JavaScript function that reads a single line of input from standard input (using Node.js `fs.readFileSync(0, "utf8")`), trims any leading/trailing whitespace, and returns the length (number of characters) of the resulting string. The input is guaranteed to be a single … | solution-first order |
| b1c099ae-a376-4ce0-899e-c43ecb4db0c3 | Write a JavaScript function named `reverseWords` that takes a non-empty string containing multiple words separated by single spaces and returns a new string where the characters of each word are reversed, while preserving the original word order and spacing. For example, `"hello … | no fence | // Optimal solution using built-in functions: function optimalSolution(str) { // split() breaks string into array of component characters ('' is a separator - in this case no separator) // reverse() built in function to reverse elements of array // join() combines el… | Write a JavaScript function named `reverseWords` that takes a non-empty string containing multiple words separated by single spaces and returns a new string where the characters of each word are reversed, while preserving the original word order and spacing. For example, `"hello … | The main algorithm involves iterating through each word in the input string, reversing its characters, and building a new result string. Since we cannot use `split`, we need to process the string character by character: accumulate characters of the current word into a temporary b… | "use strict"; // Reverse the characters of each word in a space-separated string, preserving word order and spacing. function reverseWords(input) { let result = ''; let currentWord = ''; for (let i = 0; i < input.length; i++) { const char = input[i]; … | const assert = require("assert"); assert.strictEqual(reverseWords("hello world"), "olleh dlrow"); assert.strictEqual(reverseWords("a"), "a"); assert.strictEqual(reverseWords("abc def ghi"), "cba fed ihg"); assert.strictEqual(reverseWords(" leading and trailing "), " gnidael d… | // Write a JavaScript function named `reverseWords` that takes a non-empty string containing multiple words separated by single spaces and returns a new string where the characters of each word are reversed, while preserving the original word order and spacing. For example, `"hel… | standard order |
| 22e8e853-930c-485d-a722-6439dcf29a6a | /* Create a JavaScript function that determines whether a given point is strictly inside a convex polygon. The function should take a point as an array `[x, y]` and an array of polygon vertices (also arrays of `[x, y]`) representing a convex polygon in either clockwise or counter… | code comment | export {pointIsInside, centroid, onOrLeft, left, right, crossProduct, det, distance, angle, isCCW, pointsEqual} function pointsEqual(p1, p2){ return p1[0] == p2[0] && p1[1] == p2[1]; } function onOrLeft(p1, p2, p3) { return crossProduct(p1, p2, p3) >= 0; } //For conve… | Create a JavaScript function that determines whether a given point is strictly inside a convex polygon. The function should take a point as an array `[x, y]` and an array of polygon vertices (also arrays of `[x, y]`) representing a convex polygon in either clockwise or counterclo… | The main idea is to leverage the fact that for a convex polygon with vertices in counterclockwise (CCW) order, an interior point must lie strictly to the left of every directed edge from vertex i to i+1. The helper function `left(p1, p2, p3)` returns `true` if point `p3` is stric… | "use strict"; // Return true if point is strictly inside a convex polygon (not on boundary). function pointStrictlyInsideConvexPolygon(point, polygon) { // Normalize polygon to counterclockwise order. let orderedPolygon = polygon; if (!isCCW(polygon)) { order… | const assert = require("assert"); // Test 1: Simple square (CCW order), interior point. const squareCCW = [[0, 0], [2, 0], [2, 2], [0, 2]]; assert.strictEqual(pointStrictlyInsideConvexPolygon([1, 1], squareCCW), true); // Test 2: Same square, but point on boundary (edge) should… | /* Create a JavaScript function that determines whether a given point is strictly inside a convex polygon. The function should take a point as an array `[x, y]` and an array of polygon vertices (also arrays of `[x, y]`) representing a convex polygon in either clockwise or counter… | solution-first order |