gsl_permutation__init.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* permutation/init.c
  2. *
  3. * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. */
  19. #include "gsl__config.h"
  20. #include <stdlib.h>
  21. #include "gsl_errno.h"
  22. #include "gsl_permutation.h"
  23. gsl_permutation *
  24. gsl_permutation_alloc (const size_t n)
  25. {
  26. gsl_permutation * p;
  27. if (n == 0)
  28. {
  29. GSL_ERROR_VAL ("permutation length n must be positive integer",
  30. GSL_EDOM, 0);
  31. }
  32. p = (gsl_permutation *) malloc (sizeof (gsl_permutation));
  33. if (p == 0)
  34. {
  35. GSL_ERROR_VAL ("failed to allocate space for permutation struct",
  36. GSL_ENOMEM, 0);
  37. }
  38. p->data = (size_t *) malloc (n * sizeof (size_t));
  39. if (p->data == 0)
  40. {
  41. free (p); /* exception in constructor, avoid memory leak */
  42. GSL_ERROR_VAL ("failed to allocate space for permutation data",
  43. GSL_ENOMEM, 0);
  44. }
  45. p->size = n;
  46. return p;
  47. }
  48. gsl_permutation *
  49. gsl_permutation_calloc (const size_t n)
  50. {
  51. size_t i;
  52. gsl_permutation * p = gsl_permutation_alloc (n);
  53. if (p == 0)
  54. return 0;
  55. /* initialize permutation to identity */
  56. for (i = 0; i < n; i++)
  57. {
  58. p->data[i] = i;
  59. }
  60. return p;
  61. }
  62. void
  63. gsl_permutation_init (gsl_permutation * p)
  64. {
  65. const size_t n = p->size ;
  66. size_t i;
  67. /* initialize permutation to identity */
  68. for (i = 0; i < n; i++)
  69. {
  70. p->data[i] = i;
  71. }
  72. }
  73. void
  74. gsl_permutation_free (gsl_permutation * p)
  75. {
  76. free (p->data);
  77. free (p);
  78. }