Esempio n. 1
0
void start() {
    char name[20];
    char size[1];
    int sizes;
    printf("Sudoku Board Sizes:\na. 1\nb. 4\nc. 9\nd. 16\ne. 25\n\nEnter letter: ");
    scanf("%s", size);
    if (AreEqual(size, "a")) {
        sizes = 1;
    }else if (AreEqual(size, "b")) {
        sizes = 4;
    }else if (AreEqual(size, "c")) {
        sizes = 9;
    }else if (AreEqual(size, "d")) {
        sizes = 16;
    }else if (AreEqual(size, "e")) {
        sizes = 25;
    }
    boardSize = sizes;
    int grid[25][25];
    printf("\nEnter File Name: ");
    scanf("%s", name);
    FILE* fp = fopen(name, "r");
    subBoard = (sqrt(boardSize));

    if (fp == NULL) {
        // char save[20];
        // printf("Save Results to:\n");
        // scanf("%s", save);
        // FILE* ofp = fopen(save, "w");
        //fprintf(ofp, "Error: No Such File or Directory!\n");
        printf("\nError: No Such File or Directory!\n\n");
        system("pause");
        //fclose(ofp);
        exit(1);
    } else /*if (elementCount(fp) == 81)*/ {
        for (int i = 0; i < boardSize; i++) {
            for (int j = 0; j < boardSize; j++) {
                fscanf(fp, "%d", &grid[i][j]);
            }
        }
        memcpy(table, grid, sizeof(table));
        solveSudoku(0, 0); // The solving starts by passing parameters
        exit(1);
    } /*else {
        char save[20];
        printf("Save Results to:\n");
        scanf("%s", save);
        FILE* ofp = fopen(save, "w");
        fprintf(ofp, "Error: Invalid Sudoku Inputs!\n");
        fclose(ofp);
        exit(1);
    }*/
    fclose(fp);
    exit(1);
}
// Spherical linear interpolation of two quaternions p and q, with parameter t, result in slerp
void Slerp
(
	const CQuaternion& p,
	const CQuaternion& q,
	const TFloat32     t,
	CQuaternion&       slerp
)
{
	// Slerp formula: qt = (sin((1-t)*theta)*p + sin(t*theta)*q) / sin theta , theta is angle
	// between quaternions. First get cos of angle between quaternions - can use dot product if
	// we assume our quaternions are normalised
	TFloat32 cosTheta = Dot( p, q );

	// Two routes round a circle from q0 to q1, choose the short one with this test
	if (cosTheta >= 0.0f)
	{
		// Slerp formula prone to error with small angles, ensure that is not the case
		if (!AreEqual( cosTheta, 1.0f ))
		{
			// Slerp calculation
			TFloat32 theta = ACos( cosTheta );
			
			// Now we have p, q, t and theta. Calculate slerp from the equation in the notes
			TFloat32 invSinTheta = 1.0f / Sin( theta );
			TFloat32 w1 = Sin( (1.0f-t)*theta ) * invSinTheta;
			TFloat32 w2 = Sin( t*theta ) * invSinTheta;
			slerp = p*w1 + q*w2;
		}
		else
		{
			// Small angle - lerp calculation is better
			slerp = p*(1.0f-t) + q*t;
		}
	}
	else
	{
		// Want opposite route round circle - negate first quaternion, otherwise same formula
		if (!AreEqual( cosTheta, -1.0f ))
		{
			TFloat32 theta = ACos( -cosTheta);

			// Same calculation as above but use (t-1) instead of (1-t), to perform negation
			TFloat32 invSinTheta = 1.0f / Sin( theta );
			TFloat32 w1 = Sin( (t-1.0f)*theta ) * invSinTheta;
			TFloat32 w2 = Sin( t*theta ) * invSinTheta;
			slerp = p*w1 + q*w2;
		}
		else
		{
			// Small angle - lerp calculation is better, but use (t-1) instead of (1-t)
			slerp = p*(t-1.0f) + q*t;
		}
	}
}
Esempio n. 3
0
/** Returns 1 if vectors are parallel OR anti-parallel */
static FORCEINLINE bool AreParallel(const FVector& a, const FVector& b)
{
    float Dot = a | b;

    if( AreEqual(FMath::Abs(Dot), 1.f) )
    {
        return true;
    }
    else
    {
        return false;
    }
}
Esempio n. 4
0
File: main.cpp Progetto: mboghiu/try
int main()
{
    AreEqual("dcba", Reverse("abcd"));
    AreEqual("cba", Reverse("abc"));
    AreEqual("aA", Reverse("Aa"));
    AreEqual("airaM", Reverse("Maria"));
    AreEqual("xelA", Reverse("Alex"));
    AreEqual("", Reverse(""));

    return 0;
}
Esempio n. 5
0
void WriteBufferAndReadOneByteSuccessful(struct test_result *testResult)
{
    int buf_size = 0x20;
    char input[] = {(char) 0xBB};
    int input_size = 1;
    char *output = NULL;

    Log(L_INFO, "Start WriteBufferAndReadOneByteSuccessful");
    output = malloc(buf_size * sizeof(char));
    Assert(CreateBuffer(buf_size) == buf_size, testResult);
    Assert(WriteBuffer(input, input_size) == input_size, testResult);
    Assert(ReadBuffer(output, input_size) == input_size, testResult);
    Assert(AreEqual(input, output, input_size), testResult);

    ReleaseBuffer();
    free(output);
    if (testResult->status == STATUS_INCOMPLETE) {
        testResult->status = STATUS_PASS;
    }
}
Esempio n. 6
0
void CompletelyFillAndEmptyBuffer(struct test_result *testResult)
{
    /* Setup */
    int buf_size = 8;
    char input[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
    int input_size = 8;
    char *output = NULL;

    Log(L_INFO, "Start CompletelyFillAndEmptyBuffer");
    /* Test */
    output = malloc(sizeof(char) * input_size);
    Assert(CreateBuffer(buf_size) == buf_size, testResult);
    Assert(WriteBuffer(input, input_size) == input_size, testResult);
    Assert(ReadBuffer(output, input_size) == input_size, testResult);
    Assert(AreEqual(input, output, input_size), testResult);

    /* Cleanup */
    ReleaseBuffer();
    free(output);
    if (testResult->status == STATUS_INCOMPLETE) {
        testResult->status = STATUS_PASS;
    }
}
Esempio n. 7
0
/**
 *	Function for adding a box collision primitive to the supplied collision geometry based on the mesh of the box.
 *
 *	We keep a list of triangle normals found so far. For each normal direction,
 *	we should have 2 distances from the origin (2 parallel box faces). If the
 *	mesh is a box, we should have 3 distinct normal directions, and 2 distances
 *	found for each. The difference between these distances should be the box
 *	dimensions. The 3 directions give us the key axes, and therefore the
 *	box transformation matrix. This shouldn't rely on any vertex-ordering on
 *	the triangles (normals are compared +ve & -ve). It also shouldn't matter
 *	about how many triangles make up each side (but it will take longer).
 *	We get the centre of the box from the centre of its AABB.
 */
void AddBoxGeomFromTris( const TArray<FPoly>& Tris, FKAggregateGeom* AggGeom, const TCHAR* ObjName )
{
    TArray<FPlaneInfo> Planes;

    for(int32 i=0; i<Tris.Num(); i++)
    {
        bool bFoundPlane = false;
        for(int32 j=0; j<Planes.Num() && !bFoundPlane; j++)
        {
            // if this triangle plane is already known...
            if( AreParallel( Tris[i].Normal, Planes[j].Normal ) )
            {
                // Always use the same normal when comparing distances, to ensure consistent sign.
                float Dist = Tris[i].Vertices[0] | Planes[j].Normal;

                // we only have one distance, and its not that one, add it.
                if( Planes[j].DistCount == 1 && !AreEqual(Dist, Planes[j].PlaneDist[0]) )
                {
                    Planes[j].PlaneDist[1] = Dist;
                    Planes[j].DistCount = 2;
                }
                // if we have a second distance, and its not that either, something is wrong.
                else if( Planes[j].DistCount == 2 && !AreEqual(Dist, Planes[j].PlaneDist[1]) )
                {
                    UE_LOG(LogStaticMeshEdit, Log, TEXT("AddBoxGeomFromTris (%s): Found more than 2 planes with different distances."), ObjName);
                    return;
                }

                bFoundPlane = true;
            }
        }

        // If this triangle does not match an existing plane, add to list.
        if(!bFoundPlane)
        {
            check( Planes.Num() < Tris.Num() );

            FPlaneInfo NewPlane;
            NewPlane.Normal = Tris[i].Normal;
            NewPlane.DistCount = 1;
            NewPlane.PlaneDist[0] = Tris[i].Vertices[0] | NewPlane.Normal;

            Planes.Add(NewPlane);
        }
    }

    // Now we have our candidate planes, see if there are any problems

    // Wrong number of planes.
    if(Planes.Num() != 3)
    {
        UE_LOG(LogStaticMeshEdit, Log, TEXT("AddBoxGeomFromTris (%s): Not very box-like (need 3 sets of planes)."), ObjName);
        return;
    }

    // If we don't have 3 pairs, we can't carry on.
    if((Planes[0].DistCount != 2) || (Planes[1].DistCount != 2) || (Planes[2].DistCount != 2))
    {
        UE_LOG(LogStaticMeshEdit, Log, TEXT("AddBoxGeomFromTris (%s): Incomplete set of planes (need 2 per axis)."), ObjName);
        return;
    }

    FMatrix BoxTM = FMatrix::Identity;

    BoxTM.SetAxis(0, Planes[0].Normal);
    BoxTM.SetAxis(1, Planes[1].Normal);

    // ensure valid TM by cross-product
    FVector ZAxis = Planes[0].Normal ^ Planes[1].Normal;

    if( !AreParallel(ZAxis, Planes[2].Normal) )
    {
        UE_LOG(LogStaticMeshEdit, Log, TEXT("AddBoxGeomFromTris (%s): Box axes are not perpendicular."), ObjName);
        return;
    }

    BoxTM.SetAxis(2, ZAxis);

    // OBB centre == AABB centre.
    FBox Box(0);
    for(int32 i=0; i<Tris.Num(); i++)
    {
        Box += Tris[i].Vertices[0];
        Box += Tris[i].Vertices[1];
        Box += Tris[i].Vertices[2];
    }

    BoxTM.SetOrigin( Box.GetCenter() );

    // Allocate box in array
    FKBoxElem BoxElem;
    BoxElem.SetTransform( FTransform( BoxTM ) );
    // distance between parallel planes is box edge lengths.
    BoxElem.X = FMath::Abs(Planes[0].PlaneDist[0] - Planes[0].PlaneDist[1]);
    BoxElem.Y = FMath::Abs(Planes[1].PlaneDist[0] - Planes[1].PlaneDist[1]);
    BoxElem.Z = FMath::Abs(Planes[2].PlaneDist[0] - Planes[2].PlaneDist[1]);
    AggGeom->BoxElems.Add(BoxElem);
}
bool V4MagnitudeTest::DoTest()
{
	float Result = m_oVector.GetMagnitude();
	cout<< "\n---------------V4MagnitudeTest---------------\n";
	return AreEqual(Result, m_fResult);
}
Esempio n. 9
0
bool CRemoteConsole :: Update( void *fd )
{
	if( !m_Socket )
		return true;
	sockaddr_in recvAddr;
	string recvString;
	m_Socket->RecvFrom( (fd_set *)fd, &recvAddr, &recvString);

	if( !recvString.empty( ) )
	{
		// erase newline if found
		if ( /*!recvString.empty( ) &&*/ recvString[recvString.size()-1] == '\n' )
			recvString.erase( recvString.size()-1, 1 );
		string cmd, payload, target = "";
		SplitLine( recvString, cmd, payload, target );
		CRemoteConsoleClient *client = NULL;
		for( vector<CRemoteConsoleClient *> :: iterator i = m_KnownClients.begin( ); i != m_KnownClients.end( ); i++ )
		{
			if( AreEqual( (*i)->GetEndPoint( ), &recvAddr , true) )
			{
				client = *i;
				// update LastReceived time
				client->Pong( );
				break;
			}
		}

		if( !client )
		{
			// client is not known yet
			if( recvAddr.sin_addr.s_addr == localhost.s_addr || ( !m_Password.empty( ) && cmd == "rcon_password" && payload == m_Password ) )
			{
				// client has authed himself
				client = new CRemoteConsoleClient( m_Socket, recvAddr, -1, true );
				client->Send( "[RCON] You are now authed" );
				CONSOLE_Print("[RCON] User [" + client->GetIPString( ) + "] is now authorized");
				m_KnownClients.push_back( client );
			}
			else if( cmd == "rcon_broadcast" && payload.empty( ) )
			{
				bool authorized = false;
				if( !authorized )
					for( vector<CRemoteConsoleClient *> :: iterator i = m_KnownClients.begin( ); i != m_KnownClients.end( ); i++ )
					{
						// only respond if IP is already connected and authed as rcon user
						if( AreEqual( (*i)->GetEndPoint( ), &recvAddr, false ) && (*i)->IsAuthed( ) )
						{
							authorized = true;
							break;
						}
					}
				if( authorized || m_AnonymousBroadcast )
				{
					if( m_GHost->m_CurrentGame )
						m_GHost->m_CurrentGame->SendGame( m_Socket, recvAddr );

					if( m_GHost->m_AdminGame && ( authorized || m_AnonymousAdminGame ) )
						m_GHost->m_AdminGame->SendGame( m_Socket, recvAddr );
				}
				else
				{
					// ban client for 5 seconds for not being authorized
					client = new CRemoteConsoleClient( m_Socket, recvAddr, 5 , false);
					m_KnownClients.push_back( client );
					CONSOLE_Print("[RCON] User [" + client->GetIPString( ) + "] is not allowed to receive broadcasts");
				}
			}
			else
			{
				// ban client for 5 seconds for sending an unkown command or the wrong password
				client = new CRemoteConsoleClient( m_Socket, recvAddr, 5, false );
				m_KnownClients.push_back( client );
				CONSOLE_Print("[RCON] User [" + client->GetIPString( ) + "] failed to authenticate");
			}
		}
		else if( client->IsBanned( ) )
		{
			// we have seen this user before, but he is banned
			CONSOLE_Print("[RCON] Banned user [" + client->GetIPString( ) + "] tried to execute command [" + recvString + "]");
		}
		else if( !client->IsAuthed( ) )
		{
			// we have seen this user before, but he hasn't provided the right login credentials yet
			if( !m_Password.empty( ) && cmd == "rcon_password" && payload == m_Password )
			{
				client->Send( "[RCON] You are now authed" );
				CONSOLE_Print("[RCON] User [" + client->GetIPString( ) + "] is now authorized");
				client->SetAuthed( true );
			}
			else
			{
				// ban client for 5 seconds for sending an unkown command or the wrong password
				client->Ban( 5 );
				CONSOLE_Print("[RCON] User [" + client->GetIPString( ) + "] failed to authenticate");
			}
		}
		else if( cmd == "rcon_password" )
		{
			// client is already authed and tries to auth again, just tell him he is now authed
			client->Send( "[RCON] You are now authed" );
		}
		else if( cmd == "rcon_sendlobbychat" )
		{
			if ( m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetGameLoading( ) && !m_GHost->m_CurrentGame->GetGameLoaded( ) )
				m_GHost->m_CurrentGame->SendAllChat( payload );
		}
		else if( cmd == "rcon_kick" )
		{
			if ( m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetGameLoading( ) && !m_GHost->m_CurrentGame->GetGameLoaded( ) )
			{
				CGamePlayer *player = m_GHost->m_CurrentGame->GetPlayerFromName( payload, true );
				if( player )
				{
					player->SetDeleteMe( true );
					player->SetLeftReason( m_GHost->m_Language->WasKickedByPlayer( "Remote Console" ) );
					player->SetLeftCode( PLAYERLEAVE_LOBBY );
					m_GHost->m_CurrentGame->OpenSlot( m_GHost->m_CurrentGame->GetSIDFromPID( player->GetPID( ) ), false );
				}
			}
		}
		// disabled for now
		/*else if( cmd == "rcon_gamedetails" )
		{
			if( m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetGameLoading( ) && !m_GHost->m_CurrentGame->GetGameLoaded( ) )
				client->Send( "[RCON] Game details: " + m_GHost->m_CurrentGame->GetGameDetails( ) );
			else
				client->Send( "[RCON] Game details: no game in lobby" );
		}*/
		else if( !cmd.empty( ) )
		{
			// this is a legitimate user, do what he says
			ProcessInput( cmd, payload, target, client );
		}
	}

	for( vector<CRemoteConsoleClient *> :: iterator i = m_KnownClients.begin( ); i != m_KnownClients.end( ); )
	{
		//(*i)->AutoBroadcast( m_GHost->m_CurrentGame, m_GHost->m_AdminGame );

		if( GetTime( ) > (*i)->GetLastReceived( ) + m_KeepAliveTime + m_Timeout && (*i)->IsAuthed( ) )
		{
			// user has not responded in time, de-auth him
			(*i)->SetAuthed( false );
			(*i)->Send( "[RCON] Your session timed out" );
			CONSOLE_Print("[RCON] User [" + (*i)->GetIPString( ) + "] timed out");
		}
		else if( GetTime( ) > (*i)->GetLastReceived( ) + m_KeepAliveTime
					&& GetTime( ) > (*i)->GetLastPinged( ) + m_KeepAliveInterval )
		{
			// user has not sent an command in quite some time, send him a keep-alive packet (containing the word "PING")
			(*i)->Ping( );
		}

		if ( !(*i)->IsAuthed( ) && !(*i)->IsBanned( ) )
		{
			delete *i;
			i = m_KnownClients.erase( i );
		}
		else
			i++;
	}

	return false;
}