Problem http://nabetani.sakura.ne.jp/hena/orde05dokitruck/ Implementation links http://qiita.com/Nabetani/items/c516875b13a4d282affe is.
so.
There are several implementation policies.
I'm going to choose freely around.
I calculated from behind at once, and the data is a bit.
First, implementation by C11 or C99:
// clang -std=c11 -Wall
// clang x86_64-apple-darwin15.5.0
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <memory.h>
char * build_ans( int s )
{
char * r = calloc(4, 1);
for( int i=0 ; i<3 ; ++i ){
if ( s&(1<<i) ){
strcat( r, (char[2]){'a'+i});
}
}
if ( !*r ){
r[0]='-';
}
return r;
}
char * solve( char const * src )
{
int s=7;
for( char const * it = src + strlen( src ) -1 ; src<=it ; --it ){
switch(*it-'0'){
case 1: s|=s/2; break;
case 2: s|=(s&2)*2+!!(s&4); break;
case 3: s|=!!(s&4)+(s&1)*2; break;
case 4: s|=s*2; break;
case 5: s|=(s&1)*4+(s&4)/2; break;
case 6: s|=(s&1)*4+!!(s&2); break;
case 7: s&=5; break;
case 8: s&=6; break;
case 9: s&=3; break;
}
}
return build_ans(s);
}
void test( char const * src, char const * expected )
{
char const * actual = solve( src );
bool okay = 0==strcmp( actual, expected );
printf( "%s %s->%s ( e:%s )\n", ( okay ? "ok" : "**NG**" ), src, actual , expected );
free( actual );
}
int main()
{
/*0*/ test( "1728398", "bc" );
//Abbreviation
/*36*/ test( "697535114542", "ac" );
return 0;
}
As usual, most of the test data is omitted.
There are three states, life and death, so it can be expressed in 3 bits.
Since the life is set to 1, "& =
" brings death and increases the possibility that "| =
" will live.
The inside of solve
is messed up, but it can't be helped because it expresses the messiness of the blocks that make up the course.
It would be cool to have it as data, but this time it is expressed in code.
As a reminder, "!!
" means a calculation to the effect that logic denial is performed twice and non-zero is set to 1.
The following is a calculation written in ruby with exactly the same purpose. Or rather, I wrote it in ruby earlier.
def apply( s, c )
case c
when "0"; s
when "1"; s | s[1] | s[2]*2
when "2"; s | s[1]*4 | s[2]
when "3"; s | s[0]*2 | s[2]
when "4"; s | s[0]*2 | s[1]*4
when "5"; s | s[0]*4 | s[2]*2
when "6"; s | s[0]*4 | s[1]
when "7"; s & 5
when "8"; s & 6
when "9"; s & 3
end
end
def solve( src )
r=src.chars.reverse.inject(7) do |s,c|
apply( s, c )
end
%w( a b c ).each.with_index(0).map{ |c,ix|
r[ix]==0 ? "" : c
}.join.tap{ |x| return x.empty? ? "-" : x }
end
$stdout.sync=true
DATA.map do |line|
num, src, expected = line.split(/\s+/)
actual = solve( src )
okay = actual==expected
puts( "%s %2d %s->%s ( e:%s )" % [ ( okay ? "ok" : "**NG**" ), num, src, actual, expected ] )
okay
end.all?.tap{|x| puts( x ? "everything is ok" : "something wrong" ) }
__END__
0 1728398 bc
1 789 -
2 274 ac
3 185 abc
36 697535114542 ac
Even bit operations are easier to write with ruby.
Recommended Posts