반응형

파이어 베이스 주소 : https://firebase.google.com/?hl=ko

 

Firebase

Firebase는 고품질 앱을 빠르게 개발하고 비즈니스를 성장시키는 데 도움이 되는 Google의 모바일 플랫폼입니다.

firebase.google.com

1. 우선 firebase 프로젝트를 만든다. (굳이 처음에 안만들어도 안드로이드 스튜디오에서 만들 수 있음.)

프로젝트 제목은 20200523으로 설정하였다.

2. 여기서 실시간 데이터 베이스를 선택한다.

3. 실시간 데이터베이스를 들어가면 이런 화면이 뜨는데 여기서 데이터 옆에 규칙을 눌러준다.

4. 규칙에 들어가면 이런 화면이 뜨는데 데이터베이스에 저장된 내용을 읽고 쓰기 위해서 readwritetrue로 바꿔준다.(기본 상태는 false이다.)

5. 안드로이드 스튜디오에서 새로운 프로젝트를 만든뒤에 Tools에 firebase를 눌러준다.

6. 파이어베이스를 누르면 이런 화면이 나오게 되는데 여기서 Realtime Database를 눌러준다.

7. 새로운 프로젝트를 만들거나 이미 만들어놓은 프로젝트를 선택한 뒤 Connect to Firebase를 누른다.

 그러면 이렇게 로그인 화면이 나오게 되고 파이어베이스를 사용할 때 쓰는 구글 아이디로 로그인하면 된다.

이런 화면이 나오게 되는데

허용을 누르면 이렇게 완료라는 화면이 나온다.

밑에는 파이어베이스와 앱을 연결해주는 코드 

   1) MainActivitay.java

package com.example.dbexam;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private EditText editText;
    private Button button;

    DatabaseReference mRoootRef = FirebaseDatabase.getInstance().getReference();
    // DatabaseReference 는 데이터베이스에서 데이터를 읽고 쓰려면 꼭 필요
    DatabaseReference conditionRdf = mRoootRef.child("text");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 데이터의 변화를 알기 위해
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);
    }
    protected void onStart(){
        super.onStart();

        conditionRdf.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // 데이터 값이 변했을 때마다 작동, text 안에 받아온 데이터 문자열을 넣어줌
                String text = dataSnapshot.getValue(String.class);
                textView.setText(text);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // 에러가 날 때 작동
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conditionRdf.setValue(editText.getText().toString());
            }
        });
    }


}

   2) activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="10dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:textSize="30dp"
        android:layout_weight="1"
        android:layout_gravity="center_vertical|center_horizontal"
        android:text="TextView" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="TEXT를 입력하세요"
            android:inputType="text"
            />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send" />
    </LinearLayout>
</LinearLayout>

안드로이드 스튜디오를 사용하기 전에는 앱인벤터로 firebase와 연결했는데 앱인벤터가 알다시피 제약이 많기에 불편했는데 안드로이드 스튜디오는 너무 쉽고 빠르게 잘 연결 되어서 좋았다.

반응형
반응형

(1) MainActivity.java

package com.example.mutitouch;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MultiTouchView(this, null));
    }
}

(2) MultTouchView.java

package com.example.mutitouch;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.jar.Attributes;

public class MultiTouchView extends View {
    private static final int SIZE = 60;
    final int MAX_POINTS = 10;
    float[] x = new float[MAX_POINTS];
    float[] y = new float[MAX_POINTS];
    boolean[] touching = new boolean[MAX_POINTS];

    private Paint mPaint;

    public MultiTouchView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint((Paint.ANTI_ALIAS_FLAG));
        mPaint.setColor(Color.BLUE);
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int index = event.getActionIndex();
        int id = event.getPointerId(index);
        int action = event.getActionMasked();
        switch (action){
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                x[id] = (int) event.getX(index);
                y[id] = (int) event.getY(index);
                touching[id] = true;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
            case MotionEvent.ACTION_CANCEL:
                    touching[id] = false;
                break;
        }
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for(int i = 0; i < MAX_POINTS; i++){
            if(touching[i]){
                canvas.drawCircle(x[i], y[i], SIZE, mPaint);
            }
        }
    }
}

반응형
반응형

xml 파일은 필요하지 않음.

(1)MainActivity.java

package com.example.touchevent;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    protected class MyView extends View {
        int x = 100, y = 100;
        String str;
        public MyView(Context context) {
            super(context);
            setBackgroundColor(Color.YELLOW);
        }
        @Override
        protected void onDraw(Canvas canvas) {
            Paint paint = new Paint(); // paint.setColor(Color.BLUE);
            paint.setColor(Color.rgb(0,0,255));
            canvas.drawCircle(x, y, 50, paint);
            paint.setTextSize(50);
            canvas.drawText("액션의 종류: " + str, 0, 100, paint);
        }
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            x = (int) event.getX();
            y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP)
                str = "ACTION_UP";
            if (event.getAction() == MotionEvent.ACTION_DOWN)
                str = "ACTION_DOWN";
            if (event.getAction() == MotionEvent.ACTION_MOVE)
                str = "ACTION_MOVE";
            invalidate();
            return true;
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView myView = new MyView(this);
        setContentView(myView);
    }
}

(2) 실행화면

반응형
반응형

배달앱이나 여러 쇼핑사이트들에서 흔히 볼 수 있는 평점 다는 기능을 (별점) ratingbar로 구현 해보았다.

(1) MainActivity.java

package com.example.ratingapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView textView2;
    RatingBar ratingBar;
    String str;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ratingBar = findViewById(R.id.ratingBar);
        textView2 = findViewById(R.id.textView2);
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                Toast.makeText(getApplicationContext(),"New Rating: "+ rating, Toast.LENGTH_SHORT).show();
                str = String.valueOf(rating);
                str = Float.toString(rating);
                textView2.setText(str);
            }
        });
    }
}

결과 텍스트의 rating에서 얻은 값을 넣고 싶어서 float형을 string형으로 바꾸었다. 

-> float 형을 string으로 바꾸는 법

str = String.valueOf(rating);
str = Float.toString(rating);

(2) activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:backgroundTint="#C11515"
        android:numStars="5"
        android:stepSize="1.0" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="평점은: "
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:hint="결과"
            android:textSize="20dp" />
    </LinearLayout>

</LinearLayout>

평점 어플

 

반응형
반응형

RadioButton을 사용하여 성별을 체크하는 앱 만들기 

먼저 라디오 그룹 밑에 라디오 버튼 3개를 넣어준다. (레이아웃은 LinearLayout으로 한다. 사실 이 레이아웃으로 왠만한 레이아웃 만들기 다 가능)

 

1. activity_main.xml

이제 버튼이나 텍스트 그리고 배경에 색을 입혀주었다.

색 참고 주소 https://color.adobe.com/ko/create

 

https://color.adobe.com/ko/create

 

color.adobe.com

여기에 들어가서 색을 조합한 다음 복사해서 붙여준다.

android:textColor="#000000"
android:background="#E6D7BE"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FDFBDE"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="당신은 ?"
        android:textColor="#000000"
        android:textSize="20dp"
        android:background="#E6D7BE"
        android:padding="16dp"
        android:gravity="center"
        android:singleLine="true"
        android:textStyle="bold" />

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radio_men"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="남자" />

        <RadioButton
            android:id="@+id/radio_women"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="여자" />

        <RadioButton
            android:id="@+id/radio_robot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="로봇" />

    </RadioGroup>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#E8CA90"
        android:textSize="17dp"
        android:textStyle="bold"
        android:text="확인" />

</LinearLayout>

이 상태에서 저 View Options(눈모양 저거 말하는 거임) 누르고 show Layout Decorations를 누르면 

이렇게 된다.

2. MainActivity.java

package com.example.myapplicationtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    RadioButton radio_men, radio_women, radio_robot;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        radio_men = findViewById(R.id.radio_men);
        radio_men.setChecked(true);
        radio_men.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(radio_women.isChecked())
                    textView.setText("여자가 체크되었습니다.");
                else
                    textView.setText("로봇이 체크되었습니다.");
            }
        });
        radio_women = findViewById(R.id.radio_women);
        radio_women.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(radio_men.isChecked())
                    textView.setText("남자가 체크되었습니다.");
                else
                    textView.setText("로봇이 체크되었습니다.");
            }
        });
        radio_robot = findViewById(R.id.radio_robot);
        radio_robot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(radio_robot.isChecked())
                    textView.setText("로봇이 체크되었습니다.");
                else
                    textView.setText("여자가 체크되었습니다.");

            }
        });
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                String str;
                if(radio_men.isChecked()) {
                    str = "남자";
                }
                else if(radio_women.isChecked()){
                    str = "여자";
                }
                else{
                    str = "로봇";
        }
            Toast.makeText(getApplicationContext(),"당신은" + str,Toast.LENGTH_SHORT).show();
            }
        });

    }
}

 

3. 실행화면 

반응형
반응형

버튼을 누르면 다른 화면으로 넘어감.

 

MainActivity.java

package com.example.intentexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Button btn_move;
    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_move = findViewById(R.id.btn_move);
        editText = findViewById(R.id.editText);
        btn_move.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = editText.getText().toString();
                editText.setText("clear");
                Intent intent = new Intent(MainActivity.this, SubActivity.class);
                intent.putExtra("str",str);
                startActivity(intent);
            }
        });
    }

}

이동이라는 버튼을 누르면 "글자를 입력하세요" 창이 clear로 변하고 다음 창으로 thanks를 가지고 넘어감. 

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint = "글자를 입력하세요" />

    <Button
        android:id="@+id/btn_move"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="이동" />

</LinearLayout>

"글자를 입력하세요" 창은 EditText, weight를 1로해서 길게 만듬

이동이라는 버튼은 wrap_content로 글씨 길이에 맞게 설정

 

1번째 화면

SubActivity.java

package com.example.intentexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SubActivity extends AppCompatActivity {
    private TextView textSub;
    private Button btn_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);

        textSub = findViewById(R.id.textSub);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 액티비티 종료 메인화면으로
            }
        });
        Intent intent = getIntent();
        String str = intent.getStringExtra("str");
        textSub.setText(str);
    }
}

activity_sub.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SubActivity" >

    <Button
        android:id="@+id/btn_back"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="메인으로 돌아가기" />

    <TextView
        android:id="@+id/textSub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical|center_horizontal"
        android:text="TextView" />
</LinearLayout>
public void onClick(View v) {
	finish(); // 액티비티 종료 메인화면으로
}

2번째 이동한 화면

토스트메세지 

Toast.makeText(getApplicationContext(),"버튼이 눌렸습니다.",Toast.LENGTH_LONG).show();

반응형
반응형

삽입정렬이란?

주어진 원소들을 하나씩 뽑은 후, 나열된 원소들이 항상 정렬된 형태를 가지도록 뽑은 원소를 바른 위치에 삽입하여 나열하는 정렬방식

 

삽입정렬의 특징 

1. 입력이 거의 정렬된 경우 빠른 수행시간을 보인다.

2. 안정적인 정렬이다.

-  두 데이터가 정렬되지 않은 경우에만 교환이 일어난다.

3. 제자리 정렬이다.

- 데이터를 움직이는 경우는 두원소를 서로 교환하는 경우밖에 없으므로, 데이터가 저장된 공간 이외에 별도 공간을 상수 개만 사용한다.

 

뽑은 원소를 어떻게 바른 위치에 삽입할 수 있을까?

- 컴퓨터에서는 나열된 원소를 하나씩 차례대로 비교하면서 삽입된 위치를 찾을 수 있다.

 

#include<stdio.h>
int temp, n= 10;
InsertSort(int A[],int n){
	for(int i = 0; i<n; i++){
		for(int j = i; j>0 && A[j]<A[j-1]; j--){ //정렬된 원소들과 비교 
			temp = A[j]; // 원소를 서로 교환 
			A[j] = A[j-1];
			A[j-1] = temp;
		}
		printf("%d단계를 출력 :", i);
		for(int k=0; k<n; k++){ //정렬되는 과정 출력 
			printf("%d ", A[k]);
		}
		printf("\n");
	}
}
int main(){
	int n = 10; //원소의 개수 
	int A[10]; //정렬 선언 
	printf("입력하세요 :");
	for(int i= 0; i<n; i++){ //정렬할 배열 입력하기 
		scanf("%d",&A[i]);
	}
	InsertSort(A, n);
	for(int i=0; i<n; i++){
		printf("%d ", A[i]); //정렬완료
	}
}
/*
입력하세요 :5 4 3 2 1
0단계를 출력 :5 4 3 2 1
1단계를 출력 :4 5 3 2 1
2단계를 출력 :3 4 5 2 1
3단계를 출력 :2 3 4 5 1
4단계를 출력 :1 2 3 4 5
1 2 3 4 5
--------------------------------
Process exited after 3.268 seconds with return value 0
계속하려면 아무 키나 누르십시오 . . .
*/

정렬 공부하면서 느꼈던 건데 내 입장에서는 단순하게 오름차 or 내림차순으로 정렬하면 되니까 쉽다고 생각되는데 컴퓨터로 구현해보면 생각보다 복잡함.(대충알면 쉽다고 느껴지는데 공부할 수록 때려치고 싶음.) 특히 자료구조 시험을 치면서 느낀건데 대충 정렬 안되어있는 상태에서 오름차순으로 정렬할때까지 몇단계가 필요한가? 이런 문제는 비교적 쉬운데 초기 상태에 숫자들이 많다거나 아니면 어떤수가 어디에 위치되어 있는 경우는 몇단계인가? 이런식의 질문은 많이 화가남. 특히 중간에서 계산실수하면 멘탈나가는거임. 신기한 건 나이를 먹어갈 수록 사칙연산을 못하는 거 같은 느낌 이상하다. 왜 반비례하는 건지 사칙연산은 초등학교 2학년때 가장 잘했던 거 같다.

반응형

'2019~2020 > 자료구조' 카테고리의 다른 글

선택정렬이란  (0) 2019.09.11
버블정렬  (0) 2019.09.11
최댓값 찾기 알고리즘  (0) 2019.09.03
bfs-dfs  (0) 2019.08.26
행렬을 이용한 BFS (c)  (0) 2019.08.20
반응형

먼저 파이어베이스에 접속하여 로그인한다. 

파이어베이스 주소 : https://firebase.google.com/?hl=ko

 

Firebase

Firebase는 고품질 앱을 빠르게 개발하고 비즈니스를 성장시키는 데 도움이 되는 Google의 모바일 플랫폼입니다.

firebase.google.com

 

먼저 콘솔로 이동을 클릭한다. 그리고 자신의 프로젝트를 선택하여 들어간 뒤 

옆에 톱니바퀴 우리가 흔히 설정의 아이콘으로 알고 있는 저 익숙한 아이콘을 선택하면 프로젝트 설정과 사용자 및 권한이 나오게 되는 데 그 중에 '프로젝트 설정'을 누르면 된다.

그 후 서비스 계정을 누르고 밑으로 내려보면 '데이터베이스 비밀번호'라고 써 있는 곳이 있는데 거기를 클릭한다.

클릭하면 저렇게 비밀번호가 동그라미로 나오게 되는 데 가장 오른쪽에 마우스를 가져다 놓으면 표시라는 것이 뜨게 된다. 그것을 꾹 클릭하면 복사하기 라는 아이콘이 나오는데 그걸 클릭한 후 저기 아두이노 코드에 붙여넣기 하면 된다.

 

 

여기서 환경설정(Ctrl + Comma)를 누른다. 그러면 

이런 화면이 나오게 되는데 여기서 저기 추가적인 보드 매니저 URLs 줄에 있는 파란색 네모를 누른다(네모 두개 겹쳐져있는 거 말하는 거임.)

그걸 누르면 

이런 화면이 나오는데(원래 있었는데 설명하느라 지워버림. ㅎ) 저 화면 흰색 부분에 http://arduino.esp8266.com/stable/package_esp8266com_index.json 를 삽입하고 확인을 누른다.

 

+ 2020-11-26

요즘 새로 파이어베이스 라이브러리가 바뀌면서 기존코드가 안되고 있는 상황이라고 들었는데 그래서 나도 열심히 여러 사람들의 포스팅을 참고해서 보드 매니저에 dl.espressif.com/dl/package_esp32_index.json

도 추가해보고 툴-> 보드매니저에서 esp8266를 검색해서 설치했더니 된다. (진짜 식은땀 좔좔)

 

툴 -> 라이브러리 관리를 눌러준다. 그러면 

이런 화면이 나오는데 여기서 json 이라고 친다. 그러면 ArduinoJson by Benoit Blanchon를 누르고 설치를 눌러준다.

 

그리고 나서 파이어베이스 라이브러리를 추가해줘야하는데

https://github.com/mobizt/Firebase-ESP8266

 

mobizt/Firebase-ESP8266

ESP8266 Firebase RTDB Arduino Library. Contribute to mobizt/Firebase-ESP8266 development by creating an account on GitHub.

github.com

여기로 들어가서 다운받으면 된다. 하지만 나는 귀찮고 이 글을 보시는 분들중에 아주 귀찮아 하시는 분들이 있을 수 있으니까 파일을 올려드리겠습니다.

Firebase-ESP8266-master.zip
0.14MB

이걸 다운받으신 후에 'libraries'폴더 안에 압축을 풀면 된다. (사람마다 경로가 다를 수 있다. 왜냐하면 아두이노를 어디에 설치했는지 모르니까?)

 

풀코드 

#include <ESP8266WiFi.h>
#include "FirebaseArduino.h" // 파이어베이스 라이브러리

#define FIREBASE_HOST "파이어베이스아이디"
#define FIREBASE_AUTH "비밀번호"
#define WIFI_SSID " "
#define WIFI_PASSWORD " "

#include "DHT.h"
#define DHTPIN 5     // what digital pin we're connected to
#define DHTTYPE DHT11  // DHT 22  (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());
  
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

  Serial.println("DHT11 test!");
  dht.begin();
}

int n = 0;

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.print("Error");
    return;
  }
  Firebase.setFloat("Humidity",h);
  Firebase.setFloat("Temperature",t);

  
  n++;
  // set value
  Firebase.setFloat("number", n);
  // handle error
  if (Firebase.failed()) {
      Serial.print("setting /number failed:");
      Serial.println(Firebase.error());  
      return;
  }
  delay(1000); 
}

 

 

반응형
반응형

선택정렬이란?

주어진 원소 중에서 가장 작은 킷값을 갖는 원소를 선택하여 차례대로 나열하는 정렬방식. 그러니까

처음부터 끝까지 비교해가면서 가장 작은(큰) 수를 찾아 순서대로 만들어 간다.

 

선택정렬의 특징

1. 정렬할 원소의 개수가 일정하다면, 언제나 동일한 수행시간이 걸린다.

2. 안정적이지 않은 정렬이다.(삽입정렬과 반대)

ex) 1 5 30 30 25

-> 1 5 30 30 25 

-> 1 5 30 30 25

-> 1 5 25 30 30

-> 1 5 25 30 30 

정렬이 끝난 시점에 30 30이 30 30으로 순서가 바뀌므로 안정적이지 않은 정렬임.

3. 제자리 정렬이다.

#include<stdio.h>
SelectionSort(int A[],int n){
	int Min, temp, i, j;
	for(i= 0; i<10; i++){
		Min = i; //최솟값 설정   
		for(j=0; j<10; j++){
			if(A[j]<A[Min])
				Min = j; //새로운 최솟값  
		}
		if(Min =! i){ 
		//만약 Min이 i가 아닐때 A[i]와 A[Min] 교환  
			temp = A[i];
			A[i] = A[Min];
			A[Min] = temp;
		}
        printf("%d단계를 출력 :", i);
		for(int k=0; k<n; k++){ //정렬되는 과정 출력 
			printf("%d ", A[k]);
		}
		printf("\n");
	}
}
int main(){
	int A[10];
	printf("입력하세요:");
	for(int i=0; i<10; i++){
		scanf("%d",&A[i]);
	}
	SelectionSort(A, 10);
	for(int i=0; i<10; i++){
		printf("%d",A[i]);
	}
}
/*
입력하세요 :1 3 2 5 4 7 6 0 8 9
0 1 2 3 4 5 6 7 8 9
--------------------------------
Process exited after 1.416 seconds with return value 0
계속하려면 아무 키나 누르십시오 . . .
*/

아마 버블정렬이랑 함께 내가 가장 많이 쓰는 정렬이지 않을까 싶음. 이유는 나도 모르겠음. 근데 C++과 파이썬 그리고 자바 등등으로 넘어가면서 정렬하는 그런 기본적인 코드에 대한 생각을 안한지는 진짜 오래된듯. 그래서 지금 이렇게 보니까 되게 새로움. 그렇다고 다시 공부하겠다거나 그런 생각은 들지 않을 거라 생각하긴 했는데 진짜 신기하기만 하고 그때 열심히 공부했던 게 떠올라서 별로..라는 생각이 드네^^

반응형

'2019~2020 > 자료구조' 카테고리의 다른 글

삽입정렬이란  (0) 2019.09.16
버블정렬  (0) 2019.09.11
최댓값 찾기 알고리즘  (0) 2019.09.03
bfs-dfs  (0) 2019.08.26
행렬을 이용한 BFS (c)  (0) 2019.08.20
반응형

정렬은 오름차순 또는 내림차순으로 이루어지는데, 특별한 언급이 없으면 오름차순 정렬을 기본으로 한다.

 

버블정렬이란?

주어진 리스트의 왼쪽에서부터 모든 인접한 두 원소를 순서대로 비교하면서 자리바꿈을 통해 정렬된 순서를 맞추는 것을 반복함녀서 정렬하는 방식.

 

 - 이름의 유래 -

이웃한 값끼리 비교하여 교환하는 모습이 마치 거품이 보글보글하는 모양과 비슷하다고 해서 붙여진 이름임.

 

버블정렬의 특징 

1. 선택정렬에 비해 원소의 교환이 많이 발생하여 비효율적이다.

2. 안정적인 정렬이다.

- 인접한 두 데이터가 정렬되지 않은 경우에만 교환이 일어나므로 킷값이 같은 겨웅에는 교환이 일어나지 않는다.

3. 제자리 정렬이다.

- 데이터가 움직이는 경우는 두 원소를 서로 교환하는 경우밖에 없으므로, 데이터가 저장된 공간 이외에 별도의 공간을 상수 개만 사용한다. 

#include<stdio.h>
int BubbleSort(int A[],int n){
	int BOUND, temp, top, j;
	BOUND= -1;
	do{
		top = n;
		for(j=top-1; j>BOUND; j--){
			if(A[j]<A[j-1]){
				temp = A[j];
				A[j] = A[j-1];
				A[j-1] = temp;
				top = j;
			}	
            printf("%d단계를 출력 :", i);
			for(int k=0; k<n; k++){ //정렬되는 과정 출력 
				printf("%d ", A[k]);
			}
		printf("\n");
		}
		BOUND = top;
	}while(top<n);
}

int main(){
	
	int n = 10;
	int A[10];
	printf("입력하세요 :");
	for(int i= 0; i<n; i++){
		scanf("%d",&A[i]);
	}
	BubbleSort(A, n);
	for(int i=0; i<n; i++){
		printf("%d ", A[i]);
	}
}
/*
입력하세요 :1 3 2 5 4 7 6 0 8 9
0 1 2 3 4 5 6 7 8 9
--------------------------------
Process exited after 8.36 seconds with return value 0
계속하려면 아무 키나 누르십시오 . . .
*/

선택정렬 다음으로 제일 많이 사용하는 버블정렬.

그렇게까지 효율적이지도 않은데 많이 사용했었음. 이유는 없다. 그냥 이름이 귀여워서 그런가 물론 실제로는 귀엽지 않지만^^ 이름이라도 귀여우니까^^

반응형

'2019~2020 > 자료구조' 카테고리의 다른 글

삽입정렬이란  (0) 2019.09.16
선택정렬이란  (0) 2019.09.11
최댓값 찾기 알고리즘  (0) 2019.09.03
bfs-dfs  (0) 2019.08.26
행렬을 이용한 BFS (c)  (0) 2019.08.20

+ Recent posts