【问题标题】:Remember Previous Output in a Random Array记住随机数组中的先前输出
【发布时间】:2010-09-21 19:34:41
【问题描述】:

我有一个应用程序,其中包含下面列出的代码,它为最终用户显示随机问题。我试图弄清楚如何让用户能够在随机显示的数组中向后导航。例如,一个用户正在浏览问题并且不小心超过了一个并想要返回,我希望他们能够简单地点击一个返回按钮。您能否提供有关如何执行此操作的任何指导?非常感谢!!!

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

  myArray5= [NSArray arrayWithObjects:           
      @"Question 1",
      @"Question 2",
      @"Question 3",
      @"Question 4",
      nil];

  int chosen = arc4random() % [myArray5 count]; 
  NSString *item = [myArray5 objectAtIndex: chosen];
  label3.text = [NSString stringWithFormat: @"%@", item];
  label3.alpha = 0;
  label3.transform = CGAffineTransformIdentity;
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationDuration:1.0];
  label3.alpha = 1;
  label3.transform = CGAffineTransformMakeScale(1, 1);
  [UIView commitAnimations];
  UITouch *touch = [[event allTouches] anyObject];
  if (touch.tapCount == 2) {
  }
}

【问题讨论】:

    标签: iphone arrays nsarray


    【解决方案1】:

    您当然可以创建一个 NSMutableArray,它可以保护您随机选择的问题的索引(选择的整数)。您可能还想查看UINavigationController,它提供了在一系列视图中向后导航的方法。 最后,您应该考虑封装您的问题逻辑。似乎您在一个类中既有界面代码,又有问题代码。一旦您的应用程序变得更大,您将遇到这种方法的问题。看Model-View-Controllers.的概念

    【讨论】:

      【解决方案2】:

      一种可能性是预先计算在您的应用初始化时将询问用户的问题的索引。但是,这意味着您要问的问题数量会有硬编码限制,或者如果您到达数组的末尾,您可能会回到开头。我对 Objective-C 不熟悉,所以请耐心等待

      const int NUM_QUEsTIONS = 1000; // Arbitrary number
      int questions[NUM_QUESTIONS];
      
      init()
      {
          for (int i = 0; i < NUM_QUESTIONS; ++i)
          {
              questions[i] = RandomNumber();
          }
      }
      

      然后在您的事件处理程序中,您只需在该数组中增加一个计数器并提出该问题。

      对于无限的问题,您可能应该使用双向链表。

      【讨论】:

        【解决方案3】:

        几个想法:

        想法 1. 将所选问题的 id 存储在一个额外的数组中。

        想法 2. 随机化数组,然后逐步遍历它。

        想法3.如果你想避免使用两次,你可以

        • 使用索引指示有多少问题可供选择
        • 根据该索引创建一个随机整数
        • 您在该随机位置显示存储在数组中的问题
        • 您将该位置的元素移动到最大索引
        • 你减少了最大索引

        有点像这样:

          NSMutableArray *array = [NSMutableArray arrayWithObjects: @"a", @"b", @"c", @"d", @"e", @"f", nil];
         NSInteger maxIndex = [array count]-1;
         do {
        
          NSInteger randomIndex = arc4random() % (maxIndex+1);
        
          NSLog(@"%@", [array objectAtIndex:randomIndex]);
          [array exchangeObjectAtIndex:randomIndex withObjectAtIndex:maxIndex];
          maxIndex--;
        
        
        
         } while (maxIndex > -1);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多