[JAVA][동적할당]Hamming code

stack overflow/JAVA 2013. 6. 29. 16:24 posted by Allen Park


Hamming.java

HammingTest.java







<HammingTest.java> - 메인함수


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;


public class HammingTest {

public static void main(String[] args) throws IOException {

int parityLength = 1; //패리티 길이(예시 : 4)

int[] parityData; //패리티 값 (자동생성)

int numOfDataBits; //데이터 길이(직접 입력)

int[] data; // 데이터 값 (직접 입력)

int[] hammingData; //패리티 + 데이터 값 (자동 생성)

int hammingDataLength; //패리티 + 데이터 길이 (자동 생성)

int[][] location; //매트릭스 값 (자동 생성)

int[] enteredHamming; //비교 대상 값 (직접 입력)

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

//Hamming hamming = new Hamming(); //굳이 인스턴스화 될 필요가 없음


//Data 비트 수 입력 받기

while (true) {

System.out.println("Enter number of bits : ");

String str = br.readLine();

if(str.length() == 0) {

System.out.println("Please enter an integer value over 0.");

}

else {

numOfDataBits = Integer.parseInt(str);

if(numOfDataBits < 1)

System.out.println("Please enter an integer value over 0.");

else break;

}

}

//Parity 길이 구하고 해밍코드 길이 산출하기

while(true) {

if(Math.pow(2, parityLength) >= numOfDataBits + parityLength + 1)

break;

else parityLength++;

}

hammingDataLength = numOfDataBits + parityLength;

//배열 크기 할당

data = new int[numOfDataBits];

parityData = new int[parityLength];

hammingData = new int[hammingDataLength];

enteredHamming = new int[hammingDataLength];

location = new int[parityLength][hammingDataLength];

System.out.println("Number of parity bits : " + parityLength);

System.out.println("Number of hamming bits : " + hammingDataLength);

//Data 값 입력 받고 출력

System.out.println("Enter bit number : ");

for(int i = 0; i < numOfDataBits; i++) {

while(true) {

String str = br.readLine();

if(str.length() == 0) {

System.out.println("Please enter a bit value 0 or 1.");

}

else {

data[i] = Integer.parseInt(str);

if(data[i] < 0 || data[i] > 1)

System.out.println("Please enter a bit value 0 or 1.");

else break;

}

}

}

Hamming.showDataBit(numOfDataBits, data);

Hamming.hammingArrayGeneration(data, hammingData, parityLength, hammingDataLength);

Hamming.setLocationsToZero(parityLength, hammingDataLength, location);

for(int i = 0; i < parityLength; i++)

Hamming.getLocations(i, hammingData, location, hammingDataLength);

Hamming.showMatrix(parityLength, hammingDataLength, location);

Hamming.generateParity(location, parityData, parityLength, hammingDataLength);

Hamming.showParity(parityLength, parityData);

Hamming.hammingArrayCompletion(hammingDataLength, hammingData, parityData);

Hamming.showHammingCode(hammingData, hammingDataLength);

//틀린 Hamming Data 입력받기

System.out.println("Enter hamming code of " + hammingDataLength + " bits :");

for(int i = 0; i < hammingDataLength; i++) {

while(true) {

String str = br.readLine();

if(str.length() == 0) {

System.out.println("Please enter a bit value 0 or 1.");

}

else {

enteredHamming[i] = Integer.parseInt(str);

if(enteredHamming[i] < 0 || enteredHamming[i] > 1)

System.out.println("Please enter a bit value 0 or 1.");

else break;

}

}

}

Hamming.setLocationsToZero(parityLength, hammingDataLength, location);

for(int i = 0; i < parityLength; i++)

Hamming.getLocations(i, enteredHamming, location, hammingDataLength);

Hamming.generateParity(location, parityData, parityLength, hammingDataLength);

Hamming.errorCalculate(enteredHamming, parityData, parityLength, hammingDataLength);

Hamming.showHammingCode(enteredHamming, hammingDataLength);

}

}




<Hamming.java>

public class Hamming {

static void hammingArrayGeneration(int data[], int hammingData[], int parityLength, int hammingDataLength) {

for(int i = 0; i < hammingDataLength; i++) {

hammingData[i] = 3; //초기화를 제 3의 수로 함

}

for(int i = 0; i < parityLength; i++) {

int cur = (int)Math.pow(2, i) - 1;

hammingData[cur] = 2; //패리티 비트가 들어갈 자리를 값 2로 미리 마킹함

}

for(int i = 0; i < hammingDataLength; i++) {

for(int j = 0; j < hammingDataLength; j++) {

if(hammingData[j] == 3) {

hammingData[j] = data[i]; //2로 마킹되지 않은 데이터 비트 자리에 data 배열의 값들을 채워 넣음

break;

}

else continue;

}

}

}

static void hammingArrayCompletion(int hammingDataLength, int[] hammingData, int[] parityData) {

int order_parity = 0;

for(int i = 0; i < hammingDataLength; i++) {

if(hammingData[i] == 2) {

hammingData[i] = parityData[order_parity++];

}

}

}

static void setLocationsToZero(int parityLength, int hammingDataLength, int[][] location) {

for(int i = 0; i < parityLength; i++) {

for(int j = 0; j < hammingDataLength; j++) {

location[i][j] = 0;

}

}

}

static void getLocations(int i, int hammingData[], int location[][], int hammingDataLength) {

int step = (int) Math.pow(2, i); //int step : 탐지 범위와 탐지 배제 범위 역할을 동시에 하는 변수

int cur = step - 1; ////변수 cur은 hammingData 배열 위를 돌아다니는 지시자 같은 역할을 하도록 고안함

for(int cur_inner = cur; cur_inner < hammingDataLength;) {

for(int j = 0; j < step; j++) {

if(cur_inner > hammingDataLength - 1) break;

if(hammingData[cur_inner] == 1) {

location[i][cur_inner] = 1;

}

cur_inner++;

}

cur_inner += step;

}

}

static void generateParity(int location[][], int parityData[], int parityLength, int hammingDataLength) {

for(int i = 0; i < parityLength; i++) {

int cnt = 0;

for(int j = 0; j < hammingDataLength; j++) {

if(location[i][j] == 1) {

cnt++;

}

} //System.out.println(i + "번째 cnt : " + cnt);

if(cnt % 2 == 1) { //짝수 패리티를 맞추기 위한 조건문

parityData[i] = 1;

}

else {

parityData[i] = 0;

}

cnt = 0;

}

}

static void errorCalculate(int enteredHamming[], int parityData[], int parityLength, int hammingDataLength) {

int error_total = 0;

for(int i = parityLength - 1; i > -1; i--) {

if(parityData[i] == 1) {

error_total += (int)(Math.pow(2, i)); //2진수인 값들을 10진수로 취합한다

}

}

System.out.println("The " + error_total + " bit is wrongly received\n");

if(enteredHamming[error_total - 1] == 1) { //고쳐야 할 비트가 1일 경우 0으로 0일 경우 1로 정정한다

enteredHamming[error_total - 1] = 0;

}

else {

enteredHamming[error_total - 1] = 1;

}

System.out.println("The correct hamming code is");

}


//////////////////////////////출력함수//////////////////////////////

static void showHammingCode(int hammingData[], int hammingDataLength) { //오류를 수정하고 난 해밍 코드 출력에도 이 함수를 씀

System.out.println("HAMMING CODE ARRAY : ");

for(int i = 0; i < hammingDataLength; i++) {

System.out.print(hammingData[i]);

} System.out.println("\n");

}

static void showDataBit(int numOfDataBits, int[] data) {

System.out.println("Data bits are : ");

for(int i = 0; i < numOfDataBits; i++)

System.out.print(data[i]);

System.out.println("\n");

}

static void showMatrix(int parityLength, int hammingDataLength, int[][] location) {

System.out.println("Location is :");

for(int i = 0; i < parityLength; i++) {

for(int j = 0; j < hammingDataLength; j++) {

System.out.print(location[i][j] + " ");

}

System.out.println();

} System.out.println("");

}

static void showParity(int parityLength, int[] parityData) {

System.out.println("Even Parity : ");

for(int i = 0; i < parityLength; i++) {

System.out.print(parityData[i] + " ");

} System.out.println("\n");

}

}




[안드로이드]OpenGL ES ①

stack overflow/Android 2013. 3. 24. 22:41 posted by Allen Park

뷰 컨테이너 생성

더 좋은 방법은 GLSurfaceView and a GLSurfaceView.Renderer 두 개를 구현

GLSurfaceView는 OpenGL로 그려진 그래픽의 뷰 컨테이너

GLSurfaceView.Renderer는 그 뷰 안에 그려진 것들을 제어

GLSurfaceView는 전체 화면

TextureView는 일부 화면

menifest에 선언 : <uses-feature android:glEsVersion="0x00020000" android:required="true" />

일반 어플과 다르게 GLSurfaceView 추가 (Android 2.2 (API Level 8) or higher)

이벤트 처리를 위해

 

1. menifest에 선언

 

<uses-feature android:glEsVersion="0x00020000" android:required="true" />

 

 

2. class 추가

 

class MyGLSurfaceView extends GLSurfaceView {

    public MyGLSurfaceView(Context context) {
        super(context);

 

        // OpenGL ES 2.0 버전 사용
        setEGLContextClientVersion(2);

 

        // 렌더러를 GLSurfaceView에 세트
        setRenderer(new MyGLRenderer());

 

        // 그리는 값에 변화가 있을 경우에만 렌더링 함
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }
}

 

 

3. 렌더러 클래스 생성 (따로 분리된 java 파일로 생성)

 

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView;
import android.opengl.GLES20;

 

public class MyGLRenderer implements GLSurfaceView.Renderer {

    public void onSurfaceCreated(GL10 unused, EGLConfig config) {


        // 배경색 설정
        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    }

    public void onDrawFrame(GL10 unused) {


        // 배경 다시 그림
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
    }

    public void onSurfaceChanged(GL10 unused, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }
}

 

'stack overflow > Android' 카테고리의 다른 글

[안드로이드]타이틀 바 없애기  (0) 2013.03.20
[안드로이드]Starting an Activity  (0) 2013.01.28
[안드로이드]액티비티란?  (0) 2013.01.28

스카이림 + 던가드 + 히스파이어

epicureanism 2013. 3. 20. 23:38 posted by Allen Park

 

 

 

 

 

스팀에서 이제 조금 싸게 팔기 시작 함 (39.99$)

 

 

예전 부터 가지고 싶었던 거라 싸지자마자 사버림

 

 

던가드 스토리는 정말 괜찮았는데 소울 케어른 안을 헤매는 건 정말 넓고 어렵고 빡이 쳤다.

 

 

'epicureanism' 카테고리의 다른 글

말파리  (0) 2012.08.02

[1920 * 1080] 박보영 배경화면

conquered media 2013. 3. 20. 23:25 posted by Allen Park

 

 

 

 

처음으로 큰 모니터 써봐서

 

큰 배경화면 찾다가 이걸 발견함

 

진리

 

 

'conquered media' 카테고리의 다른 글

고혜미 장마리  (0) 2012.08.10

아디다스 가방 + 머드초콜릿

day walker 2013. 3. 20. 23:22 posted by Allen Park

 

 

 

 

여치니한테 생일 선물로 앞은 회색이고 뒤는 형광인 까리한 가방을 받음!

 

 

그리고 사람 많아서 못갔었던 TAPIOCA FACTORY에 버블티 먹으러 드디어 가봄!

 

 

머드초콜릿은 그 이름 따라 엄청 진하고 무겁고 폭풍 초코라서 완전 달았다.

 

 

 


타피오카 팩토리 / -

주소
경기 용인시 기흥구 보정동 1193-7번지
전화
031-896-5907
설명
-
지도보기

'day walker' 카테고리의 다른 글

비대칭이냐 깐머리냐  (0) 2012.08.07
수원 치킨거리  (0) 2012.08.01
강화도  (0) 2012.08.01

루나글라이드4 회형

financial crisis 2013. 3. 20. 23:17 posted by Allen Park

 

 

남성용 : 524977-003

여성용 : 524978-007

 

 

 

근데 같은 회형이라고 불릴지라도 공용 사이즈로 나온게 없기 때문에 상품 코드가 틀림

 

그래서 형광 부분 색이 딱 보면 좀 다름 짱나게

 

 

'financial crisis' 카테고리의 다른 글

아보키 제너럴 스니커즈  (0) 2012.08.01
iPad2  (0) 2012.07.29

[안드로이드]타이틀 바 없애기

stack overflow/Android 2013. 3. 20. 22:54 posted by Allen Park

 

1. AndroidMenifest.xml 에서 없애는 방법

 

-제목 표시줄 없애기
<activity android:name=".AAA" android:theme="@android:style/Theme.NoTitleBar" />

-다 없애기
<activity android:name=".AAA" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />

 

 

 

2. Java 소스에서 설정 하는 방법

 

-제목 표시줄 없애기

requestWindowFeature(Window.FEATURE_NO_TITLE);

-상태 바만 없애기

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

 

'stack overflow > Android' 카테고리의 다른 글

[안드로이드]OpenGL ES ①  (0) 2013.03.24
[안드로이드]Starting an Activity  (0) 2013.01.28
[안드로이드]액티비티란?  (0) 2013.01.28

[안드로이드]Starting an Activity

stack overflow/Android 2013. 1. 28. 18:11 posted by Allen Park

안드로이드 트레이닝 페이지 대충 번역

http://developer.android.com/training/basics/activity-lifecycle/starting.html




Starting an Activity


 기존 프로그램들이 main() 함수에 의해 시작되는 일반적인 배경과는 달리 안드로이드는 각 상황에 맞는 특정한 콜백 메소드를 불러들여 액티비티 객체 안의 코드를 수행한다. 다시 말해서 시작부터 종료까지 모든 단계에 따른 각각의 메소드의 시퀸스화 이다. 이 글에서는 그 중 가장 중요한 라이프사이클 메소드와 가장 처음 새로운 액티비티 객체를 생성하는 메소드의 사용법을 소개한다.




Understand the Lifecycle Callbacks


 액티비티의 일생에서 시스템은 다음 그림처럼 피라미드와 같은 일련의 과정을 이루는 라이프사이클 메소드들을 불러온다. 이 피라미드 그림을 따라 동작하며 피라미드의 가장 위야 말로 유저와 본격적인 인터렉트를 할 수 있는 상태라고 할 수 있다. 이 때 유저가 뒤로 가기 등을 눌러 해당 액티비티를 떠나면 액티비티의 상태는 피라미드의 한 계단을 내려오게 된다. 때에 따라서 액티비티가 소멸되지 않고 가려진 상태로 대기를 하는 경우도 있다. 예를 들어 화면 전환과 같은 경우를 말한다. 그림을 보면 쉽게 이해할 수 있다.





그림에 있는 콜백 함수들을 언제나 모두 쓰는 것은 아니지만 각각을 이해하고 구현해두는 것은 어플이 유저의 기대대로 잘 작동하도록 하는 좋은 방법이다. 콜백함수들의 내용들을 잘 구현해두면 다음 이점들을 얻을 수 있다.

  • 유저가 전화를 받거나 다른 어플로 전환하는 등의 경우 어플이 튕기지 않는다.

  • 액티비티가 활성화되지 않은 경우 리소스를 불필요하게 점유하지 않는다.

  • 유저가 액티비티를 떠났다가 돌아와도 그 전까지의 진행상황을 잃어버리지 않는다.

  • 화면이 가로모드나 세로모드로 전환되어도 진행을 잃거나 튕기지 않는다.


포커스를 얻거나 일는 등의 전환 상태가 발생되더라도 다음 세 가지의 상태만은 static(시스템에 잔류) 하다.


Resumed

액티비티가 앞화면에 있어 포커스를 얻고 유저와 인터렉트 한다. (이를 running 상태라고도 한다.)


Paused

부분적으로 가려진 상태를 말하며 작은 창 등에 의해 포커스를 뺏긴 경우이다. 이 때, 유저에 의한 입력을 받을 수 도 없고 어떠한 코드도 수행할 수 없다.


Stopped

액티비티가 완전히 포커스를 잃어 화면에 표시되지 않고 백그라운드에 들어간다. 이 상태에 들어가면 액티비티 객체와 그 멤버변수 값들은 보존되지만 코드를 수행할 수는 없게 된다.


이 외의 Created나 Started 상태는 "일시적" 이다. 예를 들어 onCreate() 함수가 불려오고 나면 onStart() 함수가 재빨리 불려진다.



'stack overflow > Android' 카테고리의 다른 글

[안드로이드]OpenGL ES ①  (0) 2013.03.24
[안드로이드]타이틀 바 없애기  (0) 2013.03.20
[안드로이드]액티비티란?  (0) 2013.01.28

[안드로이드]액티비티란?

stack overflow/Android 2013. 1. 28. 17:33 posted by Allen Park

Activities


 액티비티란 어플리케이션을 이루는 페이지들이라고 보면 되겠다. 보통 화면을 가득 메우지만 중간에 창으로 떠 있을수도 있다. 하나의 어플은 여러개의 액티비티로 이루어져 있고 그중 하나는 어플을 맨 처음 시작할때 띄우는 "main" 액티비티이다. 액티비티들은 기능을 구현하기 위해 서로를 불러올 수 있다. 다른 액티비티를 불러올 경우 화면에서 사라진 액티비티는 스택(back stack)에 쌓여 보존된다. 즉 새로운 액티비티가 시작되면 back stack에 push 되는 것이다. 그리고 나서 포커스를 얻는다. back stack은 기본적인 LIFO 방식에 의해 관리된다. 즉 액티비티의 생성은 push요, 소멸은 pop이다. 만약 새로운 액티비티가 생성되어 기존 액티비티가 비활성화되면 이는 비활성화 되어있는 동안 콜백 메소드에 의해 상태정보를 받게 된다. 콜백 함수들은 상태변화에 따른 적절한 작동을 할 수 있도록 하는 수단이 된다.

'stack overflow > Android' 카테고리의 다른 글

[안드로이드]OpenGL ES ①  (0) 2013.03.24
[안드로이드]타이틀 바 없애기  (0) 2013.03.20
[안드로이드]Starting an Activity  (0) 2013.01.28

[C][math.h] 2차원 방정식 근 구하기

stack overflow/C 2012. 8. 30. 16:04 posted by Allen Park



root_src.cpp






#include <stdio.h>

#include <math.h>



void rooter(double a, double b, double c)

{

double x, pan = (pow(b, 2) - (4 * a * c));


printf("판별식 값 : %lf\n", pan);

if(pan > 0) {

x = (-b + (sqrt(pan))) / (2 * a);

printf("실근 1 : %lf\n", x);

x = (-b - (sqrt(pan))) / (2 * a);

printf("실근 2 : %lf\n", x);

} else if(pan == 0) {

x = (-b + (sqrt(pan))) / (2 * a);

printf("중근 : %lf\n", x);

} else {

double sil, huh;

pan = -pan;

sil = -b / (2 * a);

huh = pan / (2 * a);

printf("허근 1 : %lf + %lfi\n", sil, huh);

printf("허근 2 : %lf - %lfi\n", sil, huh);

}

}



int main()

{

double a, b, c;


while(1) {

printf("2차 방정식의 계수 3개 입력 : ");

scanf("%lf %lf %lf", &a, &b, &c);

rooter(a, b, c);

}


return 0;

}