Skip to content

Instantly share code, notes, and snippets.

@mazabin
Last active June 12, 2020 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mazabin/ba8537a74f249c444303f2dad90a8925 to your computer and use it in GitHub Desktop.
Save mazabin/ba8537a74f249c444303f2dad90a8925 to your computer and use it in GitHub Desktop.
Task: Sequence C contains elements from A if they are present in B p times, and p is prime number
import kotlin.math.*
//Task: Sequence C contains elements from A if they are present in B p times, and p is prime number
fun main() {
val a = arrayListOf(2, 3, 9, 2, 5, 1, 3, 7, 10)
val b = intArrayOf(2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10)
val c = ArrayList<Int>(a)
//check every unique number in B sequence
for(i in b.distinct()){
if(isPrimeNumber(countNumber(i, b)))
//if we didn't care about original contents of A, at this point we could remove the values from A and we would get the expected C.
// while loop to remove all of the instances of checked number.
while(c.contains(i))
c.remove(i)
}
//And just to prove that it works, we print it all out
for(i in c)
println(i)
}
//Naive primality test
//This works well for small set of data, with the complexity of O(n).
fun isPrimeNumber(n : Int) : Boolean {
if (n < 2)
return false
val upperRange = floor(sqrt(n.toDouble())).toInt()
for(i in 2..upperRange) {
val division = n%i
if(division == 0)
return false
}
return true
}
fun countNumber(n : Int, sequence : IntArray) : Int{
val predicate : (Int) -> Boolean = { it == n}
return sequence.count(predicate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment