Swift: How to swap two axes of a four-dimensional array? - arrays

To feed the data to a function correctly, I need to swap two axes in a four-dimensional array in Swift. I'd like to know how to implement or are there any useful function for this purpose.
In Python, if I use numpy.swapaxes(a, axis1, axis2), it's straightforward (https://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html):
def swapaxes_from_tail_to_head(nparray):
nparray = np.swapaxes(nparray, 2, 3)
nparray = np.swapaxes(nparray, 1, 2)
nparray = np.swapaxes(nparray, 0, 1)
return nparray
Just note that if the array is two-dimensional, I can do like this:
func prettyPrintMatrix( _ matrix:[[Int]] ) {
for array in matrix {
print( array )
}
}
func main() -> (){
print( "MatrixTranspose_Demo" )
print()
let matrix =
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
]
print( "Matrix:")
prettyPrintMatrix( matrix )
print()
let transpose = transposeMatrix( matrix )
print( "Transpose matrix:")
prettyPrintMatrix( transpose )
print()
}
func transposeMatrix( _ matrix:[[Int]] ) -> [[Int]] {
var result = [[Int]](
repeating: [Int]( repeating: 0, count: matrix.count ),
count: matrix[ 0 ].count
)
for i in 0 ..< matrix.count {
for k in 0 ..< matrix[ 0 ].count {
result[ k ][ i ] = matrix[ i ][ k ]
}
}
return result
}
main()
// Reference: http://www.runswiftlang.com/
If you have any ideas how to do swapaxes for four-dimentional (or more) array, please let me know. I appreciate your help.

The simplest way is to hard code everything like the followings:
internal func swapaxesOfFlatArray4d<T>(originalArray: [T], axis1: Int, axis2: Int, dimensionOfArray: [Int]) -> [T] {
assert(axis1 != axis2)
assert(dimensionOfArray.count == 4)
assert(axis1 < dimensionOfArray.count)
assert(axis2 < dimensionOfArray.count)
assert(originalArray.count == dimensionOfArray.reduce(1, *))
assert((T.self == Float.self) || (T.self == Double.self))
var newArray = Array<T>()
if ((axis1 == 0 && axis2 == 1) || (axis1 == 1 && axis2 == 0)) {
for j in 0..<dimensionOfArray[1] {
for i in 0..<dimensionOfArray[0] {
for k in 0..<dimensionOfArray[2] {
for l in 0..<dimensionOfArray[3] {
newArray.append(originalArray[i*dimensionOfArray[1]*dimensionOfArray[2]*dimensionOfArray[3] + j*dimensionOfArray[2]*dimensionOfArray[3] + k*dimensionOfArray[3] + l])
}
}
}
}
} else if ((axis1 == 0 && axis2 == 2) || (axis1 == 2 && axis2 == 0)) {
for k in 0..<dimensionOfArray[2] {
for j in 0..<dimensionOfArray[1] {
for i in 0..<dimensionOfArray[0] {
for l in 0..<dimensionOfArray[3] {
newArray.append(originalArray[i*dimensionOfArray[1]*dimensionOfArray[2]*dimensionOfArray[3] + j*dimensionOfArray[2]*dimensionOfArray[3] + k*dimensionOfArray[3] + l])
}
}
}
}
} else if ((axis1 == 0 && axis2 == 3) || (axis1 == 3 && axis2 == 0)) {
for l in 0..<dimensionOfArray[3] {
for j in 0..<dimensionOfArray[1] {
for k in 0..<dimensionOfArray[2] {
for i in 0..<dimensionOfArray[0] {
newArray.append(originalArray[i*dimensionOfArray[1]*dimensionOfArray[2]*dimensionOfArray[3] + j*dimensionOfArray[2]*dimensionOfArray[3] + k*dimensionOfArray[3] + l])
}
}
}
}
} else if ((axis1 == 1 && axis2 == 2) || (axis1 == 2 && axis2 == 1)) {
for i in 0..<dimensionOfArray[0] {
for k in 0..<dimensionOfArray[2] {
for j in 0..<dimensionOfArray[1] {
for l in 0..<dimensionOfArray[3] {
newArray.append(originalArray[i*dimensionOfArray[1]*dimensionOfArray[2]*dimensionOfArray[3] + j*dimensionOfArray[2]*dimensionOfArray[3] + k*dimensionOfArray[3] + l])
}
}
}
}
} else if ((axis1 == 1 && axis2 == 3) || (axis1 == 3 && axis2 == 1)) {
for i in 0..<dimensionOfArray[0] {
for l in 0..<dimensionOfArray[3] {
for k in 0..<dimensionOfArray[2] {
for j in 0..<dimensionOfArray[1] {
newArray.append(originalArray[i*dimensionOfArray[1]*dimensionOfArray[2]*dimensionOfArray[3] + j*dimensionOfArray[2]*dimensionOfArray[3] + k*dimensionOfArray[3] + l])
}
}
}
}
} else if ((axis1 == 2 && axis2 == 3) || (axis1 == 3 && axis2 == 2)) {
for i in 0..<dimensionOfArray[0] {
for j in 0..<dimensionOfArray[1] {
for l in 0..<dimensionOfArray[3] {
for k in 0..<dimensionOfArray[2] {
newArray.append(originalArray[i*dimensionOfArray[1]*dimensionOfArray[2]*dimensionOfArray[3] + j*dimensionOfArray[2]*dimensionOfArray[3] + k*dimensionOfArray[3] + l])
}
}
}
}
} else {
fatalError("Didn't match all the case")
}
return newArray
}
To decrease the amount of the code, you can a class to change the order of for loops.
Change order of for loops?

It is fairly easy to make a transpose function for a 2d matrix:
func transpose<T>(_ matrix:[[T]]) -> [[T]]
{
return matrix.reduce([[T]]())
{
zip($0,$1).map{$0+[$1]}
+ $0.dropFirst($1.count)
+ $1.dropFirst($0.count).map{[$0]}
}
}
Once you have that, all other transpositions of any dimensions can be converted to a series of 2d transposes on consecutive dimensions (essentially swapping them)
let array12 = (1...4).map{ n in (1...4).map{n*10 + $0} }
let array123 = (1...4).map{ n in array12.map{ $0.map{ n*100 + $0 } } }
let array1234 = (1...4).map{ n in array123.map{ $0.map{ $0.map{ n*1000 + $0 } } } }
let array2134 = transpose(array1234) // swap dimensions 1 and 2
let array1324 = array1234.map{transpose($0)} // swap dimensions 2 and 3
let array1243 = array1234.map{$0.map{transpose($0)}} // swap dimensions 3 and 4
Reusing these 3 basic dimension swaps, all other combinations of the 4 dimensions are possible.
let array2143 = array2134.map{$0.map{transpose($0)}}
let array2413 = array2143.map{transpose($0)}
let array4213 = transpose(array2413)
let array4231 = array4213.map{$0.map{transpose($0)}}
let array4321 = array4231.map{transpose($0)}
// and so on ...
To help test this, I made a 4d print function for the matrix that I used in the playground:
It prints in row column order so you get dimension one as a vertical group of "blocks", dimension 2 as a column of blocks, dimension 3 is rows of each block and dimension 4 is the columns of each block:
func print4d<T>(_ matrix4d:[[[[T]]]])
{
var lines:[String] = []
for d1 in matrix4d
{
lines = []
for (indent,d2) in d1.enumerated()
{
let indentWidth = indent * 80
var lineNumber = 0
let blankLine = "".padding(toLength:indentWidth, withPad:" ", startingAt:0)
for d34 in d2
{
while lines.count <= lineNumber
{ lines.append(blankLine) }
lines[lineNumber] = lines[lineNumber]
.padding(toLength:indentWidth, withPad:" ", startingAt:0)
+ " \(d34)"
lineNumber += 1
}
for index in lines.indices
{
while lines[index].contains(" ")
{ lines[index] = lines[index].replacingOccurrences(of: " ", with: " ") }
}
}
lines.forEach{ print($0) }
print("")
}
}
4d matrix : d1, d2, d3, d4
===========================
[1111, 1112, 1113, 1114] [1211, 1212, 1213, 1214] [1311, 1312, 1313, 1314] [1411, 1412, 1413, 1414]
[1121, 1122, 1123, 1124] [1221, 1222, 1223, 1224] [1321, 1322, 1323, 1324] [1421, 1422, 1423, 1424]
[1131, 1132, 1133, 1134] [1231, 1232, 1233, 1234] [1331, 1332, 1333, 1334] [1431, 1432, 1433, 1434]
[1141, 1142, 1143, 1144] [1241, 1242, 1243, 1244] [1341, 1342, 1343, 1344] [1441, 1442, 1443, 1444]
[2111, 2112, 2113, 2114] [2211, 2212, 2213, 2214] [2311, 2312, 2313, 2314] [2411, 2412, 2413, 2414]
[2121, 2122, 2123, 2124] [2221, 2222, 2223, 2224] [2321, 2322, 2323, 2324] [2421, 2422, 2423, 2424]
[2131, 2132, 2133, 2134] [2231, 2232, 2233, 2234] [2331, 2332, 2333, 2334] [2431, 2432, 2433, 2434]
[2141, 2142, 2143, 2144] [2241, 2242, 2243, 2244] [2341, 2342, 2343, 2344] [2441, 2442, 2443, 2444]
[3111, 3112, 3113, 3114] [3211, 3212, 3213, 3214] [3311, 3312, 3313, 3314] [3411, 3412, 3413, 3414]
[3121, 3122, 3123, 3124] [3221, 3222, 3223, 3224] [3321, 3322, 3323, 3324] [3421, 3422, 3423, 3424]
[3131, 3132, 3133, 3134] [3231, 3232, 3233, 3234] [3331, 3332, 3333, 3334] [3431, 3432, 3433, 3434]
[3141, 3142, 3143, 3144] [3241, 3242, 3243, 3244] [3341, 3342, 3343, 3344] [3441, 3442, 3443, 3444]
[4111, 4112, 4113, 4114] [4211, 4212, 4213, 4214] [4311, 4312, 4313, 4314] [4411, 4412, 4413, 4414]
[4121, 4122, 4123, 4124] [4221, 4222, 4223, 4224] [4321, 4322, 4323, 4324] [4421, 4422, 4423, 4424]
[4131, 4132, 4133, 4134] [4231, 4232, 4233, 4234] [4331, 4332, 4333, 4334] [4431, 4432, 4433, 4434]
[4141, 4142, 4143, 4144] [4241, 4242, 4243, 4244] [4341, 4342, 4343, 4344] [4441, 4442, 4443, 4444]
4d matrix : d2, d1, d3, d4
===========================
[1111, 1112, 1113, 1114] [2111, 2112, 2113, 2114] [3111, 3112, 3113, 3114] [4111, 4112, 4113, 4114]
[1121, 1122, 1123, 1124] [2121, 2122, 2123, 2124] [3121, 3122, 3123, 3124] [4121, 4122, 4123, 4124]
[1131, 1132, 1133, 1134] [2131, 2132, 2133, 2134] [3131, 3132, 3133, 3134] [4131, 4132, 4133, 4134]
[1141, 1142, 1143, 1144] [2141, 2142, 2143, 2144] [3141, 3142, 3143, 3144] [4141, 4142, 4143, 4144]
[1211, 1212, 1213, 1214] [2211, 2212, 2213, 2214] [3211, 3212, 3213, 3214] [4211, 4212, 4213, 4214]
[1221, 1222, 1223, 1224] [2221, 2222, 2223, 2224] [3221, 3222, 3223, 3224] [4221, 4222, 4223, 4224]
[1231, 1232, 1233, 1234] [2231, 2232, 2233, 2234] [3231, 3232, 3233, 3234] [4231, 4232, 4233, 4234]
[1241, 1242, 1243, 1244] [2241, 2242, 2243, 2244] [3241, 3242, 3243, 3244] [4241, 4242, 4243, 4244]
[1311, 1312, 1313, 1314] [2311, 2312, 2313, 2314] [3311, 3312, 3313, 3314] [4311, 4312, 4313, 4314]
[1321, 1322, 1323, 1324] [2321, 2322, 2323, 2324] [3321, 3322, 3323, 3324] [4321, 4322, 4323, 4324]
[1331, 1332, 1333, 1334] [2331, 2332, 2333, 2334] [3331, 3332, 3333, 3334] [4331, 4332, 4333, 4334]
[1341, 1342, 1343, 1344] [2341, 2342, 2343, 2344] [3341, 3342, 3343, 3344] [4341, 4342, 4343, 4344]
[1411, 1412, 1413, 1414] [2411, 2412, 2413, 2414] [3411, 3412, 3413, 3414] [4411, 4412, 4413, 4414]
[1421, 1422, 1423, 1424] [2421, 2422, 2423, 2424] [3421, 3422, 3423, 3424] [4421, 4422, 4423, 4424]
[1431, 1432, 1433, 1434] [2431, 2432, 2433, 2434] [3431, 3432, 3433, 3434] [4431, 4432, 4433, 4434]
[1441, 1442, 1443, 1444] [2441, 2442, 2443, 2444] [3441, 3442, 3443, 3444] [4441, 4442, 4443, 4444]
4d matrix : d1, d2, d4, d3
===========================
[1111, 1121, 1131, 1141] [2111, 2121, 2131, 2141] [3111, 3121, 3131, 3141] [4111, 4121, 4131, 4141]
[1112, 1122, 1132, 1142] [2112, 2122, 2132, 2142] [3112, 3122, 3132, 3142] [4112, 4122, 4132, 4142]
[1113, 1123, 1133, 1143] [2113, 2123, 2133, 2143] [3113, 3123, 3133, 3143] [4113, 4123, 4133, 4143]
[1114, 1124, 1134, 1144] [2114, 2124, 2134, 2144] [3114, 3124, 3134, 3144] [4114, 4124, 4134, 4144]
[1211, 1221, 1231, 1241] [2211, 2221, 2231, 2241] [3211, 3221, 3231, 3241] [4211, 4221, 4231, 4241]
[1212, 1222, 1232, 1242] [2212, 2222, 2232, 2242] [3212, 3222, 3232, 3242] [4212, 4222, 4232, 4242]
[1213, 1223, 1233, 1243] [2213, 2223, 2233, 2243] [3213, 3223, 3233, 3243] [4213, 4223, 4233, 4243]
[1214, 1224, 1234, 1244] [2214, 2224, 2234, 2244] [3214, 3224, 3234, 3244] [4214, 4224, 4234, 4244]
[1311, 1321, 1331, 1341] [2311, 2321, 2331, 2341] [3311, 3321, 3331, 3341] [4311, 4321, 4331, 4341]
[1312, 1322, 1332, 1342] [2312, 2322, 2332, 2342] [3312, 3322, 3332, 3342] [4312, 4322, 4332, 4342]
[1313, 1323, 1333, 1343] [2313, 2323, 2333, 2343] [3313, 3323, 3333, 3343] [4313, 4323, 4333, 4343]
[1314, 1324, 1334, 1344] [2314, 2324, 2334, 2344] [3314, 3324, 3334, 3344] [4314, 4324, 4334, 4344]
[1411, 1421, 1431, 1441] [2411, 2421, 2431, 2441] [3411, 3421, 3431, 3441] [4411, 4421, 4431, 4441]
[1412, 1422, 1432, 1442] [2412, 2422, 2432, 2442] [3412, 3422, 3432, 3442] [4412, 4422, 4432, 4442]
[1413, 1423, 1433, 1443] [2413, 2423, 2433, 2443] [3413, 3423, 3433, 3443] [4413, 4423, 4433, 4443]
[1414, 1424, 1434, 1444] [2414, 2424, 2434, 2444] [3414, 3424, 3434, 3444] [4414, 4424, 4434, 4444]
4d matrix : d1, d3, d2, d4
===========================
[1111, 1112, 1113, 1114] [1121, 1122, 1123, 1124] [1131, 1132, 1133, 1134] [1141, 1142, 1143, 1144]
[2111, 2112, 2113, 2114] [2121, 2122, 2123, 2124] [2131, 2132, 2133, 2134] [2141, 2142, 2143, 2144]
[3111, 3112, 3113, 3114] [3121, 3122, 3123, 3124] [3131, 3132, 3133, 3134] [3141, 3142, 3143, 3144]
[4111, 4112, 4113, 4114] [4121, 4122, 4123, 4124] [4131, 4132, 4133, 4134] [4141, 4142, 4143, 4144]
[1211, 1212, 1213, 1214] [1221, 1222, 1223, 1224] [1231, 1232, 1233, 1234] [1241, 1242, 1243, 1244]
[2211, 2212, 2213, 2214] [2221, 2222, 2223, 2224] [2231, 2232, 2233, 2234] [2241, 2242, 2243, 2244]
[3211, 3212, 3213, 3214] [3221, 3222, 3223, 3224] [3231, 3232, 3233, 3234] [3241, 3242, 3243, 3244]
[4211, 4212, 4213, 4214] [4221, 4222, 4223, 4224] [4231, 4232, 4233, 4234] [4241, 4242, 4243, 4244]
[1311, 1312, 1313, 1314] [1321, 1322, 1323, 1324] [1331, 1332, 1333, 1334] [1341, 1342, 1343, 1344]
[2311, 2312, 2313, 2314] [2321, 2322, 2323, 2324] [2331, 2332, 2333, 2334] [2341, 2342, 2343, 2344]
[3311, 3312, 3313, 3314] [3321, 3322, 3323, 3324] [3331, 3332, 3333, 3334] [3341, 3342, 3343, 3344]
[4311, 4312, 4313, 4314] [4321, 4322, 4323, 4324] [4331, 4332, 4333, 4334] [4341, 4342, 4343, 4344]
[1411, 1412, 1413, 1414] [1421, 1422, 1423, 1424] [1431, 1432, 1433, 1434] [1441, 1442, 1443, 1444]
[2411, 2412, 2413, 2414] [2421, 2422, 2423, 2424] [2431, 2432, 2433, 2434] [2441, 2442, 2443, 2444]
[3411, 3412, 3413, 3414] [3421, 3422, 3423, 3424] [3431, 3432, 3433, 3434] [3441, 3442, 3443, 3444]
[4411, 4412, 4413, 4414] [4421, 4422, 4423, 4424] [4431, 4432, 4433, 4434] [4441, 4442, 4443, 4444]
4d matrix : d4, d2, d3, d1
===========================
[1111, 2111, 3111, 4111] [1211, 2211, 3211, 4211] [1311, 2311, 3311, 4311] [1411, 2411, 3411, 4411]
[1121, 2121, 3121, 4121] [1221, 2221, 3221, 4221] [1321, 2321, 3321, 4321] [1421, 2421, 3421, 4421]
[1131, 2131, 3131, 4131] [1231, 2231, 3231, 4231] [1331, 2331, 3331, 4331] [1431, 2431, 3431, 4431]
[1141, 2141, 3141, 4141] [1241, 2241, 3241, 4241] [1341, 2341, 3341, 4341] [1441, 2441, 3441, 4441]
[1112, 2112, 3112, 4112] [1212, 2212, 3212, 4212] [1312, 2312, 3312, 4312] [1412, 2412, 3412, 4412]
[1122, 2122, 3122, 4122] [1222, 2222, 3222, 4222] [1322, 2322, 3322, 4322] [1422, 2422, 3422, 4422]
[1132, 2132, 3132, 4132] [1232, 2232, 3232, 4232] [1332, 2332, 3332, 4332] [1432, 2432, 3432, 4432]
[1142, 2142, 3142, 4142] [1242, 2242, 3242, 4242] [1342, 2342, 3342, 4342] [1442, 2442, 3442, 4442]
[1113, 2113, 3113, 4113] [1213, 2213, 3213, 4213] [1313, 2313, 3313, 4313] [1413, 2413, 3413, 4413]
[1123, 2123, 3123, 4123] [1223, 2223, 3223, 4223] [1323, 2323, 3323, 4323] [1423, 2423, 3423, 4423]
[1133, 2133, 3133, 4133] [1233, 2233, 3233, 4233] [1333, 2333, 3333, 4333] [1433, 2433, 3433, 4433]
[1143, 2143, 3143, 4143] [1243, 2243, 3243, 4243] [1343, 2343, 3343, 4343] [1443, 2443, 3443, 4443]
[1114, 2114, 3114, 4114] [1214, 2214, 3214, 4214] [1314, 2314, 3314, 4314] [1414, 2414, 3414, 4414]
[1124, 2124, 3124, 4124] [1224, 2224, 3224, 4224] [1324, 2324, 3324, 4324] [1424, 2424, 3424, 4424]
[1134, 2134, 3134, 4134] [1234, 2234, 3234, 4234] [1334, 2334, 3334, 4334] [1434, 2434, 3434, 4434]
[1144, 2144, 3144, 4144] [1244, 2244, 3244, 4244] [1344, 2344, 3344, 4344] [1444, 2444, 3444, 4444]

The lack of direct support for matrix operations in Swift was bothering me so I played around with array extensions and cam up with a few methods that could probably make thing a bit easier.
extension Array
{
func asMatrix(_ axisSizes: Int ...) -> [Any] { return asMatrix(axisSizes) }
func asMatrix(_ axisSizes:[Int]) -> [Any]
{
if count == 0 { return [] }
let requiredVectorSize = axisSizes.reduce(1,*)
let flatData = asVector
var newArray:[Any] = flatData
while newArray.count < requiredVectorSize { newArray = newArray + flatData }
for axisSize in axisSizes.dropFirst().reversed()
{
newArray = (0..<newArray.count/axisSize)
.map{($0*axisSize,($0+1)*axisSize)}
.map{newArray[$0..<$1].map{$0}}
}
return newArray
}
var matrixSize:[Int]
{
get { return [count] + ((first as? [Any])?.matrixSize ?? []) }
set { self = asVector.asMatrix(newValue) as! [Element] }
}
func vectorIndex(of indexes:[Int]) -> Int
{
return zip(matrixSize,indexes).reduce(0){ $0 * $1.0 + $1.1 }
}
func matrixIndex(of vectorIndex:Int) -> [Int]
{
var result:[Int] = []
var vectorIndex = vectorIndex
for dim in matrixSize.reversed()
{
result.append(vectorIndex % dim)
vectorIndex = vectorIndex / dim
}
return result.reversed()
}
func enumeratedMatrix() -> [([Int],Any)]
{
return asVector.enumerated().map{(self.matrixIndex(of:$0),$1)}
}
var vectorSize:Int { return matrixSize.reduce(1,*) }
var asVector:[Any]
{
get { return (self as? [[Any]])?.reduce(Array<Any>()){$0+$1}.asVector ?? self}
set { self = newValue.asMatrix(matrixSize) as! [Element] }
}
subscript(indexes:[Int]) -> Any
{
get { return indexes.reduce(self as Any){ ($0 as! [Any])[$1] } }
set {
if indexes.count == 1
{
self[indexes.first!] = newValue as! Element
}
else
{
var subArray = self[indexes.first!] as! Array<Any>
let subIndexes:[Int] = indexes.dropFirst().map{$0}
subArray[subIndexes] = newValue
self[indexes.first!] = subArray as! Element
}
}
}
func transposedMatrix(_ dim1:Int=0, _ dim2:Int=1) -> [Any]
{
if dim1 == dim2 { return self }
var transposedSizes = matrixSize
swap(&transposedSizes[dim1],&transposedSizes[dim2])
var indexMap = (0..<transposedSizes.count).map{$0}
swap(&indexMap[dim1],&indexMap[dim2])
let mapping = (0..<vectorSize)
.map{($0, matrixIndex(of:$0))}
.map{(vi,mi) in (vi,indexMap.map{mi[$0]})}
.map{(vi,mi) in (vi,self.vectorIndex(of:mi)) }
var flatData = asVector
return mapping
.sorted{$0.1 < $1.1}
.map{flatData[$0.0]}
.asMatrix(transposedSizes)
}
}
The only issue remaining is that I had to use type erasure so these matrices are treated as arrays or Any and require some type casting for actual use. Nevertheless, it is easier to manipulate them:
// initialized from vectors:
//
let squareNumbers = (0..<64).map{$0}
var chessBoard = squareNumbers.asMatrix(8,8)
// swapping axes
//
let m4Dim4842 = [0].asMatrix(4,8,4,2) // 1 element vector is repeated to fill content
let m4Dim2844 = m4Dim4842.transposedMatrix(3,0) // swapped dimensions 0 and 3
// double brackets to access elements
//
let queenPos = chessBoard[[4,0]] as! Int
chessBoard[[4,0]] = queenPos
// enumeration to traverse all elements
// (and data assignment using a 1d vector)
chessBoard.asVector = chessBoard.enumeratedMatrix().map{$0.0[0]==$0.0[1] ? 1 : 0}

Related

table array security request Bollinger Pine script

I am attempting to create a scanner for higher time frame Bollingers to place in a table. I have the code working partially using variable. But have been unable to successfully add the data to a table array. My goal is to create a table array that list assets and color codes then in table when conditions are met i.e. price is above or below my signal bollinger deviation.
I have added the assets into arrays but have not been successful in getting them to plot as an array.
as a variable using table cell i get a single asset that plot.
`//#version=5
indicator('Matrix Radar test', overlay=true)
custom_tf = input.timeframe('', title='Timeframe for Screening')
lbl_col = color.new(color.gray, 100)
len3= input.int(50, minval=1, title="Ma Length 1")
len4= input.int(100, minval=1, title="Ma Length 2")
len5= input.int(200, minval=1, title="Ma Length 3")
BB_sdev25 = input.float(2.5, minval=0.001, maxval = 2.8, title="Signal")
//dev for signal 100
dev37 = BB_sdev25 * ta.stdev(close, len4)
//dev for signal 200
dev38 = BB_sdev25 * ta.stdev(close, len5)
//dev for signal 50
dev39 = BB_sdev25 * ta.stdev(close, len3)
//50 1h signals
dma50_up1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len3) + dev39)
dma50_dwn1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len3) - dev39)
//50 4hr signals
dma50_up4hs=request.security(syminfo.tickerid, "240", ta.sma(close, len3) + dev39)
dma50_dwn4hs=request.security(syminfo.tickerid, "240", ta.sma(close, len3) - dev39)
//50 day signals
dma50_upDs=request.security(syminfo.tickerid, "D", ta.sma(close, len3) + dev39)
dma50_dwnDs=request.security(syminfo.tickerid, "D", ta.sma(close, len3) - dev39)
// 100 1 hr signals
dma100_up1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len4) + dev37)
dma100_dwn1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len4) - dev37)
//100 4 hr signal 4hr
dma100s_up4=request.security(syminfo.tickerid, "240", ta.sma(close, len4) + dev37)
dma100s_dwn4=request.security(syminfo.tickerid, "240", ta.sma(close, len4) - dev37)
//100 day signals
dma100_upDs=request.security(syminfo.tickerid, "D", ta.sma(close, len4) + dev37)
dma100_dwnDs=request.security(syminfo.tickerid, "D", ta.sma(close, len4) - dev37)
//200 1h signal
dma200_up1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len5) + dev38)
dma200_dwn1hs=request.security(syminfo.tickerid, "60", ta.sma(close, len5) - dev38)
// 200 4hr signal
dma200_up4s=request.security(syminfo.tickerid, "240", ta.sma(close, len5) + dev38)
dma200_dwn4s=request.security(syminfo.tickerid, "240", ta.sma(close, len5) - dev38)
//200 day signals
dma200_upDs=request.security(syminfo.tickerid, "D", ta.sma(close, len5) + dev38)
dma200_dwnDs=request.security(syminfo.tickerid, "D", ta.sma(close, len5) - dev38)
// plot for visual to check if working
upper10s = ta.sma(close, len4) + dev37
lower10s = ta.sma(close, len4) - dev37
var sma1label9Us = label.new(x = bar_index, y = dma100_up1hs, style = label.style_label_left, color=lbl_col, textcolor = color.yellow, text = "---- --1HUSignal-")
label.set_xy(sma1label9Us, x = bar_index, y = dma100_up1hs)
var sma1label9Ls = label.new(x = bar_index, y = dma100_dwn1hs, style = label.style_label_left, color=lbl_col, textcolor = color.yellow, text = "---- --1HLSignal-")
label.set_xy(sma1label9Ls, x = bar_index, y = dma100_dwn1hs)
// plot for visual to check if working end
indiSet = input(false, '═════════ MRC Parameter ════════')
screenSet = input(false, '═════════ Screening Setting ════════')
screenList = input(false, '═════════ Asset for Screening ════════')
asset_01 = input.symbol(title='Asset 01', defval='')
asset_02 = input.symbol(title='Asset 02', defval='')
asset_03 = input.symbol(title='Asset 03', defval='')
asset_04 = input.symbol(title='Asset 04', defval='')
asset_05 = input.symbol(title='Asset 05', defval='')
asset_06 = input.symbol(title='Asset 06', defval='')
asset_07 = input.symbol(title='Asset 07', defval='')
asset_08 = input.symbol(title='Asset 08', defval='')
asset_09 = input.symbol(title='Asset 09', defval='')
asset_10 = input.symbol(title='Asset 10', defval='')
asset_11 = input.symbol(title='Asset 11', defval='')
asset_12 = input.symbol(title='Asset 12', defval='')
asset_13 = input.symbol(title='Asset 13', defval='')
asset_14 = input.symbol(title='Asset 14', defval='')
asset_15 = input.symbol(title='Asset 15', defval='')
asset_16 = input.symbol(title='Asset 16', defval='')
asset_17 = input.symbol(title='Asset 17', defval='')
asset_18 = input.symbol(title='Asset 18', defval='')
asset_19 = input.symbol(title='Asset 19', defval='')
asset_20 = input.symbol(title='Asset 20', defval='')
asset_21 = input.symbol(title='Asset 21', defval='')
asset_22 = input.symbol(title='Asset 22', defval='')
screen_mrc() =>
int condition = 0
// if low < dma50_dwn1hs or low < dma50_dwn4hs or low < dma50_dwnDs
//condition := 1
//if high > dma50_up1hs or high > dma50_up4hs or high > dma50_upDs
//condition := 1
/// this line below the greater than and less than reversed to force signal for testing
if low > dma100_dwn1hs or high < dma100_up1hs /////////////////////////////////////////
condition := 1 /////////////////////////////////////////
/// this code above the greater than and less than reversed to force signal for testing
//if low < dma100s_dwn4 or high > dma100s_up4
//condition := 3
//if low < dma100_dwnDs or high > dma100_upDs
// condition := 4
//if low < dma200_dwn1hs or high > dma200_up1hs
// condition := 5
// if low < dma200_dwn4s or high > dma200_up4s
// condition := 6
// if low < dma200_dwnDs or high > dma200_upDs
//condition := 7
// Retrieves the names of the ticker
//************************************************************************************************** **********
// Screener Logic
//************************************************************************************************************
// set asset status {
asset_01_status = asset_01 == '' ? 0 : request.security(asset_01, custom_tf, screen_mrc())
asset_02_status = asset_02 == '' ? 0 : request.security(asset_02, custom_tf, screen_mrc())
asset_03_status = asset_03 == '' ? 0 : request.security(asset_03, custom_tf, screen_mrc())
asset_04_status = asset_04 == '' ? 0 : request.security(asset_04, custom_tf, screen_mrc())
asset_05_status = asset_05 == '' ? 0 : request.security(asset_05, custom_tf, screen_mrc())
asset_06_status = asset_06 == '' ? 0 : request.security(asset_06, custom_tf, screen_mrc())
asset_07_status = asset_07 == '' ? 0 : request.security(asset_07, custom_tf, screen_mrc())
asset_08_status = asset_08 == '' ? 0 : request.security(asset_08, custom_tf, screen_mrc())
asset_09_status = asset_09 == '' ? 0 : request.security(asset_09, custom_tf, screen_mrc())
asset_10_status = asset_10 == '' ? 0 : request.security(asset_10, custom_tf, screen_mrc())
asset_11_status = asset_11 == '' ? 0 : request.security(asset_11, custom_tf, screen_mrc())
asset_12_status = asset_12 == '' ? 0 : request.security(asset_12, custom_tf, screen_mrc())
asset_13_status = asset_13 == '' ? 0 : request.security(asset_13, custom_tf, screen_mrc())
asset_14_status = asset_14 == '' ? 0 : request.security(asset_14, custom_tf, screen_mrc())
asset_15_status = asset_15 == '' ? 0 : request.security(asset_15, custom_tf, screen_mrc())
asset_16_status = asset_16 == '' ? 0 : request.security(asset_16, custom_tf, screen_mrc())
asset_17_status = asset_17 == '' ? 0 : request.security(asset_17, custom_tf, screen_mrc())
asset_18_status = asset_18 == '' ? 0 : request.security(asset_18, custom_tf, screen_mrc())
asset_19_status = asset_19 == '' ? 0 : request.security(asset_19, custom_tf, screen_mrc())
asset_20_status = asset_20 == '' ? 0 : request.security(asset_20, custom_tf, screen_mrc())
asset_21_status = asset_21 == '' ? 0 : request.security(asset_21, custom_tf, screen_mrc())
asset_22_status = asset_22 == '' ? 0 : request.security(asset_22, custom_tf, screen_mrc())
//} end
//symbol name
s_arr = array.new_string(0)
array.push(s_arr, asset_01)
array.push(s_arr, asset_02)
array.push(s_arr, asset_03)
array.push(s_arr, asset_04)
array.push(s_arr, asset_05)
array.push(s_arr, asset_06)
array.push(s_arr, asset_07)
array.push(s_arr, asset_08)
array.push(s_arr, asset_09)
array.push(s_arr, asset_10)
array.push(s_arr, asset_11)
array.push(s_arr, asset_12)
array.push(s_arr, asset_13)
array.push(s_arr, asset_14)
array.push(s_arr, asset_15)
array.push(s_arr, asset_16)
array.push(s_arr, asset_17)
array.push(s_arr, asset_18)
array.push(s_arr, asset_19)
array.push(s_arr, asset_20)
array.push(s_arr, asset_21)
array.push(s_arr, asset_22)
//asset condition state
asset_condition = array.new_bool()
array.push(asset_condition, asset_01_status)
array.push(asset_condition, asset_02_status)
array.push(asset_condition, asset_03_status)
array.push(asset_condition, asset_04_status)
array.push(asset_condition, asset_05_status)
array.push(asset_condition, asset_06_status)
array.push(asset_condition, asset_07_status)
array.push(asset_condition, asset_08_status)
array.push(asset_condition, asset_09_status)
array.push(asset_condition, asset_10_status)
array.push(asset_condition, asset_11_status)
array.push(asset_condition, asset_12_status)
array.push(asset_condition, asset_13_status)
array.push(asset_condition, asset_14_status)
array.push(asset_condition, asset_15_status)
array.push(asset_condition, asset_16_status)
array.push(asset_condition, asset_17_status)
array.push(asset_condition, asset_18_status)
array.push(asset_condition, asset_19_status)
array.push(asset_condition, asset_20_status)
array.push(asset_condition, asset_21_status)
array.push(asset_condition, asset_22_status)
// set lower 1001h signal
lower_100hsignal = ''
lower_100hsignal := asset_01 != '' and asset_01_status == 1 ? lower_100hsignal + asset_01 + ' (100 Lower Signal) \n ' : lower_100hsignal
// set upper 1001h signal
upper_100hsignal = ''
upper_100hsignal := asset_01 != '' and asset_01_status == 1 ? upper_100hsignal + asset_01 + ' (100 Upper Signal) \n ' : upper_100hsignal
// Prep Label Value
//--------------
var assetcount = asset_01 == '' and asset_02 == '' and asset_03 == '' and asset_04 == '' and asset_05 == '' and asset_06 == '' and asset_07 == '' and asset_08 == '' and asset_09 == '' and asset_10 == '' and asset_11 == '' and asset_12 == '' and asset_13 == '' and asset_14 == '' and asset_15 == '' and asset_16 == '' and asset_17 == '' and asset_18 == '' and asset_19 == '' and asset_20 == '' and asset_21 == '' and asset_22 == '' ? 0 : 1
var tf = custom_tf == '' ? timeframe.period : custom_tf
var brl = '\n-----------------------\n'
title = 'Bollinger Band Signals:\nTimeframe = ' + tf + brl
var lowertable = table.new(position = position.bottom_left, columns = 1, rows = 40, bgcolor = color.blue, border_width = 3 )
if assetcount > 0
if lower_100hsignal + lower_100hsignal != ''
lower_100hsignal := '\lower100' + lower_100hsignal
lower_100hsignal
if barstate.islast
table.cell(lowertable, column = 0, row = 0, text=title + lower_100hsignal)
var upperTable = table.new(position = position.middle_left, columns = 1, rows = 40, bgcolor = color.red, border_width = 1)
if assetcount > 0
if upper_100hsignal + upper_100hsignal != ''
upper_100hsignal := '\upper100' + upper_100hsignal
upper_100hsignal
if barstate.islast
table.cell(table_id = upperTable, column = 0, row = 0, text=title + upper_100hsignal)`

How to get sum of array in foreach in laravel 6

from my controller sum is not working
public function show($id)
{
$workers = DB::table('workers')
->select('wrk_id','f_name','m_name','l_name')
;
$attendance = DB::table('attendance')->where('payroll_daily_id', $id)
->select('attendance.*','f_name','l_name','m_name',DB::raw('SUM(reg_hour)as tots'))
->rightjoinSub($workers,'worker', function($join){
$join->on('attendance.wrk_id','=','worker.wrk_id');
})
->groupBy('payroll_attn_id')
->get();
foreach($attendance as $key){
$fetch[$key->wrk_id]['wrk_id'] = $key->wrk_id;
$fetch[$key->wrk_id]['f_name'] = $key->f_name;
$fetch[$key->wrk_id]['l_name'] = $key->l_name;
$fetch[$key->wrk_id]['m_name'] = $key->m_name;
$fetch['total_work_hours'] = $key->tots;
$fetch[$key->wrk_id]['date'][$key->date]['work_hours'] = $key->reg_hour;
}
return $fetch;
}
this is the result total_work_hours display only 8 instead of 56
2: {wrk_id: 2, f_name: "John", l_name: "Doe", m_name: null,…}
date: {2020-09-27: {work_hours: 8}, 2020-09-28: {work_hours: 8}, 2020-09-29: {work_hours: 8},…}
2020-09-27: {work_hours: 8}------------------
2020-09-28: {work_hours: 8}------------------
2020-09-29: {work_hours: 8}------------------
2020-09-30: {work_hours: 8}------------------ TOTAL OF THIS IS 56
2020-10-01: {work_hours: 8}------------------
2020-10-02: {work_hours: 8}------------------
2020-10-03: {work_hours: 8}-----------------
f_name: "John"
l_name: "Doe"
m_name: null
wrk_id: 2
total_work_hours: "8" <------------- 56 is the total off work_hours from array
try this
$fetch = [];
foreach($attendance as $key){
if(!isset($fetch[$key->wrk_id]['total_work_hours'])){
$fetch[$key->wrk_id]['total_work_hours'] = 0;
}
$fetch[$key->wrk_id]['wrk_id'] = $key->wrk_id;
$fetch[$key->wrk_id]['f_name'] = $key->f_name;
$fetch[$key->wrk_id]['l_name'] = $key->l_name;
$fetch[$key->wrk_id]['m_name'] = $key->m_name;
$fetch['s'] = $key->tots;
$fetch[$key->wrk_id]['date'][$key->date]['work_hours'] = $key->reg_hour;
$fetch[$key->wrk_id]['total_work_hours'] += $key->reg_hour;
}
return $fetch;
Use foreach like this:
foreach($attendance as $key){
if(empty($fetch[$key->wrk_id]['total_work_hours'])){
$fetch[$key->wrk_id]['total_work_hours'] = 0;
}
$fetch[$key->wrk_id]['wrk_id'] = $key->wrk_id;
$fetch[$key->wrk_id]['f_name'] = $key->f_name;
$fetch[$key->wrk_id]['l_name'] = $key->l_name;
$fetch[$key->wrk_id]['m_name'] = $key->m_name;
$fetch['s'] = $key->tots;
$fetch[$key->wrk_id]['total_work_hours'] += $key->reg_hour;
}

AngularJS Getting Data response in console as null but in Postman is not null

Postman and Direct URL Response
"MenuId": 2010,
"KitchenId": 2005,
"Categoryid": 1,
"CategoryName": "Starters",
"SubCategoryId": 1,
"SubCategoryName": "Veg Starters",
"Name": "Paneer Kabab",
"Description": "Paneer fried",
"ImageURL": "noimage.png",
"Foodtype": 1,
"NetPrice": 70.00,
"NetGST": 3.50,
"NetTotal": 83.50,
"ListPrice": 84.00,
"ListGST": 4.20,
"ListTotal": 99.20,
"PackingCharge": 11.00,
"Discount": null,
"TotalOrders": 0.00,
"Ratings": null,
"MenuStatus": 1,
"VegTypeId": 1,
"GetButton_no": [
{
**"ButtonNo_No": 99.20**
}
],
Browser Console
{ "MenuId": 2010,
"KitchenId": 2005,
"Categoryid": 1,
"CategoryName": "Starters",
"SubCategoryId": 1,
"SubCategoryName": "Veg Starters",
"Name": "Paneer Kabab",
"Description": "Paneer fried",
"ImageURL": "noimage.png",
"Foodtype": 1,
"NetPrice": 70.00,
"NetGST": 3.50,
"NetTotal": 83.50,
"ListPrice": 84.00,
"ListGST": 4.20,
"ListTotal": 99.20,
"PackingCharge": 11.00,
"Discount": null,
"TotalOrders": 0.00,
"Ratings": null,
"MenuStatus": 1,
"VegTypeId": 1,
"GetButton_no": [
{
**"ButtonNo_No": null**
}
],
}
Why is the same API Behaving different behaviour , I am using Entity Framework for that.
public IEnumerable<KitchenMenu_CategoryModel> GetKitchenMenubyKitchennew(int kid,string Username)
{
var result = db.tblKitchens.Where(x => x.Id == kid).Select(x => new KitchenMenu_CategoryModel
{
KitchenId = x.Id,
KitchenName = x.KitchenName,
KitchenType = x.KitchenType,
Area = x.Area,
Address1 = x.Address1,
Address2 = x.Address2,
//CId = x.CityId,
Pincode = x.Pincode,
Email = x.Email,
Website = x.Website,
Landline = x.Landline,
Halal = x.Halal,
Category = x.Category,
Branches = x.Branches,
AvgCost = x.AvgCost,
Fssai = x.Fssai,
FssaiPath = x.FssaiPath,
RegisterStatus = x.RegisterStatus,
Logo = db.tblKitchenMedias.Where(r => r.KitchenId == x.Id).Select(r => r).FirstOrDefault().Logo,
Banner = db.tblKitchenMedias.Where(s => s.KitchenId == x.Id).Select(s => s).FirstOrDefault().Banner,
GetCategory = db.tblGetCategories.Where(y => y.Kitchenid == x.Id).Select(y => new CategoryModel
{
CategoryId = y.Categoryid,
Kitchenid = y.Kitchenid,
CategoryName = y.tblCategory.CategoryName,
SubCateogry = db.tblGetSubCategories.Where(z => z.Categoryid == y.Categoryid && z.Kitchenid == y.Kitchenid).Select(z => new SubCategoryModel
{
Categoryid = z.Categoryid,
SubCategoryName = z.tblSubCategory.SubCategoryName,
Kitchenid = z.Kitchenid,
GetMenu = db.tblMenus.Where(a => a.SubCategoryId == z.SubCategoryid && a.KitchenId == z.Kitchenid).Select(a => new MenuModel
{
MenuId = a.MenuId,
Name = a.Name,
Description = a.Description,
Discount = a.Discount,
ImageURL = a.ImageURL,
ListGST = a.ListGST,
ListPrice = a.ListPrice,
ListTotal = a.ListTotal,
NetGST = a.NetGST,
NetPrice = a.NetPrice,
TotalOrders = a.TotalOrders,
KitchenId = a.KitchenId,
SubCategoryId = a.SubCategoryId,
MenuStatus = a.MenuStatus,
NetTotal = a.NetTotal,
VegTypeId = a.VegTypeId,
Categoryid = a.Categoryid,
CategoryName = a.tblCategory.CategoryName,
SubCategoryName = a.tblSubCategory.SubCategoryName,
Ratings = a.Ratings,
Foodtype = a.Foodtype,
PackingCharge = a.PackingCharge,
GetButton_no =db.tblcarts.Where(d => d.Username == Username && d.KitchenId == kid && d.MenuId == a.MenuId).Select(d => new ButtonModel
{
ButtonNo_No =d.TotalPrice,
}
).ToList(),
//ButtonNo_No = db.tblcarts.Where(d => d.Username == Username && d.KitchenId == a.KitchenId && d.MenuId == a.MenuId).Select(d => d).FirstOrDefault().Quantity,
//Button_No =db.spCountCartButton(Username,a.KitchenId,a.MenuId).Select(d=>d).FirstOrDefault(),
GetMenuAttribute = db.tblMenuAttributes.Where(b => b.Menuid == a.MenuId).Select(b => new MenuAttributeModel
{
MenuAttributeId = b.MenuAttributeId,
Menuid = b.Menuid,
AttributeType = b.AttributeType,
MenuAttribute = b.MenuAttribute,
MenuDescription = b.MenuDescription,
NetPrice = b.NetPrice,
NetGST = b.NetGST,
NetTotal = b.NetTotal,
ListPrice = b.ListPrice,
ListGST = b.ListGST,
ListTotal = b.ListTotal,
PackingCharge = b.PackingCharge,
}
).ToList(),
}
).ToList(),
}
).ToList(),
}
).ToList(),
}
).ToList();
return result;
}
--API Controller
[Route("api/GetMenuBykidnew")]
[HttpGet]
public HttpResponseMessage GetMenuBykid(int kid, string Username)
{
//var data = new List();
ApiBusiness ApiBus = new ApiBusiness();
var result = ApiBus.GetKitchenMenubyKitchennew(kid, Username);
return new HttpResponseMessage()
{
Content = new StringContent(JArray.FromObject(result).ToString(), Encoding.UTF8, "application/json")
};
}
The response is very strange getting different response in browser console and postman

how to remove duplicate from result in datastax solr

wt=json&indent=true&q=*%3A*&start=0&rows=100&fq=scorer%3A2269ae85-b738-49c2-b188-17c3d79400a6
I am Getting Response Like :
{
"responseHeader":{
"status":0,
"QTime":0},
"response":{"numFound":5,"start":0,"docs":[
{
**"tournament_scheduler_id":"e405cfab-18c6-43df-ab6d-1279b91cddaa",**
"modified_date":"2016-01-08T14:20:48.433Z",
"win_team_runs":0,
"elect_to":"Elected to bat",
"ground_id":"93b5d90c-16a9-4fb8-a21f-f549bb080ac5",
"scorer":["2269ae85-b738-49c2-b188-17c3d79400a6"],
"modified_by":"96588171-ef8b-43f2-a86d-e7d3460aac29",
"tournament_id":"1ff0ae4e-146e-4ef1-ad07-507d0b9be9de",
"no_of_overs":20,
"lose_team_wickets":0,
"created_by":"96588171-ef8b-43f2-a86d-e7d3460aac29",
"created_date":"2016-01-07T07:01:24.419Z",
"away_team_id":"e3ca398f-ae3b-42f0-bc87-e0edadaebb53",
"lose_team_runs":0,
"match_type":"Twenty 20",
"status":"InProgress",
"game_date":"2016-01-30T00:00:00Z",
"win_team_wickets":0,
"status_of_match":"",
"toss_won_by":"e38877ec-f44f-498f-ada1-049d097a13dc",
"home_team_id":"e38877ec-f44f-498f-ada1-049d097a13dc",
"active":1,
"umpire_id_1":"679c0940-b1da-4297-a969-4d0be8018b1b",
"umpire_id_2":"ae28b91d-58af-4f00-92f9-4f7f3ce61ec5"},
{
"tournament_scheduler_id":"cca34732-d2d0-4662-9567-2748d9b3888d",
"modified_date":"2016-01-07T10:56:23.385Z",
"win_team_runs":0,
"elect_to":"Elected to bat",
"ground_id":"485cdf29-bf9b-4330-aa31-e2e3a411c741",
"scorer":["2269ae85-b738-49c2-b188-17c3d79400a6"],
"modified_by":"63b4a76f-b9c3-49da-8f31-6772ac5d3dc5",
"tournament_id":"c91244a0-a42a-44a3-bf10-a20023d4d2e9",
"no_of_overs":20,
"lose_team_wickets":0,
"created_by":"63b4a76f-b9c3-49da-8f31-6772ac5d3dc5",
"created_date":"2016-01-06T06:26:04.765Z",
"away_team_id":"a0dad51e-1398-413f-9d4d-cdff470e90c2",
"lose_team_runs":0,
"match_type":"Twenty 20",
"status":"InProgress",
"game_date":"2016-01-15T00:00:00Z",
"win_team_wickets":0,
"status_of_match":"",
"toss_won_by":"a0dad51e-1398-413f-9d4d-cdff470e90c2",
"home_team_id":"f62b86f9-2b65-4352-964b-9572803835d9",
"active":1,
"umpire_id_1":"acb01386-5fc6-45db-a186-715ec2fd7ce2"},
{
**"tournament_scheduler_id":"e405cfab-18c6-43df-ab6d-1279b91cddaa",**
"modified_date":"2016-01-08T14:20:48.433Z",
"win_team_runs":0,
"elect_to":"Elected to bat",
"ground_id":"93b5d90c-16a9-4fb8-a21f-f549bb080ac5",
"scorer":["2269ae85-b738-49c2-b188-17c3d79400a6"],
"modified_by":"96588171-ef8b-43f2-a86d-e7d3460aac29",
"tournament_id":"1ff0ae4e-146e-4ef1-ad07-507d0b9be9de",
"no_of_overs":20,
"lose_team_wickets":0,
"created_by":"96588171-ef8b-43f2-a86d-e7d3460aac29",
"created_date":"2016-01-07T07:01:24.419Z",
"away_team_id":"e3ca398f-ae3b-42f0-bc87-e0edadaebb53",
"lose_team_runs":0,
"match_type":"Twenty 20",
"status":"InProgress",
"game_date":"2016-01-30T00:00:00Z",
"win_team_wickets":0,
"status_of_match":"",
"toss_won_by":"e38877ec-f44f-498f-ada1-049d097a13dc",
"home_team_id":"e38877ec-f44f-498f-ada1-049d097a13dc",
"active":1,
"umpire_id_1":"679c0940-b1da-4297-a969-4d0be8018b1b",
"umpire_id_2":"ae28b91d-58af-4f00-92f9-4f7f3ce61ec5"},
{
"tournament_scheduler_id":"c012b682-b0d9-4f75-8261-a6f4728f70a0",
"modified_date":"2016-01-08T17:17:51.043Z",
"win_team_runs":0,
"elect_to":"",
"ground_id":"93b5d90c-16a9-4fb8-a21f-f549bb080ac5",
"scorer":["2269ae85-b738-49c2-b188-17c3d79400a6"],
"modified_by":"96588171-ef8b-43f2-a86d-e7d3460aac29",
"tournament_id":"1ff0ae4e-146e-4ef1-ad07-507d0b9be9de",
"no_of_overs":0,
"lose_team_wickets":0,
"created_by":"96588171-ef8b-43f2-a86d-e7d3460aac29",
"created_date":"2016-01-08T17:17:51.043Z",
"away_team_id":"e3ca398f-ae3b-42f0-bc87-e0edadaebb53",
"lose_team_runs":0,
"match_type":"",
"status":"Upcoming",
"game_date":"2016-02-24T00:00:00Z",
"win_team_wickets":0,
"status_of_match":"",
"home_team_id":"e38877ec-f44f-498f-ada1-049d097a13dc",
"active":1,
"umpire_id_1":"679c0940-b1da-4297-a969-4d0be8018b1b"},
{
"tournament_scheduler_id":"93be7a28-4867-461a-bff2-d81615c6d360",
"modified_date":"2016-01-08T18:59:47.567Z",
"win_team_runs":0,
"elect_to":"Elected to bowl",
"ground_id":"485cdf29-bf9b-4330-aa31-e2e3a411c741",
"scorer":["2269ae85-b738-49c2-b188-17c3d79400a6"],
"modified_by":"63b4a76f-b9c3-49da-8f31-6772ac5d3dc5",
"tournament_id":"c91244a0-a42a-44a3-bf10-a20023d4d2e9",
"no_of_overs":20,
"lose_team_wickets":0,
"created_by":"63b4a76f-b9c3-49da-8f31-6772ac5d3dc5",
"created_date":"2016-01-08T14:31:35.298Z",
"away_team_id":"f62b86f9-2b65-4352-964b-9572803835d9",
"lose_team_runs":0,
"match_type":"Twenty 20",
"status":"InProgress",
"game_date":"2016-03-14T00:00:00Z",
"win_team_wickets":0,
"status_of_match":"",
"toss_won_by":"f62b86f9-2b65-4352-964b-9572803835d9",
"home_team_id":"a0dad51e-1398-413f-9d4d-cdff470e90c2",
"active":1,
"umpire_id_1":"4e113da2-5be9-40e5-a689-1a3e9d959c3d"}]
}}
here,tournament_scheduler_id is uniquekey in core

Most Efficient Ways To Compare Multiple Array Values in VBA?

Before I begin, let me say that I know this probably isn't best done in excel and VBA, but my hands are tied in that regard.
I have a spreadsheet of 29 columns (always), and anywhere between 100 and 10,000 rows each day.
I need a way to automatically move rows from one sheet to another based on multiple criteria. The basic logic is that it needs to search the first sheet, and if C OR D equal a certain text value, AND Y contains a certain numeric value, it needs to be added to the second sheet and removed from the first.
The problem is that I've built a test version that only looks at ONE of the three criteria, and it is already very slow - If I had two more arrays and if/and/or logic, I don't think this is going to be usable on the 10,000 row days.
What can I do to speed this up? I feel like there has to be a better/faster way than arrays and for loops. I'm very much a novice, so I'm sure this is a very bad solution.
Option Explicit
Sub MacroSoFar()
Dim lColumnLength As Long
Dim intArrayCounter As Integer
Dim TestArray(165) As String
TestArray(0) = "4"
TestArray(1) = "5"
TestArray(2) = "6"
TestArray(3) = "7"
TestArray(4) = "8"
TestArray(5) = "9"
TestArray(6) = "10"
TestArray(7) = "11"
TestArray(8) = "12"
TestArray(9) = "14"
TestArray(10) = "19"
TestArray(11) = "20"
TestArray(12) = "21"
TestArray(13) = "25"
TestArray(14) = "30"
TestArray(15) = "35"
TestArray(16) = "36"
TestArray(17) = "37"
TestArray(18) = "41"
TestArray(19) = "42"
TestArray(20) = "43"
TestArray(21) = "46"
TestArray(22) = "47"
TestArray(23) = "48"
TestArray(24) = "51"
TestArray(25) = "52"
TestArray(26) = "53"
TestArray(27) = "60"
TestArray(28) = "63"
TestArray(29) = "65"
TestArray(30) = "66"
TestArray(31) = "67"
TestArray(32) = "68"
TestArray(33) = "69"
TestArray(34) = "70"
TestArray(35) = "71"
TestArray(36) = "72"
TestArray(37) = "73"
TestArray(38) = "74"
TestArray(39) = "75"
TestArray(40) = "76"
TestArray(41) = "77"
TestArray(42) = "78"
TestArray(43) = "79"
TestArray(44) = "80"
TestArray(45) = "81"
TestArray(46) = "82"
TestArray(47) = "83"
TestArray(48) = "84"
TestArray(49) = "85"
TestArray(50) = "86"
TestArray(51) = "87"
TestArray(52) = "88"
TestArray(53) = "89"
TestArray(54) = "90"
TestArray(55) = "91"
TestArray(56) = "92"
TestArray(57) = "93"
TestArray(58) = "94"
TestArray(59) = "96"
TestArray(60) = "97"
TestArray(61) = "98"
TestArray(62) = "99"
TestArray(63) = "101"
TestArray(64) = "102"
TestArray(65) = "103"
TestArray(66) = "106"
TestArray(67) = "107"
TestArray(68) = "108"
TestArray(69) = "109"
TestArray(70) = "111"
TestArray(71) = "112"
TestArray(72) = "113"
TestArray(73) = "115"
TestArray(74) = "116"
TestArray(75) = "117"
TestArray(76) = "118"
TestArray(77) = "121"
TestArray(78) = "122"
TestArray(79) = "125"
TestArray(80) = "129"
TestArray(81) = "130"
TestArray(82) = "131"
TestArray(83) = "132"
TestArray(84) = "133"
TestArray(85) = "134"
TestArray(86) = "137"
TestArray(87) = "138"
TestArray(88) = "142"
TestArray(89) = "143"
TestArray(90) = "144"
TestArray(91) = "145"
TestArray(92) = "146"
TestArray(93) = "147"
TestArray(94) = "155"
TestArray(95) = "156"
TestArray(96) = "157"
TestArray(97) = "158"
TestArray(98) = "159"
TestArray(99) = "161"
TestArray(100) = "162"
TestArray(101) = "169"
TestArray(102) = "170"
TestArray(103) = "173"
TestArray(104) = "174"
TestArray(105) = "175"
TestArray(106) = "176"
TestArray(107) = "180"
TestArray(108) = "181"
TestArray(109) = "182"
TestArray(110) = "183"
TestArray(111) = "184"
TestArray(112) = "185"
TestArray(113) = "186"
TestArray(114) = "187"
TestArray(115) = "188"
TestArray(116) = "189"
TestArray(117) = "190"
TestArray(118) = "192"
TestArray(119) = "193"
TestArray(120) = "194"
TestArray(121) = "195"
TestArray(122) = "196"
TestArray(123) = "201"
TestArray(124) = "202"
TestArray(125) = "205"
TestArray(126) = "206"
TestArray(127) = "207"
TestArray(128) = "208"
TestArray(129) = "211"
TestArray(130) = "212"
TestArray(131) = "214"
TestArray(132) = "215"
TestArray(133) = "217"
TestArray(134) = "218"
TestArray(135) = "220"
TestArray(136) = "221"
TestArray(137) = "222"
TestArray(138) = "223"
TestArray(139) = "224"
TestArray(140) = "225"
TestArray(141) = "226"
TestArray(142) = "228"
TestArray(143) = "229"
TestArray(144) = "230"
TestArray(145) = "235"
TestArray(146) = "236"
TestArray(147) = "237"
TestArray(148) = "240"
TestArray(149) = "241"
TestArray(150) = "242"
TestArray(151) = "244"
TestArray(152) = "249"
TestArray(153) = "250"
TestArray(154) = "251"
TestArray(155) = "255"
TestArray(156) = "256"
TestArray(157) = "259"
TestArray(158) = "260"
TestArray(159) = "262"
TestArray(160) = "263"
TestArray(161) = "264"
TestArray(162) = "265"
TestArray(163) = "266"
TestArray(164) = "267"
TestArray(165) = "269"
For intArrayCounter = 0 To 165 Step 1
For lColumnLength = Cells(Rows.Count, 25).End(xlUp).Row To 1 Step -1
If InStr(Cells(lColumnLength, 25), TestArray(intArrayCounter)) > 0 Then
Range("a" & lColumnLength & ":AC" & lColumnLength).Copy Sheet10.Cells(Rows.Count, 1).End(xlUp).Offset(1)
Cells(lColumnLength, 29).EntireRow.Delete
End If
Next
Next
End Sub
I haven't tested this, but I got to run.
But it may give you some food for thought.
Option Explicit
Sub MacroSoFar()
Dim lColumnLength As Long
Dim intArrayCounter As Integer
Dim TestArray(165) As String
TestArray(0) = "4"
TestArray(1) = "5"
TestArray(2) = "6"
TestArray(3) = "7"
TestArray(4) = "8"
TestArray(5) = "9"
TestArray(6) = "10"
TestArray(7) = "11"
TestArray(8) = "12"
TestArray(9) = "14"
TestArray(10) = "19"
TestArray(11) = "20"
TestArray(12) = "21"
TestArray(13) = "25"
TestArray(14) = "30"
TestArray(15) = "35"
TestArray(16) = "36"
TestArray(17) = "37"
TestArray(18) = "41"
TestArray(19) = "42"
TestArray(20) = "43"
TestArray(21) = "46"
TestArray(22) = "47"
TestArray(23) = "48"
TestArray(24) = "51"
TestArray(25) = "52"
TestArray(26) = "53"
TestArray(27) = "60"
TestArray(28) = "63"
TestArray(29) = "65"
TestArray(30) = "66"
TestArray(31) = "67"
TestArray(32) = "68"
TestArray(33) = "69"
TestArray(34) = "70"
TestArray(35) = "71"
TestArray(36) = "72"
TestArray(37) = "73"
TestArray(38) = "74"
TestArray(39) = "75"
TestArray(40) = "76"
TestArray(41) = "77"
TestArray(42) = "78"
TestArray(43) = "79"
TestArray(44) = "80"
TestArray(45) = "81"
TestArray(46) = "82"
TestArray(47) = "83"
TestArray(48) = "84"
TestArray(49) = "85"
TestArray(50) = "86"
TestArray(51) = "87"
TestArray(52) = "88"
TestArray(53) = "89"
TestArray(54) = "90"
TestArray(55) = "91"
TestArray(56) = "92"
TestArray(57) = "93"
TestArray(58) = "94"
TestArray(59) = "96"
TestArray(60) = "97"
TestArray(61) = "98"
TestArray(62) = "99"
TestArray(63) = "101"
TestArray(64) = "102"
TestArray(65) = "103"
TestArray(66) = "106"
TestArray(67) = "107"
TestArray(68) = "108"
TestArray(69) = "109"
TestArray(70) = "111"
TestArray(71) = "112"
TestArray(72) = "113"
TestArray(73) = "115"
TestArray(74) = "116"
TestArray(75) = "117"
TestArray(76) = "118"
TestArray(77) = "121"
TestArray(78) = "122"
TestArray(79) = "125"
TestArray(80) = "129"
TestArray(81) = "130"
TestArray(82) = "131"
TestArray(83) = "132"
TestArray(84) = "133"
TestArray(85) = "134"
TestArray(86) = "137"
TestArray(87) = "138"
TestArray(88) = "142"
TestArray(89) = "143"
TestArray(90) = "144"
TestArray(91) = "145"
TestArray(92) = "146"
TestArray(93) = "147"
TestArray(94) = "155"
TestArray(95) = "156"
TestArray(96) = "157"
TestArray(97) = "158"
TestArray(98) = "159"
TestArray(99) = "161"
TestArray(100) = "162"
TestArray(101) = "169"
TestArray(102) = "170"
TestArray(103) = "173"
TestArray(104) = "174"
TestArray(105) = "175"
TestArray(106) = "176"
TestArray(107) = "180"
TestArray(108) = "181"
TestArray(109) = "182"
TestArray(110) = "183"
TestArray(111) = "184"
TestArray(112) = "185"
TestArray(113) = "186"
TestArray(114) = "187"
TestArray(115) = "188"
TestArray(116) = "189"
TestArray(117) = "190"
TestArray(118) = "192"
TestArray(119) = "193"
TestArray(120) = "194"
TestArray(121) = "195"
TestArray(122) = "196"
TestArray(123) = "201"
TestArray(124) = "202"
TestArray(125) = "205"
TestArray(126) = "206"
TestArray(127) = "207"
TestArray(128) = "208"
TestArray(129) = "211"
TestArray(130) = "212"
TestArray(131) = "214"
TestArray(132) = "215"
TestArray(133) = "217"
TestArray(134) = "218"
TestArray(135) = "220"
TestArray(136) = "221"
TestArray(137) = "222"
TestArray(138) = "223"
TestArray(139) = "224"
TestArray(140) = "225"
TestArray(141) = "226"
TestArray(142) = "228"
TestArray(143) = "229"
TestArray(144) = "230"
TestArray(145) = "235"
TestArray(146) = "236"
TestArray(147) = "237"
TestArray(148) = "240"
TestArray(149) = "241"
TestArray(150) = "242"
TestArray(151) = "244"
TestArray(152) = "249"
TestArray(153) = "250"
TestArray(154) = "251"
TestArray(155) = "255"
TestArray(156) = "256"
TestArray(157) = "259"
TestArray(158) = "260"
TestArray(159) = "262"
TestArray(160) = "263"
TestArray(161) = "264"
TestArray(162) = "265"
TestArray(163) = "266"
TestArray(164) = "267"
TestArray(165) = "269"
Dim oSheet As Variant, nSheet As Variant, oList As New Collection, nList As New Collection
oSheet = Range("A1:AC" & Cells(Rows.Count, 25).End(xlUp).Row).Value
For intArrayCounter = 0 To 165 Step 1
For lColumnLength = Cells(Rows.Count, 25).End(xlUp).Row To 1 Step -1
If InStr(oSheet(lColumnLength, 25), TestArray(intArrayCounter)) > 0 Then
' Add to list in order
nList.Add Range("a" & lColumnLength & ":AC" & lColumnLength).Value
Else
' Add to list in reverse order
oList.Add Range("a" & lColumnLength & ":AC" & lColumnLength).Value
End If
Next
Next
For i = oList.Count To 1 Step -1
For j = 1 To 29
oSheet(i, j) = oList(i)(1, j)
Next j
Next i
Range("A1:AC" & Cells(Rows.Count, 25).End(xlUp).Row) = oSheet
Range("A" & oList.Count + 1 & ":A" & Cells(Rows.Count, 25).End(xlUp).Row).EntireRow.Delete Shift:=xlUp
nSheet = Sheet10.Range("A1:AC" & nList.Count).Offset(Sheet10.Range("A" & Sheet10.UsedRange.Rows.Count).End(xlUp).Row).Value
For i = nList.Count To 1
For j = 1 To 29
nSheet(i, j) = nList(i)(1, j)
Next j
Next i
Sheet10.Range("A1:AC" & nList.Count).Offset(Sheet10.Range("A" & Sheet10.UsedRange.Rows.Count).End(xlUp).Row) = nSheet
Set nList = Nothing: Set oList = Nothing:Set oSheet = Nothing: Set nSheet = Nothing
End Sub

Resources