Why doesn't this coffee-script print out? - coffeescript

So when the index is 0, I want to print it out:
a = [ 1, 2, 3 ]
for i of a
if i == 0
console.log a[i]
But there is no output.
i == 0 is never true...

i returns the index as a string, if you parse them as an integer, it would work
a = [ 1, 2, 3 ]
for i of a
if parseInt(i) == 0
console.log a[i]

It's because i will only be 1, 2 or 3, as you loop over the items in a, not the index numbers.
This works the way you described above:
a = [ 1, 2, 3 ]
for i in [0..a.length]
if i == 0
console.log a[i]

You shouldn't use of to loop over an array, you should use in. From the fine manual:
Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array.
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
So you're trying to iterate over the properties of an array object, not its indexes.
You should use one of these for your loop:
for e, i in a
if(i == 0)
console.log(a[i])
for e, i in a
console.log(e) if(i == 0)
console.log(e) for e, i in a when i == 0
#...
Or, since you have an array and a numeric index, why not just skip the loop and get right to the point:
console.log(a[0])

Related

Increment variable for if statement

Is there a more elegant way to write this? I dont want to use a for loop
if i==1 || i==6 || i==11 || i==16 || i==21 || i==26 || i==31 || i==36
function
end
basically i is the index of a vector, after each fifth element of this vector (starting with the first ) a specific function is applied. i starts with 1 and it increments after the if statement and just if it equals these values of the if condition the if statement is valid
EDITTED FOR MATLAB CODE OF MODULO
output = mod(input, 5); //this will output 1 if it is 1, 5, 11, 16
//input is your 1, 5, 11, 16 etc
//output is the result of modulo. else it is 0, 2, 3, 4
if(output == 1)
[previous answer]
i forgot how to write this in matlab but with your values, put it this way.
if(number%5==1)
any input 1 or 6 or 11 or any else that can add 5 to it, you'll end up in 1. else it will return false

Swift 3.0 multiple conditions in c-style for loop

I understand how to write a for loop using swift syntax (using .enumerate() and .revers()), however how would I re-write (in swift) the following javascript version of for loop, considering I have multiple conditions to adhere to:
for(var j = 10; j >= 0 && array[j] > value; j--) {
array[j + 1] = array[j];
}
What about this?
for j in (0...10).reversed() {
guard array[j] > value else { break }
array[j + 1] = array[j]
}
I'm not sure that produces exactly the same result, but this is one of the approaches in Swift 3
for j in stride(from:10, through:0, by: -1) {
if array[j] <= value { break }
array[j + 1] = array[j]
}
For the sake of completion (I would personally prefer to use a for loop with a check for an early break, as others have already suggested) – in Swift 3.1 you could use Sequence's prefix(while:) method in order to get the suffix of the array's indices where the elements meet a given predicate.
var array = [2, 3, 6, 19, 20, 45, 100, 125, 7, 9, 21, 22]
let value = 6
for i in array.indices // the array's indices.
.dropLast() // exclude the last index as we'll be accessing index + 1 in the loop.
.reversed() // reversed so we can get the suffix that meets the predicate.
.prefix(while: {array[$0] > value}) // the subsequence from the start of the
{ // collection where elements meet the predicate.
array[i + 1] = array[i]
}
print(array) // [2, 3, 6, 19, 19, 20, 45, 100, 125, 7, 9, 21]
This is assuming that you're looking to begin iterating at the penultimate index of the array. If you want to start at a particular index, you can say:
for i in (0...10).reversed().prefix(while: {array[$0] > value}) {
array[i + 1] = array[i]
}
This will start at the index 10 and iterate down to 0, giving you the same behaviour to the code in your question.
It's worth noting that both of the above variants will first iterate through the reversed indices (until the predicate isn't met), and then through the array's elements. Although, in Swift 3.1, there is a version of prefix(while:) which operates on a lazy sequence – which would allow for just a single iteration through the elements until the predicate isn't met.
Until Swift 3.1, you can use the below extension to get prefix(while:) on a Collection:
extension Collection {
func prefix(while predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Self.SubSequence {
var index = startIndex
while try index < endIndex && predicate(self[index]) {
formIndex(after: &index)
}
return self[startIndex..<index]
}
}

does Swift array.count get evaluated each time in a loop

I suppose this is a question that must get asked for every language, but when you write for example:
while i < array.count {
...
}
does array.count get evaluated each time the loop runs? Is it better to store it in a let constant before running the loop like this?
let length = array.count
while i < length {
...
}
Array gets the count property because it conforms to Collection. The documentation for count in Collection states
Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.
Source
Since Array also conforms to RandomAccessCollection, it is a constant time operation to get the count of the array. There shouldn't be any major performance difference between getting it once at the start vs every loop iteration.
while loops (and do while loops) have their predicates evaluated on each iteration.
for loops evaluate the sequences once.
Here's is a demonstration:
var array: [Int]
print("Test Case 1 - while i < array.count")
array = [1, 2, 3, 4, 5, 6]
var i = 0
while i < array.count {
print(array[i])
if i < 3 { array.append(123) }
i += 1
}
print("\r\nTest Case 2 - for i in array.indices")
array = [1, 2, 3, 4, 5, 6]
for i in array.indices {
print(array[i])
if i < 3 { array.append(123) }
}
print("\r\nTest Case 3 - for i in 0 ..< array.count")
array = [1, 2, 3, 4, 5, 6]
for i in 0 ..< array.count {
print(array[i])
if i < 3 { array.append(123) }
}
Test Case 1 - while i < array.count
1
2
3
4
5
6
123
123
123
Test Case 2 - for i in array.indices
1
2
3
4
5
6
Test Case 3 - for i in 0 ..< array.count
1
2
3
4
5
6
Yes it's evaluated on each iteration.
Assigning to a constant will be slightly more performant. However with all of the optimisations in a modern compiler I wouldn't bother. Unless the loop count is going to be humongous.
Careful with for loops like the following. Since elems.count is part of a range that gets constructed once at the top of the loop, it is evaluated exactly once. The following code will die when i = 4:
var elems = [1, 2, 3, 4, 5, 6]
for i in 0 ..< elems.count {
if i % 2 == 0 { // remove even elements
elems.remove(at: i)
}
}
The array.count in your while does indeed get evaluated each time the condition is evaluated.
Yes, it gets called every time
Let's run a simple test, first of all we need the following Array Extension
extension Array {
var myCustomCount: Int {
print("myCustomCount")
return self.count
}
}
And then we can try this code
let nums = [1, 2, 3, 4, 5]
var i = 0
while i < nums.myCustomCount {
i += 1
}
The output is
myCustomCount
myCustomCount
myCustomCount
myCustomCount
myCustomCount
myCustomCount

Check a multiple in Swift?

I am trying to find the odd numbers and a multiple of 7 between a 1 to 100 and append them into an array. I have got this far:
var results: [Int] = []
for n in 1...100 {
if n / 2 != 0 && 7 / 100 == 0 {
results.append(n)
}
}
Your conditions are incorrect. You want to use "modular arithmetic"
Odd numbers are not divisible by 2. To check this use:
if n % 2 != 0
The % is the mod function and it returns the remainder of the division (e.g. 5 / 2 is 2.5 but integers don't have decimals, so the integer result is 2 with a remainder of 1 and 5 / 2 => 2 and 5 % 2 => 1)
To check if it's divisible by 7, use the same principle:
if n % 7 == 0
The remainder is 0 if the dividend is divisible by the divisor. The complete if condition is:
if n % 2 != 0 && n % 7 == 0
You can also use n % 2 == 1 because the remainder is always 1. The result of any mod function, a % b, is always between 0 and b - 1.
Or, using the new function isMultiple(of:, that final condition would be:
if !n.isMultiple(of: 2) && n.isMultiple(of: 7)
Swift 5:
Since Swift 5 has been released, you could use isMultiple(of:) method.
In your case, you should check if it is not multiple of ... :
if !n.isMultiple(of: 2)
Swift 5 is coming with isMultiple(of:) method for integers , so you can try
let res = Array(1...100).filter { !$0.isMultiple(of:2) && $0.isMultiple(of:7) }
Here is an efficient and concise way of getting the odd multiples of 7 less than or equal to 100 :
let results: [Int] = Array(stride(from: 7, through: 100, by: 14))
You can also use the built-in filter to do an operation on only qualified members of an array. Here is how that'd go in your case for example
var result = Array(1...100).filter { (number) -> Bool in
return (number % 2 != 0 && number % 7 == 0)
}
print(result) // will print [7, 21, 35, 49, 63, 77, 91]
You can read more about filter in the doc but here is the basics: it goes through each element and collects elements that return true on the condition. So it filters the array and returns what you want

Merging two sorted lists, one with additional 0s

Consider the following problem:
We are given two arrays A and B such that A and B are sorted
except A has B.length additional 0s appended to its end. For instance, A and B could be the following:
A = [2, 4, 6, 7, 0, 0, 0]
B = [1, 7, 9]
Our goal is to create one sorted list by inserting each entry of B
into A in place. For instance, running the algorithm on the above
example would leave
A = [1, 2, 4, 6, 7, 7, 9]
Is there a clever way to do this in better than O(n^2) time? The only way I could think of is to insert each element of B into A by scanning linearly and performing the appropriate number of shifts, but this leads to the O(n^2) solution.
Some pseudo-code (sorta C-ish), assuming array indexing is 0-based:
pA = A + len(A) - 1;
pC = pA; // last element in A
while (! *pA) --pA; // find the last non-zero entry in A
pB = B + len(B) - 1;
while (pA >= A) && (pB >= B)
if *pA > *pB
*pC = *pA; --pA;
else
*pC = *pB; --pB;
--pC
while (pB >= B) // still some bits in B to copy over
*pC = *pB; --pB; --pC;
Not really tested, and just written off the top of my head, but it should give you the idea... May not have the termination and boundary conditions exactly right.
You can do it in O(n).
Work from the end, moving the largest element towards the end of A. This way you avoid a lot of trouble to do with where to keep the elements while iterating. This is pretty easy to implement:
int indexA = A.Length - B.Length - 1;
int indexB = B.Length - 1;
int insertAt = A.Length;
while (indexA > 0 || indexB > 0)
{
insertAt--;
A[insertAt] = max(B[indexB], A[indexA]);
if (A[indexA] <= B[indexB])
indexB--;
else
indexA--;
}