What's wrong with my pascal's triangle? - objective-c

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

Related

I am currently learning Javascript by grasshopper. And i am stucked in for loop

Good im enter image descrre
Um can you see that example explanation?
"They said i-1 inside loop should start on the 2nd character" but i think it isn't am i right??? It should start first character
I confuse the first one because
Every time the loop start 1st character, not 2nd character.
It's important to note the array is 0-based (in JavaScript).
Let's use "jump" as the string in an array:
0 1 2 3
j u m p
The first loop will begin with "u" because i = 1.
egStr = "jump";
for (let i=1; i<egStr.length; i++) {
let neighbor = i - 1; // i - 1 = 0
console.log(egStr[i]); // returns 'u' first
console.log(egStr[neighbor]); // returns 'j' first
}
The second loop will begin with "j" because i = 0.
egStr = "jump";
for (let i=0; i<egStr.length - 1; i++) {
let neighbor = i + 1; // i + 1 = 1
console.log(egStr[i]); // returns 'j' first
console.log(egStr[neighbor]); // returns 'u' first
}

Looping over an NSmutatable Array starting from a certain index

I have a quick question how can I loop over an NSMutable array starting from a certain index.
For Example I have these double loops I want k to start from the same index as l.
for (Line *l in L)
{
for (Line *k in L)
{
............
}
}
To elaborate further, lets say L has 10 object so l start from 0-10 and k from 0 -10. What I want is if l is equal 1 k should start from 1-10 rather than 0 - 10 and when l is equal 2 k should start from 2- 10 rather than 0. Any help is Appreciated
Objective-C is an extension of C, lookup the C for loop and you'll have your answer. HTH
Addendum
I was going to let you benefit from the learning experience of looking up the C for yourself, however at the time of writing all other answers since added give the code but it is not complete, so here is what you need to produce the l and k values in the order you wish:
for(NSInteger lIndex = 0; lIndex < L.count; lIndex++)
{
Line *l = L[lIndex]; // index into your array to get the element
for(NSInteger kIndex = lIndex; kIndex < L.count; kIndex++)
{
Line *k = L[kIndex];
// process your l and k
}
}
As you can see the for has three sub-parts which are the initialisation, condition, and increment. The initialisation is performed first, then the condition to determine whether to execute the for body, and the increment is executed after the statements in the body and before the condition is tested to determine if another iteration should be performed. A for loop is roughly (there are some differences that are unimportant here) to the while loop:
initialisation;
while(condition)
{
body statements;
increment;
}
You simply need to modify for-statement.
NSInteger indexYouNeed;
NSInteger iterationCount;
for (int i = indexYouNeed; i < iterationCount; i++) {
/* Your code here */
}
You may find this link helpfulll.
You have to use an indexed (ordinary) for loop instead of fast enumeration (for-in):
int l;
for (l=startValue; l<=endValue; l++)
{
int i;
for (int i=l; i<=endValue; i++)
{
…
}
}

Cyclomatic Complexity edges

So I'm trying to figure out if that blue line is in the right place, I know that I should have 9 edges but not sure if it's correct.
The code
public int getResult(int p1, int p2) {
int result = 0; // 1
if (p1 == 0) { // 2
result += 1; //3
} else {
result += 2; //4
}
if (p2 == 0) { //5
result += 3; //6
} else {
result += 4; //7
}
return result; //8 exit node
}
so 8 nodes and it should have 9 edges, right? Did I do the right thing?
Yes, the blue line is placed correctly because after the 3rd line, your program is going to jump to the 5th line.
The easiest way to compute cyclomatic complexity without drawing any flow diagram is as follows:
Count all the loops in the program for, while, do-while, if. Assign a value of 1 to each loop. Else should not be counted here.
Assign a value of 1 to each switch case. Default case should not be counted here.
Cyclomatic complexity = Total number of loops + 1
In your program, there are 2 if loops, so the cyclomatic complexity would be 3(2+1)
You can cross-check it with the standard formulae available as well which are as below:
C = E-N+2 (9-8+2=3)
OR
C = Number of closed regions + 1 (2+1=3)
According to wikipedia:
M = E − N + 2P,
where
E = the number of edges of the graph.
N = the number of nodes of the graph.
P = the number of connected components.
so:
9 - 8 + 2*1 = 3

Checking a series of numbers for consistency

I maintain an array of integers. It is important that at all times the integers in this array are in sequence from 0. For example, if there are 5 integers in the array, their values must be 0, 1, 2, 3, 4 (though in any order).
I would like to design a simple, efficient method that checks this. It will return true if the array contains all positive integers in sequence from 0 to array.count - 1.
I would love to hear some different ideas for handling this!
Or, given the integers [0..N-1] if you raise 2 to the power of each in turn the sum will be -1+2^N. This is not a property that any other set of N integers has.
I offer this as an alternative, making no claim about suitability, performance or efficiency, and I recognise that there will be problems as N gets large.
Basically what you want to test is if your array is a permutation of [0...n-1]. There are easy algorithms for this that are O(n) in both time and memory. See for example this PDF file.
Sometimes I use a very simple check that is O(n) in time and O(1) in memory. It can in theory return false positives, but it is a good way to find most mistakes. It is based on the following facts:
0 + 1 + 2 + ... + n-1 == n * (n-1) / 2
0 + 1² + 2² + ... + (n-1)² == n * (n-1) * (2 * n - 1) / 6
I don't know objective-c, but the code would look like this in C#:
bool IsPermutation(int[] array)
{
long length = array.Length;
long total1 = 0;
long total2 = 0;
for (int i = 0; i<length; i++)
{
total1 += array[i];
total2 += (long)array[i] * array[i];
}
return
2 * total1 == length * (length - 1) &&
6 * total2 == length * (length - 1) * (2 * length - 1);
}
This isn't too different from your itemsSequencedCorrectlyInSet: method, but it uses a mutable index set which will be faster than doing -[NSSet containsObject:]. Probably not an issue until you've got thousands of table rows. Anyway, the key insight here is that the Pigeonhole Principle says if you've got N integers less than N and none is duplicated, then you have each of 0...N-1 exactly once.
-(BOOL)listIsValid:(NSArray*)list
{
NSMutableIndexSet* seen = [NSMutableIndexSet indexSet];
for ( NSNumber* number in list )
{
NSUInteger n = [number unsignedIntegerValue];
if ( n >= [array count] || [seen containsIndex:n] )
return NO;
[seen addIndex:n];
}
return YES;
}
Here's my current implementation (testSet is a set of NSNumbers) -
- (BOOL)itemsSequencedCorrectlyInSet:(NSSet *)testSet{
for (NSInteger i = 0; i < testSet.count; i++) {
if (![testSet containsObject:[NSNumber numberWithInteger:i]]) {
return NO;
}
}
return YES;
}

Objective-C loop logic

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