|
컴퓨터 이야기/cocos2d-x 2.x 2015. 12. 9. 06:31
APP_TOOLCHAIN_VERSION 는 자기한테 맞는 버전으로.
컴퓨터 이야기/C++ 2015. 12. 9. 06:00
template <typename Node>
class CircularQueue
{
private:
Node* node; // 노드 배열
int capacity; // 큐의 용량
int front; // 전단의 인덱스
int rear; // 후단의 인덱스
public:
CircularQueue(int capacity)
{
this->capacity = capacity + 1; // 노드 배열의 크기는 실제 용량에서 1을 더한 크기 (더미 공간 때문)
node = new Node[this->capacity]; // Node 구조체 capacity + 1개를 메모리 공간에 할당한다
front = 0; rear = 0; // 전단과 후단의 초기화
}
~CircularQueue()
{
delete []node; // 노드 배열 소멸
}
void clear()
{
front = rear = 0;
}
void enqueue(const Node& data)
{
int pos; // 데이터가 들어갈 인덱스
pos = rear;
rear = (rear + 1) % (capacity);
node[pos] = data; // pos 번째의 노드의 데이터에 data를 대입한다
}
Node dequeue() {
int pos = front; // pos에 전단의 인덱스 대입
front = (front + 1) % capacity;
return node[pos]; // 제외되는 데이터를 반환한다
}
int getSize() {
if (front <= rear) // 전단의 인덱스가 후단의 인덱스와 같거나 그보다 작다면
return rear - front; // 후단의 인덱스에서 전단의 인덱스를 뺀값을 반환한다
else // 전단의 인덱스가 후단의 인덱스보다 크다면
return capacity - front + rear; // 용량에서 전단의 인덱스를 뺀 뒤에 후단의 인덱스를 더한 값을 반환한다
}
bool isEmpty() {
return front == rear; // 전단의 인덱스와 후단의 인덱스가 같을 경우 true, 아니면 false
}
bool isFull() {
return front == (rear + 1) % capacity;
}
int getRear() { return rear; }
int getFront() { return front; }
vector<Node> getTotalData()
{
int tempFront = front;
vector<Node> T;
while(tempFront != rear)
{
T.push_back(node[tempFront]);
tempFront = (tempFront + 1) % capacity;
}
return T;
}
// void show()
// {
// int tempFront = front;
// while(tempFront != rear)
// {
// cout << node[tempFront].data << "/";
//
// tempFront = (tempFront + 1) % capacity;
// }
// cout << endl;
// }
};
컴퓨터 이야기/C++ 2015. 12. 9. 05:58
일반적으로 new/delete 를 통해서 메모리를 할당하는것은 비용을 발생시키고 보기에 위험해 보입니다. C/C++ 에선 메모리를 할당 하기 위해서 시스템 콜(OS 내부 함수를 요청)을 해야만 하는데 이는 생각보다 큰 비용을 발생 시킵니다. 그래서 할당을 미리 해놓고 꺼내오고 해제된 메모리를 다시 쓰는 방식으로 재활용을 해야하는데, 라이브러리를 잘 짜기가 힘이 듭니다. boost 로 해결할 수 있습니다.
#include <iostream>
#include <boost/pool/pool.hpp>
#include <boost/pool/object_pool.hpp>
using namespace std;
struct SomeObject
{
SomeObject() { static int no=0; cout << "SomeObject() :" << (m_no=++no) << endl; }
~SomeObject() { cout << "~SomeObject():" << m_no << endl; }
int m_no;
};
int main()
{
{
// sizeof(int) 바이트 사용
boost::pool<> p( sizeof(int) );
int* x = (int*)p.malloc();
int* y = (int*)p.malloc();
int* z = (int*)p.malloc();
*x = 10;
p.free(z); // 명시적 free
// free 명시적안해도 알아서 해제됨
}
{
// SomeObject 객체
boost::object_pool<SomeObject> p;
SomeObject* x = p.construct();
SomeObject* y = p.construct();
SomeObject* z = p.construct();
p.destroy(y);// 명시적 해제
// destroy 명시적으로 해제 안해도 알아서 됨.
}
return 0;
}
컴퓨터 이야기/AVR 2015. 12. 9. 05:56
#include <avr/io.h>
#include<avr/interrupt.h>
#define F_CPU 16000000UL // 사용하고 있는 크리스탈 주파수 값을 상수로 설정합니다.
#include <util/delay.h> // 지연 함수 관련 헤더파일을 포함합니다.
char rx_char(void) // 문자형 rx_char 수신 사용자 함수를 생성합니다.
{
// 문자 수신이 완료될 때까지 대기 UCSRA의 RXC가 비트1 이 되면 다음라인으로
while((UCSR0A&0x80) == 0);
return UDR0; // UDR 수신데이터 반환
}
void tx_char(char tx_data) // 문자형 tx_char 송신 사용자 함수를 생성합니다.
{
while((UCSR0A&0x20) == 0); // UDR레지스터가 빌 때까지 대기 UCSRA의 UDRE가 비트1 이 되면 다음라인으로
UDR0 = tx_data; // UDR레지스터에 입력한 tx_data 입력합니다.
}
int main(void) // 메인함수를 호출합니다.
{
char i, data; // 부호없는 문자형 변수 i, data를 생성합니다.
DDRB=0xFF; // B포트 8비트 전체를 출력으로 설정합니다.
PORTB=0x00; // B포트 8비트 전체의 초기값을 논리0 (0V)로 설정합니다.
UCSR0A=0x00; // UART설정 레지스터A 별도 설정 없음
UCSR0B=0x18; // UART설정 레지스터B RXEN과 TXEN을 비트1로 설정해서 송수신기능을 활성화 합니다.
UCSR0C=0x06; // UART설정 레지스터C UCSZ1과 UCSZ0을 비트1로 설정해서 8비트 데이터 전송으로 설정합니다.
//UBRR = 416;
int baud = 2400;
int ubrr= F_CPU/16/baud-1;
// 통신 속도 설정
UBRR0H = (unsigned char)(ubrr>>8);
UBRR0L=(unsigned char)ubrr;
while(1) // 아래 구문을 무한 반복합니다.
{
tx_char('B');
_delay_ms(100);
/* data = rx_char(); // data 변수에 rx_char 사용자 함수사용으로 수신된 데이터를 저장합니다. */
/* if(data=='y') // data변수와 문자y가 같으면 */
/* { */
/* PORTB=0xFF; // B포트 전체 논리1 (5V)를 출력합니다. */
/* tx_char('_'); // tx_char 사용자 함수 사용으로 _문자를 송신합니다. */
/* tx_char('o'); // tx_char 사용자 함수 사용으로 o문자를 송신합니다. */
/* tx_char('k'); // tx_char 사용자 함수 사용으로 k문자를 송신합니다. */
/* } */
/* if(data=='n') // data변수와 문자n과 같으면 */
/* { */
/* PORTB=0x00; // B포트 전체 논리0 (0V)를 출력합니다. */
/* tx_char('_'); // tx_char 사용자 함수 사용으로 _문자를 송신합니다. */
/* tx_char('o'); // tx_char 사용자 함수 사용으로 o문자를 송신합니다. */
/* tx_char('k'); // tx_char 사용자 함수 사용으로 k문자를 송신합니다. */
/* } */
/* if(data=='b') // data변수와 문자b가 같으면 */
/* { */
/* for(i=0;i<3;i++) // 아래구문을 3번 반복합니다. */
/* { */
/* PORTB=0xFF; // B포트 전체 논리1 (5V)를 출력합니다. */
/* _delay_ms(200); // 위 상태를 0.2초 동안 유지합니다. */
/* PORTB=0x00; // B포트 전체 논리0 (0V)를 출력합니다. */
/* _delay_ms(200); // 위 상태를 0.2초 동안 유지합니다. */
/* } */
/* tx_char('_'); // tx_char 사용자 함수 사용으로 _문자를 송신합니다. */
/* tx_char('o'); // tx_char 사용자 함수 사용으로 o문자를 송신합니다. */
/* tx_char('k'); // tx_char 사용자 함수 사용으로 k문자를 송신합니다. */
/* } */
}
return 0; // 정상종료 값 0을 리턴합니다.
}
컴퓨터 이야기/AVR 2015. 12. 9. 05:55
#include <avr/interrupt.h>
#include <avr/io.h>
void port_init(void)
{
PORTA = 0x00;
DDRA = 0x00;
PORTB = 0x00;
DDRB = 0x00;
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
PORTE = 0x00;
DDRE = 0x00;
PORTF = 0x00;
DDRF = 0x00;
PORTG = 0x00;
DDRG = 0b00001111;
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
cli(); //disable all interrupts
XDIV = 0x00; //xtal divider
XMCRA = 0x00; //external memory
port_init();
MCUCR = 0x00;
EICRA = 0x00; //extended ext ints
EICRB = 0x00; //extended ext ints
EIMSK = 0x00;
TIMSK = 0x00; //timer interrupt sources
ETIMSK = 0x00; //extended timer interrupt sources
sei(); //re-enable interrupts
//all peripherals are now initialized
}
void delay(int n)
{
volatile int i,j;
for(i=1;i<n;i++)
{
for(j=1;j<600;j++);
}
}
int main(void)
{
unsigned int temp, i;
init_devices();
delay(600);
while(1){
if(PING & 0b00000100){
PORTG = 0x01;
}
if(PING & 0b00001000){
PORTG = 0x02;
}
delay(10);
}
return 0;
}
컴퓨터 이야기 2011. 4. 28. 00:17
파이썬은 참 편한 언어다.
기본 언어기능이 막강하다보니 힘들게 배워서 썼던 C++ 의 STL 보다 심플하다.
컴퓨터 이야기 2011. 4. 14. 09:18
ㅣ현재 배우고 있는 과목에서 나온 과제다. 처음에 접근을 잘못해서 오류에 빠졌다가 새로이 생각을 고쳐먹고 다시 접근했다.
n숫자 제거하기
¨1~3까지의 수를 임의로 선택하여 아래 6개의 수열을 만든다.
(1, 3, 2, 3, 2, 2)
¨두 사람이 번갈아 가면서 각각 3개의 숫자를 제거한다. 단 제거할 수 있는 숫자는 남아 있는 수 중에서 양 끝에 있는 수이다.
¨각자 제거한 수를 더하여 그 값이 큰 쪽이 이긴다.
¨두 사람은 자신이 승리하기 위해 선택할 수 있는 최선의 방법만 선택한다.
¨먼저 제거하는 사람과 나중에 제거하는 사람 중에서 누가 승리하는가?
¨승패가 어떻게 결정되는지 설명하라.
def P(arr):
if len(arr) == 2:
return max(arr) - min(arr)
else:
return max(arr[0] - P(arr[1:]), arr[-1] - P(arr[0:-1]) )
def test(arr):
res = P(arr)
if(res == 0) :
print arr, "배열 일 때 비김."
else:
print arr, "배열 일 때, ", P(arr), "차이로 먼저 뽑는 사람이 이김."
test([1,2])
test([1,2,3])
test([3,2,1])
test([3,2,1,2])
test([3,2,1,2,1,2])
test([2,1,2,1,2,3])
test([3,2,1,2,1,2])
test([3,3,3,3,3,3])
test([1,1,1,2,1,1])
test([1,2])
test([1,2,3])
test([3,2,1])
test([3,2,1,2,1,2])
test([3,2,1,3,2,2,1,2])
test([2,1,2,3,3,1,2,3])
test([3,2,1,3, 2, 2,1,2])
test([3,3,3,1,1,3,3])
test([1,1,1,2,3,2,1,1])
---------------------------
if len(arr) == 2:
return max(arr) - min(arr)
else:
return max(arr[0] - P(arr[1:]), arr[-1] - P(arr[0:-1]) )
이 부분이 핵심 점화식인데,
P(arr) : 들어온 배열에서 최초로 뽑는 사람이 (모든 사람이 최선을 다했을 경우)이기는 차이로 정의
P([1,2]) 라면 처음 뽑는 사람이 2, 다음사람이 1 뽑아서
1 차이로 이김.
이렇게 하면 두개일 때 base 연산이 진행되고 세개 이상일 경우
첫번째 원소를 제거하는쪽이 더 유리한지, 다음 원소를 제거하는 쪽이 더 유리한지, 판단해서 재귀 호출이 이뤄짐.
사실상 정확한 결과를 알고 싶다면 재귀의 끝까지 들어가봐야 결과를 알 수가 있음.
6개인 경우는 사람이 이 알고리즘을 생각할 수는 있지만, 일반적인 개수 n(=짝수) 가 들어올 때는, n 이 8 이상만 되더라도 분기점이 2의 승수로 올라가기 때문에 사람 머리로 이 게임에서 승패가 이뤄지는지는 알 수가 없다.
e.g) P([1,2]) = 1
[1,2,3] 일 때,
1을 선택하고 나머지를 최선을 다들 다 했을 때 이기는 차이는 다음과 같다.
P([1,2,3]) = max(1 - P([2,3], 3 - P[1,2])
[1,2,3,2] 일 때,
1을 선택하고 나머지를 최선을 다들 다 했을 때 이기는 차이는 다음과 같다.
P[1,2,3,2] = max(1 - P[2,3,2], 2 - P[1,2,3])
...
base 연산 두개일 때를 생각해보면 같지 않은 이상 제일 처음뽑는 사람이 이기므로 둘다 최선을 다할 경우, 먼저 뽑는 사람이 이기거나 비긴다.
컴퓨터 이야기/C++ 2011. 2. 5. 16:49
컴퓨터 이야기 2011. 1. 22. 11:20
MFC 보다 훨씬 쓰기 간편하다.
C++ 을 그대로 쓸 수 있는 강력함과 편한 GUI 프로그래밍 환경.
컴퓨터 이야기/C++ 2011. 1. 13. 03:27
예전에 KLDP에 음수에 대한 나머지 연산질문을 올린적이 있었다. 허접한 질문에도 불구하고 성심성의껏 다들 댓글을 달아주셨다.
------------------------------------------------------------------------------------------------------------------------------------------
나머지 연산자를 쓰다가 음수를 생각하게 되었습니다.
예를 들어서 (-3) % 2 는 1 이 될 수도 있고 -1 이 될 수도 있는거 같습니다. 한번 궁금해서 여러 프로그램에 이 식을 넣고 답을 기다렸습니다.
먼저 MS 의 VC는 답을 -1 로 내놓았습니다.
윈도우즈 내장 계산기는 답을 -1 로 내놓았습니다.
하지만, MS Excel 은 답을 1 로 내놓았습니다...
뭐가 정답일까요?
셋다 MS 제품인데 말이죠. 글 올리기전에 검색 해봤으나 찾지 못하고 글 올립니다. (__)
자세한 내용 : http://kldp.org/node/55978
Home :: navigate form elements forward
컴퓨터 이야기/C++ 2011. 1. 13. 03:25
[옛날 쓴글 가져오기 - mmoz]
제가 간단히 아는 ㅇ명령어로만 해봤는데 결과가 아주 비참하군요!!
셀러론 1Ghz 입니다.
__declspec(naked) int mmojz_strlen(const char* s)
{
__asm
{
push ebp
mov ebp, esp
}
__asm
{
push ecx
push esi
mov ecx, -1
mov esi, dword ptr[ebp+8];
cld
l:
lodsb
inc ecx
cmp al, 0
jne l
mov eax, ecx
pop esi
pop ecx
}
__asm
{
pop ebp
ret
}
}
int mmojz2_strlen(const char* ch)
{
int i=0;
while (*ch++) i++;
return i;
}
int main()
{
unsigned int t;
t = timeGetTime();
for(volatile unsigned int i=0; i<10000000; i++)
{
strlen("345349534583495834958589358938595");
}
printf("라이브러리 : %d\n", timeGetTime()-t);
t = timeGetTime();
for(volatile unsigned int i=0; i<10000000; i++)
{
mmojz_strlen("345349534583495834958589358938595");
}
printf("허접 어셈 : %d\n", timeGetTime()-t);
t = timeGetTime();
for(volatile unsigned int i=0; i<10000000; i++)
{
mmojz2_strlen("345349534583495834958589358938595");
}
printf("C언어 : %d\n", timeGetTime()-t);
return 0;
}
debug 버전에서는
라이브러리 : 1065
허접 어셈 : 2658
C언어 : 6016
Release 버전에서는
라이브러리 : 89
허접 어셈 : 2625
C언어 : 941
비참...
덧
philossh wrote:int asmstrlen(const char* ch)
{
__asm
{
mov edi, dword ptr [ebp+8];
xor al, al;
mov ecx, -1;
repne scasb;
xor eax, eax;
mov eax, -2;
sub eax, ecx;
}
}
은 Release 버전에서는 작동하지 않습니다. (.NET 2003 입니다.)
http://kldp.org/node/56157
BackSpace :: back
BackSpace :: back
컴퓨터 이야기/C++ 2011. 1. 8. 14:50
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <limits>
using namespace std;
#ifdef mycom
ifstream fin("input");
#else
#define fin cin
#endif
vector<int> v;
vector<int> orders;
int N, P, R;
unsigned long long counter=0;
void back(int order)
{
if(v.size() == orders.size())
{
vector<int> arr;
for(int i=0; i<orders.size(); i++)
{
arr.push_back(v[orders[i]]);
}
int myp, myr;
myp = myr = 0;
for(int i=0; i<arr.size(); i++)
{
bool allsmall = true;
for(int j=0; j<=i; j++)
{
if(arr[j] > arr[i])
{
allsmall = false;
break;
}
}
if(allsmall) // arr[i] 가 leftable 하다
{
myp++;
}
}
if(myp != P)
return;
for(int i=arr.size()-1; i>=0; i--)
{
bool allsmall = true;
for(int j=arr.size()-1; j>i; j--)
{
if(arr[j] > arr[i])
{
allsmall = false;
break;
}
}
if(allsmall) // arr[i] 가 rightable 하다
{
myr++;
}
}
if(myr != R)
return;
counter++;
}
else
{
for(int i=0; i<v.size(); i++)
{
if( find(orders.begin(), orders.end(), i) == orders.end() )
{
vector<int> arr;
for(int i=0; i<orders.size(); i++)
{
arr.push_back(v[orders[i]]);
}
int myp, myr;
myp = myr = 0;
for(int i=0; i<arr.size(); i++)
{
bool allsmall = true;
for(int j=0; j<=i; j++)
{
if(arr[j] > arr[i])
{
allsmall = false;
break;
}
}
if(allsmall) // arr[i] 가 leftable 하다
{
myp++;
}
}
if(myp > P)
return;
orders.push_back(i);
back(i);
orders.pop_back();
}
}
}
}
int main()
{
int mycase;
fin >> mycase;
while(fin >> N >> P >> R)
{
v.clear();
for(int i=1; i<=N; i++)
{
v.push_back(i);
}
counter = 0;
back(0);
cout << counter << endl;
}
return 0;
}
컴퓨터 이야기/C++ 2011. 1. 8. 01:57
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <limits>
using namespace std;
#ifdef mycom
ifstream fin("input");
#else
#define fin cin
#endif
char chess[100][100] = {0,};
int n, k;
long long total = 0;
bool possible(int y, int x)
{
int newy = y;
int newx = x;
for( ; newy >= 0 && newx >= 0; newy--, newx--)
{
if(chess[newy][newx] == true)
{
return false;
}
}
newy = y;
newx = x;
for( ; newy < n && newx < n; newy++, newx++)
{
if(chess[newy][newx] == true)
{
return false;
}
}
newy = y;
newx = x;
for( ; newy < n && newx >= 0; newy++, newx--)
{
if(chess[newy][newx] == true)
{
return false;
}
}
newy = y;
newx = x;
for( ; newy >= 0 && newx < n; newy--, newx++)
{
if(chess[newy][newx] == true)
{
return false;
}
}
return true;
}
inline bool sizecompare(int _y, int _x, int __y, int __x)
{
//_ 가 크면 true;
if(_y != __y)
return _y > __y;
else if(_y == __y)
{
return _x > __x;
}
}
void back(int selcount, int lasty, int lastx)
{
if(selcount == k)
{
total++;
}
else
{
for(int y=0; y<n; y++)
{
for(int x=0; x<n; x++)
{
if(sizecompare(y, x, lasty, lastx) && possible(y, x))
{
chess[y][x] = true;
back(selcount+1, y, x);
chess[y][x] = false;
}
}
}
}
}
int main()
{
bool bfirst = true;
while(fin >> n >> k && n != 0 && k != 0)
{
if(bfirst != true)
{
cout << endl;
}
bfirst = false;
total = 0;
back(0, -1, 0);
cout << total;
}
return 0;
}
컴퓨터 이야기/C++ 2011. 1. 7. 22:05
vector<int> v;
vector<char> select;
void back(int order)
{
if(select.size() == v.size())
{
for(int i=0; i<select.size(); i++)
{
cout << v[select[i]] << ", ";
}
cout << endl;
}
else
{
for(int i=0; i<v.size(); i++)
{
if(find(select.begin(), select.end(), i) == select.end())
{
select.push_back(i);
back(i);
select.pop_back();
}
}
}
}
int main()
{
int arr[] = {1,2,3};
v.assign(arr, arr+3);
back(-1);
return 0;
}
컴퓨터 이야기/C++ 2011. 1. 7. 21:58
vector<int> v;
vector<char> select;
void back(bool sel)
{
if(select.size() == v.size())
{
for(int i=0; i<v.size(); i++)
{
if(select[i] == true)
cout << v[i] << ", ";
}
cout << endl;
}
else
{
select.push_back(true);
back(true);
select.pop_back();
select.push_back(false);
back(false);
select.pop_back();
}
}
int main()
{
int arr[] = {1,2,3};
v.assign(arr, arr+3);
back(0);
return 0;
}
|