/* * This file is a part of CMSLU -- Content Management System like Unix * and is not publicly distributed * * Copyright (c) 2008-2009, Tomasz Sowa * All rights reserved. * */ #include #include #include "log.h" #include "rebus.h" #include "misc.h" bool Rebus::InitPair(int a, int b, Item & item) { char buffer[100]; bool add = false; if( a+b <= 15 ) { sprintf(buffer, "%d+%d", a, b); item.question = buffer; item.answer = a+b; add = true; } if( a-b >= 0 ) { sprintf(buffer, "%d-%d", a, b); item.question = buffer; item.answer = a-b; add = true; } return add; } void Rebus::Init() { int a, b; Item item; item.key = 0; for(a=1 ; a<10 ; ++a) { for(b=1 ; b<10 ; ++b) { if( InitPair(a, b, item) ) { table.push_back(item); item.key += 1; } } } } Rebus::Item * Rebus::Rand() { size_t len = table.size(); if( len == 0 ) // empty table, call Init() first return 0; size_t i = size_t( ((double)rand()*(double)len) / (double(RAND_MAX)+1.0) ); if( i >= table.size() ) { log << log1 << "Rebus: Rand() index too big" << logend; // oops, it should not be greater then table.size() return &table[0]; } return &table[0] + i; } bool Rebus::IsAnswerOk(Rebus::Item * item, const std::string & answer) { if( item == 0 ) return false; char * end; const char * a = answer.c_str(); a = SkipWhite(a); int value = (int)strtol(a, &end, 10); if( a == end ) // nothing has been read return false; log << log2 << "Rebus: your answer is: " << value << logend; end = (char*)SkipWhite(end); if( *end != 0 ) { // something is at the end return false; } bool result = (item->answer == value); if( result ) log << log3 << "Rebus: the answer is correct" << logend; return result; }