這兩天略廢,前兩天有哥們兒,讓我打印一個棱形,手寫真的費勁啊。
於是乎,我用了幾乎一下午,用代碼畫了出來。
先曬一下,結果
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
- (void)draw
{
NSInteger maxStarCount = 10;
NSInteger width = maxStarCount*2 -1;
NSInteger height = width;
NSInteger middleIndex = maxStarCount - 1;
NSMutableArray *currentRowStarIndexArray = [NSMutableArrayarray];
NSInteger currentRowStarCount ;
//上半個棱形
for (NSInteger row =0; row < maxStarCount; row ++) {
currentRowStarCount = row + 1;
currentRowStarIndexArray = [self currentRowStarIndexArray:currentRowStarCount middleIndex:middleIndexrow:row];
[self printCurrentRowStarIndexArray:currentRowStarIndexArraywidth:width row:row];
printf("\n");
}
//下半個棱形
for (NSInteger row = maxStarCount; row < height; row ++) {
currentRowStarCount = maxStarCount - (row - maxStarCount + 1);
currentRowStarIndexArray = [self currentRowStarIndexArray:currentRowStarCount middleIndex:middleIndexrow:row];
[self printCurrentRowStarIndexArray:currentRowStarIndexArraywidth:width row:row];
printf("\n");
}
}
- (NSMutableArray *)currentRowStarIndexArray:(NSInteger)currentRowStarCount middleIndex:(NSInteger)middleIndex row:(NSInteger)row
{
NSMutableArray *currentRowStarIndexArray = [NSMutableArrayarray];
NSInteger printTimes = ceil((double)currentRowStarCount/(double)2.0f);
for (int step =0; step < printTimes; step++) {
//第一行,奇數行
if (row % 2 == 0) {
if (step == 0) {
[currentRowStarIndexArray addObject:@(middleIndex + step)];
}
else
{
[currentRowStarIndexArray addObject:@(middleIndex +2*step)];
[currentRowStarIndexArray addObject:@(middleIndex -2*step)];
}
}
else
{
if (step == 0) {
[currentRowStarIndexArray addObject:@(middleIndex +1)];
[currentRowStarIndexArray addObject:@(middleIndex -1)];
}
else
{
[currentRowStarIndexArray addObject:@(middleIndex +1 + 2*step)];
[currentRowStarIndexArray addObject:@(middleIndex -1 - 2*step)];
}
}
}
return currentRowStarIndexArray;
}
- (void)printCurrentRowStarIndexArray:(NSMutableArray *)currentRowStarIndexArray width:(NSInteger)width row:(NSInteger)row
{
for (int column =0; column < width; column ++) {
NSPredicate *pred = [NSPredicatepredicateWithFormat:@"SELF = %@",@(column)];
NSArray *resultArray = [currentRowStarIndexArrayfilteredArrayUsingPredicate:pred];
BOOL isStar = [resultArray count] > 0 ? YES:NO;
if (isStar) {
printf("*");
}
else
{
printf(" ");
}
}
}
end
大概的思路是,從中間開始畫,如果是奇數行,第一次畫一個點,如果是偶數行,第一次畫兩個點。
因爲知道每一行,有幾個點,所以可以知道,畫了多少次。先實現吧,別的方法再議。
1.先畫一個平行四邊形,然後旋轉,挪移?