我有5個骰子的一個NSArray(dice1,dice2,dice3 ...)。一旦我運行了隨機數生成器,每個dice1,dice2,dice3 ...都可以返回1-6之間的值。計數次數對象出現在的NSArray
我希望能夠指望有多少次爲1-6的值已返回。 我不是太肯定的最佳方式,我是否應該將INT數1-6成字符串相匹配。
我有5個骰子的一個NSArray(dice1,dice2,dice3 ...)。一旦我運行了隨機數生成器,每個dice1,dice2,dice3 ...都可以返回1-6之間的值。計數次數對象出現在的NSArray
我希望能夠指望有多少次爲1-6的值已返回。 我不是太肯定的最佳方式,我是否應該將INT數1-6成字符串相匹配。
用詞典:
let arrNum = [「one」, 「two」, 「three」, 「two」]
var countNumber:[String:Int] = [:]
for item in arrNum {
countNumber[item] = (countNumber[item] ?? 0) + 1
}
for (key, value) in countNumber {
print("\(key) occurs \(value) time")
}
O/P:
one occurs 1 time
two occurs 2 time
three occurs 1 time
的問題是標記的Objective-C,不夫特。 – rmaddy
這是那些情形之一的,我不覺得有一個特別優雅的解決方案,由於無法基金會類型(如NSCountedSet
)來存儲固有類型(如int
)。斯威夫特在NSNumber
中對整數進行自動裝箱/拆箱是一種很好的功能。
既然你用少量的骰子和一個小的可能值的處理,那麼你可以忽略的對象,組和所有的,只是遍歷你的骰子陣列,更新整數計數組成的數組。
的其他更復雜,但面向對象的方法是創建一個Die
類:
Die.h
#import <Foundation/Foundation.h>
@interface Die : NSObject
-(instancetype)initWithSides:(NSUInteger)sides;
-(instancetype)initWithSides:(NSUInteger)sides initialValue:(NSUInteger)value;
-(NSUInteger)value;
-(NSUInteger)roll;
-(NSUInteger)sides;
@end
Die.m
#import "Die.h"
@interface Die()
@property NSUInteger currentValue;
@property NSUInteger numberOfsides;
@end
@implementation Die
- (instancetype)initWithSides:(NSUInteger)sides {
NSAssert(sides>1, @"Dice must have at least 2 sides");
if (self = [super init]) {
self.numberOfsides = sides;
[self roll];
}
return self;
}
- (instancetype)initWithSides:(NSUInteger)sides initialValue:(NSUInteger)value {
NSAssert(sides>1, @"Dice must have at least 2 sides");
NSAssert(value <= sides, @"Initial value must not exceed number of sides");
if (self = [super init]) {
self.numberOfsides = sides;
self.currentValue = value;
}
return self;
}
- (NSUInteger)roll {
self.currentValue = arc4random_uniform((UInt32)self.numberOfsides)+1;
return self.currentValue;
}
- (NSUInteger)value {
return self.currentValue;
}
- (NSUInteger)sides {
return self.numberOfsides;
}
- (NSUInteger)hash {
return self.currentValue;
}
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
if (![object isKindOfClass:[Die class]]) {
return NO;
}
return [self isEqualToDie:(Die *)object];
}
- (BOOL) isEqualToDie:(Die *)otherDie {
return self.currentValue == otherDie.value;
}
@end
所以現在你有一個可以存儲在NSCountedSet
中的對象,你可以檢索計數。該位是略顯尷尬,因爲你需要比較的Die
用合適的值,而不是本身的價值:
// self.dice is an array of `Die` objects
NSCountedSet *valueCounts = [NSCountedSet setWithArray:self.dice];
for (int i=1;i<7;i++) {
NSUInteger count = [valueCounts countForObject:[[Die alloc] initWithSides:6 initialValue:i]];
NSLog(@"There are %lu dice showing %d",count,i);
}
結帳['NSCountedSet'](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCountedSet_Class /) – Anurag
分享您的代碼以獲得快速結果 – PinkeshGjr
@PinkeshGjr 'NSCountedSet * filter = [NSCountedSet setWithObjects:self.diceLabel [0],self.diceLabel [1],self .diceLabel [2],self.diceLabel [3],self.diceLabel [4],nil]; //的NSLog(@ 「%@」,@([濾波器countForObject:@ 「2」]));' –