반응형

파이썬 Quick Sort로 오름차순으로 정렬하는 방식입니다.


시간복잡도 : O(n^2) - Worst Case 일 때 이지만,

일반적으로는 가장 빠른 정렬으로 시간복잡도를 O(nlogn) 으로 봅니다.


def quickSort(A, first, last):

    left = first + 1

    right = last


    if first >= last:

        return

    pivot = A[first]


    while left <= right:

        while left <= last and A[left] < pivot:

            left += 1

        while right > first and A[right] >= pivot:

            right -= 1

        if left <= right:

            A[left], A[right] = A[right], A[left]

            left += 1

            right -= 1


    A[right], A[first] = A[first], A[right]

    quickSort(A, first, right-1)

    quickSort(A, left, last)


if __name__ == '__main__':

    A = [4, 1, 5, 8, 6, 2, 3, 7, 10]

    quickSort(A, 0, len(A)-1)


    print A



반응형

WRITTEN BY
SiriusJ

,
반응형

파이썬 Bubble Sort로 오름차순으로 정렬하는 방식입니다.

시간복잡도 : O(n^2)


def bubbleSort(A):

    for i in range(len(A)):

        for j in range(1, len(A)):

            if A[j-1] > A[j]:

                A[j-1], A[j] = A[j], A[j-1]


if __name__ == '__main__':

    A = [1, 9, 2, 5, 4, 8, 15, 3]

    bubbleSort(A)

    print A

반응형

WRITTEN BY
SiriusJ

,
반응형

Algorithm 메뉴에 포스팅했던 백준 알고리즘 문제들에 대하여,


예전에 알고리즘을 처음 해보기 시작할 때 문제풀어보기에 급급히 작성했던 코드들이어서 


부족한 코드도, 수정해야하는 코드도 많은데 보완없이 그대로 올렸던 터라 많이 고쳐야 할 것 같습니다.


최근 블로그 활동을 많이 못하게 되었는데, 조만간 전체적인 코드 수정과 함께 


시간이 된다면 추가적으로 문제들을 더 올려보도록 노력하겠습니다.

반응형

WRITTEN BY
SiriusJ

,
반응형

지난번, 네이버 음성인식 API를 다루는 포스팅을 

1. Android(7) - 네이버 음성인식 API 이용하기 (1) : http://jwprogramming.tistory.com/168

2. Android(8) - 네이버 음성인식 API 이용하기 (2) : http://jwprogramming.tistory.com/169

에서 다루었습니다.


지난 번에는 코드를 직접 옮기면서 조금은 복잡하게 설명드렸다고 생각되어 조금 더 이해하기 쉽게 다시 포스팅하게 되었습니다. 

실질적으로 본인의 Android Studio 툴에서, 네이버 음성인식 API를 바로 테스트해보겠습니다.

우리는 이전 포스팅에서 네이버 음성인식 라이브러리를 다운받은 적이 있습니다. 압축을 풀어줍시다. (* 이전 포스팅들에서 네이버 개발자 센터에서 음성인식 API를 신청하고, Client ID와 Secret을 얻는 것까지는 진행해주셔야 합니다.!)


Import Project 를 통하여 훨씬 쉽고 간편하게 바로 테스트 해보실 수 있습니다.

처음 프로젝트 생성 시, New Project 외에 여러가지 메뉴가 있습니다. 여기서 Import Project를 클릭하여 이전에 다운받은 라이브러리를 import 해주어야 합니다.

보시는 바와 같이 다운받고, 압축을 풀어준 폴더를 찾아서, NaverspeechClient-android-studio 를 선택 후, OK 버튼을 눌러주면 아래와 같이 Android Studio Project가 새로 생성됩니다.



이렇게 네이버에서 제공하는 라이브러리를 이용하여 바로 테스트 해볼 수 있습니다.

단, Package name은 신경 써야하는데, Android_Manifest.xml 내의 

[Package name]

package="com.naver.naverspeech.client"

부분과, 

Gradle Scripts 내의 build.gradle(Module:app)

[applicationId]

defaultConfig {
applicationId "com.naver.naverspeech.client"
targetSdkVersion 23
}

부분을 자신이 네이버 개발자센터에서 API신청을 할 때, Android package name 을 등록한 부분과 맞춰주어야 합니다.


그 외, 프로젝트 내에서 각 소스들 상단의 package 이름이

package com.naver.naverspeech.client;

와 같이 되어있을 것입니다.

이 부분을 자신의 package 로 전부 바꿔주시고, 마지막으로 MainActivity.java 에서 CLIENT_ID를 자신의 CLIENT_ID 로 바꿔주신 후 테스트하면 될 것입니다.

반응형

WRITTEN BY
SiriusJ

,
반응형

지난 File Test에 이어서 path와 file에 대해 이것저것 Check해보는 메소드들을 사용해보았습니다.


/**
* Created by 진우 on 2016-07-19.
*/
public class MyFileTest {
public static void main(String[] args) {
MyFileTest fileTest = new MyFileTest();

String path = "C:\\";
// String path = "C:\\sirius.txt";
fileTest.checkPath(path);

String fileName = "jinwoo.txt";
fileTest.checkFile(path, fileName);
fileTest.checkList(path);
}

public void checkPath(String path) {
File file = new File(path);
System.out.println(path + "is exists?" + file.exists());

System.out.println("Make " + path + " Result => " + file.mkdir());
System.out.println(path + "is Directory? => " + file.isDirectory());
System.out.println(path + "is File? => " + file.isFile());
System.out.println(path + "is hidden? => " + file.isHidden());

System.out.println(path + "can Read? => " + file.canRead());
System.out.println(path + "can Write? => " + file.canWrite());
System.out.println(path + "can Execute? => " + file.canExecute());

System.out.println(path + " last modified => " + file.lastModified());
System.out.println(path + " last modified => " + new Date(file.lastModified()));
System.out.println("Delete " + path + " result => " + file.delete());
}

public void checkFile(String path, String fileName) {
File file = new File(path, fileName);
try {
System.out.println("Create Result => " + file.createNewFile());
System.out.println("Absolute Path => " + file.getAbsolutePath());
System.out.println("Absolute File => " + file.getAbsoluteFile());
System.out.println("Canonical Path => " + file.getCanonicalPath());
System.out.println("Canonical File => " + file.getCanonicalFile());

System.out.println("Name => " + file.getName());
System.out.println("Path => " + file.getPath());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}


결과 창)

참고로, C 디렉토리는 권한이 필요하기 때문에 Make Result와 Delete는 false가 되었습니다. 

(코드 내부에서 Delete는 조심해서 사용하시기 바랍니다. FileName을 중요한 파일로 테스트하시면 날릴수도 있습니다.)

반응형

WRITTEN BY
SiriusJ

,
반응형

Java로 개발 시에 File을 열고 쓰는 등의 기초 작업에 대하여 다뤄보겠습니다.


/**
* Created by 진우 on 2016-07-19.
*/
public class MyManageTextFile {
public static void main(String[] args) {
MyManageTextFile managerTest = new MyManageTextFile();
int count = 10;

String path = "C:\\" + separator + "jinwoo.txt";
//managerTest.writeFile(path, numberCount);
managerTest.readFile(path);
System.out.println();
managerTest.readFileScanner(path);
}

public void writeFile(String fileName, int count) {
FileWriter fw = null;
BufferedWriter bw = null;

try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);

for(int loop=0; loop<=count; loop++) {
bw.write(Integer.toString(loop));
bw.newLine();
}
System.out.println("Write Success!");
} catch(IOException ioe) {
ioe.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
if(bw != null) {
try {
bw.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
if(fw != null) {
try {
fw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}

public void readFile(String fileName) {
FileReader fr = null;
BufferedReader br = null;

try {
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String data;
while((data = br.readLine()) != null) {
System.out.println(data);
}
System.out.println("Read Success!");
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if(fr != null) {
try {
fr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}

public void readFileScanner(String fileName) {
File file = new File(fileName);
Scanner sc = null;
try {
sc = new Scanner(file);
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
System.out.println("Read Scanner Success!");
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(sc != null) {
sc.close();
}
}
}
}


반응형

WRITTEN BY
SiriusJ

,
반응형

팩토리패턴(factory pattern)이란?

- 팩토리를 쓰면 객체 생성을 캡슐화 할 수 있습니다.

애플리케이션의 구상 클래스에 대한 의존성을 줄여줌으로써 느슨한 결합을 도와줍니다.

구상 클래스가 아닌 추상 클래스/인터페이스에 맞춰서 코딩할 수 있게 해주는 강력한 기법입니다.

 

1) simple factory pattern

- 클라이언트와 구상 클래스를 분리시키기 위한 간단한 기법으로 활용 가능

2) factory method pattern

- 추상클래스에서 팩토리 메소드를 위한 인터페이스를 제공

서브 클래스에서 실제 팩토리 메소드 내용을 구현하고 생성하는 일을 수행.

어떤 서브클래스를 호출하느냐에 따라 다른 인스턴스가 생성 됨.

3) abstract factory pattern

- 인터페이스를 이용하여 연관된 또는 의존하는 객체를 구상 클래스를 지정하지 않고도 생성 할 수 있습니다.


반응형

'Design Pattern' 카테고리의 다른 글

싱글톤패턴(singleton Pattern)  (0) 2016.04.24
디자인 패턴의 정의와 종류  (2) 2016.04.24
디자인 패턴(Design Pattern)의 목적?  (0) 2016.04.24

WRITTEN BY
SiriusJ

,
반응형

이어온 Collection 포스팅에서 이제 마지막, Set에 대한 부분입니다.

다른 List, Queue, Map과 같은 collection들과 함께 마지막으로 Set을 살펴봅시다.


/*
* java.util패키지에 Collection이라는 인터페이스가 있는데, List, Set, Queue가 이 인터페이스를 구현한 것이다.
* 보통은 List, Set, Queue, Map이라는 네 가지 자료구조를 사용한다.
* Set은 중복되는 데이터를 허용하지 않는다. 즉, 중복되는 데이터는 하나만 뽑는다.
*/
/**
* Created by 진우 on 2016-07-17.
*/
public class MySetTest {
public static void main(String[] args) {
MySetTest test = new MySetTest();

String[] fruits = new String[]{
"Apple", "Banana", "Orange",
"Grapefruit", "Pineapple", "Mango",
"Watermelon", "Melon", "Strawberry",
"Orange", "Blueberry", "Lemon",
"Apple"
};
System.out.println(test.getFruits(fruits));
}

public int getFruits(String[] fruits) {
if(fruits == null) return 0;
if(fruits.length == 1) return 1;
HashSet<String> fruitsSet = new HashSet<String>();
for(String fruit:fruits) {
fruitsSet.add(fruit);
}
showFruitSet(fruitsSet); //Same function with showFruitSet2
//showFruitSet2(fruitsSet); //Same function with showFruitSet
return fruitsSet.size();
}
//////////////////////////////////////////////////////
public void showFruitSet(HashSet<String> fruitSet) {
for(String tmp : fruitSet) {
System.out.print(tmp + " ");
}
System.out.println();
}

public void showFruitSet2(HashSet<String> fruitSet) {
Iterator<String> iter = fruitSet.iterator();
while(iter.hasNext()) {
System.out.print(iter.next()+" ");
}
System.out.println();
}
}


반응형

WRITTEN BY
SiriusJ

,