Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // main.m
- // ApptopiaTest
- //
- // Created by Nikita Pankiv on 2/19/17.
- // Copyright © 2017 Neutral. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- NSString *location = @"/Users/Nikita/Desktop/Test/";// Place your directory here
- NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:location];
- NSString *fileName = nil;
- NSMutableArray *files = [NSMutableArray new];
- while (fileName = [enumerator nextObject]) {
- if ([fileName hasSuffix:@".txt"]) { // Only txt's
- [files addObject:[location stringByAppendingString:fileName]];
- }
- }
- // Find the largest number in all files to generate the Eratosthenes only once
- // Not the most benefit way, but I decided to do so
- unsigned long size = 0;
- for (NSString *fileName in files) {
- NSArray *numbers = [[[NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil] componentsSeparatedByString:@","] sortedArrayUsingComparator:^NSComparisonResult(NSString* _Nonnull obj1, NSString* _Nonnull obj2) {
- return [obj1 integerValue] > [obj2 integerValue];
- }];
- size = MAX([[numbers lastObject] integerValue], size);
- }
- // Calculate Sieve Array for prime numbers
- NSMutableArray *checkNumbers = [NSMutableArray new];
- for (int i = 0; i < size + 1; i++) {
- [checkNumbers insertObject:@(YES) atIndex:i];
- }
- for (int i = 2; i * i <= size; ++i) {
- if ([checkNumbers[i] boolValue] && i % 2 != 0) {
- for (int j = 2; j <= size / i; j++) {
- if ([checkNumbers[i * j] boolValue]) {
- checkNumbers[i * j] = @(NO);
- }
- }
- }
- }
- // Find prime numbers
- for (NSString *fileName in files) {
- NSArray *numbers = [[NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil] componentsSeparatedByString:@","];
- NSMutableArray *resultedNumbers = [NSMutableArray new];
- for (NSString *num in numbers) {
- if ([checkNumbers[[num integerValue]] boolValue]) {
- [resultedNumbers addObject:num];
- }
- }
- // Write to same directory
- NSData *resultedData = [[resultedNumbers componentsJoinedByString:@","] dataUsingEncoding:NSUTF8StringEncoding];
- [[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@modified_%@", location, [fileName lastPathComponent]] contents:resultedData attributes:nil];
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement