0

我用 Java 编写了一个程序,它可以向后或向前“走”500 个随机步骤(-1 或 +1)。结束步骤(在 500 步后停止)正在打印到控制台。我希望将这些存储在一个列表中,它会告诉我结束步骤登陆的次数,比如说-5。结束步骤需要循环 100 次:

public class RandomWalk {

    public static void main(String[] args) {
        int[] y;
        for(int i = 0; i < 100; i++){

            int[] x;
            x = new int[500];
            for (int i1 = 0; i1 < 500; i1++){
                 int L = (int) (Math.random()*2);
                 x[i1] = (L==0) ? -1 : 1;
            }
            int total_value = 0;
            for (int i1 = 0; i1 < 500; i1++)
                total_value += x[i1];

                System.out.println("Total: "+ total_value);
        }
    }
}

如何查询并返回结果?

4

2 回答 2

1

像这样的东西。我已经清理了一些代码,但更重要的是,我添加了 HashMap 总数和它的用法。

package se.wederbrand.stackoverflow;

import java.util.HashMap;

public class RandomWalk {

    public static final int NBR_WALKS = 100;
    public static final int NBR_STEPS = 500;

    public static void main(String[] args) {
        HashMap<Integer, Integer> totals = new HashMap<>();
        for (int i = -NBR_STEPS; i <= NBR_STEPS; i++) {
            totals.put(i, 0);
        }

        for (int i = 0; i < NBR_WALKS; i++) {
            int total_value = 0;
            for (int j = 0; j < NBR_STEPS; j++) {
                int L = (int) (Math.random() * 2);
                total_value += (L == 0) ? -1 : 1;
            }

            System.out.println("For run number " + i + " the total is " + total_value);
            totals.put(total_value, totals.get(total_value) + 1);
        }

        System.out.println("Number of times you ended on -5 " + totals.get(-5));
    }
}
于 2013-11-09T13:52:04.420 回答
0

傻走部进一步推荐以下多线程替代方案:

package test;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {

  private static final int NUMBER_WALKS = 100;
  private static final int NUMBER_STEPS = 500;

  private static class Counter implements Runnable {

    private final AtomicInteger counter;
    private final ConcurrentSkipListMap<Integer, Integer> totals;

    public Counter(final AtomicInteger counter, final ConcurrentSkipListMap<Integer, Integer> totals) {
      this.counter = counter;
      this.totals = totals;
    }

    @Override
    public void run() {
      int result;
      Integer oldValue;

      while ((Thread.currentThread().isInterrupted() == false) && (this.counter.decrementAndGet() >= 0)) {
        result = 0;

        for (int i = 0; i < NUMBER_STEPS; ++i) {
          result += ThreadLocalRandom.current().nextInt(2) == 0 ? -1 : 1;
        }

        oldValue = totals.putIfAbsent(result, 1);
        if (oldValue != null) {
          while (totals.replace(result, oldValue, oldValue + 1) == false) {
            oldValue = totals.get(result);
          }
        }
      }
    }
  }

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    final AtomicInteger counter = new AtomicInteger(NUMBER_WALKS);
    final ConcurrentSkipListMap<Integer, Integer> totals = new ConcurrentSkipListMap<>();

    final int numCPUs = Runtime.getRuntime().availableProcessors();
    final ExecutorService executor = Executors.newFixedThreadPool(numCPUs);

    for (int i = 0; i < numCPUs; ++i) {
      executor.submit(new Counter(counter, totals));
    }
    executor.shutdown();
    if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
      for (Integer key : totals.keySet()) {
        System.out.println(String.format("%3d was called %3d times.", key, totals.get(key)));
      }
    } else {
      executor.shutdownNow();
      System.err.println("Executor did not terminate as expected.");
    }
  }
}
于 2013-11-09T14:45:42.537 回答