/**
 * Given a list of elements, replace all occurrences of 'oldValue' with 'newValue' and return the modified list.
 * Additionally, only keep the elements that are divisible by 3 and less than 10.
 *
 * @param elements A list of integer elements.
 * @param oldValue The value to be replaced.
 * @param newValue The new value to be inserted.
 * @return Modified list after replacing elements and filtering divisible elements.
 *
 * Example:
 * sliceAndReplace(listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 2, 7) -> [3, 6, 7, 9]
 */
fun sliceAndReplace(elements: List<Int>, oldValue: Int, newValue: Int): List<Int> {

    val result = mutableListOf<Int>()

    for (num in elements.reversed()) {
        if (num % 3 == 0 && num < 10) {
            if (num == oldValue) {
                result.add(newValue)
            } else {
                result.add(num)
            }
        }
    }

    return result
}
/**
 * Given a list of elements, replace all occurrences of 'oldValue' with 'newValue' and return the modified list.
 * Additionally, only keep the elements that are divisible by 3 and less than 10.
 *
 * @param elements A list of integer elements.
 * @param oldValue The value to be replaced.
 * @param newValue The new value to be inserted.
 * @return Modified list after replacing elements and filtering divisible elements.
 *
 * Example:
 * sliceAndReplace(listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 2, 7) -> [3, 6, 7, 9]
 */
fun sliceAndReplace(elements: List<Int>, oldValue: Int, newValue: Int): List<Int> {
/**
 * Given a list of elements, replace all occurrences of 'oldValue' with 'newValue' and return the modified list.
 * Additionally, only keep the elements that are divisible by 3 and less than 10.
 *
 * @param elements A list of integer elements.
 * @param oldValue The value to be replaced.
 * @param newValue The new value to be inserted.
 * @return Modified list after replacing elements and filtering divisible elements.
 *
 * Example:
 * sliceAndReplace(listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 2, 7) -> [3, 6, 7, 9]
 */
fun sliceAndReplace(elements: List<Int>, oldValue: Int, newValue: Int): List<Int> {

    val result = mutableListOf<Int>()

    for (num in elements.reversed()) {
        if (num % 3 == 0 && num < 10) {
            if (num == oldValue) {
                result.add(newValue)
            } else {
                result.add(num)
            }
        }
    }

    return result
}