[알고리즘] 배열 역순

[알고리즘] 배열 역순
// 배열 역순

function reverse(&$a) {
    $start = 0; // 배열시작 인덱스 
    $count = count($a);
$end = $count - 1; // 배열끝 인텍스,  0 부터 시작하니 배열갯수에서 1을 뺌

    while ($start < $count/2) {
        /* 요소 교체 */
        $temp = $a[$end];
        $a[$end--] = $a[$start];
        $a[$start++] = $temp;
    }
}
$a = array(1,2,3,4,5,6,7,8,9);

foreach ($a as $k => $v) echo($a[$k]);
echo '<br />';

reverse($a);

foreach ($a as $k => $v) echo($a[$k]);

 

/* output 

123456789

987654321

*/ 

[알고리즘] 배열로 구현하는 스택(stack)

[알고리즘] 배열로 구현하는 스택(stack)
// 배열로 구현하는 스택 

// 스택 최대크기 5

define('MAX', 5);
$top = 0;
$stack = array();
 
function init_stack() {
    Global $top;
    $top = -1;
}
 
function push($t) {
    Global $top, $stack;
 
    if ($top >= MAX - 1) {
        println('Stack overflow.');
return -1;    
}
    $stack[++$top] = $t;
}
 
function pop() {
    Global $top, $stack;
 
    if ($top < 0) {
        println('Stack underflow.');
return -1;
    } 
    return $stack[$top--];
}
 
function print_stack() {
    Global $top, $stack;
 
    println('Stack contents : Top ----> Bottom');
    for ($i = $top; $i >= 0; $i--) 
        println($stack[$i]);
}
 
init_stack();
 
println('Push 1, 2, 3');
push(1);
push(2);
push(3);
 
print_stack();
println();
 
$i = pop();
println("Pop ". $i);
print_stack();
println();
 
println('Push 4, 5, 6');
push(4);
push(5);
push(6);
 
print_stack();
println();
 
println('Now stack is full, push 7');
push(7);
print_stack();
println();
 
println('Initialize stack');
init_stack();
print_stack();
println();
 
println('Now stack is empty');
println('Pop');
pop();
 
 
println('Push 7, 8');
push(7);
push(8);
print_stack();
println();
 
function println($val='') {
echo $val.'<br />';

 

/* output

Push 1, 2, 3

Stack contents : Top ----> Bottom
3
2
1

Pop 3
Stack contents : Top ----> Bottom
2
1

Push 4, 5, 6
Stack contents : Top ----> Bottom
6
5
4
2
1

Now stack is full, push 7
Stack overflow.
Stack contents : Top ----> Bottom
6
5
4
2
1

Initialize stack
Stack contents : Top ----> Bottom

Now stack is empty
Pop
Stack underflow.
Push 7, 8
Stack contents : Top ----> Bottom
8
7

*/

[알고리즘] 단순 연결 리스트를 이용한 스택(stack)

[알고리즘] 단순 연결 리스트를 이용한 스택(stack)

/*

연결 리스트, 링크드 리스트(linked list)는 각 노드가 데이터와 포인터를 가지고 한 줄로 연결되어 있는 방식으로 

데이터를 저장하는 자료 구조이다. 

이름에서 말하듯이 데이터를 담고 있는 노드들이 연결되어 있는데, 

노드의 포인터가 다음이나 이전의 노드와의 연결을 담당하게 된다. 

연결 리스트의 종류로는 단순 연결 리스트, 이중 연결 리스트 등이 있다. 

*/

// 단순 연결 리스트를 이용한 스택의 구현

 

class Node {

    public $key;

    public $next = Node;

 

$head = new Node;

$tail = new Node;

 

function init_stack() {

    Global $head, $tail;

 

    $head->next = $tail;

    $tail->next = $tail;

}

 

function clear_stack() {

    Global $head, $tail;

    $t = Node;

    $s = Node;

 

    $t = $head->next;

    while ($t != $tail) {

        $s = $t;

        $t = $t->next;

        $s = null;

    }

    $head->next = $tail;

}

 

function push($k) {

    Global $head, $tail;

    $t = new Node;

   

    if ($t == NULL) {

        println("   Out of memory...");        

    }

  

    $t->key = $k;

    $t->next = $head->next;

    $head->next = $t;

}

 

function pop() {

    Global $head, $tail;

    $t = new Node;

 

    if ($head->next == $tail)  /* if empty */ {

        println("  Stack underflow.");

        return -1;

    }

    $t = $head->next;

    $i = $t->key;

    $head->next = $t->next;

    $t = null;

    

    return $i;

}

 

function print_stack() {

    Global $head, $tail;

    $t = new Node;

 

    $t = $head->next;

    println("  Stack contents : Top ----> Bottom");

    while ($t != $tail) {

        println($t->key);

        $t = $t->next;

    }

}

 

init_stack();

 

println('Push 1, 2, 3');

push(1);

push(2);

push(3);

print_stack();

 

$i = pop();

println('Pop '.$i);

print_stack();

 

println('Push 4, 5, 6');

push(4);

push(5);

push(6);

print_stack();

 

println('Initialize stack');

clear_stack();

print_stack();

 

println('Now stack is empty,');

println('Pop');

$i = pop();

print_stack();

 

function println($str=''){

    echo $str.'<br />';

 

/* output

Push 1, 2, 3

Stack contents : Top ----> Bottom
3
2
1
Pop 3
Stack contents : Top ----> Bottom
2
1
Push 4, 5, 6
Stack contents : Top ----> Bottom
6
5
4
2
1
Initialize stack
Stack contents : Top ----> Bottom
Now stack is empty,
Pop
Stack underflow.

Stack contents : Top ----> Bottom 

*/

[알고리즘] 이중연결리스트를 이용한 큐(queue)

[알고리즘] 이중연결리스트를 이용한 큐(queue)

<?

/* 

큐(queue)는 컴퓨터의 기본적인 자료 구조의 한가지로, 

먼저 집어 넣은 데이터가 먼저 나오는 FIFO (First In First Out)구조로 저장하는 형식을 말한다 

 

http://terms.naver.com/entry.nhn?docId=834442&cid=42344&categoryId=42344

http://ko.wikipedia.org/wiki/%ED%81%90_(%EC%9E%90%EB%A3%8C_%EA%B5%AC%EC%A1%B0)

*/

 

// 시작노드와 끝노드만 남기고 나머지 노드 삭제

function clear_queue() {

    global $head, $tail;

 

    $t = new dnode;

    $s = new dnode;

    $t = $head->next;

    while ($t != $tail) {

        $s = $t;

        $t = $t->next;

        $s = null;

    }

    $head->next = $tail;

    $tail->prev = $head;

}

 

// 마지막 노드 앞에 새 노드 삽입

function put($k) {

    global $head, $tail;

 

    $t = new dnode;

 

    $t->key = $k;

    $tail->prev->next = $t;

    $t->prev = $tail->prev;

    $tail->prev = $t;

    $t->next = $tail;

 

    return $k;

}

 

// 큐에 시작노드 다음 노드의 key 값 가져오기

function get() {

    global $head, $tail;

 

    $t = new dnode;

    $i = 0;

    $t = $head->next;

    if ($t == $tail) {

        printf('<br />    Queue underflow.');

        return -1;

    }

    $i = $t->key;

    $head->next = $t->next;

    $t->next->prev = $head;

    $t = null;

    return $i;

}

 

// 큐에 저장된 key 값 보여주기

function print_queue() {

    global $head, $tail;

 

    $t = $head->next;

    printf('<br />  Queue contents : Front ----> Rear<br />');

    while ($t != $tail) {

        printf('%2d', $t->key);

        $t = $t->next;

    }

}

 

// 노드정의

class dnode {

    public $key = 0, 

$prev = null, 

$next = null;

 

$head = new dnode; // 시작노드

$tail = new dnode; // 끝노드

 

$head->prev = $head;

$head->next = $tail;

$tail->prev = $head;

$tail->next = $tail;

 

printf('<br />Put 1, 2, 3, 4, 5, 6');

put(1);

put(2);

put(3);

put(4);

put(5);

put(6);

print_queue();

 

echo ('<br /><br />Get');

$i = get();

printf('<br />   getting value is %d', $i);

print_queue();

 

printf('<br /><br />Put 7, 8, 9, 1');

put(7);

put(8);

put(9);

put(1);

print_queue();

 

printf('<br /><br />Put 2');

put(2);

print_queue();

 

printf('<br /><br />Initialize queue');

clear_queue();

print_queue();

 

printf('<br /><br />Now queue is empty');

echo ('<br />Get');

$i = get();

printf('<br />   getting value is %d', $i);

print_queue();

?> 

범위사이에서 중복없이 랜덤(random)으로 뽑기

범위사이에서 중복없이 랜덤(random)으로 뽑기function random($min, $max, $num) {

$arr = array();
while ($num > count($arr)) {
$i = rand($min, $max);
$arr[$i] = $i; 
}
return $arr;
}

foreach (random(1,9, 5) as $v) echo $v;

 

/* output

1과 9사이에서 랜덤으로 중복없이 5개 뽑기

43186

*/

 

[알고리즘] 하노이의 탑

[알고리즘] 하노이의 탑

/*

하노이의 탑 

http://ko.wikipedia.org/wiki/%ED%95%98%EB%85%B8%EC%9D%B4%EC%9D%98_%ED%83%91 

 

1. 한번에 하나만 이동.(모든 원반을 마지막 기둥으로.)

2. 작은원반 위로 큰 원반을 이동할 수 없다.
3. 가장위의 원반만 이동가능.

알고리즘
1. 기둥 1에서 N-1개의 원반을 기둥 2로 옮긴다
2. 기둥 1에서 1개의 원반을 기둥 3으로 옮긴다.
3. 기둥 2에서 N-1개의 원반을 기둥 3으로 옮긴다.

from 기둥에서 to기둥으로 by기둥을 이용하여 옮기기
from : 이동할 기둥
to : 이동되어질 기둥

hanoi(원반수, 이동할 기둥, 나머지기둥, 이동되어질 기둥)
*/

 

function move($from, $to) {

    printf("<br />Move from %d to %d", $from, $to);

}

 

function hanoi($n, $from, $by, $to) {

    if ($n == 1)

        move($from, $to);

    else {

        hanoi($n-1, $from, $to, $by); // 1

        move($from, $to); // 2

        hanoi($n-1, $by, $from, $to); // 3

   }

}

 

$height = 3;

printf("Height of HANOI tower is %d <br />",$height);

hanoi($height, 1, 2, 3); 

 

/* output

Height of HANOI tower is 3 


Move from 1 to 3
Move from 1 to 2
Move from 3 to 2
Move from 1 to 3
Move from 2 to 1
Move from 2 to 3

Move from 1 to 3 

*/

php 에러 출력하기

php 에러 출력하기

error_reporting(E_ALL);

ini_set("display_errors", 1);


위 두 소스를 이용하면 되는데요

 웹 호스팅을 사용하다보면 에러출력을 php.ini에서 막는 경우가 있어요


그럴 경우 위 소스를 페이지 상단에 넣어두면 에러를 출력하게 되요 

php에서 배열에 담긴 값을 중복제거 하기

php에서 배열에 담긴 값을 중복제거 하기

$array_ = array();

$array_[0] = "1";

$array_[1] = "2";

$array_[2] = "1";

 

​array_unique($array_);

 

이렇게 할 경우 이것을 출력하게 되면 1, 2만 나오게 되요

 

배열에서 중복된 값을 제거하는 명령어에요

페이지에 좋은글,책속의 한줄 랜덤으로 뿌리기

페이지에 좋은글,책속의 한줄 랜덤으로 뿌리기

book.zip



한글 다 깨지니 


페이지 상단에 밑에 태그 넣고

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


파일 저장은 UTF-8 로 반드시 해야 합니다.(메모장 또는 editplus 추천 다른 에디터는 제대로 적용안되더군요)



1.파일형식으로  코딩


밑의 코드페이지와 위의 첨부파일(book.txt)을 같은 폴더에 둡니다.



<?


$mentFile = "book.txt";  

$fp = fopen($mentFile, "r");


while(!feof($fp)) $ment[] = fgets($fp, 1024);

 





//### $ment 배열에서 랜덤키 생성

$key = array_rand($ment);

### 랜덤 생성된 명언 출력

echo $text_this=$ment[$key];


?>



2.my_sql 연동방식


 

1.테이블 생성


CREATE TABLE IF NOT EXISTS `books` (

  `no` int(11) NOT NULL AUTO_INCREMENT,

  `content` text NOT NULL,

  PRIMARY KEY (`no`),

  KEY `no` (`no`)

)


 


2.mysql 에 위에 첨부된 book.txt 집어 넣습니다.

 

phpmyadmin 에서 import 탭에서 

필드 구분자 ->   \t

필드 구분자-> content


로 하는것 유의 


방법은 서기님 강좌 참고http://vod.singsinghe.co.kr/movie/php/48/php_48.html


 




3.코딩


 

<?

$conn=mysql_connect("","","");

mysql_select_db("");




$random = rand(1,283);  //no 의 처음과 끝사이에 랜덤하게 1개 $random 변수에 지정 (db 넘버 반드시 확인 )


$query="select * from books where no='$random'"; // 랜덤 생성된 1개 no 필드에서 가져오기


$result=mysql_query($query,$conn);

$data=mysql_fetch_array($result);

$text_this=$data[1]; 



echo $text_this;




?>

 


하면 됩니다..


3.

JQuery 로 

 뿌리기 

 

 

위와 같이 바로 해도 되고..같은 폴더에 코딩 한거 두고 뿌리기 원하는 페이지에 

JQuery 로 가져 와도 됩니다.

 

 

 

 

 

<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>

$(document).ready(function() {

 

    $("#div1").load("books.php");

 

});

 

 

</script>

</head>

<body>

 

<div id="div1"></div><div id="div"></div>

 

</body>

 

4.이쁘게 둥근 테두리로 만들기

 

 첨부된 books.php 파일 참고하세요..

여기 게시판 중간에 글이 짤리네요..너무 길어서 그런가봐요

book.zip

아버지의 눈물

아버지의 눈물


0928_3

“어디서 난 옷이냐? 어서 사실대로 말해 봐라.”

아들이 살 수 없는 고급 브랜드의 청바지를 본 순간,
아버지는 이상한 생각이 들어 아들을 다그쳤다.

자신은 환경미화원이고
아내는 작은 고물상을 운영하고 있기에,
아들이 그런 큰돈을 쓸 수 있을 리 없었다.
결국 아들은 사실을 털어놓았다.

“죄송해요. 버스 정류장에서 지갑을 가져왔어요.”

아버지는 그만 자리에 털썩 주저앉고 말았다.
“내 아들이 남의 돈을 훔치다니…”

잠시 뒤 아버지가 정신을 가다듬고 말했다.
“환경이 어렵다고 잘못된 길로 빠져서는 안 된다.”

아버지는 눈물을 흘리며 아들의 손을 꼭 잡고
경찰서로 데려가 자수를 하게했다.
자식의 잘못을 감싸기만 바쁜 세상에
뜻밖의 상황을 대면한 경찰은 
의아해하면서 조사를 시작했다.

경찰 조사 과정에서 아들의 범죄사실이 하나 더 밝혀졌고,
결국 아들은 법정까지 서게 되었다.

그 사이 아버지는 아들이 남의 돈을 훔친 것에 
가슴 아파하다가 그만…
심장마비로 세상을 떠나고 말았다.

재판이 열린 날,
어머니는 법정에서 울먹이면서 말했다.
“아들이 올바른 사람이 되기를 바랬던 남편의 뜻대로..
안타깝지만 아들에게 엄한 벌을 내려 주십시오.”

아들도 눈물을 흘렸다.
“제가 한 행동 때문에 아버지가 돌아가셨어요. 흐흐흑.”

이를 지켜보던 주위 사람들은 모두 숙연해졌다.

드디어 판결의 시간.
판사는 입을 열었다.
“불처분 하겠습니다.”

뜻밖의 판결에 어리둥절해하는 사람들에게
판사가 그 이유를 밝혔다.

“훌륭한 아버지의 뜻을 따를 것이라 믿기 때문입니다.”

==========================================

자식의 잘못을 바로잡기 위해 노력한 아버지의 마음…
자녀를 진정으로 위하는 길은 여기에 있습니다.

 

# 오늘의 명언
가지를 잘 쳐주고 받침대로 받쳐 준 나무는 곧게 잘 자라지만,
내버려 둔 나무는 아무렇게나 자란다.
사람도 이와 마찬가지여서
남이 자신의 잘못을 지적해 주는 말을 잘 듣고
고치는 사람은 그만큼 발전한다.
- 공자 -