iPhone SDK 2d int array - iphone

I am trying to make a 2d array in objective-c and I don't really want to use NSArray because I'm using int and the code would annoying: {[array objectAtIndex:x] objectAtIndex:y], not to mention I would have to convert the numbers back from NSNumber... Seems like a lot of extra work.
Can't I do the following?
// .h file
int aTiles[10][2];
// .m file
aTiles = {
{ 0, 0}, // 0
{ 0, 1}, // 1
{ 1, 5}, // 2
{ 0, 0}, // 3
{ 0, 0}, // 4
{ 0, 0}, // 5
};
it works together in the same line (int a[x][x] = {...};), but I need the array to be public so I can access it from any function.
The second line says expecting semicolon.
Thanks

Looks like you have an extra comma near //5
Do you need to declare a type for aTiles?
int aTiles = ...

I got slightly different errors when I tried your original code, but this worked:
// .h file
extern int aTiles[10][2];
// .m file
int aTiles[10][2] = {
{ 0, 0}, // 0
{ 0, 1}, // 1
{ 1, 5}, // 2
{ 0, 0}, // 3
{ 0, 0}, // 4
{ 0, 0}, // 5
};

Since this has also been tagged C++, you can use an ivar:
std::vector<std::vector<int> > tiles;
Then you just resize and set initial element values in your object's initializer.
Otherwise, is this a global or an ivar? should it be const or mutable?

How about this awesomeness... (not really)
// .h
int aTiles[10][2];
// .m
int a[10][2] = {
{ 0, 0}, // 0
{ 0, 1}, // 1
{ 1, 5}, // 2
{ 0, 0}, // 3
{ 0, 0}, // 4
{ 0, 0}, // 5
};
for (int r = 0; r <= 5; r++) {
for (int c = 0; c < 2; c++) {
aTiles[r][c] = a[r][c];
}
}
definitely a work around, but... cant figure out any other way. If anyone figures out the correct way, please let me know :P

Related

Swift: Index out of range (for)

I am trying to do challange, but i stumbled on error, that my index is out of range. I do not know what can be the problem.
I tried anything that came to my mind. Thanks for any help.
func countApplesAndOranges(s: Int, t: Int, a: Int, b: Int, apples: [Int], oranges: [Int]) -> Void {
var positionApples : [Int] = apples
var positionOranges : [Int] = oranges
for i in positionApples {
positionApples[i] += a //This line
}
for i in positionOranges {
positionOranges[i] += b //This line
}
var hitApples : Int = 0
var hitOranges : Int = 0
for i in positionApples {
if i >= s && i <= t {
hitApples += 1
}
}
for i in positionOranges {
if i >= s && i <= t {
hitOranges += 1
}
}
print(hitApples)
print(hitOranges)
}
Array apples and oranges should copy to positionApples and positionOranges. Then to each item in the array, value should be added, but that just throws runtime error.
Assuming the value of apples is [2, 4, 6, 8] then the code
for i in positionApples {
print(i)
}
prints the elements 2, 4, 6, 8 and not the indices 0, 1, 2, 3 so in the second iteration of
for i in positionApples {
positionApples[i] += a //This line
}
i is 4 but the end index is actually 3 and the code will 🧨.
If you need the loop index enumerate the array
for (index, element) in positionApples.enumerated() {
print(index, element)
}
Let say, we call this method as shown below.
countApplesAndOranges(s: 3, t: 3, a: 3, b: 3, apples: [1,2,3], oranges: [4,5,6])
In the below code, possible value of i in the for loop is 1,2,3. But the actual indices of positionApples can be 0,1,2 only. When it tries to access array of index=3, it throws
"Fatal error: Index out of range"
for i in positionApples {
positionApples[i] += a //This line
}
I think this is what you wanted to do.
for i in 0 ..< positionApples.count {
positionApples[i] += a
}
This way, you can modify each element in the array.

How can I replace mutex with proper fucntion in using Vivado HLS?

Sorry in advance because I am a beginner in Vivado HLS.
In my code in the following, I wanna Synthesis it, but Vivado tells me you cannot use the mutex and whatever dependent and gives me following errors.
ERROR: [SYNCHK 200-11] Global Variable 'readyQMutex' has an unsynthesizable struct type '%union.pthread_mutex_t.2.12.22 = type { %struct.__pthread_mu...' (a member pointer to struct itself).
ERROR: [SYNCHK 200-71] ../fpga_top.c:221: function 'pthread_mutex_lock' has no function body.
ERROR: [SYNCHK 200-71] ../fpga_top.c:225: function 'pthread_cond_wait' has no function body.
ERROR: [SYNCHK 200-71] ../fpga_top.c:237: function 'pthread_cond_signal' has no function body.
ERROR: [SYNCHK 200-71] ../fpga_top.c:238: function 'pthread_mutex_unlock' has no function body.
ERROR: [SYNCHK 200-11] ../fpga_top.c:18: Constant 'workerInfos' has an unsynthesizable type '[4 x %struct.threadInfo.6.16.26]*' (possible cause(s): structure variable cannot be decomposed due to (1) unsupported type conversion; (2) memory copy operation; (3) function pointer used in struct; (4) unsupported pointer comparison).
ERROR: [SYNCHK 200-61] ../fpga_top.c:75: unsupported memory access on variable 'child_task_ID' which is (or contains) an array with unknown size at compile time.
ERROR: [SYNCHK 200-71] ../fpga_top.c:77: function 'pthread_mutex_init' has no function body.
INFO: [SYNCHK 200-10] 8 error(s), 0 warning(s).
I found I should write the related code to handle it by myself, if so, how and what I should write?!
#include <stdbool.h>
#include "fpga_top.h"
int outputIndex = 0;
double core_speed[CORE_MAX] = {1.0, 1.0, 1.0, 1.0};
double outputTable[WORKLOAD_MAX*TASK_COUNT_MAX][EXCEL_Column_Size];
int readyQueueHead = 0;
int readyQueueRear = 0;
int readyQueueSize = 0;
char canContinue_ = 1;
int wlCounter = 0;
bool flag = 1;
// Add Task to assignedQueue
void addToAssignedQueue(int task_ID, int workload_ID, int q)
{
pthread_mutex_lock(&(workerInfos[q].workerMutex));
while( workerInfos[q].assignedQSize>=DEEP)
{
pthread_cond_wait(&(workerInfos[q].workerWaitHandle_Add), &(workerInfos[q].workerMutex));
}
int i = workerInfos[q].assignedQRear;
workerInfos[q].assignedQueue[i].task_ID = task_ID;
workerInfos[q].assignedQueue[i].workload_ID = workload_ID;
workerInfos[q].assignedQRear = (workerInfos[q].assignedQRear + 1) % DEEP;
workerInfos[q].assignedQSize++;
// A signal to a worker waiting to read from this queue
pthread_cond_signal(&(workerInfos[q].workerWaitHandle));
pthread_mutex_unlock(&(workerInfos[q].workerMutex));
}
// Read from assignedQueue
struct workItem readFromAssignedQueue(int q)
{
struct threadInfo *workerInfo_ = &workerInfos[q];
pthread_mutex_lock(&(workerInfo_->workerMutex));
struct workItem tas_;
// Initialize the output values (which may not be necessary now)
tas_.task_ID = -1;
tas_.workload_ID = -1;
if(workerInfo_->assignedQSize <= 0)
{
struct timespec time_to_wait = {10, 0}; //10 sec wait
pthread_cond_timedwait(&(workerInfo_->workerWaitHandle), &(workerInfo_->workerMutex), &time_to_wait);
}
if(workerInfo_->assignedQSize >0)
{
// Reading the assignedQueue if data is available
tas_ = workerInfo_->assignedQueue[workerInfo_->assignedQHead];
// Move forward the queue head index rotationally
workerInfos[q].assignedQHead = (workerInfos[q].assignedQHead + 1) % DEEP;
// Decreasing the count number of queue elements
workerInfos[q].assignedQSize--;
pthread_cond_signal(&(workerInfos[q].workerWaitHandle_Add));
}
pthread_mutex_unlock(&(workerInfo_->workerMutex));
return tas_;
}
// Add Definition of Task to DAG
void addTask(int task_ID, int parentCount, int child_task_ID[], int childCount, int processingTime)
{
struct Task_Package_Profile *p_task_ = &(taskArray[task_ID]);
p_task_->parentCount = parentCount;
p_task_->childCount = childCount;
p_task_->processingTime = processingTime;
// Initialize the parentReady variable for all workloads
for (int i = 0; i < WORKLOAD_MAX;i++) {p_task_->parentReady[i] = 0;}
// Copy the child's index
for (int i = 0; i < childCount; i++) {p_task_->child_task_ID[i] = child_task_ID[i];}
// Make parentReady mutex
pthread_mutex_init(&(p_task_->parentReadyMutex), NULL);
}
// DAG Definition
void initDag()
{
int ch0[] = { 1, 2, 3, 4}; addTask( 0, 0, ch0, 4, 10000);
int ch1[] = { 5, 6, 7, 8}; addTask( 1, 1, ch1, 4, 20000);
int ch2[] = { 5, 6, 7, 8}; addTask( 2, 1, ch2, 4, 20000);
int ch3[] = { 5, 6, 7, 8}; addTask( 3, 1, ch3, 4, 20000);
int ch4[] = { 5, 6, 7, 8}; addTask( 4, 1, ch4, 4, 20000);
int ch5[] = { 9, 10}; addTask( 5, 4, ch5, 2, 30000);
int ch6[] = { 9, 10}; addTask( 6, 4, ch6, 2, 30000);
int ch7[] = { 9, 10}; addTask( 7, 4, ch7, 2, 30000);
int ch8[] = { 9, 10}; addTask( 8, 4, ch8, 2, 30000);
int ch9[] = { 11, 12}; addTask( 9, 4, ch9, 2, 40000);
int ch10[] = { 11, 12}; addTask( 10, 4, ch10, 2, 40000);
int ch11[] = {}; addTask( 11, 2, ch11, 0, 50000);
int ch12[] = {}; addTask( 12, 2, ch12, 0, 50000);
addToReadyQueue(0, 0); // Root task, addToReadyQueue(int task_ID, int workload_ID)
readFromReadyQueue();
//allocateTask(0, 0, 0); // allocateTask(int task_ID, int workload_ID, int core_ID)
}
// Add Task to the end of the readyQueue
void addToReadyQueue(int task_ID, int workload_ID)
{
pthread_mutex_lock(&readyQMutex);
while(readyQueueSize >= READY_LOOP_DEEP)
{
// Waiting for the queue to be empty if there is no space
int res = pthread_cond_wait( &readyQWaitHandleAdd, &readyQMutex);
}
#ifdef PRINT_ReadyQ
printf("Task #%d (workload #%d) added to readyQueue %d:%d.\n", task_ID, workload_ID,readyQueueRear, readyQueueSize);
#endif
readyQueue[readyQueueRear].task_ID = task_ID;
readyQueue[readyQueueRear].workload_ID = workload_ID;
// Move forward the queue rear index in rotation
readyQueueRear = (readyQueueRear + 1) % READY_LOOP_DEEP;
// Increasing the number of the queue elements
readyQueueSize++;
// The signal is given to workers waiting to read from the queue
pthread_cond_signal(&readyQWaitHandleRead);
pthread_mutex_unlock(&readyQMutex);
}
// Read from the beginning of the readyQueue
struct workItem readFromReadyQueue()
{
struct workItem witem;
witem.task_ID = -1;
witem.workload_ID = -1;
pthread_mutex_lock(&readyQMutex);
// Waiting to queue if empty
while(readyQueueSize <= 0)
{
pthread_cond_wait( &readyQWaitHandleRead, &readyQMutex);
}
// Picking up from queue head
witem = readyQueue[readyQueueHead];
// Move forward the queue head index in rotation
readyQueueHead = (readyQueueHead + 1) % READY_LOOP_DEEP;
// Reduce the number of queue elements
readyQueueSize--;
#ifdef PRINT_ReadyQ
printf("Task #%d (workload #%d) removed to readyQueue. %d : %d\n", witem.task_ID , witem.workload_ID, readyQueueHead, readyQueueSize);
#endif
// The signal is given to workers who are waiting for the queue to be empty
pthread_cond_signal(&readyQWaitHandleAdd);
pthread_mutex_unlock(&readyQMutex);
return witem;
}
// Check if the reaadyQueue is empty with the corresponding mutex
int isReadyQueueEmpty()
{
int res = 0;
pthread_mutex_lock(&readyQMutex);
res = (readyQueueSize == 0);
pthread_mutex_unlock(&readyQMutex);
return res;
}
// Assigning Task to the Worker (Cores)
struct outputsFromFPGA allocateTask(int task_ID, int workload_ID, int core_ID)
{
if (flag == 1)
{
initDag();
flag = 0;
}
#ifdef PRINT_AllocateTask
printf("Task #%d (workload #%d) assigned to Core #%d;\n", task_ID, workload_ID, core_ID);
#endif
addToAssignedQueue( task_ID, workload_ID, core_ID);
struct outputsFromFPGA FPGAOutputs;
FPGAOutputs.task_ID = task_ID;
FPGAOutputs.workload_ID = workload_ID;
FPGAOutputs.core_ID = core_ID;
}
// Ending each task and inform the children
void taskDone(int task_ID, int workload_ID, int core_ID)
{
struct Task_Package_Profile task_ = taskArray[task_ID];
#ifdef PRINT_TaskDone
printf("taskDone: Task #%d (workload #%d);\n", task_ID, workload_ID);
#endif
// Increase the child's parentReady variable and send the children to the ready queue if all parents are finished
struct Task_Package_Profile *p_task_ = &(taskArray[task_ID]);
for(int i = 0; i < p_task_->childCount; i++)
{
struct Task_Package_Profile *p_childTsk = &(taskArray[p_task_->child_task_ID[i]]);
int nbParentReady = 0;
// Increase the parentReady variable
pthread_mutex_lock(&(p_childTsk->parentReadyMutex));
nbParentReady = ++(p_childTsk->parentReady[workload_ID]);
pthread_mutex_unlock(&(p_childTsk->parentReadyMutex));
// Send the child to the ready queue if all parents are finished
if (nbParentReady == p_childTsk->parentCount)
addToReadyQueue(p_task_->child_task_ID[i], workload_ID);
}
pthread_mutex_lock(&assignQSizeCheckMutex);
// Find the most empty assignedQueue and assign ready tasks as much as possible
while(!isReadyQueueEmpty())
{ // Finds the best assignedQueue
int minQueue = 0;
int minSize = workerInfos[0].assignedQSize;
for (int i = 1; i < CORE_MAX; i++)
{
if(workerInfos[i].assignedQSize < minSize)
{
minSize = workerInfos[i].assignedQSize;
minQueue = i;
}
}
// The most empty queue should be smaller than Deep so that it can be added to the queue
if(minSize < DEEP)
{
struct workItem witem = readFromReadyQueue();
struct outputsFromFPGA FPGAOutputs = allocateTask(witem.task_ID, witem.workload_ID, minQueue);
}
else
{
break; // All assignedQueue are full
}
}
pthread_mutex_unlock(&assignQSizeCheckMutex);
}
// Check the end of the program that has all the tests done
void finishCheck()
{
if (wlCounter != WORKLOAD_MAX) return;
for(int i = 0; i < CORE_MAX; i++)
{
if (workerInfos[i].assignedQSize > 0) return;
if (workerInfos[i].coreState > 0) return;
}
if (!isReadyQueueEmpty()) return;
canContinue_ = 0;
for(int i = 0; i < CORE_MAX; i++)
pthread_cond_signal(&(workerInfos[i].workerWaitHandle));
}
Thread synchronization can be done in HLS as shown in this paper for example, but it is not supported in Vivado HLS yet.
That being said, it does not mean that it is impossible to implement your application on hardware. One approach is to implement every thread as a separate hardware kernel. Shared data can be put in another kernel, which ensures that accesses to the data are synchronized the way that you want. The kernels can communicate with the shared object via streaming interfaces. You can implement function parameters as streaming interfaces with hls::stream. After implementing each of the kernels as an IP module, you can connect them via FIFOs generated with FIFO generator in a Vivado block design.
You could make for example a control stream from each processing kernel to the shared object that allow the kernels to send a request to access the shared object. In the shared object, you use non-blocking reads from the streams to see whether any of them wants exclusive access. Then you take write or read requests only from the control stream from the kernel that was granted exclusive access. The data associated with the reads and writes can be communicated via dedicated data streams between the kernels and shared object. When a kernel is done using the shared object, it can send a release command, and the shared object starts looking again for requests on all control streams. It takes a bit of labor, but it is a feasible solution...

Geting object from array of array and it's array number

I'm using Swift 2.3 and I have the following type array of arrays of my custom object called Player
`var playing = [[obj-one, obj-two],[obj-three, obj-four]]`
How would I use a for-in loop or something else so I can get the array index and the object?
I have the following:
for (index, p) in playing { -- Expression type [[Player]] is ambigious
I've also tried
for in (index, p: Player) in playing { -- same result.
and
for in (index, p) in playing as! Player { -- doesn't conform to squence type
I want to just be able to print out which array the object belongs to and then work with that current object
Use enumerated() to pair up an index and an element, like this:
let a = [["hello", "world"], ["quick", "brown", "fox"]]
for outer in a.enumerated() {
for inner in outer.element.enumerated() {
print("array[\(outer.offset)][\(inner.offset)] = \(inner.element)")
}
}
This produces the following output:
array[0][0] = hello
array[0][1] = world
array[1][0] = quick
array[1][1] = brown
array[1][2] = fox
Functional approach:
let items = [["0, 0", "0, 1"], ["1, 0", "1, 1", "1, 2"]]
items.enumerated().forEach { (firstDimIndex, firstDimItem) in
firstDimItem.enumerated().forEach({ (secondDimIndex, secondDimItem) in
print("item: \(secondDimItem), is At Index: [\(firstDimIndex), \(secondDimIndex)]")
})
}
prints:
item: 0, 0, is At Index: [0, 0]
item: 0, 1, is At Index: [0, 1]
item: 1, 0, is At Index: [1, 0]
item: 1, 1, is At Index: [1, 1]
item: 1, 2, is At Index: [1, 2]
I wouldn't use a for loop, I would do something like this:
import Foundation
var playing = [["one", "two"], ["three", "four"]]
if let index = playing.index(where: { $0.contains("two") }) {
print(index)
} else {
print("Not found")
}
This prints:
0
Or to get the entire subarray containing what you want:
if let subarray = playing.first(where: { $0.contains("three") }) {
print(subarray)
} else {
print("Not found")
}
Prints:
["three", "four"]

Find Difference between the two sequence of points value in AmCharts?

I am using the AmCharts. I need to display value in the balloon text , that value is not a value field.
For example : X axis Value 0 , Y axis 1, (0,1) is 2 ; (1,2) is 5.
I need to display the Difference between the values (0,1) and (1,2) - that means "3" as Balloon in the point (1,2). Any ideas ?
Yes, the chart on your screenshot is possible to implement.
At first, add additional fields to your chart data, for example, labelGraph1, labelGraph2. Then you can use the labelText property of the AmCharts.AmGraph object.
var chartData = [{
title: "Apples",
value1: 24,
value2: 28,
labelGraph1: null,
labelGraph2: null
}, {
title: "Bananas",
value1: 27,
value2: 31,
labelGraph1: null,
labelGraph2: null
}, {
title: "Cherries",
value1: 27,
value2: 39,
labelGraph1: null,
labelGraph2: null
}];
for(var i = 0; i < chartData.length; i++) {
chartData[i].labelGraph1 = chartData[i].value1;
chartData[i].labelGraph2 = chartData[i].value2 - chartData[i].value1;
}
var chart;
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "title";
// GRAPHS
var graph1 = new AmCharts.AmGraph();
graph1.valueField = "value1";
graph1.type = "line";
graph1.fillAlphas = 0.6;
graph1.labelText = "[[labelGraph1]]";
chart.addGraph(graph1);
var graph2 = new AmCharts.AmGraph();
graph2.valueField = "value2";
graph2.type = "line";
graph2.fillAlphas = 0.6;
graph2.labelText = "[[labelGraph2]]";
chart.addGraph(graph2);
// WRITE
chart.write("chartdiv")
});
The only one difficulty is to calculate values of the displayed fields.
I did it so, and you should change that function according to your data:
for(var i = 0; i < chartData.length; i++) {
chartData[i].labelGraph1 = chartData[i].value1;
chartData[i].labelGraph2 = chartData[i].value2 - chartData[i].value1;
}

How can I specify an array at runtime?

What I'm Trying To Do
Basically, I've got several possible arrays that I define with macros:
#define ARRAY_ONE {0, 2, 7, 8}
#define ARRAY_TWO {3, 6, 9, 2}
#define ARRAY_THREE {3, 6, 4, 5}
//etc...
At runtime, I have a C-Array that gets used in a lot of places in a certain class. I want this array to use one of the #define values, i.e:
int components[4];
if (caseOne)
{
components = ARRAY_ONE;
}
else if (caseTwo)
{
components = ARRAY_TWO;
}
else if (caseThree)
{
//etc...
}
-
The Problem
However, the above code does not work. Instead, I get a weird error
Expected expression before '[' token
Would anyone mind explaining what's going on, and how I could achieve what I'm attempting to? Any help would be much appreciated - Thanks!
I don't think that C arrays can be initialized using the curly-brace syntax after they've been declared. You can only do that when initializing them while declaring them.
Try adjusting the previously posted answer with:
const int ARRAY_ONE[] = {0, 2, 7, 8};
const int ARRAY_TWO[] = {3, 6, 9, 2};
const int ARRAY_THREE[] = {3, 6, 4, 5};
int *components;
if (case1) {
components = ARRAY_ONE;
} else if (case2) {
components = ARRAY_TWO;
} else if (case3) {
components = ARRAY_THREE;
}
I can't really work out what the error is. I suspect it might be coming from some code you haven't posted. Does it say the error is on the int components[4]; line?
Would this do? I uses constants instead of defines.
const int ARRAY_ONE[] = {0, 2, 7, 8};
const int ARRAY_TWO[] = {3, 6, 9, 2};
const int ARRAY_THREE[] = {3, 6, 4, 5};
int* components = ARRAY_ONE;
int whatever = components[2];
try this:
int ARRAY_ONE[] = {0,2,7,8};
int ARRAY_TWO [] = {3,6,9,2};
int ARRAY_THREE[] = {3,6,4,5};
int components[4];
int count =sizeof(components)/4 //this will get array length, or you can just put array lenght ;
if (case1)
for (int i =0; i< count; i++)
components[i] = ARRAY_ONE[i];
else if (case2)
for (int i =0; i< count; i++)
components[i] = ARRAY_TWO[i];