How to resolve the algorithm Filter step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Filter step by step in the Wren programming language
Table of Contents
Problem Statement
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Filter step by step in the Wren programming language
Source code in the wren programming language
var a = [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]
System.print("The original array is : %(a)")
System.print("\nFiltering to a new array :-")
var evens = a.where { |e| e%2 == 0 }.toList
System.print("The even numbers are : %(evens)")
System.print("The original array is still : %(a)")
// Destructive filter, permanently remove even numbers.
evens.clear()
for (i in a.count-1..0) {
if (a[i]%2 == 0) {
evens.add(a[i])
a.removeAt(i)
}
}
evens = evens[-1..0]
System.print("\nAfter a destructive filter :-")
System.print("The even numbers are : %(evens)")
System.print("The original array is now : %(a)")
You may also check:How to resolve the algorithm Animate a pendulum step by step in the Euler Math Toolbox programming language
You may also check:How to resolve the algorithm Archimedean spiral step by step in the Quackery programming language
You may also check:How to resolve the algorithm Bitwise IO step by step in the Julia programming language
You may also check:How to resolve the algorithm Brazilian numbers step by step in the F# programming language
You may also check:How to resolve the algorithm Memory layout of a data structure step by step in the Perl programming language