Is there a way to instantly generate an array filled with a range of decreasing values in Swift? - ios

I know you can generate a normal range with Array(0...10), but how about reversed?
For example:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

You can do:
let tenToZero: [Int] = (0...10).reversed()
Note that it is necessary to specify the type here, otherwise it would use the overload of reversed that returns a ReversedCollection.
Alternatively, you can use either of the stride functions and use -1 for the by argument:
stride(from:to:by:)
stride(from:through:by:)
Example:
let tenToZero = Array(stride(from: 10, through: 0, by: -1))

Related

How to generate conditions within constraints in Z3py

Let us assume there are 5-time slots and at each time slot, I have 4 options to choose from, each with a known reward, for eg. rewards = [5, 2, 1, -3]. At every time step, at least 1 of the four options must be selected, with a condition that, if option 3 (with reward -3) is chosen at a time t, then for the remaining time steps, none of the options should be selected. As an example, considering the options are indexed from 0, both [2, 1, 1, 0, 3] and [2, 1, 1, 3, 99] are valid solutions with the second solution having option 3 selected in the 3rd time step and 99 is some random value representing no option was chosen.
The Z3py code I tried is here:
T = 6 #Total time slots
s = Solver()
pick = [[Bool('t%d_ch%d' %(j, i)) for i in range(4)] for j in range(T)]
# Rewards of each option
Rewards = [5, 2, 1, -3]
# Select at most one of the 4 options as True
for i in range(T):
s.add(Or(Not(Or(pick[i][0], pick[i][1], pick[i][2], pick[i][3])),
And(Xor(pick[i][0],pick[i][1]), Not(Or(pick[i][2], pick[i][3]))),
And(Xor(pick[i][2],pick[i][3]), Not(Or(pick[i][0], pick[i][1])))))
# If option 3 is picked, then none of the 4 options should be selected for the future time slots
# else, exactly one should be selected.
for i in range(len(pick)-1):
for j in range(4):
s.add(If(And(j==3,pick[i][j]),
Not(Or(pick[i+1][0], pick[i+1][1], pick[i+1][2], pick[i+1][3])),
Or(And(Xor(pick[i+1][0],pick[i+1][1]), Not(Or(pick[i+1][2], pick[i+1][3]))),
And(Xor(pick[i+1][2],pick[i+1][3]), Not(Or(pick[i+1][0], pick[i+1][1]))))))
if s.check()==False:
print("unsat")
m=s.model()
print(m)
With this implementation, I am not getting solutions such as [2, 1, 1, 3, 99]. All of them either do not have option 3 or have it in the last time slot.
I know there is an error inside the If part but I'm unable to figure it out. Is there a better way to achieve such solutions?
It's hard to decipher what you're trying to do. From a basic reading of your description, I think this might be an instance of the XY problem. See https://xyproblem.info/ for details on that, and try to cast your question in terms of what your original goal is; instead of a particular solution, you're trying to implement. (It seems to me that the solution you came up with is unnecessarily complicated.)
Having said that, you can solve your problem as stated if you get rid of the 99 requirement and simply indicate -3 as the terminator. Once you pick -3, then all the following picks should be -3. This can be coded as follows:
from z3 import *
T = 6
s = Solver()
Rewards = [5, 2, 1, -3]
picks = [Int('pick_%d' % i) for i in range(T)]
def pickReward(p):
return Or([p == r for r in Rewards])
for i in range(T):
if i == 0:
s.add(pickReward(picks[i]))
else:
s.add(If(picks[i-1] == -3, picks[i] == -3, pickReward(picks[i])))
while s.check() == sat:
m = s.model()
picked = []
for i in picks:
picked += [m[i]]
print(picked)
s.add(Or([p != v for p, v in zip(picks, picked)]))
When run, this prints:
[5, -3, -3, -3, -3, -3]
[1, 5, 5, 5, 5, 1]
[1, 2, 5, 5, 5, 1]
[2, 2, 5, 5, 5, 1]
[2, 5, 5, 5, 5, 1]
[2, 1, 5, 5, 5, 1]
[1, 1, 5, 5, 5, 1]
[2, 1, 5, 5, 5, 2]
[2, 5, 5, 5, 5, 2]
[2, 5, 5, 5, 5, 5]
[2, 5, 5, 5, 5, -3]
[2, 1, 5, 5, 5, 5]
...
I interrupted the above as it keeps enumerating all the possible picks. There are a total of 1093 of them in this particular case.
(You can get different answers depending on your version of z3.)
Hope this gets you started. Stating what your original goal is directly is usually much more helpful, should you have further questions.

How to get multiple random elements from list in Dart

When i have list
[1, 2, 3, 4, 5, 6, 7]
i want to get 3 random elements from list
e.g
[1, 3, 4] or [4, 5, 1] or [3, 2, 5]
how can i solve that simply
is there any dart library??
The previous solution is good but could have been written in a more generic way so we don't loose the type information of the List. Also, take does not return a List but instead Iterable.
I have rewritten the code to be more generic and shorter by using the cascade operator. I am not sure if you want a List or Iterable as output so I have made multiple solutions:
void main() {
final items = [1, 2, 3, 4, 5, 6, 7];
print(pickRandomItems(items, 3)); // (7, 4, 3)
print(pickRandomItemsAsList(items, 3)); // [2, 4, 5]
print(pickRandomItemsAsListWithSubList(items, 3)); // [1, 3, 6]
print(items); // [1, 2, 3, 4, 5, 6, 7] (just to show that the original List is untouched)
}
Iterable<T> pickRandomItems<T>(List<T> items, int count) =>
(items.toList()..shuffle()).take(count);
List<T> pickRandomItemsAsList<T>(List<T> items, int count) =>
(items.toList()..shuffle()).take(count).toList();
List<T> pickRandomItemsAsListWithSubList<T>(List<T> items, int count) =>
(items.toList()..shuffle()).sublist(0, count);
Instead of using take in pickRandomItemsAsList you can instead use sublist. But the catch with subList is that if the length are greater than the List it will give an error but with take you just get all the elements in the List shuffled.
Simply shuffle list and take sublist (slice):
List pickRandomItems(List items, int count) {
final list = List.from(items); // cloning original list
list.shuffle(); // shuffling items
return list.take(count); // taking N items
}
List items = [1, 2, 3, 4, 5, 6, 7];
print(pickRandomItems(items, 3));

How to remove array elements and append it to the front of the array in ruby without using any inbuilt methods?

I have an array say [1,2,3,4,5,6,7,8]. I need to take an input from the user and remove the last input number of array elements and append it to the front of the array. This is what I have achieved
def test(number, array)
b = array - array[0...(array.length-1) - number]
array = array.unshift(b).flatten.uniq
return array
end
number = gets.chomp_to_i
array = [1,2,3,4,5,7,8,9]
now passing the argument to test gives me the result. However, there are two problems here. first is I want to find a way to do this append on the front without any inbuilt method.(i.e not using unshift).Second, I am using Uniq here, which is wrong since the original array values may repeat. So how do I still ensure to get the correct output? Can some one give me a better solution to this.
The standard way is:
[1, 2, 3, 4, 5, 7, 8, 9].rotate(-3) #=> [7, 8, 9, 1, 2, 3, 4, 5]
Based on the link I supplied in the comments, I threw this together using the answer to that question.
def test(number, array)
reverse_array(array, 0, array.length - 1)
reverse_array(array, 0, number - 1)
reverse_array(array, number, array.length - 1)
array
end
def reverse_array(array, low, high)
while low < high
array[low], array[high] = array[high], array[low]
low += 1
high -= 1
end
end
and then the tests
array = [1,2,3,4,5,7,8,9]
test(2, array)
#=> [8, 9, 1, 2, 3, 4, 5, 7]
array = [3, 4, 5, 2, 3, 1, 4]
test(2, array)
#=> [1, 4, 3, 4, 5, 2, 3]
Which I believe is what you're wanting, and I feel sufficiently avoids ruby built-ins (no matter what way you look at it, you're going to need to get the value at an index and set a value at an index to do this in place)
I want to find a way to do this append on the front without any inbuilt method
You can decompose an array during assignment:
array = [1, 2, 3, 4, 5, 6, 7, 8]
*remaining, last = array
remaining #=> [1, 2, 3, 4, 5, 6, 7]
last #=> 8
The splat operator (*) gathers any remaining elements. The last element will be assigned to last, the remaining elements (all but the last element) are assigned to remaining (as a new array).
Likewise, you can implicitly create an array during assignment:
array = last, *remaining
#=> [8, 1, 2, 3, 4, 5, 6, 7]
Here, the splat operator unpacks the array, so you don't get [8, [1, 2, 3, 4, 5, 6, 7]]
The above moves the last element to the front. To rotate an array n times this way, use a loop:
array = [1, 2, 3, 4, 5, 6, 7, 8]
n = 3
n.times do
*remaining, last = array
array = last, *remaining
end
array
#=> [6, 7, 8, 1, 2, 3, 4, 5]
Aside from times, no methods were called explicitly.
You could create a new Array with the elements at the correct position thanks to modulo:
array = %w[a b c d e f g h i]
shift = 3
n = array.size
p Array.new(n) { |i| array[(i - shift) % n] }
# ["g", "h", "i", "a", "b", "c", "d", "e", "f"]
Array.new() is a builtin method though ;)

Sort array from particular index to an particular index

Guys.
How to sort an array from particular index to a particular index, not full array sort. I am searching a lot but not find any solution so please tell me how to do this.
You can call sort() directly on a slice of the array:
var array = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
array[2...7].sort()
print(array)
// [9, 8, 2, 3, 4, 5, 6, 7, 1, 0]
The simplest way is extract that specific range from array sort it and after that replace that specific range with sorted array.
Ex
var array = [1,50,42,15,3,25,63,7,26,8,10,36,78,12]
let sliceSortedArray = array[5...10].sorted()
array.removeSubrange(5...10)
array.insert(contentsOf: sliceSortedArray, at: 5)
print(sliceSortedArray) // [7, 8, 10, 25, 26, 63]
print(array) // [1, 50, 42, 15, 3, 7, 8, 10, 25, 26, 63, 36, 78, 12]
Edit As #Martin R suggested you can also use replaceSubrange(_:with:).
array.replaceSubrange(5...10, with: array[5...10].sorted())
You can use a combination of filter and sort which will return a new array with sorted elements. Something along the lines of
let newArray = originalArray.filter {
//This is where you filter based on indexes
}.sort {
//This is where you sort your filtered array
}

Swift build hexadecimal from array (active/inactive states) of Int and get an integer form hexadecimal

Let say we can mark weekend day active or inactive. I need to use Integer to say system that I marked day active or inactive, to retrieve this integer I need to use array [1, 1, 1, 1, 1, 1, 1]. So if you see at this array all day of week marked as active and in Hexadecimal it's 0000007F.
If I use [0, 0, 0, 0, 0, 0, 1] this string it means Hexadecimal = 00000001. So my question is how to create Hexadecimal from array and then get form it an Integer. So in case with 0000007F it should be 127.
I assume that it should be something like that:
let array = [1, 1, 1, 1, 1, 1, 1]
let hexadecimal = array.toHexadecimal
let intNumber = hexadecimal.toInt
print(intNumber) // prints 127
Also I guess it can be for example an array with ints like [0, 1, 1, 1, 1, 0, 1] wich means that Monday and from Wednesday till Saturday (including) are active days.
You can use reduce method to sum up your binary array (inspired at this answer) and use String(radix:) initializer to convert your integer to hexa string:
Swift 3 • Xcode 8 or later
let binaryArray = [1, 1, 1, 1, 1, 1, 1]
let integerValue = binaryArray.reduce(0, {$0*2 + $1})
let hexaString = String(integerValue, radix: 16) // "7f"

Resources