fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define T int
  5. typedef struct {
  6. T *array;
  7. int size;
  8. } Vector;
  9.  
  10. int init_vector(Vector *v, int size) {
  11. if ((v->array = malloc(sizeof(T) * size)) != 0) { /* OK */
  12. v->size = size;
  13. return 1;
  14. }
  15. return 0;
  16. }
  17.  
  18. int substitute_vector(Vector *v, int index, T value) {
  19. int n, *alloc;
  20. if (index < v->size) {
  21. (v->array)[index] = value;
  22. return 1;
  23. }
  24. n = index * 2;
  25. if ((alloc = realloc(v->array, sizeof(T) * n)) != 0) { /* OK */
  26. v->size = n;
  27. (v->array)[index] = value;
  28. return 1;
  29. }
  30. return 0;
  31. }
  32.  
  33. T refer_vector(Vector *v, int index) {
  34. if (index < v->size)
  35. return (v->array)[index];
  36. perror("out of bounds in refering, aborted\n");
  37. exit(1);
  38. }
  39.  
  40. void release_vector(Vector *v) { v->size = 0; free(v->array); }
  41.  
  42. #define N 10
  43. int main() {
  44. Vector *a;
  45. int last, i, bids, input, ferr;
  46.  
  47. if ((a = malloc(sizeof(Vector))) == 0) exit(1);
  48. if (!init_vector(a, 10)) { perror("memory full(init), aborted.\n"); exit(1); }
  49. restart:
  50. last = 3;
  51. ferr = 0;
  52. for (i = 0; i < last; i++)
  53. if(!substitute_vector(a, i, i + 1)) {
  54. ferr = 1;
  55. break;
  56. }
  57. if (ferr) { perror("memory full(subst4init), aborted.\n"); exit(1); }
  58. for (;;) {
  59. ferr = 0;
  60. for (i = 0; i < last; i++)
  61. printf("[%d]%d, ", i, refer_vector(a, i));
  62. putchar('\n');
  63. bids = refer_vector(a, 0) + refer_vector(a, last - 1);
  64. printf("bids: %d\n", bids);
  65. printf("win or loss? (win:positive, loss:zero) : "); scanf("%d", &input);
  66. if (input < 0)
  67. break;
  68. if (input) {
  69. for (i = 0; i < last - 1; i++)
  70. if (!substitute_vector(a, i, refer_vector(a, i + 1))) { ferr = 1; }
  71. last -= 2;
  72. } else {
  73. if (!substitute_vector(a, last, bids)) { ferr = 1; }
  74. last++;
  75. }
  76. if (ferr)
  77. break;
  78. if (last < 2) {
  79. printf("go for the initial step.\n");
  80. goto restart;
  81. }
  82. }
  83. if (ferr) { perror("memory full(subst4init), aborted.\n"); exit(1); }
  84. release_vector(a);
  85. return 0;
  86. }
  87. /* end */
  88.  
Success #stdin #stdout 0s 2428KB
stdin
0
1
0
1
-1
stdout
[0]1, [1]2, [2]3, 
bids: 4
win or loss? (win:positive, loss:zero) : [0]1, [1]2, [2]3, [3]4, 
bids: 5
win or loss? (win:positive, loss:zero) : [0]2, [1]3, 
bids: 5
win or loss? (win:positive, loss:zero) : [0]2, [1]3, [2]5, 
bids: 7
win or loss? (win:positive, loss:zero) : go for the initial step.
[0]1, [1]2, [2]3, 
bids: 4
win or loss? (win:positive, loss:zero) :