convert_to_c.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from evaluator import *
  2. DESCRIPTION = "Test if the model can rewrite a given Python program into an equivalent C program."
  3. TAGS = ['code', 'c']
  4. question = """
  5. Here's a python program. Please rewrite it in c with the type signature float solve_dp(float* arr, int size, int lines_left)
  6. def solve_dp(graph, lines_left):
  7. n = len(graph)
  8. dp = [[[1e9 for _ in range(10)] for _ in range(lines_left + 1)] for _ in range(n + 1)]
  9. # Initialize how as -1 indicating no decision made
  10. how = [[[-1 for _ in range(10)] for _ in range(lines_left + 1)] for _ in range(n + 1)]
  11. for i in range(n, -1, -1):
  12. for j in range(lines_left + 1):
  13. for k in range(10):
  14. if i == n and j == 0:
  15. dp[i][j][k] = 0
  16. else:
  17. # Option 1: don't take the line
  18. if i < n and k < 9:
  19. if dp[i + 1][j][k + 1] < dp[i][j][k]:
  20. dp[i][j][k] = dp[i + 1][j][k + 1]
  21. how[i][j][k] = k + 1 # Representing choosing not to take the line
  22. # Option 2: take the line
  23. if i < n and j > 0:
  24. cost = graph[i] + (k - 8)**2
  25. if cost + dp[i + 1][j - 1][0] < dp[i][j][k]:
  26. dp[i][j][k] = cost + dp[i + 1][j - 1][0]
  27. how[i][j][k] = 0 # Representing choosing to take the line
  28. # Reconstruct the solution
  29. i, j, k = 0, lines_left, 6
  30. taken_lines = []
  31. while i < n:
  32. if how[i][j][k] == 0: # Chose to take the line
  33. taken_lines.append(n - i)
  34. i += 1
  35. j -= 1
  36. k = 0
  37. else: # Chose not to take the line
  38. i += 1
  39. k += 1
  40. return dp[0][lines_left][6]
  41. """
  42. test_case, answer = make_c_test([("solve_dp(arr, 100, 100)", "11290")], header="float arr[] = {71, 89, 34, 63, 19, 94, 54, 61, 88, 20, 66, 46, 26, 87, 55, 81, 6, 2, 72, 75, 98, 78, 24, 95, 73, 7, 56, 48, 14, 99, 64, 51, 69, 77, 28, 47, 8, 22, 49, 3, 62, 32, 10, 82, 35, 18, 85, 60, 83, 23, 5, 40, 41, 68, 53, 52, 44, 45, 65, 84, 93, 25, 13, 1, 31, 11, 12, 97, 38, 0, 43, 90, 36, 70, 33, 17, 21, 30, 16, 15, 74, 67, 58, 37, 39, 96, 79, 29, 27, 92, 86, 9, 80, 42, 57, 91, 59, 4, 76, 50};")
  43. TestProgramRewriteC = question >> LLMRun() >> ExtractCode() >> CRun(test_case) >> SubstringEvaluator(answer)
  44. if __name__ == "__main__":
  45. print(run_test(TestProgramRewriteC))