스탭코딩

문제 : https://programmers.co.kr/learn/courses/30/lessons/42839

 

코딩테스트 연습 - 소수 찾기 | 프로그래머스

한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다. 각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요. 제한사항 numbers는 길이 1 이상 7 이하인 문자열입니다. numbers는 0~9까지 숫자만으로 이루어져 있습니다. 013은 0, 1, 3 숫자가 적힌 종이

programmers.co.kr

public class Solution {

   public int solution(String numbers) {
        int answer = 0;
        List numList = new ArrayList();
        Set resultSet = new HashSet();         
        
        for(int i=0; i<numbers.length(); i++) {         
         numList.add(String.valueOf(numbers.charAt(i)));
        }
        
        //순열생성
        perm(numList, resultSet, 0);
        
        //소수 확인
Iterator itr = resultSet.iterator();
while (itr.hasNext()) {
if(isPrime(itr.next())) {
answer++;
}
}

return answer;
}

//참고 (순열 생성) 
public List perm(List list, Set resultSet,int pivot) {
if (pivot == list.size()) {
//System.out.println(list);
makeResultSet(list, resultSet);
}
 
for (int i = pivot; i < list.size(); i++) {
swap(list, i, pivot);
perm(list, resultSet, pivot + 1);
swap(list, i, pivot);
}
return list;
}

public void swap(List list, int i, int j) {
String a = list.get(i);
String b = list.get(j);
list.set(i, b);
list.set(j, a);

}

// 순열별 경우의수
public Set makeResultSet(List numList,Set resultSet){
// prefix 를 정하고 뒤를 순서대로 붙임
// 다음 프리픽스로 사용한 인덱스를 제거하고 반복하면서 리절트셋에 에드
for(int k=0; k<numList.size() ; k++) {

int fixIdx = k;
resultSet.add(Integer.valueOf(numList.get(k)));
List tempNumList = new ArrayList();

//고정 값을 제외하 나머지 요소를 담을  리스트를 생성합니다.
for(int i=fixIdx+1; i<numList.size();i++) {
tempNumList.add(numList.get(i));
}

for(int i=0; i< tempNumList.size();i++) {
// 두번째로 배치할 인덱스 == i
// 두번째 배치할 요소를 고려해서 큐를 생성합니다.
Queue q = new LinkedList();
List tempNumList2 = new ArrayList();
String resultNum = numList.get(fixIdx);
   resultNum += tempNumList.get(i);

for(int j=0; j<tempNumList.size(); j++) {
if(i != j) {
resultNum += tempNumList.get(j);
}
}

resultSet.add(Integer.valueOf(resultNum));
makeResultSet(tempNumList,resultSet);
}
}
return resultSet;
}

private boolean isPrime(int num) {
if (num < 2) return false;
    if (num == 2) return true;
    if (num % 2 == 0) return false;

    /**
     * num 이 p * q 라고 할때 한 수는 항상 sqrt(num) 이하의 값을 갖는다. (ex, num = 24, p = [1, 2, 3, 4], q = [6, 8, 12, 24])
     * 따라서 num 이 sqrt(num) 이하의 값중 하나로 나눠지는지 체크한다. (ex, 24 가 4 이하의 숫자로 나눠지는지 체크,, 1,2 는 예외)
     */
    // 참고
    int sqrtn = (int) Math.sqrt(num);
    for (int i = 3; i <= sqrtn; i += 2) {
        if (num % i == 0) return false;
    }
    return true;
}

'알고리즘' 카테고리의 다른 글

[JAVA ]프로그래머스 - 오픈채팅방(openChatRoom) 42888  (0) 2020.01.13

문제 : https://programmers.co.kr/learn/courses/30/lessons/42888

 

코딩테스트 연습 - 오픈채팅방 | 프로그래머스

오픈채팅방 카카오톡 오픈채팅방에서는 친구가 아닌 사람들과 대화를 할 수 있는데, 본래 닉네임이 아닌 가상의 닉네임을 사용하여 채팅방에 들어갈 수 있다. 신입사원인 김크루는 카카오톡 오픈 채팅방을 개설한 사람을 위해, 다양한 사람들이 들어오고, 나가는 것을 지켜볼 수 있는 관리자창을 만들기로 했다. 채팅방에 누군가 들어오면 다음 메시지가 출력된다. [닉네임]님이 들어왔습니다. 채팅방에서 누군가 나가면 다음 메시지가 출력된다. [닉네임]님이 나갔습니다. 채팅

programmers.co.kr

 

public class Solution {


public String[] solution(String[] record) {
        String[] answer;       
        //반환배열 길이(인풋된 record 길이에서 change동작은 제외한 길이)
        int answerSize=0;
        //동작유형배열
        String[] operTypeArr = {"Enter","Leave","Change"};
        //아이디,닉네임 맵 
        Map<String,String> uidMap = new HashMap<String,String>();
        //동작, 반환값 맵 
        Map<String,String> answerMap = new HashMap<String,String>();
        answerMap.put("Enter", "님이 들어왔습니다.");
        answerMap.put("Leave", "님이 나갔습니다.");
        // 입력받은 값을 2차원 배열에 담습니다
        String[][] record2 = new String[record.length][3];

        for(int i=0; i<record.length; i++) {
            record2[i] = record[i].split(" ");
        }

        //아이디,닉네임맵에 정보를 담고 닉네임 변경을 반영합니다.
        for(int j=0; j<record2.length; j++) {   
            if(record2[j][0].equals("Enter")) {
                uidMap.put(record2[j][1], record2[j][2]);
                answerSize++;
            }else if(record2[j][0].equals("Change")) {
                uidMap.replace(record2[j][1], record2[j][2]);
            }else {
                answerSize++;               
            }
        }
        
        answer = new String[answerSize];

        //입력정보에서  uidMap에서 uid값을 키로 닉네임정보를 맵에서 불러 옵니다.(change동작은 제외)
        //record 배열과 answer배열의 길이가 다르기때문에 배열 인덱스를 매칭시켜줄 변수를 정의합니다.
        int answerIdx = 0;
        for(int i=0; i<record2.length; i++) {
            String operType = record2[i][0];
            if(!operType.equals(operTypeArr[2])) {
                answer[answerIdx]=uidMap.get(record2[i][1])+answerMap.get(operType);
                answerIdx++;
            }
        }
        return answer;
    }
}

 

 

 

bitcoind 구동

BLOCKCHAIN2019. 5. 17. 14:08

bitcoin 블록체인의 체인데이터를 동기화 하기 위해 bitcoind를 실행합니다.

 

bitcoind가 설치된 디렉터리에서 ./bitcoind 혹은 스타드 쉘을 작성해서 실행하면 됩니다.

스타트 쉘은 EOS BP 중 하나인 CryptoLions 깃헙 자료를 참고로 만들었습니다. https://github.com/CryptoLions/scripts/blob/master/start.sh

  !/bin/bash
    DATADIR="bitcoind가 적치된 디렉터리 위치"

    #stop bitcoind
    $DATADIR/stop.sh

    #start bitcoind
    echo -e "Starting Bitcoind.. \n";
    $DATADIR/bitcoind "$@" > $DATADIR/stdout.txt 2> $DATADIR/stderr.txt & echo $! > $DATADIR/bitcoind.pid

'BLOCKCHAIN' 카테고리의 다른 글

bitcoin.conf (for rpc)  (0) 2019.05.15

server=1

# server=1 은 Bitcoin-Qt 와 bitcoind JSON-RPC 사용하도록 합니다.

 

rpcuser=rpc유저

rpcpassword=rpc유저의 비밀번호

# rpc접속에 필요한 유저와 비밀번호를 설정합니다.

 

rpcallowip=rpc를 허용할 ip

rpcallowip=rpc를 허용할 ip2

rpcallowip=rpc를 허용할 ip3

#추가 허용 ip가 있을경우 아래에 추가합니다. 형식은 포트번호를 제외한 ip만 입력합니다.

 

rpcport=rpc포트

# 메인넷 디폴트 포트:18332, 테스트넷 디폴트 포트:8332

 

rpcthreads=4

#rpc 호출을 처리할 스래드 개수 디폴트:4

 

reindex=1

# 블록 초기화와 함께 새롭게 블록을 다운로드합니다. 이어서 블록동기화를 진행할 경우 reindex 옵션은 삭제해주세요.

 

txindex=1

#블록체인 내의 트랜잭션에 대한 데이터 조회

'BLOCKCHAIN' 카테고리의 다른 글

bitcoind 구동  (0) 2019.05.17


Remix 에서 환경을 Injected web3를 사용하려고 할때 


 'No injected Web3 provider found. Make sure your provider (e.g. MetaMask) is active and running (when recently activated you may have to reload the page).'


에러가 뜬다면 geth를 설치해주면 됩니다.





https://geth.ethereum.org/downloads/


에 접속해서 운영체제에 맞는 버전을 설치하고 브라우져를 끄고 다시 리믹스에 접속하시면 됩니다 :)

'BLOCKCHAIN > Ethereum' 카테고리의 다른 글

A next generation blockchain 차세대 블록체인  (0) 2018.08.15
What is Ethereum? 이더리움이란?  (0) 2018.08.15


A next generation blockchain


  Blockchain technology is the technological basis of Bitcoin, first described by its mysterious author Satoshi Nakamoto in his white paper “Bitcoin: A Peer-to-Peer Electronic Cash System”, published in 2008. While the use of blockchains for more general uses was already discussed in the original paper, it was not until a few years later that blockchain technology emerged as a generic term. A blockchain is a distributed computing architecture where every network node executes and records the same transactions, which are grouped into blocks. Only one block can be added at a time, and every block contains a mathematical proof that verifies that it follows in sequence from the previous block. In this way, the blockchain’s “distributed database” is kept in consensus across the whole network. Individual user interactions with the ledger (transactions) are secured by strong cryptography. Nodes that maintain and verify the network are incentivized by mathematically enforced economic incentives coded into the protocol.


-       블록체인 기술은 비트코인 기술을 기반으로 하고있음

-       블록 체인은 모든 네트워크 노드가 블록으로 그룹화 된 동일한 트랜잭션을 실행하고 기록하는 분산 컴퓨팅 아키텍처

-       한 번에 하나의 블록 만 추가 할 수 있으며 모든 블록에는 이전 블록의 순서대로 이어지는지를 검증하는 수학적 증명이 포함되고, 이러한 방식으로 블록 체인의 "분산 데이터베이스"는 전체 네트워크에 걸쳐 공감대(데이터 일치)유지


 

  In Bitcoin’s case the distributed database is conceived of as a table of account balances, a ledger, and transactions are transfers of the bitcoin token to facilitate trustless finance between individuals. But as bitcoin began attracting greater attention from developers and technologists, novel projects began to use the bitcoin network for purposes other than transfers of value tokens. Many of these took the form of “alt coins” - separate blockchains with cryptocurrencies of their own which improved on the original bitcoin protocol to add new features or capabilities. In late 2013, Ethereum’s inventor Vitalik Buterin proposed that a single blockchain with the capability to be reprogrammed to perform any arbitrarily complex computation could subsume these many other projects.


-       비트 코인 (Bitcoin)의 경우 분산 데이터베이스는 계좌 잔고, 원장 테이블로 간주되며 거래는 비트 동전 토큰을 전송하여 개개인 간의 보증 없는 금융을 촉진

-       비트코인이 개발자들로부터 주목을 받기 시작하면서 알트코인형태로 원래의 비트 동전 프로토콜을 개선하여 새로운 기능을 추가 한 독점적인 블록 체인(cryptocurrencies)을 사용

-       2013 년 말 Ethereum의 창시자인 비탈릭 부테린은 임의로 복잡한 계산을 수행하도록 다시 프로그래밍 할 수 있는 단일 블록 체인에 다른 프로젝트(알트코인)을 담을 수 있다고 제안

 

  In 2014, Ethereum founders Vitalik Buterin, Gavin Wood and Jeffrey Wilcke began work on a next-generation blockchain that had the ambitions to implement a general, fully trustless smart contract platform.


-       2014 년 이더리움 창립자인 비탈릭 부테린, 개빈 우드 및 제프리 윌케는 완전한 보증 없는 스마트 계약 플랫폼을 구현하고자하는 차세대 블록 체인에 대한 작업 시작


출처

Ethereum Homestead Documentation

(http://www.ethdocs.org/en/latest/index.html)

Docs » Introduction » What is Ethereum?




What is Ethereum?



Ethereum is an open blockchain platform that lets anyone build and use decentralized applications that run on blockchain technology. Like Bitcoin, no one controls or owns Ethereum – it is an open-source project built by many people around the world. But unlike the Bitcoin protocol, Ethereum was designed to be adaptable and flexible. It is easy to create new applications on the Ethereum platform, and with the Homestead release, it is now safe for anyone to use those applications.


-       누구나 블록 체인 기술록 실행되는 분산된 애플리케이션을 구축하고 사용할 수 있는 개방형 블록 체인 플랫폼

-       오픈소스 프로젝트

-       적용도와 유연성이 높게 고안됨





출처

Ethereum Homestead Documentation

(http://www.ethdocs.org/en/latest/index.html)

Docs » Introduction » What is Ethereum?


* 대부분의 이클립스 버전에 동일하게 적용돼요.



1. 이클립스 실행 후 상단의 Window텝에서 preferences 클릭




2. General > Appearance 에서 Theme를 Dark로 설정해줍니다. 

요즘 버전은 에이터화면 배경이 자동으로 바뀌지만 예전 버전은 따로 설정해 줘야 바뀌니 에이터 화면이 다크 테마 적용안되신 분은 3번을 진행해주세요.





3. 에디터 배경화면 설정

General > Editors >Text Editors 에서 Background color 선택 > System Default 체크박스 해제 > 배경색 변경



셀렉트 박스에서 이미 선택된 값을 출력하고 변경을 못하게 하고 싶을때 쓰면 유용합니다.


* disabled를 사용하게 되면 폼데이터를 컨트롤러로 보낼 수 없게됩니다.

* 당연히 아래 코드를 사용하면 데이터를 보낼 수 있습니다 ^^


샘플예제 입니다.


1
2
3
4
5
6
7
8
9
10
11
12
<select name="fruit" id="fruit" readonly 
        style="background-color:#ababab" 
        onFocus="this.initialSelect = this.selectedIndex;" 
        onChange="this.selectedIndex = this.initialSelect;">
 
<option value=''>ALL</option>
 
<option value='apple' selected>apple</option>
 
<option value='banana'>banana</option>
 
</select>

cs



selected 옵션의 apple이 기본으로 출력되고 다른 선택옵션을 클릭해도 변경되지 않습니다.



빅데이터의 특징으로 거론되는 큰 3가지 내용으로는



Volume : 이터의 규모 

일단 빅데이터는 대용량이다. 

페이스북이 하둡(Hadoop) 데이터베이스에 저장하는 사진문서 용량은 30페타바이트(대략 30,000TB)에 이른다. 

그리고 뉴욕 증권거래소는 매일같이 1TB에 해당하는 데이터를 쏟아낸다고 한다.



Velocity : 데이터의 생성 속도


데이터가 빠른 속도로 생성되기 때문에 적시에 유용한 정보를 뽑아내기 위해서는 속도가 빨라야 한다.



Variety : 데이터의 다양성 


- 구조화 데이터 : 테이블에 저장 할 수 있는 정형화된 데이터
-
비구조화 데이터 : 영상, 이미지 등





V3에서 2개의 개념을 더해서 V5로 특징이 정의되기도 한다



Veracity : 정확성


표본이 크므로 정확도가 높다.



Value : 가치


빅 데이터 분석을 통해 도출된 결론은 기업이나 조직의 당면한 문제를 해결할 수 있어야 하며 통찰력 있는 유용한 정보를 제공해야 한다.





'HADOOP' 카테고리의 다른 글

빅데이터란? 빅데이터의 정의  (0) 2018.08.07