jjzjj

iOS 在大数组中查找已删除的项目(即 : > 1 million items)

coder 2024-01-12 原文

在 iOS 开发职位的面试中,他们问我在大型数组(> 100 万项)中查找已删除项目的最快解决方案,即:在本地,应用程序已经从服务器获取数组(我们不关心方法来从服务器获取这个数组)。然后,在服务器上,他们删除了这个数组和本地的几个项目,我们不知道。那么,我们如何根据服务器上的新数组和本地数组在本地找到已删除的项目? 我想在 02 天后&在下面找到这个循环但是当服务器删除数组开头或结尾的项目时就没问题了。当删除数组中间的项目时,这个循环需要很长时间才能完成。

#define rchar (rand() % ('z'-'a') + 'a')

- (void)viewDidLoad :

NSMutableArray * mar = [NSMutableArray new]; // represent server array. 



for (int i = 0; i<50000; i++) //10 50000 200000 400000 600000 800000
{
    NSString * str = [NSString stringWithFormat:@"%c%c%c%c",rchar, rchar, rchar, rchar];
    [mar addObject:str];

}

NSMutableArray *tmpServerArr = [[NSMutableArray alloc] initWithArray:mar copyItems:YES];

NSMutableArray *localArr = [[NSMutableArray alloc]initWithCapacity:50002]; // represent local array
for (int i = 0; i<50002; i++) //10 50000 200000
{
    switch (i) {
        case 32111: [localArr addObject:[NSString stringWithFormat:@"%c%c%c%c",rchar, rchar, rchar, rchar]];

            break;
            case 41234: [localArr addObject:[NSString stringWithFormat:@"%c%c%c%c",rchar, rchar, rchar, rchar]];
            break;
        case 50000: [localArr addObject:mar[32111]];
            break;
        case 50001: [localArr addObject:mar[41234]];
            break;

        default: [localArr addObject:mar[i]];
            break;
    }

}

NSUInteger localremainItem = [localArr count];

NSDate *start;

NSUInteger  loopWhile = 0;
 while (localremainItem > 0 ) {
// while ([localArr count] > 0 ) {


     NSUInteger idxItemStr = (localremainItem -1 - pow(-1, loopWhile)*(localremainItem-1))/2; // -1;
     NSLog(@"idxstring: %li -- pow: %f", idxItemStr, pow(-1, loopWhile));
     NSString *itemStr = localArr[idxItemStr];
      NSLog(@"item checked : %@]", itemStr);
      NSPredicate *pre = [ NSPredicate predicateWithFormat:@"NOT (SELF like %@)", itemStr];
     NSCountedSet * localCountedSet = [[ NSCountedSet alloc] initWithArray:localArr];
     NSCountedSet * serverCountedSet = [[ NSCountedSet alloc] initWithArray:tmpServerArr];

     if ([localCountedSet countForObject:itemStr] > [serverCountedSet countForObject:itemStr]) {
         NSLog(@"this item %@ was deleted in server.", itemStr);

     }
     //else {
         [localArr filterUsingPredicate: pre];
         [tmpServerArr filterUsingPredicate:pre];
         NSLog(@"localremain: %li", [localArr count]);
         NSLog(@"tmpserverremain: %li", [tmpServerArr count]);
    // }

     if ([localArr count] == [tmpServerArr count]) {
         localremainItem = 0;
     }
     else localremainItem = [localArr count];

      loopWhile +=1;
 }

NSLog(@"now server arr is controled! time: %f", -[start timeIntervalSinceNow]);

谢谢你的帮助。
** 2015 年 11 月 14 日更新:下面这个循环快了 8 倍:
在 viewDidLoad 中:

while ([localArr count] >0) {

    NSUInteger maxRange =0;
if ([localArr count] >500) {
    maxRange = 500;
}else maxRange = [localArr count];


    NSArray *sampleTest = [[NSArray alloc] initWithArray:[localArr subarrayWithRange:NSMakeRange(0,maxRange)]];
    NSLog(@"sampleTest cnt: %lu", (unsigned long)[sampleTest count]);

if ([self countSampleTest:localArr serverArr:tmpServerArr sampleTest:sampleTest]) {

    NSPredicate *pre = [ NSPredicate predicateWithFormat:@"NOT (SELF in %@)", sampleTest];
    [localArr filterUsingPredicate: pre];
    [tmpServerArr filterUsingPredicate:pre];
    NSLog(@"localremain: %li", [localArr count]);
    NSLog(@"tmpserverremain: %li", [tmpServerArr count]);
     }
else {
    NSLog(@"deleted item in here!: %i, %li", 0, [sampleTest count]); //[localArr count]/10);
    int found = 0;
    while (found <10) {
        maxRange =0;
        if ([localArr count] >50) {
            maxRange = 50;
        }else maxRange = [localArr count];


        NSArray *sampleTest1 = [[NSArray alloc] initWithArray:[localArr subarrayWithRange:NSMakeRange(0,maxRange)]];
        NSLog(@"sampleTest1 cnt: %lu", (unsigned long)[sampleTest1 count]);
        if ([self countSampleTest:localArr serverArr:tmpServerArr sampleTest:sampleTest1]) {


            NSPredicate *pre = [ NSPredicate predicateWithFormat:@"NOT (SELF in %@)", sampleTest1];
            [localArr filterUsingPredicate: pre];
            [tmpServerArr filterUsingPredicate:pre];
            NSLog(@"localremain: %li", [localArr count]);
            NSLog(@"tmpserverremain: %li", [tmpServerArr count]);
        }
        else {
            NSUInteger k = 0;
            while (k< [sampleTest1 count]) {

                NSLog(@"item checked %lu : %@]", (unsigned long)k, sampleTest1[k]);
                NSCountedSet * localCountedSet = [[ NSCountedSet alloc] initWithArray:localArr];
                NSCountedSet * serverCountedSet = [[ NSCountedSet alloc] initWithArray:tmpServerArr];

                if ([localCountedSet countForObject:sampleTest1[k]] > [serverCountedSet countForObject:sampleTest1[k]]) {
                    NSLog(@"this item %@ was deleted in server.", sampleTest1[k]);
                }
                NSPredicate *pre = [ NSPredicate predicateWithFormat:@"NOT (SELF like %@)", sampleTest1[k]];
                [localArr filterUsingPredicate: pre];
                [tmpServerArr filterUsingPredicate:pre];
                NSLog(@"localremain: %li", [localArr count]);
                NSLog(@"tmpserverremain: %li", [tmpServerArr count]);
                if ([localArr count] == [tmpServerArr count]) {
                    k = [sampleTest1 count];
                    found = 10;
                }else k +=1;
            }
        }
        found +=1;
    }
}


     if ([localArr count] == [tmpServerArr count]) {
         localArr = nil;
     }
    // if ([sampleTest count] == 0) {
    //     localArr = nil;
    // }

}

NSLog(@"this stuck is done!");//end viewDidLoad.  
-(BOOL)countSampleTest: (NSMutableArray *)localArr serverArr:(NSMutableArray *)tmpServerArr sampleTest:(NSArray *)sampleTest{
BOOL tf;
int cntSampleLoc = 0;
int cntSampleServer = 0;

for (int i = 0 ; i < [sampleTest count]; i++) {
    NSCountedSet * localCountedSet = [[ NSCountedSet alloc] initWithArray:localArr];
    NSCountedSet * serverCountedSet = [[ NSCountedSet alloc] initWithArray:tmpServerArr];
    cntSampleLoc += [localCountedSet countForObject:sampleTest[i]];
    //if (localArr[i] in tmpServerArr ) {
    cntSampleServer +=[serverCountedSet countForObject:sampleTest[i]];
    // }
}

if (cntSampleServer == cntSampleLoc) {
    tf= true;
}else tf = false;
return tf;}

最佳答案

我想到的第一个解决方案很简单:

NSArray *serverArray;
NSMutableArray *localArray;

// This will give you the difference.
[localArray removeObjectsInArray:serverArray];

Docs说:

removeObjectsInArray:

This method is similar to removeObject:, but it allows you to efficiently remove large sets of objects with a single operation.

关于iOS 在大数组中查找已删除的项目(即 : > 1 million items),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33674611/

有关iOS 在大数组中查找已删除的项目(即 : > 1 million items)的更多相关文章

  1. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  2. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  3. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  4. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  5. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  6. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

  7. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  8. ruby - 当使用::指定模块时,为什么 Ruby 不在更高范围内查找类? - 2

    我刚刚被困在这个问题上一段时间了。以这个基地为例:moduleTopclassTestendmoduleFooendend稍后,我可以通过这样做在Foo中定义扩展Test的类:moduleTopmoduleFooclassSomeTest但是,如果我尝试通过使用::指定模块来最小化缩进:moduleTop::FooclassFailure这失败了:NameError:uninitializedconstantTop::Foo::Test这是一个错误,还是仅仅是Ruby解析变量名的方式的逻辑结果? 最佳答案 Isthisabug,or

  9. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  10. ruby-on-rails - Nokogiri:使用 XPath 搜索 <div> - 2

    我使用Nokogiri(Rubygem)css搜索寻找某些在我的html里面。看起来Nokogiri的css搜索不喜欢正则表达式。我想切换到Nokogiri的xpath搜索,因为这似乎支持搜索字符串中的正则表达式。如何在xpath搜索中实现下面提到的(伪)css搜索?require'rubygems'require'nokogiri'value=Nokogiri::HTML.parse(ABBlaCD3"HTML_END#my_blockisgivenmy_bl="1"#my_eqcorrespondstothisregexmy_eq="\/[0-9]+\/"#FIXMEThefoll

随机推荐