Sha256: 55c187eb09e87c0ce890c8a2c935451bdf6be8197d272526b5fd6075eedcdad1
Contents?: true
Size: 1.96 KB
Versions: 1
Compression:
Stored size: 1.96 KB
Contents
#include <ruby.h> int is_palindrome(char*); void copy_string(char*, char*); void reverse_string(char*); int string_length(char*); int compare_string(char*, char*); static VALUE palindrom(VALUE self, VALUE string_raw) { char *string = StringValuePtr(string_raw); int result; result = is_palindrome(string); if ( result == 1 ) return Qtrue; else return Qfalse; } int is_palindrome(char *string) { int check, length; char *reverse; length = string_length(string); reverse = (char*)malloc(length+1); copy_string(reverse, string); reverse_string(reverse); check = compare_string(string, reverse); free(reverse); if ( check == 0 ) return 1; else return 0; } int string_length(char *string) { int length = 0; while(*string) { length++; string++; } return length; } void copy_string(char *target, char *source) { while(*source) { *target = *source; source++; target++; } *target = '\0'; } void reverse_string(char *string) { int length, c; char *begin, *end, temp; length = string_length(string); begin = string; end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++; for ( c = 0 ; c < length/2 ; c++ ) { temp = *end; *end = *begin; *begin = temp; begin++; end--; } } int compare_string(char *first, char *second) { while(*first==*second) { if ( *first == '\0' || *second == '\0' ) break; first++; second++; } if( *first == '\0' && *second == '\0' ) return 0; else return -1; } /* ruby calls this to load the extension */ void Init_calc(void) { /* assume we haven't yet defined Hola */ VALUE klass = rb_define_class("Calc_c", rb_cObject); /* the palindrom function can be called * from ruby as "Calc_c.palindrom?" */ rb_define_singleton_method(klass, "palindrom?", palindrom, 1); }
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
calc-nik-0.0.5 | ext/calc/calc.c |