Problem 1: ruby rewrite

This commit is contained in:
Ivan R. 2022-11-26 17:03:22 +05:00
parent 32f9a1dd8d
commit 459fb62da4
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
6 changed files with 28 additions and 56 deletions

View file

@ -1 +0,0 @@
../template/Makefile

View file

@ -1,18 +0,0 @@
#include <stdlib.h>
#include "lib.h"
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
for (int i=0; i<numsSize-1; i++) {
for (int j=i+1; j<numsSize; j++) {
if (nums[i] + nums[j] == target) {
int* res = malloc(2 * sizeof(int));
res[0] = i;
res[1] = j;
*returnSize = 2;
return res;
}
}
}
*returnSize = 0;
return NULL;
}

View file

@ -1,2 +0,0 @@
#pragma once
int* twoSum(int* nums, int numsSize, int target, int* returnSize);

View file

@ -1,35 +0,0 @@
#include "stdio.h"
#include "stdlib.h"
#include "lib.h"
int main() {
int returnSize = -1;
int nums1[] = {2, 7, 11, 15};
int target1 = 9;
int* res1 = twoSum(nums1, 4, target1, &returnSize);
if (returnSize == 2 && res1[0] == 0 && res1[1] == 1) {
printf("Test 1: passed\n");
}
else {
printf("Test 1: failed\n");
}
if (returnSize > 0) {
free(res1);
}
int nums2[] = {3, 2, 4};
int target2 = 6;
int* res2 = twoSum(nums2, 3, target2, &returnSize);
if (returnSize == 2 && res2[0] == 1 && res2[1] == 2) {
printf("Test 2: passed\n");
}
else {
printf("Test 2: failed\n");
}
if (returnSize > 0) {
free(res2);
}
return 0;
}

View file

@ -0,0 +1,15 @@
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
max_val = nums.max
nums[0...-1].each_with_index do |a, i|
# Skip this number if any sum will be less than target
next if a + max_val < target
nums[i + 1..].each_with_index do |b, j|
return [i, j + i + 1] if a + b == target
end
end
end

View file

@ -0,0 +1,13 @@
require_relative 'main'
require 'test/unit'
class TestTwoSum < Test::Unit::TestCase
def test_simple
assert_equal([0, 1], two_sum([2, 7, 11, 15], 9))
assert_equal([1, 2], two_sum([3, 2, 4], 6))
end
def test_execution_time
assert_equal([9_998, 9_999], two_sum(Array(1..10_000), 19_999))
end
end