본문 바로가기

IT/알고리즘

[알고리즘] 값을 만족하는 두수 찾기 알고리즘

안녕하세요 남갯입니다


두수 찾는 알고리즘입니다.


input에 arrayInt값이 들어오고 num을 수신하면 


두개의 수를 더해서 num 값이 되는 index를 모두 출력하는 알고리즘입니다.


ex)

input [2,7,13,15]  num = 9 ==> "0,1"



//input = [2,7,13,15] num = 9 => input[0],input[1]
//arrayOf(2, 4, 6, 7, 10, 13, 15), 6 = 0,1
//arrayOf(2, 4, 6, 7, 10, 13, 15), 14 = 1,4
//arrayOf(2, 4, 6, 7, 10, 13, 15), 18 = not found return null
//arrayOf(2, 3, 4, 6, 7, 10, 13, 15), 13) = 1,5 and 3,4
fun FindTwoNumber(input: Array<Int>, num: Int): ArrayList<String>? {
val result = arrayListOf<String>()

if (input.min()!!.compareTo(num) > 0) {
Log.e("FindTwoNumber", "not Found return")
return null
}
val filtered = input.filter { it < num }
for (i in 0 until filtered.size)
Log.e("FindTwoNumber", "" + filtered[i])

var index = 0
for (i in 0 until filtered.size) {
for (j in i until filtered.size) {
if (i == j) {
continue
}
if ((filtered[i] + filtered[j]) == num) {
result.add("$i,$j")
index++
Log.e("FindTwoNumber", "input[i] = ${filtered[i]} input[j] = ${filtered[j]}")
Log.e("FindTwoNumber", "input[i] + input[j] => ${filtered[i]} + ${filtered[j]} = $num")
}
}
}

if (result.isEmpty()) {
Log.e("FindTwoNumber", "not Found return")
return null
}

return result
}