chap2_8.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include "utils.h"
  2. #include <limits>
  3. #include "chap2_8.h"
  4. typedef vector<u32>* (*seq_ptr)(int) ;
  5. seq_ptr seq_array[seq_cnt] = { fibon_seq };
  6. inline bool is_size_ok(int size) {
  7. if (size <= 0 || size > 1024) {
  8. display_message("size is invalid");
  9. return false;
  10. }
  11. else {
  12. return true;
  13. }
  14. }
  15. vector<u32>* fibon_seq(int size) {
  16. static vector<u32> elems;
  17. if (!is_size_ok(size)) {
  18. return 0;
  19. }
  20. int current_size = elems.size();
  21. if (size > current_size) {
  22. for (int ix = current_size; ix < size; ++ix) {
  23. if (ix < 2) {
  24. elems.push_back(1);
  25. }
  26. else {
  27. int value_ix = elems[ix - 1] + elems[ix - 2];
  28. elems.push_back(value_ix);
  29. }
  30. }
  31. }
  32. return &elems;
  33. }
  34. /*
  35. */
  36. bool fibon_elem(int position, u32& elem) {
  37. vector<u32>* fibon_vector = fibon_seq(position);
  38. if (fibon_vector) {
  39. elem = (*fibon_vector)[position - 1]; //index overflow
  40. return true;
  41. }
  42. else {
  43. elem = 0;
  44. return false;
  45. }
  46. }
  47. bool seq_elem(int position, u32& elem,
  48. seq_ptr seq_func) {
  49. if (!seq_func) {
  50. display_message("invalid parameter seq_func=NULL_PTR!");
  51. return false;
  52. }
  53. vector<u32>* vec = seq_func(position);
  54. if (vec) {
  55. elem = (*vec)[position - 1]; //index overflow
  56. return true;
  57. }
  58. else {
  59. elem = 0;
  60. return false;
  61. }
  62. }
  63. int main() {
  64. u32 elem = 0;
  65. bool ret = fibon_elem(0, elem);
  66. if (ret) {
  67. cout << "elem is" << elem << endl;
  68. }
  69. display_message('s');
  70. display_message("test string message", 1);
  71. display_message("test string message", 1, 2);
  72. string s1("test string message 1");
  73. vector<u32>* v1 = fibon_seq(10);
  74. display(*v1);
  75. display_message(s1, *v1);
  76. ret = seq_elem(100, elem, fibon_seq);
  77. if (ret) {
  78. cout << "elem is " << elem << endl;
  79. }
  80. return 0;
  81. }