File size: 11,152 Bytes
59e65a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
defmodule Forge.Judge do
  @moduledoc """
  Judge - Deterministic comparison and correctness verification.
  
  This module performs deterministic comparison of contestant outputs
  against expected results. It handles various data types and comparison
  strategies while maintaining strict equality semantics.
  
  ## Usage
  
      # Simple value comparison
      Forge.Judge.compare(output, expected)
  
      # Type-aware comparison
      Forge.Judge.deep_compare(output, expected)
  
      # Create a judge result
      %Forge.Judge.JudgeResult{
        contestant_id: "alice",
        challenge_id: "sha256",
        passed: true,
        output: "hash_value",
        expected: "hash_value"
      }
  """

  @type judge_result :: %Forge.Judge.JudgeResult{
          contestant_id: String.t(),
          challenge_id: String.t(),
          passed: boolean(),
          execution_time: number() | nil,
          memory_used: number() | nil,
          output: any(),
          expected: any(),
          error: String.t() | nil,
          timestamp: DateTime.t(),
          comparison_notes: String.t() | nil
        }

  defstruct [
    :contestant_id,
    :challenge_id,
    :passed,
    :execution_time,
    :memory_used,
    :output,
    :expected,
    :error,
    :timestamp,
    :comparison_notes
  ]

  @type comparison_strategy :: :exact | :float_tolerance | :list_order_insensitive | :map_key_insensitive | :binary
  
  @type comparison_options :: %{
          strategy: comparison_strategy(),
          tolerance: float(),
          max_depth: integer(),
          ignore_keys: list(String.t()),
          custom_comparators: map()
        }

  @doc """
  Creates a judge result from execution data.
  
  ## Parameters
    - contestant_id: ID of the contestant
    - challenge_id: ID of the challenge
    - output: The actual output from the contestant
    - expected: The expected output
    - options: Comparison and execution options
    
  ## Returns
    - JudgeResult struct
  """
  @spec judge(String.t(), String.t(), any(), any(), map()) :: JudgeResult
  def judge(contestant_id, challenge_id, output, expected, options \ []) do
    default_options = %{
      strategy: :exact,
      tolerance: 1.0e-9,
      max_depth: 100,
      ignore_keys: [],
      execution_time: nil,
      memory_used: nil,
      timestamp: DateTime.utc_now(),
      notes: nil
    }
    
    options = Map.merge(default_options, options)
    
    # Compare the output
    {passed, comparison_notes} = compare(output, expected, options)
    
    %Forge.Judge.JudgeResult{
      contestant_id: contestant_id,
      challenge_id: challenge_id,
      passed: passed,
      execution_time: options.execution_time,
      memory_used: options.memory_used,
      output: output,
      expected: expected,
      error: if passed, do: nil, else: "Output mismatch: #{comparison_notes}",
      timestamp: options.timestamp || DateTime.utc_now(),
      comparison_notes: comparison_notes
    }
  end

  @doc """
  Compares two values with the specified strategy.
  
  ## Returns
    - {boolean(), String.t() | nil} - {passed, notes}
  """
  @spec compare(any(), any(), comparison_options()) :: {boolean(), String.t() | nil}
  def compare(actual, expected, options \ []) do
    default_options = %{strategy: :exact, tolerance: 1.0e-9, max_depth: 100, ignore_keys: []}
    options = Map.merge(default_options, options)
    
    try do
      case compare_values(actual, expected, options, 0) do
        true -> {true, nil}
        false -> {false, build_comparison_note(actual, expected)}
      end
    rescue
      e -> {false, "Comparison error: #{inspect(e)}"}
    end
  end

  @doc """
  Recursively compares two values.
  """
  defp compare_values(actual, expected, options, depth) do
    # Check depth limit
    if depth > options.max_depth do
      raise "Maximum comparison depth exceeded"
    end
    
    # Same reference?
    if actual === expected do
      true
    end
    
    # Handle nil comparison
    if actual == nil && expected == nil do
      true
    end
    if actual == nil || expected == nil do
      false
    end
    
    # Same type?
    if :erlang.element(1, :erlang.type(actual)) != :erlang.element(1, :erlang.type(expected)) do
      false
    end
    
    # Dispatch based on type
    cond do
      # Exact match (most common case)
      actual == expected -> true
      
      # Float comparison with tolerance
      is_float(actual) && is_float(expected) && options.strategy == :float_tolerance ->
        abs(actual - expected) <= options.tolerance
      
      # Binary comparison
      is_binary(actual) && is_binary(expected) ->
        actual == expected
      
      # List comparison
      is_list(actual) && is_list(expected) ->
        compare_lists(actual, expected, options, depth)
      
      # Map comparison
      is_map(actual) && is_map(expected) ->
        compare_maps(actual, expected, options, depth)
      
      # Tuple comparison
      is_tuple(actual) && is_tuple(expected) ->
        compare_tuples(actual, expected, options, depth)
      
      # Custom comparator
      if custom = options.custom_comparators[:erlang.element(1, :erlang.type(actual))] do
        apply(custom, [actual, expected])
      else
        false
      end
      
      true -> true
      _ -> false
    end
  end

  @doc """
  Compares two lists.
  """
  defp compare_lists(actual, expected, options, depth) do
    # Length check
    if length(actual) != length(expected) do
      false
    end
    
    # Element-wise comparison
    Enum.all?(Enum.zip(actual, expected), fn {a, e} ->
      compare_values(a, e, options, depth + 1)
    end)
  end

  @doc """
  Compares two maps.
  """
  defp compare_maps(actual, expected, options, depth) do
    # Key set comparison (ignoring specified keys)
    actual_keys = Map.keys(actual) -- options.ignore_keys
    expected_keys = Map.keys(expected) -- options.ignore_keys
    
    if actual_keys != expected_keys do
      false
    end
    
    # Value comparison for each key
    Enum.all?(actual_keys, fn key ->
      compare_values(Map.get(actual, key), Map.get(expected, key), options, depth + 1)
    end)
  end

  @doc """
  Compares two tuples.
  """
  defp compare_tuples(actual, expected, options, depth) do
    # Size check
    if tuple_size(actual) != tuple_size(expected) do
      false
    end
    
    # Element-wise comparison
    Enum.all?(Enum.zip(actual, expected), fn {a, e} ->
      compare_values(a, e, options, depth + 1)
    end)
  end

  @doc """
  Builds a human-readable comparison note.
  """
  defp build_comparison_note(actual, expected) do
    actual_type = type_name(actual)
    expected_type = type_name(expected)
    
    cond do
      actual_type != expected_type ->
        "Type mismatch: got #{actual_type}, expected #{expected_type}"
      
      is_list(actual) && is_list(expected) ->
        "List length mismatch: got #{length(actual)}, expected #{length(expected)}"
      
      is_map(actual) && is_map(expected) ->
        actual_keys = Map.keys(actual)
        expected_keys = Map.keys(expected)
        missing = expected_keys -- actual_keys
        extra = actual_keys -- expected_keys
        
        if missing != [] || extra != [] do
          notes = []
          if missing != [], do: notes = notes ++ ["Missing keys: #{inspect(missing)}"]
          if extra != [], do: notes = notes ++ ["Extra keys: #{inspect(extra)}"]
          Enum.join(notes, ", ")
        else
          "Map values differ"
        end
      
      is_float(actual) && is_float(expected) ->
        "Float values differ: got #{actual}, expected #{expected}"
      
      is_binary(actual) && is_binary(expected) ->
        "Binary values differ: got #{byte_size(actual)} bytes, expected #{byte_size(expected)} bytes"
      
      true ->
        "Values differ: got #{truncate(inspect(actual), 50)}, expected #{truncate(inspect(expected), 50)}"
    end
  end

  @doc """
  Gets a human-readable type name.
  """
  defp type_name(value) do
    cond do
      is_atom(value) -> "atom"
      is_binary(value) -> "binary"
      is_boolean(value) -> "boolean"
      is_float(value) -> "float"
      is_function(value) -> "function"
      is_integer(value) -> "integer"
      is_list(value) -> "list"
      is_map(value) -> "map"
      is_number(value) -> "number"
      is_pid(value) -> "pid"
      is_port(value) -> "port"
      is_reference(value) -> "reference"
      is_tuple(value) -> "tuple"
      true -> "unknown"
    end
  end

  @doc """
  Truncates a string to a maximum length.
  """
  defp truncate(string, max_length) when is_binary(string) do
    if byte_size(string) <= max_length do
      string
    else
      String.slice(string, 0, max_length - 3) <> "..."
    end
  end

  @doc """
  Checks if a value is a float.
  """
  defp is_float(value), do: is_number(value) && !is_integer(value)

  @doc """
  Default comparison for contest results.
  
  This is the main entry point for judging contestant outputs.
  """
  @spec default(String.t(), String.t(), any(), any(), map()) :: JudgeResult
  def default(contestant_id, challenge_id, output, expected, options \ []) do
    judge(contestant_id, challenge_id, output, expected, options)
  end

  @doc """
  Creates a failing judge result.
  """
  @spec fail(String.t(), String.t(), String.t(), map()) :: JudgeResult
  def fail(contestant_id, challenge_id, error, options \ []) do
    %Forge.Judge.JudgeResult{
      contestant_id: contestant_id,
      challenge_id: challenge_id,
      passed: false,
      execution_time: options[:execution_time],
      memory_used: options[:memory_used],
      output: nil,
      expected: nil,
      error: error,
      timestamp: options[:timestamp] || DateTime.utc_now(),
      comparison_notes: nil
    }
  end

  @doc """
  Creates a passing judge result.
  """
  @spec pass(String.t(), String.t(), any(), map()) :: JudgeResult
  def pass(contestant_id, challenge_id, output, options \ []) do
    %Forge.Judge.JudgeResult{
      contestant_id: contestant_id,
      challenge_id: challenge_id,
      passed: true,
      execution_time: options[:execution_time],
      memory_used: options[:memory_used],
      output: output,
      expected: options[:expected],
      error: nil,
      timestamp: options[:timestamp] || DateTime.utc_now(),
      comparison_notes: nil
    }
  end

  @doc """
  Verifies that all required test vectors pass.
  """
  @spec verify_all(list(JudgeResult)) :: boolean()
  def verify_all(results) do
    Enum.all?(results, &(&1.passed))
  end

  @doc """
  Counts the number of passing results.
  """
  @spec count_passing(list(JudgeResult)) :: integer()
  def count_passing(results) do
    Enum.count(results, &(&1.passed))
  end

  @doc """
  Groups judge results by contestant.
  """
  @spec group_by_contestant(list(JudgeResult)) :: map()
  def group_by_contestant(results) do
    Enum.group_by(results, &(&1.contestant_id))
  end

  @doc """
  Groups judge results by challenge.
  """
  @spec group_by_challenge(list(JudgeResult)) :: map()
  def group_by_challenge(results) do
    Enum.group_by(results, &(&1.challenge_id))
  end
end