Index: base/cpp101/fibonacci.cc |
diff --git a/base/cpp101/fibonacci.cc b/base/cpp101/fibonacci.cc |
new file mode 100644 |
index 0000000000000000000000000000000000000000..ea882b3bb809dbd7baa333ba1598651d8bca69cb |
--- /dev/null |
+++ b/base/cpp101/fibonacci.cc |
@@ -0,0 +1,56 @@ |
+// Copyright 2013 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#include <stdio.h> |
+ |
+#include "base/bind.h" |
+#include "base/bind_helpers.h" |
+#include "base/callback.h" |
+#include "base/strings/string_number_conversions.h" |
+ |
+namespace { |
+ |
+struct FibonacciState { |
+ FibonacciState() : i(0), j(1) {} |
+ |
+ int i, j; |
+}; |
+ |
+int ComputeNextFibonacciNumber(FibonacciState* state) { |
+ int next = state->i + state->j; |
+ state->i = state->j; |
+ state->j = next; |
+ return state->i; |
+} |
+ |
+base::Callback<int()> MakeFibonacciClosure() { |
+ scoped_ptr<FibonacciState> state(new FibonacciState); |
+ return base::Bind(&ComputeNextFibonacciNumber, base::Owned(state.release())); |
+} |
+ |
+} // namespace |
+ |
+int main(int argc, char* argv[]) { |
+ if (argc <= 1) { |
+ printf("%s: missing operand\n", argv[0]); |
+ return -1; |
+ } |
+ |
+ int n = 0; |
+ if (!base::StringToInt(argv[1], &n) || n < 0) { |
+ printf("%s: invalid n `%s'\n", argv[0], argv[1]); |
+ return -1; |
+ } |
+ |
+ base::Callback<int()> fibonacci_closure1 = MakeFibonacciClosure(); |
+ base::Callback<int()> fibonacci_closure2 = MakeFibonacciClosure(); |
+ for (int i = 0; i < n; ++i) { |
+ int j = fibonacci_closure1.Run(); |
+ int k = fibonacci_closure2.Run(); |
+ DCHECK_EQ(j, k); |
+ printf("F_%d = %d\n", i, j); |
+ } |
+ |
+ return 0; |
+} |