0

I have a binary number. This binary has 256 possibilities. I only need to check for 47 of those possibilities.

Its hard to explain and irrelevant, but point[] is an array of Int that I obtain from checking the surrounding tiles in an SKTileMapNode.

let number = 1 * point[0] + 2 * point[1] + 4 * point[2] + 8 * point[3] + 16 * point[4] + 32 * point[5] + 64 * point[6] + 128 * point[7]
//=======o
// 1-10  { 2 = 1, 8 = 2, 10 = 3, 11 = 4, 16 = 5, 18 = 6, 22 = 7, 24 = 8, 26 = 9, 27 = 10, }
// 11-19 { 30 = 11, 31 = 12, 64 = 13, 66 = 14, 72 = 15, 74 = 16, 75 = 17, 80 = 18, 82 = 19,}
// 20-28 { 86 = 20, 88 = 21, 90 = 22, 91 = 23, 94 = 24, 95 = 25, 104 = 26, 106 = 27, 107 = 28, }
// 29-37 { 120 = 29, 122 = 30, 123 = 31, 126 = 32, 127 = 33, 208 = 34, 210 = 35, 214 = 36, 216 = 37, }
// 38-47 { 218 = 38, 219 = 39, 222 = 40, 223 = 41, 248 = 42, 250 = 43, 251 = 44, 254 = 45, 255 = 46, 0 = 47 }
//=======o

binary = 1, binary = 2, binary = 3, etc.

I only need these 47 out of the 256 possibilities. Is there an easy way to check my number against these 47 without having to write 47 if-statements?

E. Huckabee
  • 1,788
  • 1
  • 13
  • 29
  • You can simply put the numbers you want to check against in an `Array` and call `Array.contains(number)` – Dávid Pásztor Oct 10 '18 at 13:44
  • Is there a way I can return `number` when the array does contain `number`? When the array contains the number I need it to return the position in the array that it is in. – E. Huckabee Oct 10 '18 at 13:46
  • you can use `Array.filter({return $0 == number })` this will return `[47]` – hardik parmar Oct 10 '18 at 13:49
  • 1
    Why would you need that when you already have access to `number`, so you can just use `number`, there's no need to return it from the `Array`. If you need its index, you can use `Array.firstIndex(of: number)`. If you'd really want to return the actual number from the Array, you can use `Array.first(where: {$0==number})` and it will be `nil` in case the number isn't an element of the array, but again, this doesn't seem to make any sense for such a simple case. – Dávid Pásztor Oct 10 '18 at 13:49
  • Let me clarify my problem. I need the specific position in the array that `number` coincides with. – E. Huckabee Oct 10 '18 at 13:50
  • In that case you can use `Array.firstIndex(of: number)` as I've already stated. – Dávid Pásztor Oct 10 '18 at 13:59
  • Ok, I'm having trouble explaining it. I need to test if `number` is in the possibilities array. If it is, I need to return the position in the array that `number` coincides with. – E. Huckabee Oct 10 '18 at 14:00
  • @E.Huckabee: That is exactly what `firstIndex(of:)` does. – Martin R Oct 10 '18 at 14:01
  • Got it. Let me try it real quick. – E. Huckabee Oct 10 '18 at 14:02
  • 2
    it is a duplicate. I asked this question because I had no idea what to search for. – E. Huckabee Oct 10 '18 at 14:04

0 Answers0