Annotation of loncom/homework/default_homework.lcpm, revision 1.120

1.42      albertel    1: # The LearningOnline Network with CAPA 
1.1       harris41    2: # used by lonxml::xmlparse() as input variable $safeinit to Apache::run::run()
1.42      albertel    3: #
1.120   ! albertel    4: # $Id: default_homework.lcpm,v 1.119 2006/11/01 23:24:52 albertel Exp $
1.42      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.20      harris41   28: #
1.76      albertel   29: 
1.25      albertel   30: #init some globals
1.38      albertel   31: $hidden::RANDOMINIT=0;
1.22      ng         32: $pi=atan2(1,1)*4;
                     33: $rad2deg=180.0/$pi;
                     34: $deg2rad=$pi/180.0;
1.44      matthew    35: $"=' ';
1.116     albertel   36: use strict;
                     37: {
                     38:     my $n = 0;
                     39:     my $total = 0;
                     40:     my $num_left = 0;
                     41:     my @order;
                     42:     my $type;
                     43: 
                     44:     sub init_permutation {
                     45: 	my ($size,$requested_type) = @_;
                     46: 	@order = (0..$size-1);
                     47: 	$n = $size;
                     48: 	$type = $requested_type;
                     49: 	if ($type eq 'ordered') {
                     50: 	    $total = $num_left = 1;
                     51: 	} elsif ($type eq 'unordered') {
                     52: 	    $total = $num_left = &factorial($size);
                     53: 	} else {
                     54: 	    die("Unkown type: $type");
                     55: 	}
                     56:     }
                     57: 
                     58:     sub get_next_permutation {
                     59: 	if ($num_left == $total) {
                     60: 	    $num_left--;
1.117     albertel   61: 	    return \@order;
1.116     albertel   62: 	}
                     63: 
                     64: 	# Find largest index j with a[j] < a[j+1]
                     65: 
                     66: 	my $j = scalar(@order) - 2;
                     67: 	while ($order[$j] > $order[$j+1]) {
                     68: 	    $j--;
                     69: 	}
                     70: 
                     71: 	# Find index k such that a[k] is smallest integer
                     72: 	# greater than a[j] to the right of a[j]
                     73: 
                     74: 	my $k = scalar(@order) - 1;
                     75: 	while ($order[$j] > $order[$k]) {
                     76: 	    $k--;
                     77: 	}
                     78: 
                     79: 	# Interchange a[j] and a[k]
                     80: 
                     81: 	@order[($k,$j)] = @order[($j,$k)];
                     82: 
                     83: 	# Put tail end of permutation after jth position in increasing order
                     84: 
                     85: 	my $r = scalar(@order) - 1;
                     86: 	my $s = $j + 1;
                     87: 
                     88: 	while ($r > $s) {
                     89: 	    @order[($s,$r)]=@order[($r,$s)];
                     90: 	    $r--;
                     91: 	    $s++;
                     92: 	}
                     93: 
                     94: 	$num_left--;
1.117     albertel   95: 	return(\@order);
1.116     albertel   96:     }
                     97:     
                     98:     sub get_permutations_left {
                     99: 	return $num_left;
                    100:     }
                    101: }
1.3       albertel  102: 
1.91      albertel  103: sub check_commas {
                    104:     my ($response)=@_;
                    105:     #print("$response ");
                    106:     my @numbers=split(',',$response);
                    107:     #print(" numbers ".join('-',@numbers)." ");
                    108:     if (scalar(@numbers) > 1) {
                    109:         #print(" numbers[0] ".$numbers[0]." "); 
                    110: 	if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
                    111: 	shift(@numbers);
                    112: 	#print(" numbers ".scalar(@numbers)." ");
                    113: 	while (scalar(@numbers) > 1) {
                    114: 	    #print(" numbers ".join('-',@numbers)." ");
                    115: 	    if (length($numbers[0]) != 3) { return -2; }
                    116: 	    shift(@numbers);
                    117: 	}
                    118: 	my ($number)=split('\.',$numbers[0]);
                    119: 	#print(" number ".$number." ");
                    120: 	#print(" numbers[0] ".$numbers[0]." ");
                    121: 	if (length($number) != 3) { return -3; }
                    122:     } else {
                    123: 	my ($number)=split('\.',$numbers[0]);
                    124: 	if (length($number) > 3) { return -4; }
                    125:     }
                    126:     return 1;
                    127: }
                    128: 
1.117     albertel  129: 
1.7       albertel  130: sub caparesponse_check {
1.74      albertel  131:     my ($answer,$response)=@_;
1.73      albertel  132:     #not properly used yet: calc
                    133:     #not to be used: $ans_fmt
1.74      albertel  134:     my $type=$LONCAPA::CAPAresponse_args{'type'};
                    135:     my $tol=$LONCAPA::CAPAresponse_args{'tol'};
                    136:     my $sig=$LONCAPA::CAPAresponse_args{'sig'};
1.88      albertel  137:     my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
1.74      albertel  138:     my $unit=$LONCAPA::CAPAresponse_args{'unit'};
                    139:     my $calc=$LONCAPA::CAPAresponse_args{'calc'};
                    140:     my $samples=$LONCAPA::CAPAresponse_args{'samples'};
1.73      albertel  141:     
                    142:     my $tol_type=''; # gets it's value from whether tol has a % or not done
                    143:     my $sig_lbound=''; #done
                    144:     my $sig_ubound=''; #done
                    145: 
                    146: 
                    147:     #type's definitons come from capaParser.h
1.116     albertel  148: 
1.73      albertel  149:     #remove leading and trailing whitespace
                    150:     if (!defined($response)) {
                    151: 	$response='';
                    152:     }
                    153:     if ($response=~ /^\s|\s$/) {
                    154: 	$response=~ s:^\s+|\s+$::g;
1.119     albertel  155: 	&LONCAPA_INTERNAL_DEBUG("Removed ws now :$response:");
1.73      albertel  156:     }
1.116     albertel  157: 
1.117     albertel  158:     #&LONCAPA_INTERNAL_DEBUG(" type is $type ");
1.100     albertel  159:     if ($type eq 'cs' || $type eq 'ci') {
1.76      albertel  160: 	#for string answers make surec all places spaces occur, there is 
                    161:         #really only 1 space, in both the answer and the response
                    162: 	$answer=~s/ +/ /g;
                    163: 	$response=~s/ +/ /g;
1.100     albertel  164:     } elsif ($type eq 'mc') {
                    165: 	$answer=~s/[\s,]//g;
                    166: 	$response=~s/[\s,]//g;
1.76      albertel  167:     }
1.91      albertel  168:     if ($type eq 'float' && $unit=~/\$/) {
1.117     albertel  169: 	if ($response!~/^\$/)  { return ('NO_UNIT', undef); }
1.88      albertel  170: 	$response=~s/\$//g;
                    171:     }
1.91      albertel  172:     if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
                    173: 	return "COMMA_FAIL:";
                    174:     }
1.88      albertel  175:     $ans_fmt=~s/\W//g;
1.91      albertel  176:     $unit=~s/[\$,]//g;
                    177:     if ($type eq 'float') { $response=~s/,//g; }
1.88      albertel  178: 
1.117     albertel  179:     if (length($response) > 500) { return ('TOO_LONG',undef); }
1.73      albertel  180: 
                    181:     if ($type eq '' ) {
1.119     albertel  182: 	&LONCAPA_INTERNAL_DEBUG("Didn't find a type :$type: defaulting");
1.73      albertel  183: 	if ( $answer eq ($answer *1.0)) { $type = 2;
                    184: 				      } else { $type = 3; }
                    185:     } else {
1.107     albertel  186: 	if    ($type eq 'cs')    { $type = 4; }
1.73      albertel  187: 	elsif ($type eq 'ci')    { $type = 3 }
                    188: 	elsif ($type eq 'mc')    { $type = 5; }
                    189: 	elsif ($type eq 'fml')   { $type = 8; }
1.107     albertel  190:         elsif ($type eq 'math')  { $type = 9; }
1.73      albertel  191: 	elsif ($type eq 'subj')  { $type = 7; }
                    192: 	elsif ($type eq 'float') { $type = 2; }
                    193: 	elsif ($type eq 'int')   { $type = 1; }
1.117     albertel  194: 	else { return ('ERROR', "Unknown type of answer: $type") }
1.73      albertel  195:     }
                    196: 
                    197:     my $points;
                    198:     my $id_list;
                    199:     #formula type setup the sample points
                    200:     if ($type eq '8') {
                    201: 	($id_list,$points)=split(/@/,$samples);
1.119     albertel  202: 	&LONCAPA_INTERNAL_DEBUG("Found :$id_list:$points: points in $samples");
1.73      albertel  203:     }
                    204:     if ($tol eq '') {
                    205: 	$tol=0.0;
                    206: 	$tol_type=1; #TOL_ABSOLUTE
                    207:     } else {
                    208: 	if ($tol =~ /%$/) {
                    209: 	    chop $tol;
                    210: 	    $tol_type=2; #TOL_PERCENTAGE
                    211: 	} else {
                    212: 	    $tol_type=1; #TOL_ABSOLUTE
                    213: 	}
                    214:     }
                    215: 
1.85      albertel  216:     ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
                    217: 
1.73      albertel  218:     my $reterror="";
1.107     albertel  219:     my $result;
                    220:     if ($type eq '9') {
1.108     www       221:       $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
1.107     albertel  222:     } else {
1.109     albertel  223: 	if ($type eq '8') { # fml type
                    224: 	    $response = &capa_formula_fix($response);
                    225: 	    $answer   = &capa_formula_fix($answer);
                    226: 	}
                    227:        $result = &caparesponse_capa_check_answer($response,$answer,$type,
1.73      albertel  228: 						 $tol_type,$tol,
                    229: 						 $sig_lbound,$sig_ubound,
                    230: 						 $ans_fmt,$unit,$calc,$id_list,
                    231: 						 $points,$external::randomseed,
                    232: 						 \$reterror);
1.107     albertel  233:     }
1.73      albertel  234:     if    ($result == '1') { $result='EXACT_ANS'; } 
                    235:     elsif ($result == '2') { $result='APPROX_ANS'; }
                    236:     elsif ($result == '3') { $result='SIG_FAIL'; }
                    237:     elsif ($result == '4') { $result='UNIT_FAIL'; }
                    238:     elsif ($result == '5') { $result='NO_UNIT'; }
                    239:     elsif ($result == '6') { $result='UNIT_OK'; }
                    240:     elsif ($result == '7') { $result='INCORRECT'; }
                    241:     elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
                    242:     elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
                    243:     elsif ($result =='10') { $result='SUB_RECORDED'; }
                    244:     elsif ($result =='11') { $result='BAD_FORMULA'; }
1.94      albertel  245:     elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
                    246:     elsif ($result =='12') { $result='WANTED_NUMERIC'; }
1.77      albertel  247:     elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
                    248:     elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
                    249:     elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
                    250:     elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
                    251:     elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
1.73      albertel  252:     else  {$result = "ERROR: Unknown Result:$result:$@:";}
                    253: 
1.119     albertel  254:     &LONCAPA_INTERNAL_DEBUG("RetError $reterror: Answer $answer: Response $response:  type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|");
                    255:     &LONCAPA_INTERNAL_DEBUG(" $answer $response $result ");
1.116     albertel  256:     return ($result,$reterror)
1.37      albertel  257: }
                    258: 
1.108     www       259: sub maxima_cas_formula_fix {
                    260:    my ($expression)=@_;
                    261:    return &implicit_multiplication($expression);
                    262: }
                    263: 
                    264: sub capa_formula_fix {
                    265:    my ($expression)=@_;
                    266:    return &implicit_multiplication($expression);
                    267: }
                    268: 
                    269: sub implicit_multiplication {
                    270:     my ($expression)=@_;
1.111     www       271: # Escape scientific notation, so 3e8 does not become 3*e*8
                    272: # 3e8 -> 3&8; 3e-8 -> 3&-8; 3E+8 -> e&+8
1.110     www       273:     $expression=~s/(\d+)e([\+\-]*\d+)/$1\&\($2\)/gsi;
1.111     www       274: # 3x10^8 -> 3&8; 3*10^-8 -> 3&-8
1.110     www       275:     $expression=~s/(\d+)(?:x|\*)10(?:\^|\*\*)([\+\-]*\d+)/$1\&\($2\)/gsi;
1.111     www       276: # Fill in multiplication signs
1.114     albertel  277: # a b -> a*b;3 b -> 3*b;3 4 -> 3*4
                    278:     $expression=~s/(\w)\s+(\w)/$1\*$2/gs;
1.115     www       279: # )( -> )*(; ) ( -> )*(
                    280:     $expression=~s/\)\s*\(/\)\*\(/gs;
                    281: # 3a -> 3*a; 3( -> 3*(; 3 ( -> 3*(; 3A -> 3*A
                    282:     $expression=~s/(\d)\s*([a-zA-Z\(])/$1\*$2/gs;
                    283: # a ( -> a*(
                    284:     $expression=~s/(\w)\s+\(/$1\*\(/gs;
1.113     www       285: # a3 -> a*3;
1.110     www       286:     $expression=~s/([a-zA-Z])(\d)/$1\*$2/gs;
1.115     www       287: # )a -> )*a; )3 -> )*3; ) 3 -> )*3
                    288:     $expression=~s/\)\s*(\w)/\)\*$1/gs;
1.111     www       289: # 3&8 -> 3e8; 3&-4 -> 3e-4
1.110     www       290:     $expression=~s/(\d+)\&\(([\+\-]*\d+)\)/$1e$2/gs;
1.108     www       291:     return $expression;
                    292: }
1.73      albertel  293: 
1.37      albertel  294: sub caparesponse_check_list {
1.119     albertel  295:     my $responses=$LONCAPA::CAPAresponse_args{'response'};
                    296:     &LONCAPA_INTERNAL_DEBUG(" answer is ".
                    297: 			    &LONCAPA_INTERNAL_Dumper($LONCAPA::CAPAresponse_answer).":\n");
                    298:     &LONCAPA_INTERNAL_DEBUG(" respons is ".
                    299: 			    &LONCAPA_INTERNAL_Dumper($responses).":\n");
1.105     albertel  300:     &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
1.74      albertel  301:     my $type = $LONCAPA::CAPAresponse_args{'type'};
1.116     albertel  302:     &LONCAPA_INTERNAL_DEBUG("Got type :$type:\n");
1.119     albertel  303:     
                    304:     my $num_input_lines =
                    305: 	scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
1.120   ! albertel  306:     
        !           307:     if ($type ne '' ) {
1.119     albertel  308: 	if (scalar(@$responses) < $num_input_lines) {
1.105     albertel  309: 	    return 'MISSING_ANSWER';
                    310: 	}
1.119     albertel  311: 	if (scalar(@$responses) > $num_input_lines) {
                    312: 	    return 'EXTRA_ANSWER';
                    313: 	}
                    314: 
                    315:     }
                    316: 
                    317:     foreach my $which (0..($num_input_lines-1)) {
                    318: 	my $answer_size = 
                    319: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
                    320: 	if ($type ne '' 
                    321: 	    && $answer_size > 1) {
                    322: 	    $responses->[$which]=[split(/,/,$responses->[$which])];
                    323: 	} else {
                    324: 	    $responses->[$which]=[$responses->[$which]];
                    325: 	}
                    326:     }
                    327:     &LONCAPA_INTERNAL_DEBUG(" parsed response is ".
                    328: 			    &LONCAPA_INTERNAL_Dumper($responses).":\n");
                    329:     foreach my $which (0..($num_input_lines-1)) {
                    330: 	my $answer_size = 
                    331: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
                    332: 	my $response_size = 
                    333: 	    scalar(@{$responses->[$which]});
                    334: 	if ($answer_size > $response_size) {
                    335: 	    return 'MISSING_ANSWER';
                    336: 	}
                    337: 	if ($answer_size < $response_size) {
1.105     albertel  338: 	    return 'EXTRA_ANSWER';
                    339: 	}
1.73      albertel  340:     }
1.119     albertel  341: 
                    342:     &LONCAPA_INTERNAL_DEBUG("Initial final response :$responses->[0][-1]:");
1.105     albertel  343:     my $unit;
1.73      albertel  344:     if ($type eq '' || $type eq 'float') {
                    345: 	#for numerical problems split off the unit
1.119     albertel  346: 	if ( $responses->[0][-1]=~ /(.*[^\s])\s+([^\s]+)/ ) {
                    347: 	    $responses->[0][-1]=$1;
1.73      albertel  348: 	    $unit=$2;
                    349: 	}
                    350:     }
1.119     albertel  351:     &LONCAPA_INTERNAL_DEBUG("Final final response :$responses->[0][-1]:$unit:");
1.73      albertel  352:     $unit=~s/\s//;
1.119     albertel  353:     if ($unit ne '') {
                    354: 	foreach my $response (@$responses) {
                    355: 	    foreach my $element (@$response) {	    
                    356: 		$element .= " $unit";
                    357: 	    }
                    358: 	}
                    359:     }
                    360:     
1.117     albertel  361:     foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
                    362: 	if (!defined($thisanswer)) {
                    363: 	    return ('ERROR','answer was undefined');
                    364: 	}
                    365:     }
                    366: 
                    367: 
1.119     albertel  368:     &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
1.117     albertel  369:     my %memoized;
                    370:     if ($LONCAPA::CAPAresponse_answer->{'type'}  eq 'ordered') {
1.119     albertel  371: 	for (my $i=0; $i<scalar(@$responses);$i++) {
1.117     albertel  372: 	    my $answer   = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
1.119     albertel  373: 	    my $response = $responses->[$i];
1.117     albertel  374: 	    my $key = "$answer\0$response";
1.119     albertel  375: 	    my (@awards,@msgs);
                    376: 	    for (my $j=0; $j<scalar(@$response); $j++) { 
                    377: 		my ($award,$msg) = &caparesponse_check($answer->[$j],
                    378: 						       $response->[$j]);
                    379: 		push(@awards,$award);
                    380: 		push(@msgs,  $msg);
                    381: 	    }
                    382: 	    my ($award,$msg) = 
                    383: 		&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
                    384: 	    $memoized{$key} = [$award,$msg];
1.117     albertel  385: 	}
                    386:     } else {
1.119     albertel  387: 	#FIXME broken with unorder responses where one is a <value>
                    388:         #      and the other is a <vector> (need to delay parse til
                    389:         #      inside the loop?)
                    390: 	foreach my $response (@$responses) {
                    391: 	    my $response_size = scalar(@{$response});
1.117     albertel  392: 	    foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
                    393: 		my $key = "$answer\0$response";
1.119     albertel  394: 		my $answer_size =  scalar(@{$answer});
                    395: 		my ($award,$msg);
                    396: 		if ($answer_size > $response_size) {
                    397: 		    $award = 'MISSING_ANSWER';
                    398: 		} elsif ($answer_size < $response_size) {
                    399: 		    $award = 'EXTRA_ANSWER';
                    400: 		} else {
                    401: 		    my (@awards,@msgs);
                    402: 		    for (my $j=0; $j<scalar(@$response); $j++) {
                    403: 			my ($award,$msg) = &caparesponse_check($answer->[$j],
                    404: 							       $response->[$j]);
                    405: 			push(@awards,$award);
                    406: 			push(@msgs,  $msg);
                    407: 		    }
                    408: 		    ($award,$msg) = 
                    409: 			&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
                    410: 		}
                    411: 		$memoized{$key} = [$award,$msg];
1.117     albertel  412: 	    }
                    413: 	}
                    414:     }
                    415: 
1.116     albertel  416:     my ($final_award,$final_msg);
1.119     albertel  417:     &init_permutation(scalar(@$responses),
1.116     albertel  418: 		      $LONCAPA::CAPAresponse_answer->{'type'});
1.117     albertel  419: 
1.118     albertel  420:     # possible FIXMEs
                    421:     # - significant time is spent calling non-safe space routine
                    422:     #   from safe space
                    423:     # - early outs could be possible with classifying awards is to stratas
                    424:     #   and stopping as so as hitting the top strata 
                    425:     # - some early outs also might be possible with check ing the 
                    426:     #   memoized hash of results (is correct even possible? etc.)
                    427: 
1.117     albertel  428:     my (@final_awards,@final_msg);
1.116     albertel  429:     while( &get_permutations_left() ) {
1.117     albertel  430: 	my $order = &get_next_permutation();
1.116     albertel  431: 	my (@awards, @msgs, $i);
                    432: 	foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
1.119     albertel  433: 	    my $key = "$thisanswer\0".$responses->[$order->[$i]];
1.117     albertel  434: 	    push(@awards,$memoized{$key}[0]);
                    435: 	    push(@msgs,$memoized{$key}[1]);
1.116     albertel  436: 	    $i++;
1.119     albertel  437: 
1.116     albertel  438: 	}
1.119     albertel  439: 	&LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
                    440: 
1.116     albertel  441: 	my ($possible_award,$possible_msg) = 
                    442: 	    &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
1.119     albertel  443: 	&LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
1.117     albertel  444: 	push(@final_awards,$possible_award);
                    445: 	push(@final_msg,$possible_msg);
1.73      albertel  446:     }
1.117     albertel  447: 
1.119     albertel  448:     &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
1.117     albertel  449:     my ($final_award,$final_msg) = 
                    450: 	&LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
1.116     albertel  451:     return ($final_award,$final_msg);
1.7       albertel  452: }
                    453: 
1.4       albertel  454: sub tex {
1.73      albertel  455:     if ( $external::target eq "tex" ) {
                    456: 	return $_[0];
                    457:     } else {
                    458: 	return $_[1];
                    459:     }
1.4       albertel  460: }
                    461: 
1.24      ng        462: sub var_in_tex {
1.73      albertel  463:     if ( $external::target eq "tex" ) {
                    464: 	return $_[0];
                    465:     } else {
                    466: 	return "";
                    467:     }
1.24      ng        468: }
                    469: 
1.4       albertel  470: sub web {
1.73      albertel  471:     if ( $external::target eq "tex" ) {
                    472: 	return $_[1];
1.26      ng        473:     } else {
1.73      albertel  474: 	if ( $external::target eq "web" || $external::target eq "answer") {
                    475: 	    return $_[2];
                    476: 	} else {
                    477: 	    return $_[0];
                    478: 	}
1.4       albertel  479:     }
                    480: }
                    481: 
1.24      ng        482: sub html {
1.73      albertel  483:     if ( $external::target eq "web" ) {
                    484: 	return shift;
                    485:     }
1.24      ng        486: }
                    487: 
1.1       harris41  488: sub hinton {
1.73      albertel  489:     return 0;
1.1       harris41  490: }
                    491: 
                    492: sub random {
1.61      albertel  493:     my ($start,$end,$step)=@_;
                    494:     if ( ! $hidden::RANDOMINIT ) {
                    495: 	if ($external::randomseed == 0) { $external::randomseed=1; }
                    496: 	if ($external::randomseed =~/,/) {
1.84      albertel  497: 	    my ($num1,$num2)=split(/,/,$external::randomseed);
                    498: 	    &random_set_seed(1,abs($num1));
                    499: 	} elsif ($external::randomseed =~/:/) {
                    500: 	    my ($num1,$num2)=split(/:/,$external::randomseed);
1.61      albertel  501: 	    &random_set_seed(abs($num1),abs($num2));
                    502: 	} else {
                    503: 	    &random_set_seed(1,int(abs($external::randomseed)));
                    504: 	}
                    505: 	&math_random_uniform();
                    506: 	$hidden::RANDOMINIT=1;
                    507:     }
                    508:     if (!defined($step)) { $step=1; }
                    509:     my $num=1+int(($end-$start)/$step);
                    510:     my $result=$start + int(&math_random_uniform() * $num)*$step;
                    511:     return $result;
1.1       harris41  512: }
                    513: 
1.26      ng        514: sub random_normal {
1.73      albertel  515:     my ($item_cnt,$seed,$av,$std_dev) = @_;
                    516:     my @oldseed=&random_get_seed();
                    517:     my @retArray;
                    518:     &random_set_seed_from_phrase($seed);
                    519:     @retArray=&math_random_normal($item_cnt,$av,$std_dev);
                    520:     &random_set_seed(@oldseed);
                    521:     return @retArray;
1.26      ng        522: }
                    523: 
                    524: sub random_beta {
1.73      albertel  525:     my ($item_cnt,$seed,$aa,$bb) = @_;
                    526:     my @oldseed=&random_get_seed();
                    527:     my @retArray;
                    528:     &random_set_seed_from_phrase($seed);
                    529:     @retArray=&math_random_beta($item_cnt,$aa,$bb);
                    530:     &random_set_seed(@oldseed);
                    531:     return @retArray;
1.26      ng        532: }
                    533: 
                    534: sub random_gamma {
1.73      albertel  535:     my ($item_cnt,$seed,$a,$r) = @_;
                    536:     my @oldseed=&random_get_seed();
                    537:     my @retArray;
                    538:     &random_set_seed_from_phrase($seed);
                    539:     @retArray=&math_random_gamma($item_cnt,$a,$r);
                    540:     &random_set_seed(@oldseed);
                    541:     return @retArray;
1.26      ng        542: }
                    543: 
                    544: sub random_exponential {
1.73      albertel  545:     my ($item_cnt,$seed,$av) = @_;
                    546:     my @oldseed=&random_get_seed();
                    547:     my @retArray;
                    548:     &random_set_seed_from_phrase($seed);
                    549:     @retArray=&math_random_exponential($item_cnt,$av);
                    550:     &random_set_seed(@oldseed);
                    551:     return @retArray;
1.26      ng        552: }
                    553: 
                    554: sub random_poisson {
1.73      albertel  555:     my ($item_cnt,$seed,$mu) = @_;
                    556:     my @oldseed=&random_get_seed();
                    557:     my @retArray;
                    558:     &random_set_seed_from_phrase($seed);
                    559:     @retArray=&math_random_poisson($item_cnt,$mu);
                    560:     &random_set_seed(@oldseed);
                    561:     return @retArray;
1.26      ng        562: }
                    563: 
                    564: sub random_chi {
1.73      albertel  565:     my ($item_cnt,$seed,$df) = @_;
                    566:     my @oldseed=&random_get_seed();
                    567:     my @retArray;
                    568:     &random_set_seed_from_phrase($seed);
                    569:     @retArray=&math_random_chi_square($item_cnt,$df);
                    570:     &random_set_seed(@oldseed);
                    571:     return @retArray;
1.26      ng        572: }
                    573: 
                    574: sub random_noncentral_chi {
1.73      albertel  575:     my ($item_cnt,$seed,$df,$nonc) = @_;
                    576:     my @oldseed=&random_get_seed();
                    577:     my @retArray;
                    578:     &random_set_seed_from_phrase($seed);
                    579:     @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
                    580:     &random_set_seed(@oldseed);
                    581:     return @retArray;
1.26      ng        582: }
                    583: 
                    584: sub random_f {
1.73      albertel  585:     my ($item_cnt,$seed,$dfn,$dfd) = @_;
                    586:     my @oldseed=&random_get_seed();
                    587:     my @retArray;
                    588:     &random_set_seed_from_phrase($seed);
                    589:     @retArray=&math_random_f($item_cnt,$dfn,$dfd);
                    590:     &random_set_seed(@oldseed);
                    591:     return @retArray;
1.26      ng        592: }
                    593: 
                    594: sub random_noncentral_f {
1.73      albertel  595:     my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
                    596:     my @oldseed=&random_get_seed();
                    597:     my @retArray;
                    598:     &random_set_seed_from_phrase($seed);
                    599:     @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
                    600:     &random_set_seed(@oldseed);
                    601:     return @retArray;
1.26      ng        602: }
                    603: 
                    604: sub random_multivariate_normal {
1.73      albertel  605:     my ($item_cnt,$seed,$mean,$covar) = @_;
                    606:     my @oldseed=&random_get_seed();
                    607:     &random_set_seed_from_phrase($seed);
1.87      albertel  608:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
1.73      albertel  609:     &random_set_seed(@oldseed);
                    610:     return @retArray;
1.26      ng        611: }
                    612: 
                    613: sub random_multinomial {
1.73      albertel  614:     my ($item_cnt,$seed,@p) = @_;
                    615:     my @oldseed=&random_get_seed();
                    616:     my @retArray;
                    617:     &random_set_seed_from_phrase($seed);
1.87      albertel  618:     my @retArray=&math_random_multinomial($item_cnt,@p);
1.73      albertel  619:     &random_set_seed(@oldseed);
                    620:     return @retArray;
1.26      ng        621: }
                    622: 
                    623: sub random_permutation {
1.73      albertel  624:     my ($seed,@inArray) = @_;
                    625:     my @oldseed=&random_get_seed();
                    626:     my @retArray;
                    627:     &random_set_seed_from_phrase($seed);
                    628:     @retArray=&math_random_permutation(@inArray);
                    629:     &random_set_seed(@oldseed);
                    630:     return @retArray;
1.26      ng        631: }
                    632: 
                    633: sub random_uniform {
1.73      albertel  634:     my ($item_cnt,$seed,$low,$high) = @_;
                    635:     my @oldseed=&random_get_seed();
                    636:     my @retArray;
                    637:     &random_set_seed_from_phrase($seed);
                    638:     @retArray=&math_random_uniform($item_cnt,$low,$high);
                    639:     &random_set_seed(@oldseed);
                    640:     return @retArray;
1.26      ng        641: }
                    642: 
                    643: sub random_uniform_integer {
1.73      albertel  644:     my ($item_cnt,$seed,$low,$high) = @_;
                    645:     my @oldseed=&random_get_seed();
                    646:     my @retArray;
                    647:     &random_set_seed_from_phrase($seed);
                    648:     @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
                    649:     &random_set_seed(@oldseed);
                    650:     return @retArray;
1.26      ng        651: }
                    652: 
                    653: sub random_binomial {
1.73      albertel  654:     my ($item_cnt,$seed,$nt,$p) = @_;
                    655:     my @oldseed=&random_get_seed();
                    656:     my @retArray;
                    657:     &random_set_seed_from_phrase($seed);
                    658:     @retArray=&math_random_binomial($item_cnt,$nt,$p);
                    659:     &random_set_seed(@oldseed);
                    660:     return @retArray;
1.26      ng        661: }
                    662: 
                    663: sub random_negative_binomial {
1.73      albertel  664:     my ($item_cnt,$seed,$ne,$p) = @_;
                    665:     my @oldseed=&random_get_seed();
                    666:     my @retArray;
                    667:     &random_set_seed_from_phrase($seed);
                    668:     @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
                    669:     &random_set_seed(@oldseed);
                    670:     return @retArray;
1.26      ng        671: }
                    672: 
1.103     albertel  673: sub abs { CORE::abs(shift) }
                    674: sub sin { CORE::sin(shift) }
                    675: sub cos { CORE::cos(shift) }
                    676: sub exp { CORE::exp(shift) }
                    677: sub int { CORE::int(shift) }
                    678: sub log { CORE::log(shift) }
                    679: sub atan2 { CORE::atan2($_[0],$_[1]) }
                    680: sub sqrt { CORE::sqrt(shift) }
1.23      ng        681: 
1.59      albertel  682: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
1.21      harris41  683: #sub atan { atan2($_[0], 1); }
                    684: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
                    685: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
1.22      ng        686: 
1.59      albertel  687: sub log10 { CORE::log($_[0])/CORE::log(10); }
1.22      ng        688: 
1.20      harris41  689: sub factorial {
1.59      albertel  690:     my $input = CORE::int(shift);
1.20      harris41  691:     return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
                    692:     return "Error - factorial result is greater than system limit ($input)" if $input > 170;
                    693:     return 1 if $input == 0;
                    694:     my $result = 1; 
                    695:     for (my $i=2; $i<=$input; $i++) { $result *= $i }
                    696:     return $result;
                    697: }
                    698: 
                    699: sub sgn {
                    700:     return -1 if $_[0] < 0;
                    701:     return 0 if $_[0] == 0;
                    702:     return 1 if $_[0] > 0;
                    703: }
                    704: 
                    705: sub min {
                    706:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
                    707:     return shift @sorted;
                    708: }
                    709: 
                    710: sub max {
                    711:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
                    712:     return pop @sorted;
                    713: }
1.1       harris41  714: 
1.20      harris41  715: sub roundto {
                    716:     my ($input,$n) = @_;
                    717:     return sprintf('%.'.$n.'f',$input);
                    718: }
                    719: 
                    720: sub to_string {
                    721:     my ($input,$n) = @_;
1.26      ng        722:     return sprintf($input) if $n eq "";
                    723:     $n = '.'.$n if $n !~ /^\./;
1.20      harris41  724:     return sprintf('%'.$n,$input) if $n ne "";
                    725: }
                    726: 
                    727: sub sub_string {
                    728:     my ($str,$start,$len) = @_;
                    729:     return substr($str,$start-1,$len);
                    730: }
1.1       harris41  731: 
                    732: sub pow   {return $_[0] ** $_[1]; }
1.59      albertel  733: sub ceil  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
                    734: sub floor  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
1.27      ng        735: #sub floor {return int($_[0]); }
1.1       harris41  736: 
1.2       albertel  737: sub format {
1.73      albertel  738:     my ($value,$fmt)=@_;
1.81      albertel  739:     my ($dollarmode,$commamode,$alwaysperiod,$options);
                    740:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
                    741:     #if ($options =~ /\$/) { $dollamode=1; }
                    742:     #if ($options =~ /,/)  { $commamode=1; }
1.82      albertel  743:     if ($options =~ /\./) { $alwaysperiod=1; }
1.99      ng        744:     my $result;
1.97      albertel  745:     if ($fmt=~/s$/i) {
                    746: 	$result=&format_significant_figures($value,$fmt);
                    747:     } else {
                    748: 	$fmt=~s/e/E/g;
1.99      ng        749: 	$result=sprintf('%.'.$fmt,$value);
1.97      albertel  750: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
                    751: 	$result=~s/(E[+-]*)0/$1/;
                    752:     }
1.81      albertel  753:     #if ($dollarmode) {$result=&dollarformat($result);}
                    754:     #if ($commamode) {$result=&commaformat($result);}
1.73      albertel  755:     return $result;
1.46      albertel  756: }
                    757: 
1.75      albertel  758: sub chemparse {
                    759:     my ($reaction) = @_;
1.96      albertel  760:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
1.75      albertel  761:     my $formula = '';
                    762:     foreach my $token (@tokens) {
                    763: 	if ($token eq '->' ) {
                    764: 	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
                    765: 	    next;
                    766: 	}
1.96      albertel  767: 	if ($token eq '<-' ) {
                    768: 	    $formula .= '<m>\ensuremath{\leftarrow}</m> ';
                    769: 	    next;
                    770: 	}  
1.75      albertel  771: 	if ($token eq '<=>') {
                    772: 	    if ($external::target eq 'web' &&
                    773: 		&EXT('request.browser.unicode')) {
1.76      albertel  774: 		$formula .= '&#8652; ';
1.75      albertel  775: 	    } else {
                    776: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
1.95      albertel  777: 				 '&lt;=&gt; ');
1.75      albertel  778: 	    }
                    779: 	    next;
                    780: 	}
1.96      albertel  781: 	if ($token eq '.') {
                    782: 	  $formula =~ s/(\&nbsp\;| )$//;
                    783: 	  $formula .= '&middot;';
                    784: 	  next;
                    785: 	}
                    786: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
1.90      albertel  787:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
1.75      albertel  788: 	
                    789: 	my $molecule = $2;
                    790: 	# subscripts
1.78      albertel  791: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
1.75      albertel  792: 	# superscripts
                    793: 	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
                    794: 	# strip whitespace
                    795: 	$molecule =~ s/\s*//g;
                    796: 	# forced space
                    797: 	$molecule =~ s/_/ /g;
1.96      albertel  798: 	$molecule =~ s/-/&minus;/g;
1.75      albertel  799: 	$formula .= $molecule.'&nbsp;';
                    800:     }
                    801:     # get rid of trailing space
1.87      albertel  802:     $formula =~ s/(\&nbsp\;| )$//;
1.75      albertel  803:     return &xmlparse($formula);
                    804: }
                    805: 
1.46      albertel  806: sub prettyprint {
1.73      albertel  807:     my ($value,$fmt,$target)=@_;
                    808:     my $result;
                    809:     if (!$target) { $target = $external::target; }
1.75      albertel  810:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
1.81      albertel  811:     my ($dollarmode,$commamode,$alwaysperiod,$options);
                    812:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
1.86      albertel  813:     if ($options =~ /\$/) { $dollarmode=1; }
1.81      albertel  814:     if ($options =~ /,/)  { $commamode=1; }
                    815:     if ($options =~ /\./) { $alwaysperiod=1; }
1.97      albertel  816:     if ($fmt=~/s$/i) {
                    817: 	$value=&format_significant_figures($value,$fmt);
                    818:     } elsif ($fmt) {
                    819: 	$value=sprintf('%.'.$fmt,$value);
                    820:     }
1.81      albertel  821:     if ($alwaysperiod && $fmt eq '0f') {
                    822: 	if ($target eq 'tex') {
                    823: 	    $value .='\\ensuremath{.}';
                    824: 	} else {
                    825: 	    $value .='.';
                    826: 	}
                    827:     }
1.73      albertel  828:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
                    829: 	my $frac=$1;
                    830: 	if ($dollarmode) { $frac=&dollarformat($frac); }
1.80      albertel  831: 	if ($commamode) { $frac=&commaformat($frac); }
1.73      albertel  832: 	my $exponent=$2;
                    833: 	$exponent=~s/^\+0*//;
                    834: 	$exponent=~s/^-0*/-/;
                    835: 	$exponent=~s/^-0*/-/;
                    836: 	if ($exponent eq '-') { undef($exponent); }
                    837: 	if ($exponent) {
                    838: 	    if ($target eq 'web') {
                    839: 		$result=$frac.'&#215;10<sup>'.$exponent.'</sup>';
                    840: 	    } elsif ($target eq 'tex') {
                    841: 		$result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
                    842: 	    } else {
                    843: 		$result=$value;
                    844: 	    }
                    845: 	} else {
                    846: 	    $result=$frac;
                    847: 	}
                    848:     } else {
1.48      albertel  849: 	$result=$value;
1.86      albertel  850: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
                    851: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
1.46      albertel  852:     }
1.73      albertel  853:     return $result;
1.48      albertel  854: }
                    855: 
1.80      albertel  856: sub commaformat {
1.73      albertel  857:     my ($number,$target) = @_;
                    858:     if ($number =~ /\./) {
1.102     albertel  859: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
                    860: 	    $number = $1.$2.','.$3.$4;
1.73      albertel  861: 	}
                    862:     } else {
1.102     albertel  863: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
                    864: 	    $number = $1.$2.','.$3.$4;
1.73      albertel  865: 	}
                    866:     }
1.80      albertel  867:     return $number;
                    868: }
                    869: 
                    870: sub dollarformat {
                    871:     my ($number,$target) = @_;
                    872:     if (!$target) { $target = $external::target; }
                    873:     $number=&commaformat($number,$target);
1.73      albertel  874:     if ($target eq 'tex') {
                    875: 	$number='\$'.$number; #' stupid emacs
                    876:     } else {
                    877: 	$number='$'.$number; #' stupid emacs
                    878:     }
                    879:     return $number; 
1.2       albertel  880: }
1.5       albertel  881: 
1.97      albertel  882: # format of form ns or nS where n is an integer
                    883: sub format_significant_figures {
                    884:     my ($number,$format) = @_; 
                    885:     return '0' if ($number == 0);
                    886:     # extract number of significant figures needed
                    887:     my ($sig) = ($format =~ /(\d+)s/i);
                    888:     # arbitrary choice - suggestions ?? or throw error message?
                    889:     $sig = 3 if ($sig eq '');
                    890:     # save the minus sign
                    891:     my $sign = ($number < 0) ? '-' : '';
                    892:     $number = abs($number);
                    893:     # needed to correct for a number greater than 1 (or
                    894:     my $power = ($number < 1) ? 0 : 1;
                    895:     # could round up. Take the integer part of log10.
                    896:     my $x10 = int(log($number)/log(10));
                    897:     # find number with values left of decimal pt = # of sign figs.
                    898:     my $xsig = $number*10**($sig-$x10-$power);
                    899:     # get just digits left of decimal pt - also rounds off correctly
                    900:     my $xint  = sprintf('%.0f',$xsig);
                    901:     # save any trailing zero's
                    902:     my ($zeros) = ($xint =~ /(0+)$/);
                    903:     # return number to original magnitude
                    904:     my $numSig = $xint*10**($x10-$sig+$power);
                    905:     # insert trailing zero's if have decimal point
                    906:     $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1.98      albertel  907:     # put a decimal pt for number ending with 0 and length = # of sig fig
                    908:     $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
                    909:     if (length($numSig) < $sig) {
                    910: 	$numSig.='.'.substr($zeros,0,($sig-length($numSig)));
                    911:     }
1.97      albertel  912:     # return number with sign
                    913:     return $sign.$numSig;
                    914: 
                    915: }
                    916: 
1.5       albertel  917: sub map {
1.27      ng        918:     my ($phrase,$dest,$source)=@_;
1.51      albertel  919:     my @oldseed=&random_get_seed();
1.27      ng        920:     my @seed = &random_seed_from_phrase($phrase);
                    921:     &random_set_seed(@seed);
                    922:     my $destct = scalar(@$dest);
1.28      ng        923:     if (!$source) {
                    924: 	my @output;
                    925: 	my @idx = &math_random_permuted_index($destct);
                    926: 	my $ctr = 0;
                    927: 	while ($ctr < $destct) {
                    928: 	    $output[$ctr] = $$dest[$idx[$ctr]];
1.27      ng        929: 	    $ctr++;
1.28      ng        930: 	}
1.51      albertel  931:         &random_set_seed(@oldseed);
1.28      ng        932: 	return @output;
1.27      ng        933:     } else {
1.28      ng        934: 	my $num = scalar(@$source);
                    935: 	my @idx = &math_random_permuted_index($num);
                    936: 	my $ctr = 0;
                    937: 	my $tot = $num;
                    938: 	$tot = $destct if $destct < $num;
                    939: 	if (ref($$dest[0])) {
                    940: 	    while ($ctr < $tot) {
                    941: 		${$$dest[$ctr]} = $$source[$idx[$ctr]];
                    942: 	        $ctr++;
                    943:             }
                    944:         } else {
                    945: 	    while ($ctr < $tot) {
                    946: 		$$dest[$ctr] = $$source[$idx[$ctr]];
                    947: 		$ctr++;
                    948: 	    }
                    949: 	}
1.27      ng        950:     }
1.56      albertel  951:     &random_set_seed(@oldseed);
1.51      albertel  952:     return '';
1.27      ng        953: }
                    954: 
                    955: sub rmap {
                    956:     my ($phrase,$dest,$source)=@_;
1.51      albertel  957:     my @oldseed=&random_get_seed();
1.27      ng        958:     my @seed = &random_seed_from_phrase($phrase);
                    959:     &random_set_seed(@seed);
                    960:     my $destct = scalar(@$dest);
1.28      ng        961:     if (!$source) {
                    962: 	my @idx = &math_random_permuted_index($destct);
                    963: 	my $ctr = 0;
                    964: 	my @r_idx;
                    965: 	while ($ctr < $destct) {
                    966: 	    $r_idx[$idx[$ctr]] = $ctr;
                    967: 	    $ctr++;
                    968: 	}
                    969: 	my @output;
                    970: 	$ctr = 0;
                    971: 	while ($ctr < $destct) {
                    972: 	    $output[$ctr] = $$dest[$r_idx[$ctr]];
1.27      ng        973: 	    $ctr++;
1.28      ng        974: 	}
1.51      albertel  975:         &random_set_seed(@oldseed);
1.28      ng        976: 	return @output;
1.27      ng        977:     } else {
1.28      ng        978: 	my $num = scalar(@$source);
                    979: 	my @idx = &math_random_permuted_index($num);
                    980: 	my $ctr = 0;
                    981: 	my $tot = $num;
                    982: 	$tot = $destct if $destct < $num;
                    983: 	my @r_idx;
1.27      ng        984: 	while ($ctr < $tot) {
1.28      ng        985: 	    $r_idx[$idx[$ctr]] = $ctr;
1.27      ng        986: 	    $ctr++;
1.28      ng        987: 	}
                    988: 	$ctr = 0;
                    989: 	if (ref($$dest[0])) {
                    990: 	    while ($ctr < $tot) {
                    991: 		${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
                    992: 	        $ctr++;
                    993:             }
                    994:         } else {
                    995: 	    while ($ctr < $tot) {
                    996: 		$$dest[$ctr] = $$source[$r_idx[$ctr]];
                    997: 		$ctr++;
                    998: 	    }
                    999: 	}
1.6       albertel 1000:     }
1.51      albertel 1001:     &random_set_seed(@oldseed);
                   1002:     return '';
1.5       albertel 1003: }
1.22      ng       1004: 
1.23      ng       1005: sub capa_id { return }
                   1006: 
                   1007: sub problem { return }
                   1008: 
1.22      ng       1009: sub name{
1.73      albertel 1010:     my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
                   1011:     $fullname = "" if $fullname eq ",  ";
                   1012:     $fullname =~ s/\%2d/-/g;
                   1013:     return $fullname;
1.22      ng       1014: }
                   1015: 
                   1016: sub student_number { 
1.73      albertel 1017:     my $id = &EXT('environment.id');
                   1018:     $id = '' if $id eq "";
                   1019:     return $id;
1.22      ng       1020: }
                   1021: 
                   1022: sub class {
1.73      albertel 1023:     my $course = &EXT('course.description');
                   1024:     $course = '' if $course eq "";
                   1025:     return $course;
1.22      ng       1026: }
                   1027: 
1.112     www      1028: sub firstname {
                   1029:     my $firstname = &EXT('environment.firstname');
                   1030:     $firstname = '' if $firstname eq "";
                   1031:     return $firstname;
                   1032: }
                   1033:                                                                                 
                   1034: sub lastname {
                   1035:     my $lastname = &EXT('environment.lastname');
                   1036:     $lastname = '' if $lastname eq "";
                   1037:     return $lastname;
                   1038: }
                   1039: 
1.22      ng       1040: sub sec { 
1.73      albertel 1041:     my $sec = &EXT('request.course.sec');
                   1042:     $sec = '' if $sec eq "";
                   1043:     return $sec;
1.22      ng       1044: }
                   1045: 
1.23      ng       1046: sub open_date { 
1.73      albertel 1047:     my @dc = split(/\s+/,localtime(&EXT('resource.0.opendate')));
                   1048:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
                   1049:     my @hm = split(/:/,$dc[3]);
                   1050:     my $ampm = " am";
                   1051:     if ($hm[0] > 12) {
                   1052: 	$hm[0]-=12;
                   1053: 	$ampm = " pm";
                   1054:     }
                   1055:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.23      ng       1056: }
                   1057: 
                   1058: sub due_date { 
1.73      albertel 1059:     my @dc = split(/\s+/,localtime(&EXT('resource.0.duedate')));
                   1060:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
                   1061:     my @hm = split(/:/,$dc[3]);
                   1062:     my $ampm = " am";
                   1063:     if ($hm[0] > 12) {
                   1064: 	$hm[0]-=12;
                   1065: 	$ampm = " pm";
                   1066:     }
                   1067:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.23      ng       1068: }
                   1069: 
                   1070: sub answer_date { 
1.73      albertel 1071:     my @dc = split(/\s+/,localtime(&EXT('resource.0.answerdate')));
                   1072:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
                   1073:     my @hm = split(/:/,$dc[3]);
                   1074:     my $ampm = " am";
                   1075:     if ($hm[0] > 12) {
                   1076: 	$hm[0]-=12;
                   1077: 	$ampm = " pm";
                   1078:     }
                   1079:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.24      ng       1080: }
                   1081: 
                   1082: sub array_moments {
1.73      albertel 1083:     my @input=@_;
                   1084:     my (@output,$N);
                   1085:     $N=scalar (@input);
                   1086:     $output[0]=$N;
                   1087:     if ($N <= 1) {
                   1088: 	$output[1]=$input[0];
                   1089: 	$output[1]="Input array not defined" if ($N == 0);
                   1090: 	$output[2]="variance undefined for N<=1";
                   1091: 	$output[3]="skewness undefined for N<=1";
                   1092: 	$output[4]="kurtosis undefined for N<=1";
                   1093: 	return @output;
                   1094:     }
                   1095:     my $sum=0;
                   1096:     foreach my $line (@input) {
                   1097: 	$sum+=$line;
                   1098:     }
                   1099:     $output[1] = $sum/$N;
                   1100:     my ($x,$sdev,$var,$skew,$kurt) = 0;
                   1101:     foreach my $line (@input) {
                   1102: 	$x=$line-$output[1];
                   1103: 	$var+=$x**2;
                   1104: 	$skew+=$x**3;
                   1105: 	$kurt+=$x**4;
                   1106:     }
                   1107:     $output[2]=$var/($N-1);
                   1108:     $sdev=CORE::sqrt($output[2]);
                   1109:     if ($sdev == 0) {
                   1110: 	$output[3]="inf-variance=0";
                   1111: 	$output[4]="inf-variance=0";
                   1112: 	return @output;
                   1113:     }
                   1114:     $output[3]=$skew/($sdev**3*$N);
                   1115:     $output[4]=$kurt/($sdev**4*$N)-3;
1.24      ng       1116:     return @output;
                   1117: }
1.5       albertel 1118: 
                   1119: sub choose {
1.73      albertel 1120:     my $num = $_[0];
                   1121:     return $_[$num];
1.5       albertel 1122: }
1.23      ng       1123: 
1.101     albertel 1124: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
                   1125: #sub sum1 {
                   1126: #    my ($start,$end,$sub)=@_;
                   1127: #    my $sum=0;
                   1128: #    for (my $i=$start;$i<=$end;$i++) {
                   1129: #        $sum+=&$sub($i);
                   1130: #    }
                   1131: #    return $sum
                   1132: #}
                   1133: 
                   1134: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
                   1135: #sub sum2 {
                   1136: #    my ($varname,$start,$end,$line)=@_;
                   1137: #    my $sum=0;
                   1138: #    for (my $i=$start;$i<=$end;$i++) {
                   1139: #	my $func=sub {
                   1140: #	    eval("\$".$varname."=$i");
                   1141: #	    eval($line);
                   1142: #	};
                   1143: #        $sum+=&$func($i);
                   1144: #    }
                   1145: #    return $sum
                   1146: #}
                   1147: 
1.49      albertel 1148: # expiremental idea
                   1149: sub proper_path {
1.73      albertel 1150:     my ($path)=@_;
                   1151:     if ( $external::target eq "tex" ) {
                   1152: 	return '/home/httpd/html'.$path;
                   1153:     } else {
                   1154: 	return $path;
                   1155:     }
1.49      albertel 1156: }
1.23      ng       1157: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>