Skip to content

Instantly share code, notes, and snippets.

@k5trismegistus
Created March 15, 2016 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k5trismegistus/09f7c8ba5acf9764cd04 to your computer and use it in GitHub Desktop.
Save k5trismegistus/09f7c8ba5acf9764cd04 to your computer and use it in GitHub Desktop.
/*
* Your task is to implement the sum() function so that it computes the sum of
* all elements in the given array a.
*/
fun sum(a: IntArray): Int {
when {
a.size > 0 -> return a.reduce{s1, s2 -> s1 + s2}
else -> println("Array must be longer than 2")
}
return 0
}
/*
* Your task is to implement the indexOfMax() function so that it returns
* the index of the largest element in the array, or null if the array is empty.
*/
fun indexOfMax(a: IntArray): Int? {
if (a.size == 0) {
return null
}
var midx = 0
for (idx in a.indices) {
if (a[idx] >= a[midx]) {
midx = idx
}
}
return midx
}
/*
* Any array may be viewed as a number of "runs" of equal numbers.
* For example, the following array has two runs:
* 1, 1, 1, 2, 2
* Three 1's in a row form the first run, and two 2's form the second.
* This array has two runs of length one:
* 3, 4
* And this one has five runs:
* 1, 0, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0
* Your task is to implement the runs() function so that it returns the number
* of runs in the given array.
*/
fun runs(a: IntArray): Int {
if (a.size == 0) {return 0}
var cur = a[0]
var runNum = mutableListOf(cur)
for (elem in a) {
if (elem != cur) {
runNum.add(cur)
}
cur = elem
}
return runNum.size
}
/*
* Your task is to implement a palindrome test.
*
* A string is called a palindrome when it reads the same way left-to-right
* and right-to-left.
*
* See http://en.wikipedia.org/wiki/Palindrome
*/
fun isPalindrome(s: String): Boolean {
val charlist = s.toList()
return charlist == charlist.reversed()
}
/*
* Think of a perfect world where everybody has a soulmate.
* Now, the real world is imperfect: there is exactly one number in the array
* that does not have a pair. A pair is an element with the same value.
* For example in this array:
* 1, 2, 1, 2
* every number has a pair, but in this one:
* 1, 1, 1
* one of the ones is lonely.
*
* Your task is to implement the findPairless() function so that it finds the
* lonely number and returns it.
*
* A hint: there's a solution that looks at each element only once and uses no
* data structures like collections or trees.
*/
package pairless
fun findPairless(a: IntArray): Int {
var stack = mutableListOf<Int>(0)
for (elem in a) {
if (elem in stack) {
stack.remove(elem)
} else {
stack.add(elem)
}
if (0 in stack) {stack.remove(0)}
else {stack.add(0)}
}
return stack[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment