Close icon
Marketing & BusinessDown chevron icon
šŸ¤– GPT

Test-driven Code Function Generator

Test-driven Code Function Generator gpt prompt mini thumbnail
2Heart icon
45Eye icon
TestedTick icon
TipsTick icon
Learn how to write an algorithm by generating code with interactive examples. This prompt provides an efficient and reliable way to create high-quality code that is both clear and concise. With tests included in every result, you reduce the likelihood of errors and increasing its maintainability over time. Each test also includes a description of its use case, which helps readers learn the code even faster.
Get prompt
After purchasing, you will gain access to the prompt file which you can use with GPT or the app builder. You'll receive 20 free generation credits with this purchase. By purchasing this prompt, you agree to our terms of service.
1 year ago

Prompt Details

Chat - GPT-3.5 (gpt-3.5-turbo)
Token size
42 ($0.00010 / call)
Example input
Example output
Sure, here's an implementation of a binary search function in Ruby: ```ruby def binary_search(arr, target) low = 0 high = arr.length - 1 while low <= high mid = (low + high) / 2 if arr[mid] == target return mid elsif arr[mid] < target low = mid + 1 else high = mid - 1 end end return -1 end ``` This function takes an array `arr` and a `target` value to search for, and returns the index of the target if it is found in the array, or `-1` if it is not found. It works by maintaining a `low` and `high` index, which define the portion of the array that is being searched. At each iteration of the loop, the function computes the `mid` index as the average of `low` and `high`, and then checks whether the target is at that index or whether it falls in the left or right half of the search range. It then adjusts the `low` and `high` indexes accordingly to narrow down the search range until the target is found or the search range is exhausted. Here are some tests you can run to verify that the function works as expected: ```ruby # Test 1: search for an element that is in the array arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target1 = 8 index1 = binary_search(arr1, target1) puts "Test 1: Index of #{target1} in #{arr1} is #{index1} (expected: 7)" # Test 2: search for an element that is not in the array arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target2 = 11 index2 = binary_search(arr2, target2) puts "Test 2: Index of #{target2} in #{arr2} is #{index2} (expected: -1)" # Test 3: search for an element in an empty array arr3 = [] target3 = 5 index3 = binary_search(arr3, target3) puts "Test 3: Index of #{target3} in #{arr3} is #{index3} (expected: -1)" ``` These tests cover three scenarios: searching for an element that is in the array, searching for an element that is not in the array, and searching for an element in an empty array. The tests print out the expected index and the actual index returned by the function, so you can verify that they match.
Browse Marketplace