Swift Array of Ints - Find Index where the Difference to the Previous Element is Greater than 10

write a program to find the numbers which are greater than the given number from an array.
elements greater than the previous and next element in an array
previous greater element
given a list of numbers, find and print all the elements that are greater than the previous element
find the element before which all the elements are smaller than it, and after which all are greater
search an element in an array where difference between adjacent elements is 1
next greater element
given an array find the minimum of all the greater numbers for each element in the array

I have the following array:

let array = [1,3,2,1,4,3,99,3,5,2,1,45]

I'd like to create a new array - where an element, whose difference to the previous element is greater than 10, is set to 0.

// [1,3,2,1,4,3,0,3,5,2,1,0]

Currently, I'm creating a new array with the difference, then filtering that array to find those greater than 10, and then comparing those arrays - which I feel overcomplicates everything.

let diffArray = zip(array.dropFirst(), array).map(-) 
let filteredArray = diffArray.filter {abs($0) > 10}

Thanks!

So, first element stays how it is and next elements are mapped. If difference with element from initial array with index -1 is greater then 10, element is "replaced" by 0

let array = [1,3,2,1,4,3,99,3,5,2,1,45]

var temp = array
let mapped = [temp[0]] + temp.dropFirst().enumerated().map {
    let condition = abs(temp[$0.offset] - $0.element) > 10
    if condition { temp[$0.offset + 1] = 0 }
    return condition ? 0 : $0.element
}

print(mapped) // [1,3,2,1,4,3,0,3,5,2,1,0]

... if you don't want to count with replaced elements, just remove setting elements of temp array

let array = [1,3,2,1,4,3,99,3,5,2,1,45]

let mapped = [array[0]] + array.dropFirst().enumerated().map {
    let condition = abs(array[$0.offset] - $0.element) > 10
    return condition ? 0 : $0.element
}

print(mapped) // [1,3,2,1,4,3,0,0,5,2,1,0]

Alternatively, for example if you want to just change your current array, you can add this method to extension of Array of Int

var array = [1,3,2,1,4,3,99,3,5,2,1,45]

extension Array where Element == Int {

    mutating func replace(difference: Int) {
        guard count > 0 else { return }
        self = [self[0]] + self.dropFirst().enumerated().map {
            let condition = abs(self[$0.offset] - $0.element) > difference
            if condition { self[$0.offset + 1] = 0 }
            return condition ? 0 : $0.element
        }
    }

}

array.replace(difference: 10)
print(array) // [1,3,2,1,4,3,0,3,5,2,1,0]

Elements greater than the previous and next element in an Array , Given an array of N integers. The task is to print the elements from the array which are greater than their immediate previous and next elements. Now, traverse the array starting from the index 1 to N-2 and for every element arr[i] check if Get hold of all the important DSA concepts with the DSA Self Paced Course at a� Value of first element is 10 Value of second element is 10 Value of third element is 10 Modifying Arrays. You can use append() method or addition assignment operator (+=) to add a new item at the end of an array. Take a look at the following example. Here, initially, we create an empty array and then add new elements into the same array −

You can map the array while keeping track of the previous element:

let a = [1,3,2,1,4,3,99,3,5,2,1,45]

var previous = a.first ?? 0
let b = a.map { elem -> Int in
    defer { previous = elem }
    return elem - previous > 10 ? 0 : elem
}

print(b)
// [1, 3, 2, 1, 4, 3, 0, 3, 5, 2, 1, 0]

Search an element in an array where difference between adjacent , Given an array where difference between adjacent elements is 1, write an algorithm If matches, then return index. int x = 3;. cout << "Element " << x << " is present at index ". << search(arr,n,3); Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Specifically, you use the Array type to hold elements of a single type, the array’s Element type. An array can store any kind of elements—from integers to strings to classes. Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets.

This should do it. Nothing fancy though.

let array = [1,3,2,1,4,3,99,3,5,2,1,45]

func resetValues(withDifference difference: Int, in array: inout [Int]) {
    for index in array.indices.dropFirst() {
        if abs(array[index - 1] - array[index]) >= 10 {
            array[index] = 0
        }
    }
}

resetValues(withDifference: 10, in: &array)
print(array)

Array, An array can store any kind of elements—from integers to strings to classes. var digitCounts = Array(repeating: 0, count: 10) print(digitCounts) // Prints "[0, 0, 0, 0, 0, 0, Using a negative number or an index equal to or greater than count triggers a on the array to get an immutable copy and then performs additional Swift� Keep in mind that you don’t need to replace a sequence with another sequence with the same number of elements. In the example above numbers had 6 elements and after the replacement of the subsequence 24 ( [3, 4, 5]) it had 5.

The algorithm is simple enough: loop through all numbers starting from the second one, and replaces ones that are larger by an amount of 10 than the precedent. Now, with Swift's array capabilities, this can be done in one with one function call:

let array = [1,3,2,1,4,3,99,3,5,2,1,45]

let filteredNumbers = array.indices.map { i in i > 0 && array[i] - array[i-1] > 10 ? 0 : array[i] }

A somewhat little complex solution, but which avoids accessing the array by index, and thus can be applied to any sequence/collection:

let filteredNumbers = array.reduce(into: (0, [Int]())) { $0.1.append($1-$0.0 > 10 ? 0 : $1); $0.0 = $1 }.1

Array — SwiftDoc.org, An array can store any kind of elements---from integers to strings to classes. Swift var digitCounts = Array ( repeating : 0 , count : 10 ); print ( digitCounts ) Using a negative number or an index equal to or greater than count triggers a runtime error. on the array to get an immutable copy and then performs additional Swift � Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted.Java provides us with an inbuilt function which can be found in the Arrays library of Java which will rreturn the index if the element is present, else it returns -1.

There seems to be a discrepancy between your requirement statement and your example.

"an element, whose difference to the previous element is greater than 10, is set to 0" should result in:

[1, 3, 2, 1, 4, 3, 0, 0, 5, 2, 1, 0]

but your example result is [1,3,2,1,4,3,0,3,5,2,1,0] which suggests that the difference is actually with the "transformed" value of the previous element.

So, for the stated requirement, you could do it like this:

let filteredArray = array.enumerated().map{ $0 > 0 && abs($1 - array[$0-1]) > 10 ? 0 : $1 }

or like this:

let filteredArray = zip([array[0]]+array,array).map{ abs($0-$1) > 10 ? 0 : $1 }

which both produce:

[1, 3, 2, 1, 4, 3, 0, 0, 5, 2, 1, 0]

But, in order to match your example result (difference with the previous transformed value), you should do this:

let filteredArray = array.dropFirst().reduce([array[0]]){$0 + [abs($1-$0.last!)>10 ? 0 : $1]}

which produces:

[1, 3, 2, 1, 4, 3, 0, 3, 5, 2, 1, 0]

Swift - Arrays, Swift - Arrays - Swift 4 arrays are used to store ordered lists of values of the same type. If you assign a created array to a variable, then it is always mutable, which an array by using subscript syntax, passing the index of the value you want to repeatedValue: 10) var someVar = someInts[0] print( "Value of first element is� For any array, rightmost element always has next greater element as -1. For an array which is sorted in decreasing order, all elements have next greater element as -1. For the input array [4, 5, 2, 25}, the next greater elements for each element are as follows.

Find an item in an array in Swift with first(where:) – LearnAppMaking, In this article you learn how find an item in an array with functions like "first(where :)" Loop over every value in the array, from start to end; Keep track of the func find(value searchValue: String, in array: [String]) -> Int? { for (index, value) to Swift's higher-order functions map(_:) , reduce(_:) and filter(_:) . Using a Range as a Collection of Consecutive Values. When a range uses integers as its lower and upper bounds, or any other type that conforms to the Strideable protocol with an integer stride, you can use that range in a for-in loop or with any sequence or collection method.

Find pair with given sum in an array, Given an unsorted array of integers, find a pair with given sum in it. For example,. Input: arr = [8, 7, 2, 5, 3, 1] sum = 10. Output: Pair found at index 0 and 2 (8 + 2) Now let’s see how to to search elements in this Numpy array. Find index of a value in 1D Numpy array. In the above numpy array element with value 15 occurs at different places let’s find all it’s indices i.e.

ArraySlice In Swift. Original link… | by Marco Santarossa, Swift provides several ways to get a slice from a given array: array[2] // ArraySlice<Int> [5, 2, 10]// From index 0 to index less than 2 the lifetime of elements that are no longer otherwise accessible, which can appear to be� Given an array of numbers, we can construct a new array by replacing each element by the difference between itself and the previous element, except for the first element, which we simply ignore. This is called the difference array, because it contains the first differences of the original array. We will denote the difference array of array by .

Comments
  • You cannot set index of the element. You have to swap two elements or insert it at 0 index, but others will be shifted to the right. Please explain what do you want to do.
  • OK, will edit question.
  • So the first number just gets a free pass?
  • Great question. For the moment yes.
  • What will happen to this array? [5, 14, 2]
  • I'll use this answer as it offers two options. Rakesha's answer below works as well.
  • What is the purpose of checking if index == 0 if you start with var index = 1 ? Simpler would be for index in array.indices.dropFirst(). Also note that your resetValues(difference: 10, array: array) does not compile (wrong argument labels, missing &).
  • @MartinR that was some old code i forgot to remove when i changed the logic :x Thanks
  • Thanks for clarifying that, and making it aware to me. You're totally right.