From 459fb62da4fc320ffa8ed0cd5a596158d65d0ebd Mon Sep 17 00:00:00 2001 From: Ivan Reshetnikov Date: Sat, 26 Nov 2022 17:03:22 +0500 Subject: [PATCH] Problem 1: ruby rewrite --- problems/1-two-sum/Makefile | 1 - problems/1-two-sum/lib.c | 18 ------------------ problems/1-two-sum/lib.h | 2 -- problems/1-two-sum/main.c | 35 ----------------------------------- problems/1-two-sum/main.rb | 15 +++++++++++++++ problems/1-two-sum/test.rb | 13 +++++++++++++ 6 files changed, 28 insertions(+), 56 deletions(-) delete mode 120000 problems/1-two-sum/Makefile delete mode 100644 problems/1-two-sum/lib.c delete mode 100644 problems/1-two-sum/lib.h delete mode 100644 problems/1-two-sum/main.c create mode 100644 problems/1-two-sum/main.rb create mode 100644 problems/1-two-sum/test.rb diff --git a/problems/1-two-sum/Makefile b/problems/1-two-sum/Makefile deleted file mode 120000 index 25eaf27..0000000 --- a/problems/1-two-sum/Makefile +++ /dev/null @@ -1 +0,0 @@ -../template/Makefile \ No newline at end of file diff --git a/problems/1-two-sum/lib.c b/problems/1-two-sum/lib.c deleted file mode 100644 index 465ecb5..0000000 --- a/problems/1-two-sum/lib.c +++ /dev/null @@ -1,18 +0,0 @@ -#include -#include "lib.h" - -int* twoSum(int* nums, int numsSize, int target, int* returnSize) { - for (int i=0; i 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; -} diff --git a/problems/1-two-sum/main.rb b/problems/1-two-sum/main.rb new file mode 100644 index 0000000..1b96df1 --- /dev/null +++ b/problems/1-two-sum/main.rb @@ -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 diff --git a/problems/1-two-sum/test.rb b/problems/1-two-sum/test.rb new file mode 100644 index 0000000..a1815c6 --- /dev/null +++ b/problems/1-two-sum/test.rb @@ -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