I have a 2D array that absolutely will not return the values I need. I start off with this array:
var userdata:Array = new Array(new Array(1000),new Array(4))
Then I try to set all values to 0, with this:
this.onLoad()
{
for (i = 0; i < 1000; i++)
{
for (j = 0; j < 4; j++)
{
userdata[i][j] = 0
trace(userdata[i][j])
}
}
}
This trace returns 8 0s and then a giant amount of "undefined"s. I can't figure out why this would be. I try something like this as well:
userdata[5][0] = 0
trace(userdata[5][0])
It still returns "undefined". Can anyone help with this?
To understand why you got only 8 "zeros" and many undefined values, let's start by your array declaration :
var userdata:Array = new Array(new Array(1000),new Array(4));
Here you should understand that you have created an array with only 2 cells ( that's why userdata[5][0] is undefined ) : the 1st cell is an array of 1000 elements and the 2nd one is an array of 4 elements, and that's why you can only set 8 items ( 2 x 4 ) : the 4th first items from the 1000 of the the 1st cell + the the 4th first items from the 4 of the 2nd cell.
Let's return to your question, you want create a multidimensional array of 1000 rows and 4 columns. To start, we create an array of 1000 rows (cells) :
var a:Array = [1000]; // you can write it : new Array(1000);
Then, we create 4 columns for every row, and set values like this :
var i:Number, j:Number;
for (i = 0; i < 1000; i++)
{
// create the 4 columns
a[i] = [4]; // you can write it : a[i] = new Array(4);
for (j = 0; j < 4; j++)
{
a[i][j] = 0;
}
}
Then we can verify our array :
trace(a[0][0]); // gives : 0
trace(a[255][2]); // gives : 0
trace(a[255][5]); // gives : undefined, because we have only 4 columns
trace(a[1500][0]); // gives : undefined, because we have only 1000 rows
Hope that can help.
Related
I'm trying to find a solution to this coding problem:
Create a for loop that will begin with a value of 5 and end with a value of 25. In each iteration, add the incrementing value to mathTotal. (HINT: the last value used INSIDE the loop should be 25)
But the way I can think of doing it returns with a final number for mathTotal of 26. I'm not sure how to manipulate the code to stop at 25 without actually doing the math to figure out what number to make the condition for the program to stop running.
This is what I have:
int mathTotal;
for(int i = 5; mathTotal <=25; i++) {
mathTotal = mathTotal + i;
}
I know this is a simple problem, but I'm learning how to code and don't want to move on without fully understanding something.
Thank you!
There are two major issues:
mathTotal is not initialized. You have to set an initial value.
int mathTotal = 0;
The upper border (the second parameter of the for loop) is defined as mathTotal <= 25 – rather than i <= 25 – which will be reached when i is 8.
for (int i = 5; i <=25; i++) {
mathTotal = mathTotal + i;
}
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(#"%d", i); //do something
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [yourArray count]; i++)
{
NSLog([myArrayOfStrings objectAtIndex:i]);
}
Your Doubt
int mathTotal = 0;
for (i = 5 = 0; i <=25 ; i++)
{
mathTotal = mathTotal + i;
}
I'm trying to query a user to select from 4 or more sets of radio buttons where there are 5 buttons in each set (Processing 2+). Where I'm having trouble is taking the array created by selecting from each set of buttons and getting it to fill columns in a matrix where the elements can be queried and the 2D array can be printed and ultimately written as csv or tab txt file.
import controlP5.*;
ControlP5 controlP5;
RadioButton c0;
RadioButton c1;
RadioButton c2;
RadioButton c3;
int cols = 5;
int rows = 4;
int[][] myArray = new int[cols][rows];
void setup() {
size(600,650);
controlP5 = new ControlP5(this);
c0 = controlP5.addRadioButton("ch0",60,60)
.setSize(20,20)
.setItemsPerRow(5)
.setSpacingColumn(50)
.addItem("c03", 1)
.addItem("c04", 2)
.addItem("c05", 3)
.addItem("c0AM", 4)
.addItem("c0AF", 5)
;
c1 = controlP5.addRadioButton("ch1",60,80)
.setSize(20,20)
.setItemsPerRow(5)
.setSpacingColumn(50)
.addItem("c13", 1)
.addItem("c14", 2)
.addItem("c15", 3)
.addItem("c1AM", 4)
.addItem("c1AF", 5)
;
c2 = controlP5.addRadioButton("ch2",60,100)
.setSize(20,20)
.setItemsPerRow(5)
.setSpacingColumn(50)
.addItem("c23", 1)
.addItem("c24", 2)
.addItem("c25", 3)
.addItem("c2AM", 4)
.addItem("c2AF", 5)
;
c3 = controlP5.addRadioButton("ch3",60,120)
.setSize(20,20)
.setItemsPerRow(5)
.setSpacingColumn(50)
.addItem("c33", 1)
.addItem("c34", 2)
.addItem("c35", 3)
.addItem("c3AM", 4)
.addItem("c3AF", 5)
;
}
void draw() {
background(0);
}
void controlEvent(ControlEvent theEvent) {
if(theEvent.isGroup() && theEvent.name().equals("ch0") || theEvent.name().equals("ch0") || theEvent.name().equals("ch2") || theEvent.name().equals("ch3")){
println(theEvent.name());
println(theEvent.arrayValue());
//float t=float(theEvent.arrayValue());
//int[][] = { {float getGroup(),float[] getArrayValue()}, {3,2,1,0}, {3,5,6,1}, {3,8,3,4} };
//int cols = 4;
//int rows = 5;
//int[][] myArray = new int[cols][rows];
// Two nested loops allow us to visit every spot in a 2D array.
// For every column I, visit every row J.
//for (int i = 0; i < cols; i++) {
// for (int j = 0; j < rows; j++) {
//myArray[i][j] = float(theEvent.arrayValue);
}
}
You were mixing different things together. Also you don't need to check whole array and store this information. Just update clicked button. Here is new version of your controlEvent
void controlEvent(ControlEvent theEvent) {
int cols = 4;
int rows = 5;
int[][] myArray = new int[cols][rows];
switch(theEvent.getId()){
case 0:
myArray[0][(int)theEvent.value()-1] = 1;
break;
case 1:
myArray[1][(int)theEvent.value()-1] = 1;
break;
case 2:
myArray[2][(int)theEvent.value()-1] = 1;
break;
case 3:
myArray[3][(int)theEvent.value()-1] = 1;
break;
}
println("==== " + theEvent.getId() + " ===");
println(myArray[theEvent.getId()]);
}
To do this simple switch you need to add ID parameter to all your radio buttons like this:
c3 = controlP5.addRadioButton("ch3", 60, 120)
.setId(3)
.setSize(20, 20)
...
I don't know how exactly you want use this array so my implementation use it as local variable so it will be deleted every time this event is called but this could be avoided by declaring array as global variable and then deleting only updated column.
While doing some work for my lab in university
I am creating this function where there is a for loop inside another one.
It is not important to know what the method is used for. I just can't figure out why the program doesn't enter the second for loop. This is the code:
public void worseFit(int[] array){
int tempPosition = -1;
int tempWeight = 101 ;
for (int x = 0; x < (array.length - 1); x++){
if (allCrates.getSize() < 1){
Crate crate = new Crate();
crate.addWeight(array[0]);
allCrates.add(crate);
} else{
for( int i = 1; i < (allCrates.getSize() - 1); i++ ){
Crate element = allCrates.getElement(i);
int weight = element.getTotalWeight();
if (weight < tempWeight){
tempWeight = weight;
tempPosition = i;
Crate crate = new Crate();
if (weight + tempWeight <= 100){
crate.addWeight(weight + tempWeight);
allCrates.setElement(i, crate);
} else {
crate.addWeight(weight);
allCrates.setElement(allCrates.getSize(), crate);
} // if
} // if
} // for
} // if
} // for
} // worseFit
Once the program enters the else part of the code it goes straight
away back to the beginning of the first for loop.
Would anyone know how to solve this problem?
There seems to be some discrepancies with the expected values of allCrates.getSize().
If allCrates.getSize() returns 2, it will go to the second for loop, but not run it, as i < allCrates.getSize() - 1 will result in false
You might want to use <= instead of <
Initialize the variable i in your second loop to 0 instead of 1. Because if your getSize() returns 1 the it will not enter the if part and after entering the else part the for loop condition will evaluate to false and hence your for loop will not be executed.
I've been looking for some simple coding challenges recently, and discovered about Pascal's triangle (here), and I've tried to generate one myself in C/Objective-C. For those that don't know what it is, that link explains it pretty well.
I'm starting to get oddness after the fourth row, and I just can't figure out why.
My output for 5 iterations currently looks like this:
1
1 1
1 2 1
1 3 3 1
4 6 3 1
It should look like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Here is my code so far. The first loop is just a reset loop (setting all the values to 0). The actual logic happens mostly in the second loop. The third loop is where the values are concatenated and formatted in a string.
I've commented this code much more than I would for myself just to aid readability.
int iterations, i, b, mid, chars, temp;
NSLog(#"Please enter the number of itereations");
scanf("%i",&iterations); // take users input and store it in iterations
// calculate where the first 1 should go.
if (iterations % 2 == 0) mid = (iterations)/2;
else mid = (iterations+1)/2;
chars = iterations*2;
int solutions[iterations][chars];
// reset loop
for (i = 0; i<iterations; i++) {
for (b = 0; b<chars; b++) {
solutions[i][b] = 0;
}
}
solutions[0][mid] = 1; // place the initial 1 in first row
for (int row = 1; row<iterations; row++) {
for (int chi = 0; chi<chars; chi++) {
temp = 0;
if (chi > 0) {
temp += solutions[row-1][chi-1]; // add the one diagonally left
}
if (chi < iterations) {
temp += solutions[row-1][chi+1]; // add the one diagonally right
}
solutions[row][chi] = temp; // set the value
}
}
// printing below...
NSMutableString *result = [[NSMutableString alloc] initWithString:#"\n"];
NSMutableString *rowtmp;
for (i = 0; i<iterations; i++) {
rowtmp = [NSMutableString stringWithString:#""];
for (b = 0; b<chars; b++) {
if (solutions[i][b] != 0) [rowtmp appendFormat:#"%i",solutions[i][b]];
else [rowtmp appendString:#" "]; // replace any 0s with spaces.
}
[result appendFormat:#"%#\n",rowtmp];
}
NSLog(#"%#",result);
[result release];
I have a feeling the problem may be to do with the offset, but I have no idea how to fix it. If anyone can spot where my code is going wrong, that would be great.
It appears (from a brief look) that the original midpoint calculation is incorrect. I think it should simply be:
mid = iterations - 1;
In the example of 5 iterations, the midpoint needs to be at array position 4. Each iteration "moves" one more position to the left. The 2nd iteration (2nd row) would then place a 1 at positions 3 and 5. The 3rd iteration at 2 and 6. The 4th at 1 and 7. And the 5th and last iteration would fill in the 1s at 0 and 8.
Also, the second if statement for the temp addition should be as follows otherwise it reads past the end of the array bounds:
if (chi < iterations - 1) {
I'm really new to programming in Objective-C, my background is in labview which is a graphical programming language, I've worked with Visual Basic some and HTML/CSS a fair amount as well. I'm trying to figure out the logic to create an array of data for the pattern below. I need the pattern later to extract data from another 2 arrays in a specific order.
I can do it by referencing a = 1, b = 2, c = 3 etc and then creating the array with a, b, c but I want to use a loop so that I don't have 8 references above the array. These references will be used to generate another generation of data so unless I can get help figuring out the logic I'll actually end up with 72 references above the array.
// This is the first one which gives the pattern
0 0 0 0 (etc) // 1 1 1 1 // 2 2 2 2
NSMutableArray * expSecondRef_one = [NSMutableArray array];
int a1 = 0;
while (a1 < 9) {
int a2 = 0;
while (a2 < 8) {
NSNumber * a3 = [NSNumber numberWithInt:a1];
[expSecondRef_one addObject:a3];
a2++;
}
a1++;
}
// This is the second one which I'm stumbling over, I am looking for the pattern
1 2 3 4 5 6 7 8 //
0 2 3 4 5 6 7 8 //
0 1 3 4 5 6 7 8 //
0 1 2 4 5 6 7 8 // etc to -> // 0 1 2 3 4 5 6 7
If you run it in a line every 9th number is -1 but I don't know how to do that over a pattern of 8.
Thanks in advance!
Graham
I think you're looking for something like :
for(int i = 0; i < 9; ++i) {
for (int j = 0; j < 8; ++j) {
if (j < i) {
//Insert j into array
}
else {
//Insert j + 1 into array
}
}
}
I left out the code to actually insert the numbers into the array.
I'm not totally clear on how you're using this array, but if this is just an order of indexes to access data from another group of arrays, you may be able to skip the first set of arrays and just use this loop to access your data later.
--edit--
If I'm understanding you correctly, you want to compare each index in an array of 9 numbers to every other index, then store the results in an array. If that's the case, you could just do something like this:
for (int i = 0; i < 9; ++i) {
for (j = 0; j < 9; ++j) {
if (j != i) {
//Compare object at array index i with object at array index j
}
}
}
That loop works perfectly on a meta level for what I was trying to do. The array's that I was creating were to reference the original array (9 cells) With the algorithm you made I eliminated those and can reference the original array exactly as I wanted.
Thank you very much.
Cheers
Graham
NSMutableArray *a=[[NSMutableArray alloc]init];
for(int i=0;i<8;i++){
NSMutableString *s=[[NSMutableString alloc]init];
for(int j=0;j<8;j++){
if(i!=j){
[s appendString:[NSString stringWithFormat:#"%i",j]];
}
}
[a addObject:s];
}
NSLog(#"%#",a);
}
output:
1234567,
0234567,
0134567,
0124567,
0123567,
0123467,
0123457,
0123456