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

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"

Related

Swift logic - Data structure | Sort the items in Array based on similar number | Interview question [duplicate]

This question already has answers here:
Sort array elements based on their frequency
(8 answers)
Closed 12 months ago.
How to sort an integer array based on a duplicate values count. here less number of duplicates should come first.
input [5, 2, 1, 2, 4, 4, 1, 1, 2, 3, 3, 6]
OutPut [5, 6, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1]
Using Martin's comment, here is another approach which aims to reduce the number of loops and conditions we write ourselves by using some functions provided by swift.
// Input
let numbers = [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6]
// Count the occurrences based on Martin's comment
let countDict = numbers.reduce(into: [:], { $0[$1, default: 0] += 1 } )
// Get a sorted array of the countDict keys, sorted by value which
// is the number of occurrences
let sortedKeys
= countDict.keys
.sorted { countDict[$0, default: 0] < countDict[$1, default: 0] }
// Initialize an empty array to hold the final sorted numbers
var sortedNumbers: [Int] = []
// Add the elements into the sortedNumbers with in their desired order
for key in sortedKeys {
sortedNumbers.append(contentsOf: repeatElement(key,
count: countDict[key, default: 0]))
}
// prints [5, 6, 4, 4, 3, 3, 1, 1, 1, 2, 2, 2] based on the above input
print(sortedNumbers)
let numbers = [5,2,1,2,4,4,1,1,2,3,3,6]
let sortedNumber = numbers.sorted()
print("Input: ",sortedNumber)
var dict = [Int: Int]()
for item in sortedNumber {
let isExist = dict.contains(where: {$0.key == item})
if !isExist {
dict[item] = 1
} else {
if let value = dict[item] {
dict[item] = value + 1
}
}
}
var finalArray = [Int]()
let sortedArray = dict.sorted { (first, second) -> Bool in
return first.value < second.value
}
for d in sortedArray {
for _ in 1...d.value {
finalArray.append(d.key)
}
}
print("Output: ",finalArray)
Input: [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6]
Output: [5, 6, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1]

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

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))

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 convert binary code to a number in Dart

Given an array of ones and zeroes, convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11
With Prime numbers I solved everything code from below
int binaryArrayToNumber(List<int> arr) {
return
(arr[0] * 8) +
(arr[1] * 4) +
(arr[2] * 2) +
(arr[3] * 1);
}
How do I make this automatic for larger numbers
A traditional approach would be to iterate over the binary digits and to perform bitshifts and ORs:
int binaryArrayToNumber(List<int> digits) {
var result = 0;
for (var digit in digits) {
result <<= 1;
result |= digit;
}
return result;
}
A more concise, less error-prone (but less efficient) approach would be to convert the list of digits to a String and then parse it:
int binaryArrayToNumber(List<int> digits) =>
int.parse(digits.join(""), radix: 2);
It's good to learn the protocols for the core data types, like List.fold.
int binaryArrayToNumber(List<int> digits) =>
digits.fold(0,(prev, cur) => 2*prev + cur);

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 ;)

Resources