Adapt optimal C++/ JavaScript solution

This commit is contained in:
p1ng0ut 2023-02-12 21:27:05 +01:00
parent 418f9692cf
commit 41e5f46eef
2 changed files with 45 additions and 7 deletions

View File

@ -1,7 +1,7 @@
package space.dezentrale.prgrnd
class SumOfTwo {
fun twoSum(nums: IntArray, target: Int): IntArray {
fun simpleSolution(nums: IntArray, target: Int): IntArray {
nums.forEachIndexed { idxA, numA ->
nums.forEachIndexed { idxB, numB ->
if (idxA != idxB && numA + numB == target) {
@ -11,4 +11,15 @@ class SumOfTwo {
}
return intArrayOf(-1, -1)
}
fun optimalSolution(nums: IntArray, target: Int): IntArray {
val numsToIndices = nums.mapIndexed { index: Int, num: Int -> num to index }.toMap()
println("numsToIndices = $numsToIndices")
for ((index, num) in nums.withIndex()) {
if (numsToIndices.containsValue(target - num)) {
return intArrayOf(numsToIndices[target - num]!!, index)
}
}
return intArrayOf(-1, -1)
}
}

View File

@ -5,28 +5,55 @@ import kotlin.test.assertContentEquals
class SumOfTwoTest {
@Test
fun `it returns an array with 0 and 1 for 2_7_11_15 and 9`() {
fun `simpleSolution returns an array with 0 and 1 for 2_7_11_15 and 9`() {
val sumOfTwo = SumOfTwo()
val twoSum = sumOfTwo.twoSum(intArrayOf(2, 7, 11, 15), 9)
val twoSum = sumOfTwo.simpleSolution(intArrayOf(2, 7, 11, 15), 9)
assertContentEquals(twoSum, intArrayOf(0, 1))
}
@Test
fun `it returns an array with 1 and 2 for 3_2_4 and 6`() {
fun `simpleSolution returns an array with 1 and 2 for 3_2_4 and 6`() {
val sumOfTwo = SumOfTwo()
val twoSum = sumOfTwo.twoSum(intArrayOf(3, 2, 4), 6)
val twoSum = sumOfTwo.simpleSolution(intArrayOf(3, 2, 4), 6)
assertContentEquals(twoSum, intArrayOf(1, 2))
}
@Test
fun `it returns an array with 0 and 1 for 3_3 and 6`() {
fun `simpleSolution returns an array with 0 and 1 for 3_3 and 6`() {
val sumOfTwo = SumOfTwo()
val twoSum = sumOfTwo.twoSum(intArrayOf(3, 3), 6)
val twoSum = sumOfTwo.simpleSolution(intArrayOf(3, 3), 6)
assertContentEquals(twoSum, intArrayOf(0, 1))
}
@Test
fun `optimalSolution returns an array with 0 and 1 for 2_7_11_15 and 9`() {
val sumOfTwo = SumOfTwo()
val twoSum = sumOfTwo.optimalSolution(intArrayOf(2, 7, 11, 15), 9)
assertContentEquals(twoSum, intArrayOf(0, 1))
}
@Test
fun `optimalSolution returns an array with 1 and 2 for 3_2_4 and 6`() {
val sumOfTwo = SumOfTwo()
val twoSum = sumOfTwo.optimalSolution(intArrayOf(3, 2, 4), 6)
assertContentEquals(twoSum, intArrayOf(1, 2))
}
@Test
fun `optimalSolution returns an array with 0 and 1 for 3_3 and 6`() {
val sumOfTwo = SumOfTwo()
val twoSum = sumOfTwo.optimalSolution(intArrayOf(3, 3), 6)
assertContentEquals(twoSum, intArrayOf(0, 1))
}