반응형
# 바로 위에 개발한 머신러닝 모델은 길이가 25cm이고 무게가 150g이면 빙어모델로 예측한다고 함
fish_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0, 
                31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0, 
                35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0, 9.8, 
                10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]
fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0, 
                500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0, 
                700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0, 6.7, 
                7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]

import numpy as np
np.column_stack(([1, 2, 3], [4,5,6]))

fish_data = np.column_stack((fish_length, fish_weight))
print(fish_data[:5])

 

<출력>

[[ 25.4 242. ]
 [ 26.3 290. ]
 [ 26.5 340. ]
 [ 29.  363. ]
 [ 29.  430. ]]

 

 

# fish_target = [1] * 35 + [0] * 14 이 역할을 하던 놈
# np.ones(35) : 1이 35개인 배열, np.zeros(14) : 0이 14개인 배열
fish_target = np.concatenate((np.ones(35), np.zeros(14)))

# 앞에서는 훈련세트와 테스트 세트를 나눌때 
# 번거롭게 랜덤 돌린 뒤 잘라냈지만 
# 여기서는 train_test_spit()을 이용한다. 
# 이는 섞는것까지 알아서 해줌

from sklearn.model_selection import train_test_split

train_input, test_input, train_target, test_target 
 = train_test_split(fish_data, fish_target, random_state=42)
# 비율이 안맞아 샘플링 편향이 나타난다고 볼 수도 있음
# 이를 해결하려면 stratify를 사용하면된다.

print(test_target)

train_input, test_input, train_target, test_target 
 = train_test_split(fish_data, fish_target, stratify=fish_target, random_state=42)

print(test_target)

<출력>

[1. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[0. 0. 1. 0. 1. 0. 1. 1. 1. 1. 1. 1. 1.]

 

from sklearn.neighbors import KNeighborsClassifier
kn = KNeighborsClassifier()
kn.fit(train_input, train_target)
kn.score(test_input, test_target)

# 바로 위에 개발한 머신러닝 모델은 길이가 25cm이고 무게가 150g이면 빙어모델로 예측한다고 함... 고쳐졌으려나?
print(kn.predict([[25, 150]]))

<출력>

[0.]
# 삐빅... 빙어 입니다!

 

# 도미? 놉! 어찌 된일 일까요?

import matplotlib.pyplot as plt
plt.scatter(train_input[:,0], train_input[:,1])
plt.scatter(25, 150, marker='^') # marker는 특정 값의 매개변수의 모양을 지정 ^ 는 삼각형 모양으로 표시시
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

# 위 데이터 상에서는 도미 데이터에 가까운데 왜 빙어라고 평가 할까?

 

distances, indexes = kn.kneighbors([[25, 150]])

plt.scatter(train_input[:,0], train_input[:,1])
plt.scatter(25, 150, marker='^')
plt.scatter(train_input[indexes,0], train_input[indexes,1], marker='D')  # marder D는 마름모 모양
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

 

# 그래프 y축 한칸의 크기가 너무 커서 그렇지 실제로는 
plt.scatter(train_input[:,0], train_input[:,1])
plt.scatter(25, 150, marker='^')
plt.scatter(train_input[indexes,0], train_input[indexes,1], marker='D') 
plt.xlim((0,1000))
plt.xlabel('length')
plt.ylabel('weight')
plt.show()
# 그래프와 같이 현재 데이터에서는  x값은 사실 생선을 판단하는데 큰 영향이 없다고 볼 수 있음
# (y축에 비해 너무 미미하여 영향력이 거의 없다고 받아들여짐
# 범위가 다르기 때문(스케일이 다르다) 
# 다른 단위로 이루어진 샘플간에 특성값을 일정한 기준으로 맞추는 것을 데이터 전처리 라고 한다.

 

# 교재에서는 널리 사용하는 전처리 방법 중 하나가 표준점수라고하고
# 값에서 평균을 뺴고 표준편차로 나누어주면된다고 한다.

# 통계학에서는 정규화 라고 하는데 크기에 상관없이 기준을 맞추는 작업으로 볼 수 있을 것같다

mean = np.mean(train_input, axis=0)
std = np.std(train_input, axis=0)

print(mean, std)

train_scaled = (train_input - mean) / std


# train_scaled 로 산점도를 다시 그려본다.

plt.scatter(train_scaled[:,0], train_scaled[:,1])
plt.scatter(25, 150, marker='^')
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

 

# 새로 넣을 데이터도 표준화 해야한다.

new = ([25, 150] - mean) / std
plt.scatter(train_scaled[:,0], train_scaled[:,1])
plt.scatter(new[0], new[1], marker='^')
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

kn.fit(train_scaled, train_target)
test_scaled = (test_input - mean) / std
kn.score(test_scaled, test_target)

print(kn.predict([new]))

<출력>

[1.]

 

 

distances, indexes = kn.kneighbors([new])

plt.scatter(train_scaled[:,0], train_scaled[:,1])
plt.scatter(new[0], new[1], marker='^')
plt.scatter(train_scaled[indexes,0], train_scaled[indexes,1], marker='D')  # marder D는 마름모 모양
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

반응형
반응형

SQL server 의 ADO.NET 기초 및 MSSQL 문법에 대해 알아보는 포스팅 입니다.

대부분의 내용은 마이크로소프트 설명서를 기반으로 하였습니다.

 

참고로 MSSOFT 사이트의 설명서 중 하나에 따르면 

 

개발언어별 SQL 드라이버는 아래와 같습니다.

 

C# ADO.NET
Microsoft.Data.SqlClient
다음 운영 체제용 .NET Core: Linux-Ubuntu, macOS, Windows
Entity Framework Core
Entity Framework
C++ ODBC

OLE DB
Java JDBC
Node.js Node.js 드라이버, 설치 지침
PHP PHP
Python pyodbc, 설치 지침
ODBC 다운로드
Ruby Ruby 드라이버, 설치 지침
Ruby 다운로드 페이지

 

 

ADO.NET은 java 프로젝트에서 preparedstatement를 사용하는 것과 유사한 구조다.

다음은 mssoft 사이트 내에 있는 예제 이다.

 

<select 문>

using System;
using DT = System.Data;
using QC = Microsoft.Data.SqlClient;
  
namespace ProofOfConcept_SQL_CSharp  
{  
	public class Program  
	{  
		static public void Main()  
		{  
			using (var connection = new QC.SqlConnection(  
				"Server=tcp:YOUR_SERVER_NAME_HERE.database.windows.net,1433;" +
				"Database=AdventureWorksLT;User ID=YOUR_LOGIN_NAME_HERE;" +
				"Password=YOUR_PASSWORD_HERE;Encrypt=True;" +
				"TrustServerCertificate=False;Connection Timeout=30;"  
				))  
			{  
				connection.Open();  
				Console.WriteLine("Connected successfully.");  
  
				Program.SelectRows(connection);  
  
				Console.WriteLine("Press any key to finish...");  
				Console.ReadKey(true);  
			}  
		}  
  
		static public void SelectRows(QC.SqlConnection connection)  
		{  
			using (var command = new QC.SqlCommand())  
			{  
				command.Connection = connection;  
				command.CommandType = DT.CommandType.Text;  
				command.CommandText = @"  
SELECT  
	TOP 5  
		COUNT(soh.SalesOrderID) AS [OrderCount],  
		c.CustomerID,  
		c.CompanyName  
	FROM  
						SalesLT.Customer         AS c  
		LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh  
			ON c.CustomerID = soh.CustomerID  
	GROUP BY  
		c.CustomerID,  
		c.CompanyName  
	ORDER BY  
		[OrderCount] DESC,  
		c.CompanyName; ";  
  
				QC.SqlDataReader reader = command.ExecuteReader();  
  
				while (reader.Read())  
				{  
					Console.WriteLine("{0}\t{1}\t{2}",  
						reader.GetInt32(0),  
						reader.GetInt32(1),  
						reader.GetString(2));  
				}  
			}  
		}  
	}  
}  
/**** Actual output:  
Connected successfully.  
1       29736   Action Bicycle Specialists  
1       29638   Aerobic Exercise Company  
1       29546   Bulk Discount Store  
1       29741   Central Bicycle Specialists  
1       29612   Channel Outlet  
Press any key to finish...  
****/

 

<insert 문>

using System;
using DT = System.Data;
using QC = Microsoft.Data.SqlClient;
  
namespace ProofOfConcept_SQL_CSharp  
{  
	public class Program  
	{  
		static public void Main()  
		{  
			using (var connection = new QC.SqlConnection(  
				"Server=tcp:YOUR_SERVER_NAME_HERE.database.windows.net,1433;" +
				"Database=AdventureWorksLT;User ID=YOUR_LOGIN_NAME_HERE;" +
				"Password=YOUR_PASSWORD_HERE;Encrypt=True;" +
				"TrustServerCertificate=False;Connection Timeout=30;"  
				))  
			{  
				connection.Open();  
				Console.WriteLine("Connected successfully.");  
  
				Program.InsertRows(connection);  
  
				Console.WriteLine("Press any key to finish...");  
				Console.ReadKey(true);  
			}  
		}  
  
		static public void InsertRows(QC.SqlConnection connection)  
		{  
			QC.SqlParameter parameter;  
  
			using (var command = new QC.SqlCommand())  
			{  
				command.Connection = connection;  
				command.CommandType = DT.CommandType.Text;  
				command.CommandText = @"  
INSERT INTO SalesLT.Product  
		(Name,  
		ProductNumber,  
		StandardCost,  
		ListPrice,  
		SellStartDate  
		)  
	OUTPUT  
		INSERTED.ProductID  
	VALUES  
		(@Name,  
		@ProductNumber,  
		@StandardCost,  
		@ListPrice,  
		CURRENT_TIMESTAMP  
		); ";  
  
				parameter = new QC.SqlParameter("@Name", DT.SqlDbType.NVarChar, 50);  
				parameter.Value = "SQL Server Express 2014";  
				command.Parameters.Add(parameter);  
  
				parameter = new QC.SqlParameter("@ProductNumber", DT.SqlDbType.NVarChar, 25);  
				parameter.Value = "SQLEXPRESS2014";  
				command.Parameters.Add(parameter);  
  
				parameter = new QC.SqlParameter("@StandardCost", DT.SqlDbType.Int);  
				parameter.Value = 11;  
				command.Parameters.Add(parameter);  
  
				parameter = new QC.SqlParameter("@ListPrice", DT.SqlDbType.Int);  
				parameter.Value = 12;  
				command.Parameters.Add(parameter);  
  
				int productId = (int)command.ExecuteScalar();  
				Console.WriteLine("The generated ProductID = {0}.", productId);  
			}  
		}  
	}  
}  
/**** Actual output:  
Connected successfully.  
The generated ProductID = 1000.  
Press any key to finish...  
****/

 

하지만 이런 과정을 없애려고 등장했던게 자바진영에선 spring 이었고... 너무 과거의 것을 사용하기엔... 힘드니까!

 

EF Core에서 네이티브 쿼리나 프로시저를 사용할 방법을 찾아보았다.

 

SQL 쿼리 - EF Core | Microsoft Learn

 

SQL 쿼리 - EF Core

Entity Framework Core에서 SQL 쿼리 사용

learn.microsoft.com

마이크로소프트사에서 직접 설명하고 있었다.

 

대부분의 쿼리를 직접 쏴주지만 프로덕션 레벨에서는 세부적으로 직접 조정해줘야할 것도 많기 때문에 필수적으로 알아놔야 할 것 같다!

 

 - 기본 sql 쿼리 (FromSql 는 EF Core 7.0에서 도입되었습니다. )

var blogs = context.Blogs
    .FromSql($"SELECT * FROM dbo.Blogs")
    .ToList();

 - 프로시저 사용

var blogs = context.Blogs
    .FromSql($"EXECUTE dbo.GetMostPopularBlogs")
    .ToList();

 - 프로시저 사용시 변수 전달

var user = "johndoe";

var blogs = context.Blogs
    .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser {user}")
    .ToList();

 - 변수가 다중인 경우 ( 전달하는 매개 변수는 저장 프로시저 정의와 정확히 일치해야 합니다. )

// 1번째 방법
var user = new SqlParameter("user", "johndoe");

var blogs = context.Blogs
    .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser @filterByUser={user}")
    .ToList();
    
    
// 2번째 방법

var user = new SqlParameter("user", "johndoe");

var blogs = context.Blogs
    .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser {user}")
    .ToList();

 - 동적 SQL

(SQL을 동적으로 구성하기로 결정한 경우 데이터베이스 매개 변수를 사용하는 대신 변수 데이터를 SQL 문자열로 직접 보간할 수 있는 를 사용해야 FromSqlRaw합니다.)

var columnName = "Url";
var columnValue = new SqlParameter("columnValue", "http://SomeURL");

var blogs = context.Blogs
    .FromSqlRaw($"SELECT * FROM [Blogs] WHERE {columnName} = @columnValue", columnValue)
    .ToList();

 - LINQ로 작성

var searchTerm = "Lorem ipsum";

var blogs = context.Blogs
    .FromSql($"SELECT * FROM dbo.SearchBlogs({searchTerm})")
    .Where(b => b.Rating > 3)
    .OrderByDescending(b => b.Rating)
    .ToList();

위 쿼리를 SQL로 해석하면 아래와 같다.

SELECT [b].[BlogId], [b].[OwnerId], [b].[Rating], [b].[Url]
FROM (
    SELECT * FROM dbo.SearchBlogs(@p0)
) AS [b]
WHERE [b].[Rating] > 3
ORDER BY [b].[Rating] DESC
반응형
반응형

<Lv.0 대소문자 바꿔서 출력하기>

 

https://school.programmers.co.kr/learn/courses/30/lessons/181949

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

Lv0문제는 몸풀기로 몇개씩 풀고 그 이상난이도 들어가서 훨씬 많이 풀고 있지만

포스팅은 배웠던 기초개념을 상기하는 차원으로 일부만 올리고 있네요

 

이 문제는 유니코드를 알고 있느냐 묻는 문제죠

소문자는 97~122까지가 a~z

대문자는 65~90까지가 A~Z이기 때문에

char라는 형식과 int와 변환이 자유(?)롭다 그리고

소문자와 대문자 유니코드 차이가 32씩 난다 이 세가지를 알고 있으면 됩니다.

 

필자가 소문자 97~122 대문자 65~90을 외우고 있는 것은 아니지만 본적이 있고 해당개념이 있어서 System.out.println(); 을 이용하여 a, z, A, Z를 숫자로 찍어보고 유추했어요 물론 외워두고 알고 있다면 더 좋은 개발자가 되는 것일 수도!

 

다 읽으셨다면 아래 제가 푼 풀이가 바로 이해되실거예요 

 

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String result = "";
        
        for(int i = 0; i < a.length();i++){
            char x = a.charAt(i);
            int y = (int)x;
            
            if (y < 91){
               x = (char)(y + 32);
            } else {
               x = (char)(y - 32);
            }
            result += x;
        }
        System.out.println(result);  
    }
}

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

 

<코딩 기초 트레이닝 -배열 만들기 5>

https://school.programmers.co.kr/learn/courses/30/lessons/181912

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제는 위의 링크를 보시면 됩니다.

 

자르는 것은 substring()

정수화는 당연히 Integer.parseInt()

몇개인지 알 수없기 때문에 List에 add로 쌓아뒀다가

배열로 다시 반환하는데

 

int[] 배열로의 반환은 list.toArray(new int[]) 가 안먹혀서 검색하다가

람다식으로 할 수 있다는 걸 알았지만

 

람다식을 아직 잘 못쓰기 때문에 암기차원에서 포스팅하게되었습니다.

import java.util.*;

class Solution {
    public int[] solution(String[] intStrs, int k, int s, int l) {
        List<Integer> t = new ArrayList();
        
        for(int i = 0 ; i < intStrs.length;i++){
            int a = Integer.parseInt(intStrs[i].substring(s, s + l));
            if(a > k){
                t.add(a);
            }
        }
        int[] answer = t.stream()
                        .mapToInt(Integer::intValue)
                        .toArray();
        return answer;
    }
}

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

<코딩 기초 트레이닝 -문자 개수 세기>

 

문제는 아래 링크에서 보실 수 있습니다.

https://school.programmers.co.kr/learn/courses/30/lessons/181902

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

이번 포스팅은 코드 블럭내에서 설명드리겠습니다.

 

// 이 문제는 charAt()을 알고 있느냐
// 알파벳이 유니코드임을 알고 있느냐
// 를 묻는 문제죠
// 알파벳이 유니코드라는 개념이 있으면 char로 'a', 'z', 'A', 'Z'
// 를 출력해보고 유니코드를 알아내서 적용해볼 수 있습니다.

class Solution {
    public int[] solution(String my_string) {
        int[] answer = new int[52];
        for(int i = 0 ; i < my_string.length() ; i++){
            
            int a = my_string.charAt(i);
            
            // a - z 는 65~90으로 int로 변환한 후 
            // 65를 빼고 배열에 그대로 적용해도 된다
            if(a >=65 && a <= 90){
                answer[a - 65] += 1;
                
            // A - Z는 97~122으로 int로 변환한 후
            // 97을 빼면 0~25까지 들어가고 여기에
            // 26을 더하면 배열에서 26번 인덱스부터 차곡차곡 들어간다
            } else {
                answer[a - 97 + 26] += 1;
            }
        }
        return answer;
    }
}
 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

 

<코딩 기초 트레이닝 -배열조각하기>

문제는 프로그래머스에 있습니다. 문제링크

https://school.programmers.co.kr/learn/courses/30/lessons/181893

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

몇 개인지 모르면서 순서는 필요할때 List로의 변환 고려

그리고 list의 크기를 정해두고 0부터 ++ 해가면서 remove하면 의도치 않은 오류가 생기기 때문에

remove는 뒤에서 부터 하자!

(앞에서 지워지면 index가 당겨지는 등...) 

import java.util.*;
import java.util.stream.*;

class Solution {
    public int[] solution(int[] arr, int[] query) {  
        List<Integer> a =  Arrays.stream(arr)
                        .boxed()
                        .collect(Collectors.toList());
        
        for(int i = 0 ; i < query.length;i++){
            if(i % 2 == 0){
               for(int j = a.size()-1 ; j > query[i]  ; j--){
                   a.remove(j);
               }      
            } else {
               for(int j = query[i]-1; j >=0   ; j--){
                   a.remove(j);
               } 
            }
        }
        int[] answer = a.stream().mapToInt(Integer::intValue).toArray();
        return answer;
    }
}

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

<코딩 기초 트레이닝 - 문자열 묶기> 

문제 : 

https://school.programmers.co.kr/learn/courses/30/lessons/181855

 

 

사실상 제가 문제에서 map을 쓰는건 처음이라 포스팅하네요

 

key : value = (원소의 길이) : (해당 길이의 원소 갯수)

로 사용하고자 HashMap을 선언해서 사용했습니다.



더불어 map에서 최댓값을 구하려면 

Collections.max(m.keySet()) : 최댓값의 키값

Collections.max(m.values()) : 최댓값 그자체

을 사용하면 된다는 것을 찾아보게 되었습니다.

 

map의 기본 메소드들은 아시겠지만 혹시 처음 검색해서 유입하신 분들을 위해서 준비했습니다.

 

replace(a, b) : key값 a의 value를 b로 대체한다.

get(a) : key값 a의 value를 리턴한다.

put(a, b) : 해당 맵에 key는 a, value는 b인 노드를 추가한다.

containsKey(a) : key값이 a인 노드가 맵에 존재하는지 여부를 리턴

 

import java.util.*;

class Solution {
    public int solution(String[] strArr) {
        Map<Integer, Integer> m = new HashMap<>();
        
        for(String str : strArr){
            if(m.containsKey(str.length())){
                m.replace(str.length(), m.get(str.length()) + 1);
            } else {
                m.put(str.length(), 1);
            }
            
        }
        // Integer maxKey = Collections.max(m.keySet());
        // 위 주석처리는 최댓값일때 Key값을 찾는 방법이다.
        
        Integer maxValue = Collections.max(m.values());
        
        return maxValue;
    }
}

제가 사용한 것중에 m.replace(str.length(), m.get(str.length()) + 1) 으로 사용한 것의 의미는 

map에 이미 해당원소의 길이로 key값이 존재하면, 그 value를 가져와 + 1 하고 해당 key에 대한 value에 다시 집어넣는다

 

글로만 적으니 난잡하지만....

예를들어

 

str.length()가 1이고 여태까지 길이가 1인 원소의 갯수가 3이라면

str.length = 1, m.get(1) = 3이 될것이고

 

m.replace(str.length(), m.get(str.length()) + 1) 는

 -> m.replace(1, m.get(1) + 1)

 -> m.replace(1, 3 + 1)

-> m.replace(1, 4)

 

으로 key값 1에 해당하는 value가 3에서 4로 바꿔넣을 뿐이다.

따라서 진행 후 m.get(1)을 하게되면 4가 나온다.

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

 

코딩 기초 트레이닝 - 전국 대회 선발 고사

이번 풀이는 keySet()만 사용해와서

entrySet 사용법을 검색하고 처음 써보기 때문에 포스팅하게 되었습니다.

 

참석가능한 친구들만 map에 번호와 등수를 넣은뒤 최솟값을 출력, remove, 다시 최솟값을 받으면 두번째 작은값... 의 방법으로 했습니다. 최솟값일때 key값을 받아서 리턴하는 방식이죠! 그래서 entrySet을 사용

import java.util.*;

class Solution {
    public int solution(int[] rank, boolean[] attendance) {
        int answer = 0;
        
        Map<Integer, Integer> m = new HashMap<Integer, Integer>();
        for(int i = 0 ; i < rank.length;i++){
            if(attendance[i]){
                m.put(i, rank[i]);
            }
        }   
        Integer a = mini(m);
        Integer b = mini(m);
        Integer c = mini(m);

        return 10000 * a + 100 * b + c;
    }
    
    public int mini(Map<Integer, Integer> map){
        int min = 101;
        int result = 0;
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            if(entry.getValue() < min){
                min = entry.getValue();
                result = entry.getKey();
            }
        }
        map.remove(result);
        return result;
    }
}
 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

< 코딩 기초 트레이닝 - 두수의 합>

 

관련 공부를 해보신 분이라면 아주 쉬운 문제라고 볼 수도 있지만

사용할 일 별로 없을 것 같아서 다른 것들 심화로 공부할때 넘어갔던 BigInteger.....를 인터넷 검색하고 해결하였기 떄문에

포스팅하게되었습니다..

 

 

String 도 BigInteger로 선언해서 변환된다는 것을 배웠네요!

BigInteger도 import 해야 쓸 수 있는지도 다시 상기했네요...  인텔리제이의 노예...ㅋㅋㅋㅋㅋㅋㅋㅋ

import java.math.*; <= BigInteger

import java.math.*;

class Solution {
    public String solution(String a, String b) {
        BigInteger c = new BigInteger(a);
        BigInteger d = new BigInteger(b);        
        return String.valueOf(c.add(d));
    }
}

 

 

 

반응형
반응형

전체 소스는 https://github.com/msab2170/SimpleCalculator 에서 확인하실 수 있습니다.

 

GitHub - msab2170/SimpleCalculator

Contribute to msab2170/SimpleCalculator development by creating an account on GitHub.

github.com

계산기 파일은... 아직 인증서 관련 공부가 되지않아서 흑흑...... 추후에 가능하면 올릴게용

 

 

visual studio 2022를 설치하고 windows form로 새 프로젝트를 엽니다.

 

1. 도구상자를 열면 다양한 도구들을 검색할 수 있다.

 

2. 그중에서 tableLayoutPanel로 계산기 버튼 윤곽을 만들고

(초기 2x2 인데 행추가 열추가로 만들어주면 됩니다.

저와 동일하게 한다면 4x4까지,

크기가 균등하지 않을텐데 

tableLayoutPanel 좌측 상단의 사방 화살표를 우클리갛면 아래와 같이 나오고

"행 및 열 편집..."에 들어가서 %로 25%씩(4x4기준) 해주면 고르게 나뉘어집니다.)

그리고 계산 식과 결과가 나올 자리에는 kotlin에서 input 처럼 label이라는 도구를 검색하여 적어줍니다.

 

참고로 버튼과 label의 보이는 값은 도구 속성중 "text"를 찾으시면되고 각 컴포넌트들의 이름은 (name)에 해당합니다.

이제 디자인은 완성되었고 cs파일로 넘어가서 코딩하는데 저는 이미 완성이 되었기 때문에 코드 전문을 붙여 넣고 설명 드릴게요.

 

먼저 디자인을 완성하면 .Designer.cs 로 끝나는 파일에 다음과 같은 소스가 들어갑니다.

각 위치와 (name), text에 맞게 자동으로 코딩이 되고, 초기 디자인 화면에서 각 버튼을 더블클릭하면

.cs로 끝나는 파일에 자동으로 함수가 설정되기도합니다.

 

-- 아래 코드는 자동으로 설정되므로 오류가 난 경우나 필자가 의도한 이상의 부분을 건드리고 싶은 것이 아니라면

보기만 하고 넘어갑니다!

(대충 각 레이아웃, 버튼들의 위치, 사이즈 등을 지정해둔 것)

 

적당히 보시면서 쭈욱 밑으로 오시면 되겠습니다.

namespace WindowsFormsApp1
{
    partial class Form1
    {
        /// <summary>
        /// 필수 디자이너 변수입니다.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 사용 중인 모든 리소스를 정리합니다.
        /// </summary>
        /// <param name="disposing">관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form 디자이너에서 생성한 코드

        /// <summary>
        /// 디자이너 지원에 필요한 메서드입니다. 
        /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요.
        /// </summary>
        private void InitializeComponent()
        {
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.btnPlus = new System.Windows.Forms.Button();
            this.btnEnter = new System.Windows.Forms.Button();
            this.btn0 = new System.Windows.Forms.Button();
            this.btnReset = new System.Windows.Forms.Button();
            this.btnMinus = new System.Windows.Forms.Button();
            this.btn3 = new System.Windows.Forms.Button();
            this.btn2 = new System.Windows.Forms.Button();
            this.btn1 = new System.Windows.Forms.Button();
            this.btnMultiply = new System.Windows.Forms.Button();
            this.btn6 = new System.Windows.Forms.Button();
            this.btn5 = new System.Windows.Forms.Button();
            this.btn4 = new System.Windows.Forms.Button();
            this.btnDivide = new System.Windows.Forms.Button();
            this.btn9 = new System.Windows.Forms.Button();
            this.btn8 = new System.Windows.Forms.Button();
            this.btn7 = new System.Windows.Forms.Button();
            this.result = new System.Windows.Forms.Label();
            this.tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // tableLayoutPanel1
            // 
            this.tableLayoutPanel1.AutoSize = true;
            this.tableLayoutPanel1.ColumnCount = 4;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.Controls.Add(this.btnPlus, 3, 3);
            this.tableLayoutPanel1.Controls.Add(this.btnEnter, 2, 3);
            this.tableLayoutPanel1.Controls.Add(this.btn0, 1, 3);
            this.tableLayoutPanel1.Controls.Add(this.btnReset, 0, 3);
            this.tableLayoutPanel1.Controls.Add(this.btnMinus, 3, 2);
            this.tableLayoutPanel1.Controls.Add(this.btn3, 2, 2);
            this.tableLayoutPanel1.Controls.Add(this.btn2, 1, 2);
            this.tableLayoutPanel1.Controls.Add(this.btn1, 0, 2);
            this.tableLayoutPanel1.Controls.Add(this.btnMultiply, 3, 1);
            this.tableLayoutPanel1.Controls.Add(this.btn6, 2, 1);
            this.tableLayoutPanel1.Controls.Add(this.btn5, 1, 1);
            this.tableLayoutPanel1.Controls.Add(this.btn4, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.btnDivide, 3, 0);
            this.tableLayoutPanel1.Controls.Add(this.btn9, 2, 0);
            this.tableLayoutPanel1.Controls.Add(this.btn8, 1, 0);
            this.tableLayoutPanel1.Controls.Add(this.btn7, 0, 0);
            this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 94);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 4;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(776, 352);
            this.tableLayoutPanel1.TabIndex = 0;
            this.tableLayoutPanel1.Paint += new System.Windows.Forms.PaintEventHandler(this.tableLayoutPanel1_Paint);
            // 
            // btnPlus
            // 
            this.btnPlus.AutoSize = true;
            this.btnPlus.Font = new System.Drawing.Font("굴림", 15F);
            this.btnPlus.Location = new System.Drawing.Point(585, 267);
            this.btnPlus.Name = "btnPlus";
            this.btnPlus.Size = new System.Drawing.Size(188, 82);
            this.btnPlus.TabIndex = 15;
            this.btnPlus.Text = "+";
            this.btnPlus.UseVisualStyleBackColor = true;
            this.btnPlus.Click += new System.EventHandler(this.btnPlus_Click);
            // 
            // btnEnter
            // 
            this.btnEnter.AutoSize = true;
            this.btnEnter.Font = new System.Drawing.Font("굴림", 15F);
            this.btnEnter.Location = new System.Drawing.Point(391, 267);
            this.btnEnter.Name = "btnEnter";
            this.btnEnter.Size = new System.Drawing.Size(188, 82);
            this.btnEnter.TabIndex = 14;
            this.btnEnter.Text = "=";
            this.btnEnter.UseVisualStyleBackColor = true;
            this.btnEnter.Click += new System.EventHandler(this.btnEnter_Click);
            // 
            // btn0
            // 
            this.btn0.AutoSize = true;
            this.btn0.Font = new System.Drawing.Font("굴림", 15F);
            this.btn0.Location = new System.Drawing.Point(197, 267);
            this.btn0.Name = "btn0";
            this.btn0.Size = new System.Drawing.Size(188, 82);
            this.btn0.TabIndex = 13;
            this.btn0.Text = "0";
            this.btn0.UseVisualStyleBackColor = true;
            this.btn0.Click += new System.EventHandler(this.btn0_Click);
            // 
            // btnReset
            // 
            this.btnReset.AutoSize = true;
            this.btnReset.Font = new System.Drawing.Font("굴림", 15F);
            this.btnReset.Location = new System.Drawing.Point(3, 267);
            this.btnReset.Name = "btnReset";
            this.btnReset.Size = new System.Drawing.Size(188, 82);
            this.btnReset.TabIndex = 12;
            this.btnReset.Text = "AC";
            this.btnReset.UseVisualStyleBackColor = true;
            this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
            // 
            // btnMinus
            // 
            this.btnMinus.AutoSize = true;
            this.btnMinus.Font = new System.Drawing.Font("굴림", 15F);
            this.btnMinus.Location = new System.Drawing.Point(585, 179);
            this.btnMinus.Name = "btnMinus";
            this.btnMinus.Size = new System.Drawing.Size(188, 82);
            this.btnMinus.TabIndex = 11;
            this.btnMinus.Text = "-";
            this.btnMinus.UseVisualStyleBackColor = true;
            this.btnMinus.Click += new System.EventHandler(this.btnMinus_Click);
            // 
            // btn3
            // 
            this.btn3.AutoSize = true;
            this.btn3.Font = new System.Drawing.Font("굴림", 15F);
            this.btn3.Location = new System.Drawing.Point(391, 179);
            this.btn3.Name = "btn3";
            this.btn3.Size = new System.Drawing.Size(188, 82);
            this.btn3.TabIndex = 10;
            this.btn3.Text = "3";
            this.btn3.UseVisualStyleBackColor = true;
            this.btn3.Click += new System.EventHandler(this.btn3_Click);
            // 
            // btn2
            // 
            this.btn2.AutoSize = true;
            this.btn2.Font = new System.Drawing.Font("굴림", 15F);
            this.btn2.Location = new System.Drawing.Point(197, 179);
            this.btn2.Name = "btn2";
            this.btn2.Size = new System.Drawing.Size(188, 82);
            this.btn2.TabIndex = 9;
            this.btn2.Text = "2";
            this.btn2.UseVisualStyleBackColor = true;
            this.btn2.Click += new System.EventHandler(this.btn2_Click);
            // 
            // btn1
            // 
            this.btn1.AutoSize = true;
            this.btn1.Font = new System.Drawing.Font("굴림", 15F);
            this.btn1.Location = new System.Drawing.Point(3, 179);
            this.btn1.Name = "btn1";
            this.btn1.Size = new System.Drawing.Size(188, 82);
            this.btn1.TabIndex = 8;
            this.btn1.Text = "1";
            this.btn1.UseVisualStyleBackColor = true;
            this.btn1.Click += new System.EventHandler(this.btn1_Click);
            // 
            // btnMultiply
            // 
            this.btnMultiply.AutoSize = true;
            this.btnMultiply.Font = new System.Drawing.Font("굴림", 15F);
            this.btnMultiply.Location = new System.Drawing.Point(585, 91);
            this.btnMultiply.Name = "btnMultiply";
            this.btnMultiply.Size = new System.Drawing.Size(188, 82);
            this.btnMultiply.TabIndex = 7;
            this.btnMultiply.Text = "X";
            this.btnMultiply.UseVisualStyleBackColor = true;
            this.btnMultiply.Click += new System.EventHandler(this.btnMultiply_Click);
            // 
            // btn6
            // 
            this.btn6.AutoSize = true;
            this.btn6.Font = new System.Drawing.Font("굴림", 15F);
            this.btn6.Location = new System.Drawing.Point(391, 91);
            this.btn6.Name = "btn6";
            this.btn6.Size = new System.Drawing.Size(188, 82);
            this.btn6.TabIndex = 6;
            this.btn6.Text = "6";
            this.btn6.UseVisualStyleBackColor = true;
            this.btn6.Click += new System.EventHandler(this.btn6_Click);
            // 
            // btn5
            // 
            this.btn5.AutoSize = true;
            this.btn5.Font = new System.Drawing.Font("굴림", 15F);
            this.btn5.Location = new System.Drawing.Point(197, 91);
            this.btn5.Name = "btn5";
            this.btn5.Size = new System.Drawing.Size(188, 82);
            this.btn5.TabIndex = 5;
            this.btn5.Text = "5";
            this.btn5.UseVisualStyleBackColor = true;
            this.btn5.Click += new System.EventHandler(this.btn5_Click);
            // 
            // btn4
            // 
            this.btn4.AutoSize = true;
            this.btn4.Font = new System.Drawing.Font("굴림", 15F);
            this.btn4.Location = new System.Drawing.Point(3, 91);
            this.btn4.Name = "btn4";
            this.btn4.Size = new System.Drawing.Size(188, 82);
            this.btn4.TabIndex = 4;
            this.btn4.Text = "4";
            this.btn4.UseVisualStyleBackColor = true;
            this.btn4.Click += new System.EventHandler(this.btn4_Click);
            // 
            // btnDivide
            // 
            this.btnDivide.AutoSize = true;
            this.btnDivide.Font = new System.Drawing.Font("굴림", 15F);
            this.btnDivide.Location = new System.Drawing.Point(585, 3);
            this.btnDivide.Name = "btnDivide";
            this.btnDivide.Size = new System.Drawing.Size(188, 82);
            this.btnDivide.TabIndex = 3;
            this.btnDivide.Text = "/";
            this.btnDivide.UseVisualStyleBackColor = true;
            this.btnDivide.Click += new System.EventHandler(this.btnDivide_Click);
            // 
            // btn9
            // 
            this.btn9.AutoSize = true;
            this.btn9.Font = new System.Drawing.Font("굴림", 15F);
            this.btn9.Location = new System.Drawing.Point(391, 3);
            this.btn9.Name = "btn9";
            this.btn9.Size = new System.Drawing.Size(188, 82);
            this.btn9.TabIndex = 2;
            this.btn9.Text = "9";
            this.btn9.UseVisualStyleBackColor = true;
            this.btn9.Click += new System.EventHandler(this.btn9_Click);
            // 
            // btn8
            // 
            this.btn8.AutoSize = true;
            this.btn8.Font = new System.Drawing.Font("굴림", 15F);
            this.btn8.Location = new System.Drawing.Point(197, 3);
            this.btn8.Name = "btn8";
            this.btn8.Size = new System.Drawing.Size(188, 82);
            this.btn8.TabIndex = 1;
            this.btn8.Text = "8";
            this.btn8.UseVisualStyleBackColor = true;
            this.btn8.Click += new System.EventHandler(this.btn8_Click);
            // 
            // btn7
            // 
            this.btn7.AutoSize = true;
            this.btn7.Font = new System.Drawing.Font("굴림", 15F);
            this.btn7.Location = new System.Drawing.Point(3, 3);
            this.btn7.Name = "btn7";
            this.btn7.Size = new System.Drawing.Size(188, 82);
            this.btn7.TabIndex = 0;
            this.btn7.Text = "7";
            this.btn7.UseVisualStyleBackColor = true;
            this.btn7.Click += new System.EventHandler(this.btn7_Click);
            // 
            // result
            // 
            this.result.BackColor = System.Drawing.SystemColors.HighlightText;
            this.result.Font = new System.Drawing.Font("굴림", 20F);
            this.result.Location = new System.Drawing.Point(12, 10);
            this.result.Name = "result";
            this.result.Padding = new System.Windows.Forms.Padding(5);
            this.result.Size = new System.Drawing.Size(773, 70);
            this.result.TabIndex = 1;
            this.result.Text = "0";
            this.result.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(808, 464);
            this.Controls.Add(this.result);
            this.Controls.Add(this.tableLayoutPanel1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.Button btn7;
        private System.Windows.Forms.Button btnPlus;
        private System.Windows.Forms.Button btnEnter;
        private System.Windows.Forms.Button btn0;
        private System.Windows.Forms.Button btnReset;
        private System.Windows.Forms.Button btnMinus;
        private System.Windows.Forms.Button btn3;
        private System.Windows.Forms.Button btn2;
        private System.Windows.Forms.Button btn1;
        private System.Windows.Forms.Button btnMultiply;
        private System.Windows.Forms.Button btn6;
        private System.Windows.Forms.Button btn5;
        private System.Windows.Forms.Button btn4;
        private System.Windows.Forms.Button btnDivide;
        private System.Windows.Forms.Button btn9;
        private System.Windows.Forms.Button btn8;
        private System.Windows.Forms.Label result;
    }
}

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
	// 앞에서 디자인한 Form을 응용프로그램 안에 적용하는 클래스입니다.
    // 앞에서 보실필요없다고 말씀은 드렸으나
    // 앞에서 보여드렸던 소스에 현재 페이지에서 특정버튼을 클릭하면 
    // 메소드를 실행시키도록 코딩되어있습니다.
    // 앞으로 가실필욘 없고 바로 하단에 간단한 예시를 들겠습니다.
    /* 예를들면 7 버튼의 경우
    	this.btn7.AutoSize = true;
        this.btn7.Font = new System.Drawing.Font("굴림", 15F);
        this.btn7.Location = new System.Drawing.Point(3, 3);
        this.btn7.Name = "btn7";
    	this.btn7.Size = new System.Drawing.Size(188, 82);
        this.btn7.TabIndex = 0;
        this.btn7.Text = "7";
        this.btn7.UseVisualStyleBackColor = true;
        
        this.btn7.Click += new System.EventHandler(this.btn7_Click); <--- 이자리에 
        이버튼이 클릭되면이라는 이벤트가 담겨있고 앞으로 
        개발할 btnX_Click()메소드가 이벤트로 들어가있죠.
    */
    
    public partial class Form1 : Form
    {
        bool afterEnter = false;
       
        public Form1()
        {
            InitializeComponent();
        }

        private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { }
        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)  { }
  		
        // 설명드릴때는 어짜피 숫자들 버튼은 동일하므로 대표적으로 한개만 남기고 지워뒀습니다.
        
        private void btn1_Click(object sender, EventArgs e)
        {
        	// 가장 앞이 0인경우에는 0을 지운다.
            // afterEnter는 '=' 버튼을 누르고나면 true로 바뀌는 값으로 설정해두었습니다.
            // 다음계산시에 AC를 꼭 누르지않더라도 초기화 되도록 설계했습니다.
            
            if (result.Text.Equals("0") || afterEnter == true)  { result.Text = "1"; }      
            else { result.Text += 1; }
            afterEnter = false;
        }
		
         // 연산도 가장 간단하다고 판단한 방법으로 제일 밑줄만 다르므로 대표 하나만 남깁니다.
        private void btnMultiply_Click(object sender, EventArgs e)
        {
        	// 계산 시 0으로 나누면 "0으로 나눌 수 없습니다."로 표기하게끔 개발했기때문에
            // 해당 문구가 뜬 상태로 연산시 정상작동하기 위한 로직입니다.
             if(result.Text == "0으로 나눌 수 없습니다.")
            {
                result.Text = 0.ToString();
            }
            afterEnter = false;
            
            // a / b + c 식으로 연산자 두개를 붙이는 경우에는 계산이 안되는 로직이기 때문에
            // 이미 연산자가 있을때 추가 연산자가 들어오면 앞의 계산을 시행하도록 개발
            // 아주 간단한 계산기 예제 이기 때문에 괄호나 
            // +, - 보다 *, /가 먼저 계산되는 부분은 제외했습니다.
            
            if (result.Text.Contains(" "))
            {
                btnEnter_Click(sender, e);
                afterEnter = false;
            }
            result.Text += " * ";
        }
        
		// '=' 버튼을 눌렀을때 
        private void btnEnter_Click(object sender, EventArgs e)
        {
        	// 위의 버튼들 로직으로
            // ex) '15 + 4' 라는 값이 result.Text에 오게 됩니다.
            String temp = result.Text;
            
            // 연산자 없이 '='을 누르면 아무런 조치를 취하지 않음
            if (!temp.Contains(" ")) return;
             
            // 이를 Split으로 쪼개
            // {a, (연산자), b} 인 배열을 만들고
            // 각 연산을 수행하는 로직을 구성했습니다.
            // 단, 수학적으로 0으로 나누는 것은 불가능하기 때문에 예외처리를 해두었습니다.
            
            String[] arr = temp.Split(' ');
            int a = Int32.Parse(arr[0]);
            int b = Int32.Parse(arr[2]);
            afterEnter = true;
            if (arr[1] == "*")
            {
                result.Text = (a * b).ToString();
            } else if (arr[1] == "/") {
                if ( b == 0){
                    result.Text = "0으로 나눌 수 없습니다.";
                    afterEnter = true;
                } else {
                    result.Text = (a / b).ToString();
                }    
            } else if (arr[1] == "-"){
                result.Text = (a - b).ToString();
            } else if (arr[1] == "+"){
                result.Text = (a + b).ToString();
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            result.Text = "0";
        }
    }
}

 

코틀린 배울때 모바일 화면 디자인하는 과정과 유사해서 무난하게 성공했어요! 완성!

 

반응형
반응형
class Solution {
    public int solution(int a, int b, int n) {
        // 빈병 a 개 가져가면 b 개 콜라병 주는 마트
        // n개 가져다 주면 몇개?

        int answer = 0;

        while(n >= a){
            int a1 = ((int)n/a)*b;

            answer += a1;
            n = a1 + n%a;

        }

        return answer;
    }
}

우선 n이 a로 나누어떨어질 경우에는 몫을 리턴값에 추가하는 방식이 간편하다.

n을 몫으로 교체해주면서 반복하면 결과에 바로 다다른다.

 

n이 a로 나누어 떨어지지 않을때가 관건이다. 또한 b의 값이 1만 있지 않기 때문에 어떤 연산을 먼저 할지가 포인트 중 하나이다.

 

while()문의 첫째줄 int를 a로 나눈직후에 변환(버림)한것이 포인트고 나머지가 있다면 다음 연산에 사용될 수 있도록 더해주면 된다.

 

-------------------------------------------------------------------------------------------------------------- -------------------------------------------

문제:

https://school.programmers.co.kr/learn/courses/30/lessons/178871

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

이중for문을 쓰면 성능면에서 문제가 많기 때문에 배제하고 하는 방법을 찾다가 고안했습니다.

람다 스트림을 배워야 하는데 아직 기초를 다지려고 기초적인 문법으로 쓰고있어요

import java.util.*;
import java.util.stream.*;

class Solution {
    public String[] solution(String[] players, String[] callings) {
        
        Map<Integer, String> mi = new HashMap<>();
        Map<String, Integer> ms = new HashMap<>();
        
        for(int i = 0 ; i < players.length;i++) {
            mi.put(i, players[i]);
            ms.put(players[i], i);
        }
        
        for(String str : callings){
            int key = ms.get(str);
            mi.replace(key, mi.get(key - 1));
            mi.replace(key - 1, str);
            ms.replace(str, key - 1);
            ms.replace(mi.get(key), key);
        }
        
        for(int i = 0 ; i < mi.size();i++){
            players[i] = mi.get(i);
        }
        
        return players;
    }  
}

적고나서 보니 map을 하나만 써도 됐겠네요 ㅋㅋ... 수련하겠습니다....

 

-------------------------------------------------------------------------------------------------------------- -------------------------------------------

https://school.programmers.co.kr/learn/courses/30/lessons/181937

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 요약 : num이 n의 배수이면 1 아니면 0

class Solution {
    public int solution(int num, int n) {
        
        int answer = 0;
        if(num%n==0) answer = 1;
        return answer;
    }
}

-------------------------------------------------------------------------------------------------------------- -------------------------------------------

 

https://school.programmers.co.kr/learn/courses/30/lessons/181938

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 요약 :  12 $ 3 = 123, 3 $ 12 = 312 방식으로 연산한 것과 두수의 곱 x2 중 큰값을 리턴하는 함수

class Solution {
    public int solution(int a, int b) {
        int answer = 0;
        int x = Integer.parseInt("" + a + b);
        answer = Math.max(x, 2*a*b);
        return answer;
    }
}

""을 앞에 더하면 문자열로 그대로 이어지는 것에 착한하여 String으로 만들었다가 Integer.parseInt로 다시 정수로 만드는 방식을 사용

 

 

 

-------------------------------------------------------------------------------------------------------------- -------------------------------------------

https://school.programmers.co.kr/learn/courses/30/lessons/181939

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 요약 :  12 $ 3 = 123, 3 $ 12 = 312 방식 a $ b와 b$ a 중 큰 값 반환

class Solution {
    public int solution(int a, int b) {
        return Math.max(
            Integer.parseInt("" + a + b),
            Integer.parseInt("" + b + a)
        );
    }
}

 

 

 

 

-------------------------------------------------------------------------------------------------------------- -------------------------------------------

 

 

https://school.programmers.co.kr/learn/courses/30/lessons/181940

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제요약 : 문자열을 k번 반복시켜 리턴

class Solution {
    public String solution(String my_string, int k) {
        String answer = "";
        for(int i = 0 ; i < k ; i++){
            answer +=my_string;
        }
        return answer;
    }
}

 

 

 

-------------------------------------------------------------------------------------------------------------- -------------------------------------------

 

 

https://school.programmers.co.kr/learn/courses/30/lessons/181941

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

배열 arr의 원소들을 순서대로 이어붙인 문자열을 리턴

class Solution {
    public String solution(String[] arr) {
        String answer = "";
        for(int i = 0 ; i < arr.length; i++){
            answer += arr[i];
        }
        return answer;
    }
}
반응형
반응형

문제 :

 

https://school.programmers.co.kr/learn/courses/30/lessons/118666

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

class Solution {
	
    public String solution(String[] survey, int[] choices) {
        int minusRplusT = 0;
        int minusCplusF = 0;  
        int minusJplusM = 0;
        int minusAplusN = 0;
               
        for (int i = 0 ; i < survey.length; i++){
            if (survey[i].equals("RT")){
                minusRplusT += choices[i] - 4;          
            } else if (survey[i].equals("TR")){
                minusRplusT += 4 - choices[i];
                   
            } else if (survey[i].equals("CF")){
                minusCplusF += choices[i] - 4;
            } else if (survey[i].equals("FC")){
                minusCplusF += 4 - choices[i];
                   
            } else if (survey[i].equals("JM")){
                minusJplusM += choices[i] - 4;
            } else if (survey[i].equals("MJ")){
                minusJplusM += 4 - choices[i];
                   
            } else if (survey[i].equals("AN")){
                minusAplusN += choices[i] - 4;
            } else if (survey[i].equals("NA")){
                minusAplusN += 4 - choices[i];
            }
        }      
        String answer = "";
        if (minusRplusT > 0 ) answer += "T";
                       else answer += "R";
        if (minusCplusF > 0 ) answer += "F";
                        else answer += "C";
        if (minusJplusM > 0 ) answer += "M";
                        else answer += "J";
        if (minusAplusN > 0 ) answer += "N";
                        else answer += "A";
       
        return answer;
    }
                       
    
}

 

이후에 언젠가 조금 보완한 풀이

class Solution {
	
    public String solution(String[] survey, int[] choices) {
       
        int[] point = {0,0,0,0};
        String[] plus = {"RT", "CF", "JM", "AN"};
        String[] minus = {"TR", "FC", "MJ", "NA"};
               
        for (int i = 0 ; i < survey.length; i++){
            for(int j = 0; j < point.length; j++){        
                if (survey[i].equals(plus[j])){
                    point[j] += choices[i] - 4;          
                } else if (survey[i].equals(minus[j])){
                    point[j] -= choices[i] - 4;  
                }
            }          
        }      
        String answer = "";
        if (point[0] > 0 ) answer += "T";
        else answer += "R";
        if (point[1] > 0 ) answer += "F";
        else answer += "C";
        if (point[2] > 0 ) answer += "M";
        else answer += "J";
        if (point[3] > 0 ) answer += "N";
        else answer += "A";
       
        return answer;
    }
                       
    
}

 

반응형
반응형

# 머신러닝 알고리즘

 1. 지도학습

  - 훈련 데이터 : {

          데이터 : 입력,

          정답 : 타깃

     }

 2. 비지도학습

  - (추후에 나옴)

 

훈련시킬때 데이터를 입력해서 맞추는 것은 답을 알려주고 문제를 맞추는 것과 같은 개념!

따라서 훈련시킬 데이터(훈련 세트)와 평가에 사용할 데이터(테스트 세트)를 구분하는 것이 바람직!

 

fish_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0, 
                31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0, 
                35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0, 9.8, 
                10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]
fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0, 
                500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0, 
                700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0, 6.7, 
                7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]

fish_data = [[l, w] for l, w in zip(fish_length, fish_weight)]
fish_target = [1]*35 + [0]*14

# 도미 35마리와 빙어 14마리로 전체 49개의 샘플이 있고, 길이와 무게 2개의 특성을 갖는다.
# 도미인 처음 35개 데이터를 훈련세트로, 나머지 14개(빙어)를 테스트 세트로 이용해보도록 하자

from sklearn.neighbors import KNeighborsClassifier
kn = KNeighborsClassifier()

# 슬라이싱 [0:35] -> 인덱스 0부터 35 전까지(35는 미포함) 데이터를 리턴
# 시작 인덱스가 0인 경우 생략 가능 [:35]
# 마찬가지로 뒤가 마지막 인덱스인 경우 생략 가능 [35:]

train_input = fish_data[:35] # 1~35 데이터 인덱스로는 0~34
train_target = fish_target[:35]

test_input = fish_data[35:] # 36~49 데이터 인덱스로는 35~48
test_target = fish_target[35:]

kn = kn.fit(train_input, train_target)
kn.score(test_input, test_target)

# 결과인 정확도가 0.0이 나온다....
# 너무 당연하다 도미 데이터만 훈련시켰기때문에 빙어데이터와 구분할 수 있는 방법이 학습되지 않았기 때문이다.

# 넘파이를 배울 타이밍 - 파이썬의 대표적인 배열 라이브러리
import numpy as np

input_arr = np.array(fish_data)
target_arr = np.array(fish_target)

print(input_arr)

print(input_arr.shape) #(샘플수, 특성 수) 출력

# index를 랜덤하게 돌려 편향성이 없으면서도 도미와 빙어가 골고루 들어갈 수 있도록 test set를 분리한다.
np.random.seed(42)
index = np.arange(49)
np.random.shuffle(index)

train_input = input_arr[index[:35]]
train_target = target_arr[index[:35]]

test_input = input_arr[index[35:]]
test_target = target_arr[index[35:]]

# 산점도를 그려 골고루 분리가 되었는지 확인해 본다.
import matplotlib.pyplot as plt
plt.scatter(train_input[:,0], train_input[:,1])
plt.scatter(test_input[:,0], test_input[:,1])
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

# 새로 만든 데이터를 다시 학습시킨다
kn = kn.fit(train_input, train_target)
kn.score(test_input, test_target)
# 정확도는 1.0! 어디한번 테스트 세트를 돌려보자!


print('test_input')
print(kn.predict(test_input))

print('test data')
print(test_target)

위 소스에 대한 실행결과는 아래와 같음

[[  25.4  242. ]
 [  26.3  290. ]
 [  26.5  340. ]
 [  29.   363. ]
 [  29.   430. ]
 [  29.7  450. ]
 [  29.7  500. ]
 [  30.   390. ]
 [  30.   450. ]
 [  30.7  500. ]
 [  31.   475. ]
 [  31.   500. ]
 [  31.5  500. ]
 [  32.   340. ]
 [  32.   600. ]
 [  32.   600. ]
 [  33.   700. ]
 [  33.   700. ]
 [  33.5  610. ]
 [  33.5  650. ]
 [  34.   575. ]
 [  34.   685. ]
 [  34.5  620. ]
 [  35.   680. ]
 [  35.   700. ]
 [  35.   725. ]
 [  35.   720. ]
 [  36.   714. ]
 [  36.   850. ]
 [  37.  1000. ]
 [  38.5  920. ]
 [  38.5  955. ]
 [  39.5  925. ]
 [  41.   975. ]
 [  41.   950. ]
 [   9.8    6.7]
 [  10.5    7.5]
 [  10.6    7. ]
 [  11.     9.7]
 [  11.2    9.8]
 [  11.3    8.7]
 [  11.8   10. ]
 [  11.8    9.9]
 [  12.     9.8]
 [  12.2   12.2]
 [  12.4   13.4]
 [  13.    12.2]
 [  14.3   19.7]
 [  15.    19.9]]
(49, 2)
test_input
[0 0 1 0 1 1 1 0 1 1 0 1 1 0]
test data
[0 0 1 0 1 1 1 0 1 1 0 1 1 0]
반응형
반응형

지난 포스팅에 이어 1단원을 마무리 한다.

import matplotlib.pyplot as plt # matplotlib의 pyplot 함수를 plt로 줄여서 사용

# 두 종류의 물고기 길이와 무게라고 가정하고 종을 구분해내는 AI를 만들어 머신러닝한다.
# 제 3의 데이터가 주어졌을때 판단할 수 있는지 확인해보는 예제

# A종 길이와 크기 예제
bream_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0, 
                31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0, 
                35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0]
bream_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0, 
                500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0, 
                700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0]

# B종 길이와 크기 예제
smelt_length = [9.8, 10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]
smelt_weight = [6.7, 7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]

plt.scatter(bream_length, bream_weight)
plt.scatter(smelt_length, smelt_weight)
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

# 두 종의 배열을 길이별로, 그리고 무게별로 합친다.
length = bream_length + smelt_length
weight = bream_weight + smelt_weight

print('length')
print(length)

print('weight')
print(weight)

# [길이, 무게] 쌍으로 데이터를 변환한 2차원 리스트 생성성
fish_data = [[l,w] for l, w in zip(length, weight)]

print('fish_data')
print(fish_data)

# A종 35개와 B종 14개를 구분한 배열을 생성
# R 또는 다른 통계분석에서도 구분컬럼을 추가하는 방식과 동일한 개념으로 보인다.
fish_target = [1] * 35 + [0] * 14

print('fish_target')
print(fish_target)

# 사이킷런 패키지에서 k-최근접 이웃 알고리즘을 구현한 클래스를 임포트
# 통계학에서 qqplot 등에서 점이 몰려있거나 선형이거나.... 등등 일정한 규칙을 이루는 집단을 동일집단으로 보는 것과 유사한 알고리즘일 것으로 추정
# 이름부터가 해석하자면 이웃 분류
from sklearn.neighbors import KNeighborsClassifier

# 객체로 선언
kn = KNeighborsClassifier()

# 알고리즘 객체에 학습 - 요데이터는 요놈이야야
kn.fit(fish_data, fish_target)

print('kn.score')
print(kn.score(fish_data, fish_target))

#그렇다면 길이가 30, 무게가 600인 놈이 뭔지 예측해봐!(메소드 단어를 그대로 해석하는게 이해와 암기에 좋을것같아서!)

print('길이가 30, 무게가 600인 놈이 뭔지 예측해봐!')
kn.predict([[30, 600]])
length
[25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0, 31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0, 35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0, 9.8, 10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]
weight
[242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0, 500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0, 700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0, 6.7, 7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]
fish_data
[[25.4, 242.0], [26.3, 290.0], [26.5, 340.0], [29.0, 363.0], [29.0, 430.0], [29.7, 450.0], [29.7, 500.0], [30.0, 390.0], [30.0, 450.0], [30.7, 500.0], [31.0, 475.0], [31.0, 500.0], [31.5, 500.0], [32.0, 340.0], [32.0, 600.0], [32.0, 600.0], [33.0, 700.0], [33.0, 700.0], [33.5, 610.0], [33.5, 650.0], [34.0, 575.0], [34.0, 685.0], [34.5, 620.0], [35.0, 680.0], [35.0, 700.0], [35.0, 725.0], [35.0, 720.0], [36.0, 714.0], [36.0, 850.0], [37.0, 1000.0], [38.5, 920.0], [38.5, 955.0], [39.5, 925.0], [41.0, 975.0], [41.0, 950.0], [9.8, 6.7], [10.5, 7.5], [10.6, 7.0], [11.0, 9.7], [11.2, 9.8], [11.3, 8.7], [11.8, 10.0], [11.8, 9.9], [12.0, 9.8], [12.2, 12.2], [12.4, 13.4], [13.0, 12.2], [14.3, 19.7], [15.0, 19.9]]
fish_target
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
kn.score
1.0
길이가 30, 무게가 600인 놈이 뭔지 예측해봐!
Out[15]:
array([1])

그룹1 그러니까 A종으로 판단했다는 최종 결과를 얻었다.

반응형

+ Recent posts