Randomize order of a MongoDB query in Go - mongodb

Here is my query :
c := session.DB("searchV").C("video")
var results []BadVideo
err5 := c.Find(nil).All(&results)
fmt.Println("request done")
if err5 != nil {
panic(err5)
}
var i = 0
for _,badvideo := range results {
}
I would like to randomize the order of browsing the items of the query for making operation on each item of the request ...
So each time I run it, I browse it in a different order.

Manual shuffling
Here's a simple shuffle algorithm, which shuffles (randomizes) a []BadVido slice:
func shuffle(r []BadVideo) {
for i := len(r) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
r[i], r[j] = r[j], r[i]
}
}
So after you loaded your results, simply call shuffle(results) on it.
For testing, I will use a simple BadVideo type:
type BadVideo struct {
Name string
}
func main() {
rand.Seed(time.Now().UnixNano())
results := []BadVideo{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
shuffle(results)
fmt.Println(results)
}
Output (try it on the Go Playground):
[{c} {d} {b} {e} {a}]
How it works:
To shuffle a slice, the shuffle() function randomly selects one element from the slice for each index. It does it like iterating over all elements downward, and selects a random element from the remaining slice (including index of the element we're currently selecting, because random orders also include ones where an element "stays in place"), and using a random index to swaps the element with the chosen random one. The loop goes until i > 0 (and not until i >=0), because if only 1 element left, no need to swap it with itself.
Using rand.Perm()
Another variant of shuffle() could take advantage of rand.Perm() which returns a slice containing shuffled numbers. We can use these random numbers to tell how to reorder the results:
func shuffle(r []BadVideo) {
r2 := append([]BadVideo(nil), r...)
for i, j := range rand.Perm(len(r)) {
r[i] = r2[j]
}
}
Try this variant on the Go Playground.
One thing to note here: before we do the reordering, we have to save the original slice (make a copy of it), so we can select the original elements specified by random indices when writing the results in the slice. I created a copy by appending the complete slice to a nil slice.

Related

Filtering and reducing lazy structures

I would like to filter a lazy structure and then reduce it using Swift language.
func main() -> () {
let result = (1...)
.lazy
.filter { $0 < 3 }
.reduce(0, {$0 + $1})
return print(
result
)
}
main()
This code compiles; however, the program doesn't execute in a proper way (takes too long). The printed result on the screen should be 3.
Is there a way to accomplish this goal ?
The issue is not that your sequence is lazy, it's that your sequence is infinite. You might be looking for the sequence method. Example:
let s = sequence(first: 0) {
$0 > 3 ? nil : $0 + 1
}
let result = s.reduce(0) { $0 + $1 }
print(result) // 10
s is lazy and is potentially infinite but not actually infinite, because the method that generates the next item in the series does an early exit by returning nil when the sequence goes past 3. This is similar to your filter except that it is not a filter, it's a stopper. You can use any condition you like here to generate the stopper.
To get the program to terminate, you would need to add an upper limit on your original sequence (1...).
As it's written, you have an infinite sequence of numbers, starting at 1. The following operators — the filter, in particular — have no way of "knowing" that they can discard the rest of the sequence once they pass 3. They have to process the entire infinite sequence, filtering out all but the first two elements, before your reduce can produce a final result and you can print it out. (In practice, you'll eventually overflow Int, so the program would terminate then, but that's not really a good thing to rely on.)
If you don't want to change the original (1...), you can approximate the same behavior by swapping out your filter with a prefix. A filter has to look at every element; a prefix can "know" that it stops after a certain number of elements. For example, this runs very quickly and prints out 3:
let result = (1...)
.lazy
.prefix(2)
.reduce(0) {$0 + $1}

Loop through a range of an Array [duplicate]

This question already has answers here:
How to loop through an array from the second element in elegant way using Swift
(5 answers)
Closed 3 years ago.
How can I loop through an array range? Example if I had 5 objects in an array. I want to loop from index [3] to end of the array in this example it would go through and update objects 3-5 and skip objects 1 & 2. This is what I have so far using the stride method(this code isn't working). Is this the correct method? How can I achieve this?
stride(from: markers[index], to: markers.endIndex, by: 1).forEach { i in
// Do something for each array object
}
You can use the range operator to get sequences of indices or slices of the array. Which you use depends on what you are trying to do. For clarity I am going to leave out error checking.
For example:
let letters = ["a", "b", "c", "d", "e"]
letters[3...].forEach { print($0) } // prints d e
// or you can print up to index 3
letters[...3].forEach { print($0) } // prints a b c d
// or print elements 1-3 inclusive
letters[1...3].forEach { print($0) } // prints b c d
// or print elements 1-3 excluding index 3
letters[1..<3].forEach { print($0) } // prints b c d
If you wanted to modify the elements of the array you pass in the indices rather than the elements
var mutableLetters = ["a","b","c","d","e"]
(3..<mutableLetters.count).forEach {
mutableLetters[$0] = mutableLetters[$0].uppercased()
}
notice here we need to specify both limits because the range knows nothing about the array.
It's often more Swifty not to modify things in place so, if this fits your use case you might consider something like this:
let immutableLetters = ["a","b","c","d","e"]
let upperCasedFromThreeOn = immutableLetters[3...].map { $0.uppercased() }
// upperCasedFromThreeOn = ["D","E"]
As a final note, sometimes you need to know both the index and the element. You can use a forEach on the indices as above, but another way is to use enumerated() this creates a tuple of the index and element.
let range = 2...4
immutableLetters.enumerated()
.filter { (index,_) in range.contains(index) }
.forEach { (index, element) in
print("\(index) \(element)")
}
Here I've used a filter after the enumeration so that the indices match the original array.
You can simply iterate over your array slice dropping the first n elements:
let markers = ["a","b","c","d","e"]
for marker in markers.dropFirst(2) {
print(marker) // this will print 'c d e'
}
If you need to change your array you can iterate over a slice of its indices:
let markers = ["a","b","c","d","e"]
for index in markers.indices.dropFirst(2) {
print(markers[index])
}
You can simply loop through the array using Range Operator in Swift like,
var markers = ["M1","M2","M3","M4","M5"]
let count = markers.count
if count > 2 {
for i in 2..<count {
//add your code here..
}
}
In the above code, I've used half-open range operator(..<)

How do I work with the 1st and least element in Observable?

Let's say I've got an Observable<Player> and I'd like to map this to another Observable<Integer>, where Integer equals to player.height, but there's a condition: I'd like to map all players but the very first and last one (we should check one more thing for them). So in iterative programming it'll sth like this:
heights = []
num_of_players = len(players)
for idx in len(num_of_players):
if (idx == 0 or idx == num_of_players - 1):
if (isGoodEnough(players[idx]):
heights.append(player.height)
else:
heights.append(player.height)
return height
How do I rewrite this in Rx way (you should assume I'm given Observable instead of List)?
Given:
Observable<Player> players;
Single<Integer> playerHeight(int playerId);
You have to split the sequence into first, middle and last with publish(Function)s and then combine them back together:
players
.publish(sharedPlayers -> {
return Observable.merge(
// work only on the very first player
sharedPlayers.take(1)
.filter(firstPlayer -> isGoodEnough(firstPlayer))
.flatMapSingle(firstPlayer -> playerHeight(firstPlayer.playerId)),
// work with not the first and not the last
sharedPlayers.skip(1).skipLast(1)
.flatMapSingle(midPlayers -> playerHeight(midPlayers .playerId)),
// work with the last which shouldn't be the first again
sharedPlayers.skip(1).takeLast(1)
.filter(lastPlayer -> isGoodEnough(lastPlayer))
.flatMapSingle(lastPlayer-> playerHeight(lastPlayer.playerId))
);
})
.subscribe(/* ... */);
Please adapt this solution as necessary.

Whats faster: Insert at index 0 or array.Reverse?

I'm getting data from my database in the reverse order of how I need it to be. In order to correctly order it I have a couple choices: I can insert each new piece of data gotten at index 0 of my array, or just append it then reverse the array at the end. Something like this:
let data = ["data1", "data2", "data3", "data4", "data5", "data6"]
var reversedArray = [String]()
for var item in data {
reversedArray.insert(item, 0)
}
// OR
reversedArray = data.reverse()
Which one of these options would be faster? Would there be any significant difference between the 2 as the number of items increased?
Appending new elements has an amortized complexity of roughly O(1). According to the documentation, reversing an array has also a constant complexity.
Insertion has a complexity O(n), where n is the length of the array and you're inserting all elements one by one.
So appending and then reversing should be faster. But you won't see a noticeable difference if you're only dealing with a few dozen elements.
Creating the array by repeatedly inserting items at the beginning will be slowest because it will take time proportional to the square of the number of items involved.
(Clarification: I mean building the entire array reversed will take time proportional to n^2, because each insert will take time proportional to the number of items currently in the array, which will therefore be 1 + 2 + 3 + ... + n which is proportional to n squared)
Reversing the array after building it will be much faster because it will take time proportional to the number of items involved.
Just accessing the items in reverse order will be even faster because you avoid reversing the array.
Look up 'big O notation' for more information. Also note that an algorithm with O(n^2) runtime can outperform one with O(n) for small values of n.
My test results…
do {
let start = Date()
(1..<100).forEach { _ in
for var item in data {
reversedArray.insert(item, at: 0)
}
}
print("First: \(Date().timeIntervalSince1970 - start.timeIntervalSince1970)")
}
do {
let start = Date()
(1..<100).forEach { _ in
reversedArray = data.reversed()
}
print("Second: \(Date().timeIntervalSince1970 - start.timeIntervalSince1970)")
}
First: 0.0124959945678711
Second: 0.00890707969665527
Interestingly, running them 10,000 times…
First: 7.67399883270264
Second: 0.0903480052947998

How do you assign a slice of numbers to an array in swift

x is an object that holds an array called point.
x implements the subscript operator so you can do things, like x[i] to get the array's ith element (of type T, which is usually an Int or Double).
This is what I want to do:
x[0...2] = [0...2]
But I get an error that says ClosedInterval<T> is not convertible to Int/Double.
Edit1:
Here is my object x:
let x = Point<Double>(dimensions:3)
For kicks and giggles: define x as [1.0,2.0,0.0]
I can get the first n elements via x[0...2].
What I want to know is how to update x[0...2] to hold [0.0, 0.0.0.0] in one fell swoop. Intuitively, I would want to do x[0...2] = [0...2]. This does not work as can be seen in the answers. I want to update x without iteration (on my end) and by hiding the fact that x is not an array (even though it is not).
[0...2] is an array with one element which, at best, will be a Range<Int> from 0 through 2. You can't assign that to a slice containing, say, Ints.
x[0...2] on the other hand is (probably) a slice, and Sliceable only defines a get subscript, not a setter. So even if the types were more compatible - that is, if you tried x[0...2] = 0...2, which at least is attempting to replace a range within x with the values of a similarly-sized collection - it still wouldn't work.
edit: as #rintaro points out, Array does support a setter subscript for ranges – so if x were a range you could do x[0...2] = Slice(0...2) – but it has to be a slice you assign, so I'd still go with replaceRange.
If what you mean is you want to replace entries 0 through 2 with some values, what you want is replaceRange, as long as your collection conforms to RangeReplaceableCollection (which, for example, Array does):
var x = [0,1,2,3,4,5]
var y = [200,300,400]
x.replaceRange(2..<5, with: y)
// x is now [0,1,200,300,400,5]
Note, the replaced range and y don't have to be the same size, the collection will expand/contract as necessary.
Also, y doesn't have to an array, it can be any kind of collection (has to be a collection though, not a sequence). So the above code could have been written as:
var x = [0,1,2,3,4,5]
var y = lazy(2...4).map { $0 * 100 }
x.replaceRange(2..<5, with: y)
edit: so, per your edit, to in-place zero out an array of any size in one go, you can do:
var x = [1.0,2.0,0.0]
// range to replace is the whole array's range,
// Repeat just generates any given value n times
x.replaceRange(indices(x), with: Repeat(count: x.count, repeatedValue: 0.0))
Adjust the range (and count of replacing entries) accordingly if you want to just zero out a subrange.
Given your example Point class, here is how you could implement this behavior assuming it's backed by an array under the hood:
struct Point<T: FloatLiteralConvertible> {
private var _vals: [T]
init(dimensions: Int) {
_vals = Array(count: dimensions, repeatedValue: 0.0)
}
mutating func replaceRange
<C : CollectionType where C.Generator.Element == T>
(subRange: Range<Array<T>.Index>, with newElements: C) {
// just forwarding on the request - you could perhaps
// do some additional validation first to ensure dimensions
// aren't being altered...
_vals.replaceRange(subRange, with: newElements)
}
}
var x = Point<Double>(dimensions:3)
x.replaceRange(0...2, with: [1.1,2.2,3.3])
You need to implement subscript(InvervalType) to handle the case of multiple assignments like this. That isn't done for you automatically.