Skip to content

Instantly share code, notes, and snippets.

@alana-mullen
Created June 8, 2020 04:07
Show Gist options
  • Save alana-mullen/1992fef55bc7dc9cacbe4e90dea697a6 to your computer and use it in GitHub Desktop.
Save alana-mullen/1992fef55bc7dc9cacbe4e90dea697a6 to your computer and use it in GitHub Desktop.
Kotlin Playground - Display which numbers are in array 1, but not array 2
// My solution to: https://pl.kotl.in/Q1PY9OvAu
//
// Write a function called "reconcileHelper" that processes two arrays of integers.
// Each array will have only distinct numbers (no repeats of the same integer in
// the same array), and the arrays are not sorted.
// Your job is to find out which numbers are in array 1, but not array 2,
// and which numbers are in array 2, but not in array 1.
// Your function should return a string formatted as so:
// "Numbers in array 1 that aren't in array 2:
// <num1> <num2> <num3>...
//
// Numbers in array 2 that aren't in array 1:
// <num1> <num2> <num3>...
// "
//
// Each list of numbers should be listed in ascending order (lowest to largest)
//
// So for instance, if I passed in:
// reconcileHelper([5, 3, 4], [4, 3, 10, 6])
//
// The function would return this multiline string:
// "Numbers in array 1 that aren't in array 2:
// 5
//
// Numbers in array 2 that aren't in array 1:
// 6 10
// "
//
// Notes:
// 1) You are allowed to use any standard library functions, but if it has a way of
// doing this EXACT problem, please don't use it.
// For example, don't use a function to subtract one array from another. That's too easy.
// 2) Try to make your solution fast so that it can handle over 1,000,000 elements in each array.
// (Doing a linear search through array `b`, for every element in array `a` will work, but is too slow.)
// 3) We don’t anticipate this taking you more than 30 minutes or so, but there is no hard limit.
fun Array<Int>.filterANotB(secondArray: Array<Int>): String {
val listOfANotB = mutableListOf<Int>()
forEach {
if (!secondArray.contains(it)) {
listOfANotB.add(it)
}
}
return listOfANotB.sorted().toString().replace("[]\\[,]".toRegex(), "")
}
fun reconcileHelper(a : Array<Int>, b: Array<Int>) : String {
val array1 = a.filterANotB(b)
val array2 = b.filterANotB(a)
return "Numbers in array 1 that aren't in array 2:\n$array1\n\nNumbers in array 2 that aren't in array 1:\n$array2"
}
fun main() {
val result = reconcileHelper(arrayOf(5, 3, 4), arrayOf(4, 3, 10, 6))
// Should print:
// Numbers in array 1 that aren't in array 2:
// 5
//
// Numbers in array 2 that aren't in array 1:
// 6 10
println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment