For Loop in Apple Swift - for-loop

Apple's newly released language Swift has an example on the official documentation. Example is like this;
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
This is pretty simple but as an extra exercise,it requires to add another variable in order to return what type is the largest number (i.e. Square is the case here)
However, I can't seem to figure out what is "(kind,numbers)" here represent and how should I make my for-loop to go through all Dictionary(interestingNumbers) keys and find which key has the largest number.
Thank you all for your help in advance

Swift allows you to loop over a dictionary with tuple-syntax (key, value). So in every iteration of the for-loop Swift cares about reassigning the specified tuple-variables (kind and number in your case) to the actual dictionary-record.
To figure out which Key includes the highest number in your example you can extend your code as follows:
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var largestKey = ""
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largestKey = kind
}
}
}
largest // =25
largestKey // ="Square"
Or if you want to practice the tuple-syntax try that (with the same result):
var largest = 0
var largestKey = ""
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
(largestKey, largest) = (kind, number)
}
}
}
largest // =25
largestKey // ="Square"

I can't seem to figure out what is "(kind,numbers)" here represents
It's a key-value pair (a tuple) containing the kind of the number. This syntax is called decomposition, basically, inside the loop you can access kind as the kind and numbers as the numbers that map for it.
For example, in some iteration:
kind // "Prime"
numbers // [2, 3, 5, 7, 11, 13]
Quoting the guide:
You can also iterate over a dictionary to access its key-value pairs. Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated, and you can decompose the (key, value) tuple’s members as explicitly named constants for use within in the body of the for-in loop.

for (kind, numbers) in interestingNumbers{}
This for loop actually enumerating the key/value pairs of dictionary interestingNumbers. Where kind is the key and numbers is the correspoding value
kind:Prime //Key
numbers: [2, 3, 5, 7, 11, 13] //Value
Here the complete solution of the exercise
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var type: String = ""
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
type = kind
}
}
}
largest
type

However, I can't seem to figure out what is "(kind,numbers)" here represent
The loop iterates over the dictionary, and every iteration gives you a key and associated value. Those are called kind (key) and numbers (value) here. You can choose any name you want.
and how should I make my for-loop to go through all Dictionary(interestingNumbers) keys and find which key has the largest number.
You get each key in turn in the kind loop variable.
Once you find one that results in a new largest, you can assign that to a result variable, say largestKind.
At the end of the loop, largestKind will contain the key of the array with the largest number (that number being the largest you already have).

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
This will return pair of (String,Int) which we have in Our Dictionary
similar to function return multiple value as below,
func refreshWebPage() -> (status:String,code:Int){
//refresh logic
return ("Success",200)
}

Related

Return a fixed sized list based on an other list

I am looking in Kotlin for a method who return me from a list a new list with a defined number of elements (for example 10).
Whatever the size of the list, the method would always return the same number of elements.
For example, suppose a list of 3000 elements, it would return me a list of 10 elements from indexes 0, 300, 600, 900, 1200,...
Is there an extension function for this?
That's kind of a specialised thing, so there's nothing (that I know of) in the standard library - but you could easily make your own extension function:
fun <T: Any> List<T>.sample2(count: Int): List<T> {
// this allows for a fractional step, so we get a more accurate distribution of indices
// with smaller lists (where count doesn't divide into the list size evenly)
val step = size / count.toFloat()
return List(count) { i -> elementAt((i * step).toInt()) }
}
You'll get repeats if your list is too small to provide count unique indices (e.g. your list has 9 items and you want 10), so you'd have to handle that if you want different behaviour, but I think this is the easiest way to do it
Here's an idea:
Take advantage of the method chunked(size: Int), which tries to depart a given collection into sub-collections of the given size.
That's not quite what you want, but you can use it in order to implement a custom extension function which does what you want, e.g. like this:
fun List<Int>.departInto(subListCount: Int) : List<List<Int>> {
// calculate the chunk size based on the desired amount of sublists
val chunkSize = this.size / subListCount
// then apply that value to the chunked method and return the result
return this.chunked(chunkSize)
}
Using this could look as follows:
fun main() {
// define some example list (of 30 elements in this case)
val someList: List<Int> = List(30, {it})
// use the extension function
val tenSubLists = someList.departInto(10)
// print the result(s)
println(tenSubLists)
}
The output of this code will be 10 sub-lists of 3 elements (your example of 3000 elements would then result in 10 sub-lists of 300 elements each):
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]]

How to implement stack data structure to range extraction (codewars task)?

I'm struggling with codewars kata called Range Extraction - that it takes a list of integers in increasing order and returns a correctly formatted string in the range format(overlapping seperate intervals).
Example solution:
([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
// returns "-6,-3-1,3-5,7-11,14,15,17-20"
Well in my solution, instead of getting -6,-3-1,3-5,7-11,14,15,17-20, I got the last item -6,1,5,11,15,20.
How can I enhance my solution? The code:
function solution(list){
let result=[]
for(let i=0;i<list.length;i++){
let e2=list[i]
let e1 = result[result.length-1]
if(e2-e1==1){
result[result.length-1]=e2
}
else{
result.push(e2 )
}
}
return result
}
console.log(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]))
You are doing nothing to write consecutive integers in range format. Instead you are just replacing the previous result with the final item in the range which is exactly reflected in your solution:
-6: this number has no "neighbors" so is fine
1: the final item in the first range
5: the final item in the second range
...
the problem is the internal logic of the loop.
In summary, you need a while instead of an if and you need to append instead of replace:
function solution(list){
let result=[]
for(let i=0;i<list.length;i++){
//write first value in range to result
result.push(list[i].toString())
//if this is the last entry, we are done
if(i === list.length - 1){
break
}
//initialize variables
let e1 = list[i]
let e2 = list[i+1]
let isRange = false
//run thorugh array while we get consecutive numbers
while(e2-e1===1 && i < list.length-1){
//modify the OUTER LOOP index variable.
//This means when we return to the beginning of hte for loop,
// we will be at the beginning of the next range
i++
e1 = list[i]
e2 = list[i+1]
isRange = true
}
//if there were any consecutive numbers
if(isRange){
//rewrite the last entry in result as a range
result[result.length-1]+="-" + list[i].toString()
}
}
return result.toString()
}
console.log(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]))
now, your outer loop runs through the entire array once. The inner loop will make sure the outer loop skips any items in the list that appear in a range. Finally, if the inner loop found any range at all, it will rewrite the entry as the correct range.

Longest Increasing subsequence length in NlogN.[Understanding the Algo]

Problem Statement: Aim is to find the longest increasing subsequence(not contiguous) in nlogn time.
Algorithm: I understood the algorithm as explained here :
http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/.
What i did not understand is what is getting stored in tail in the following code.
int LongestIncreasingSubsequenceLength(std::vector<int> &v) {
if (v.size() == 0)
return 0;
std::vector<int> tail(v.size(), 0);
int length = 1; // always points empty slot in tail
tail[0] = v[0];
for (size_t i = 1; i < v.size(); i++) {
if (v[i] < tail[0])
// new smallest value
tail[0] = v[i];
else if (v[i] > tail[length-1])
// v[i] extends largest subsequence
tail[length++] = v[i];
else
// v[i] will become end candidate of an existing subsequence or
// Throw away larger elements in all LIS, to make room for upcoming grater elements than v[i]
// (and also, v[i] would have already appeared in one of LIS, identify the location and replace it)
tail[CeilIndex(tail, -1, length-1, v[i])] = v[i];
}
return length;
}
For example ,if input is {2,5,3,,11,8,10,13,6},
the code gives correct length as 6.
But tail will be storing 2,3,6,8,10,13.
So I want to understand what is stored in tail?.This will help me in understanding correctness of this algo.
tail[i] is the minimal end value of the increasing subsequence (IS) of length i+1.
That's why tail[0] is the 'smallest value' and why we can increase the value of LIS (length++) when the current value is bigger than end value of the current longest sequence.
Let's assume that your example is the starting values of the input:
input = 2, 5, 3, 7, 11, 8, 10, 13, 6, ...
After 9 steps of our algorithm tail looks like this:
tail = 2, 3, 6, 8, 10, 13, ...
What does tail[2] means? It means that the best IS of length 3 ends with tail[2]. And we could build an IS of length 4 expanding it with the number that is bigger than tail[2].
tail[0] = 2, IS length = 1: 2, 5, 3, 7, 11, 8, 10, 13, 6
tail[1] = 3, IS length = 2: 2, 5, 3, 7, 11, 8, 10, 13, 6
tail[2] = 6, IS length = 3: 2, 5, 3, 7, 11, 8, 10, 13, 6
tail[3] = 8, IS length = 4: 2, 5, 3, 7, 11, 8, 10, 13, 6
tail[4] = 10,IS length = 5: 2, 5, 3, 7, 11, 8, 10, 13, 6
tail[5] = 13,IS length = 6: 2, 5, 3, 7, 11, 8, 10, 13, 6
This presentation allows you to use binary search (note that defined part of tail is always sorted) to update tail and to find the result at the end of the algorithm.
Tail srotes the Longest Increasing Subsequence (LIS).
It will update itself following the explanation given in the link you provided and claimed to have understood. Check the example.
You want the minimum value at the first element of the tail, which explains the first if statement.
The second if statement is there to allow the LIS to grow, since we want to maximize its length.

Finding minimum element to the right of an index in an array for all indices

Given an array, I wish to find the minimum element to the right of the current element at i where 0=<i<n and store the index of the corresponding minimum element in another array.
For example, I have an array A ={1,3,6,7,8}
The result array would contain R={1,2,3,4} .(R array stores indices to min element).
I could only think of an O(N^2) approach.. where for each element in A, I would traverse the remaining elements to right of A and find the minimum.
Is it possible to do this in O(N)? I want to use the solution to solve another problem.
You should be able to do this in O(n) by filling the array from the right hand side and maintaining the index of the current minimum, as per the following pseudo-code:
def genNewArray (oldArray):
newArray = new array[oldArray.size]
saveIndex = -1
for i = newArray.size - 1 down to 0:
newArray[i] = saveIndex
if saveIndex == -1 or oldArray[i] < oldArray[saveIndex]:
saveIndex = i
return newArray
This passes through the array once, giving you the O(n) time complexity. It can do this because, once you've found a minimum beyond element N, it will only change for element N-1 if element N is less than the current minimum.
The following Python code shows this in action:
def genNewArray (oldArray):
newArray = []
saveIndex = -1
for i in range (len (oldArray) - 1, -1, -1):
newArray.insert (0, saveIndex)
if saveIndex == -1 or oldArray[i] < oldArray[saveIndex]:
saveIndex = i
return newArray
oldList = [1,3,6,7,8,2,7,4]
x = genNewArray (oldList)
print "idx", [0,1,2,3,4,5,6,7]
print "old", oldList
print "new", x
The output of this is:
idx [0, 1, 2, 3, 4, 5, 6, 7]
old [1, 3, 6, 7, 8, 2, 7, 4]
new [5, 5, 5, 5, 5, 7, 7, -1]
and you can see that the indexes at each element of the new array (the second one) correctly point to the minimum value to the right of each element in the original (first one).
Note that I've taken one specific definition of "to the right of", meaning it doesn't include the current element. If your definition of "to the right of" includes the current element, just change the order of the insert and if statement within the loop so that the index is updated first:
idx [0, 1, 2, 3, 4, 5, 6, 7]
old [1, 3, 6, 7, 8, 2, 7, 4]
new [0, 5, 5, 5, 5, 5, 7, 7]
The code for that removes the check on saveIndex since you know that the minimum index for the last element can be found at the last element:
def genNewArray (oldArray):
newArray = []
saveIndex = len (oldArray) - 1
for i in range (len (oldArray) - 1, -1, -1):
if oldArray[i] < oldArray[saveIndex]:
saveIndex = i
newArray.insert (0, saveIndex)
return newArray
Looks like HW. Let f(i) denote the index of the minimum element to the right of the element at i. Now consider walking backwards (filling in f(n-1), then f(n-2), f(n-3), ..., f(3), f(2), f(1)) and think about how information of f(i) can give you information of f(i-1).

how to get an order-specified subset of an array of variable length from an array of variable length?

I have an array of objects of variable length n. Defined by the number of records in my database.
I need a function to grab subsets (keeping the objects in order and always beginning at index 0) of the array of specified length m where m can be any integer I pass in.
e.g. if n = 10 and m = 4
array foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset a = [0, 1, 2, 3]
subset b = [4, 5, 6, 7]
subset c = [8, 9]
So, I need to programmatically be able to say, "Give me the i-th subset of length m from an array, given the array is length n." Using the previous example: "Give me the second subset of length four from foo" => returns the items at positions [4, 5, 6, 7].
I hope that made sense. Assistance with a ruby solution would be much appreciated! thx!
foo.each_slice(subset_length).to_a[subset_index]
e.g. foo.each_slice(4).to_a[2] returns "the second subset of length four from foo".
You can use Enumerable#each_slice:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(4).to_a
#=> [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

Resources