installing java jdk 8 on ec2 

Step 1: Check the Java Version

java -version

Step 2: Download RPM package of Oracle JDK (8u121)

wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept- securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u141-b15/336fa29ff2bb4ef291e347e091f7f4a7/jdk-8u141-linux-x64.rpm

Step 4: Install JDK 8

sudo yum install -y jdk-8u141-linux-x64.rpm

Step 5: Verify oracle JDK version

java -version

Installing JRE 1.8

sudo yum install java-1.8.0

change the Java version

sudo alternatives --config java

 

launching ec2:

https://aws.amazon.com/getting-started/tutorials/launch-a-virtual-machine/?trk=gs_card&e=gs&p=gsrc

 

가상 머신 시작하기

Windows a. 여기에서 Windows용 Git을 다운로드합니다. 다운로드 설치 프로그램을 실행하고 기본 설정을 선택하면, Git Bash를 Git의 일부로 설치하게 됩니다. b. 데스크톱(아이콘이나 파일 아님)에서 마우스 오른쪽 버튼으로 클릭하고 Git Bash Here를 선택하여 Git Bash 명령 프롬프트를 엽니다. c. SSH를 사용하여 인스턴스에 연결합니다. 이 사례에서는 사용자 이름이 ec2-user이고, SSH 키는 3단계 파트 d에서

aws.amazon.com

installing rds on ec2: 

https://aws.amazon.com/getting-started/tutorials/create-mysql-db/?nc2=type_a

 

MySQL 데이터베이스를 생성하는 방법 – Amazon Web Services

Network & Security Public accessibility: Yes를 선택합니다. 이렇게 하면 데이터베이스 인스턴스에 대한 IP 주소가 할당되므로 사용자 디바이스에서 데이터베이스에 직접 연결할 수 있습니다. Availability zone: No preference 를 선택합니다. 자세한 내용은 리전 및 가용 영역을 참조하십시오. VPC security groups: Create new VPC security group을 선택합니다. 이렇게

aws.amazon.com

 

 

install putty and converting .pem to .ppk for filezilla:

brew install putty

puttygen mykeypair.pem -o mykeypair.ppk

 

'ETC' 카테고리의 다른 글

Writing Shell script 1  (0) 2020.01.30
Linux commands 1  (0) 2020.01.30
UnsupportedClassVersionError  (0) 2020.01.29
FTP vs SFTP  (0) 2020.01.29
AWS(1/29/20 notes) 접속  (0) 2020.01.29

jdk버전이 안맞다..

 

 

 

curl ifconfig.me 

 

추가 : 

project를 자바 7버전으로 구성해서 세팅할시 mysql-connector depository를 확인하자.

mysql-connector 버전 8 이후 부터는 java 7를 지원안해준다. 

 

mysql-connector 경로는 com.mysql.cj.jdbc.Driver이지만 mysql-connector 5같은 경우에는 com.mysql.jdbc.Driver

 

 

 

'ETC' 카테고리의 다른 글

Linux commands 1  (0) 2020.01.30
Setting aws ec2 and rds, install java jdk8 on ec2(1/30/20 cudo notes1)  (0) 2020.01.30
FTP vs SFTP  (0) 2020.01.29
AWS(1/29/20 notes) 접속  (0) 2020.01.29
Apache poi(excel)  (0) 2020.01.28

FTP and STFP are two different file transfer protocols.

 

FTP stands for File Transfer Protocol is commonly used protocol for exchanging files over the internet. 

FTP uses a cilent-server architecture, often secured with SSL/TLS. 

FTP works on a server and client based architecture, meaning that the client can access any information o nthe server at any given time. 

FTP uses two separate channels for data dn control both of which are unencrypted, whcih means information can be intercepted and accessed. 

FTP runs on TCP port 21.

 

example would be downloading mp3 music or free software from the internet, where the client does not need any id or password for accesing and downloading the information. 

 

SFTP stands for SSH File Transfer Protocol. Sometimes also called the secure File Transfer Protocol. provides implements secure file transfer over SSH. supports the full security and authentication functionality of the ssh protocol, inclduing ssh keys.

SSH is a secure way of providing access to all the shell accounts on remote server. 

SFTP uses only one channel for data and control(FTP uses two).

SFTP runs on TCP port 22.

 

 

Advantages :

  • Best for uploading/downloading extremely large files.
  • very fast.
  • User friendly.
  • Ideal for backups of large data.
  • Usually used foe business or by Web developers.

SFTP stands for Secure FTP. It is similar to FTP with a very important feature of security. The data sent or received requires authentication over SSH (Secure Shell Protocol). It runs on TCP port 22. It has a single channel for both Data and Control.

Advantages:

  • Used for sensitive data that requires encryption.
  • Popular on LINUX/UNIX.
  • Delievers detailed metadata with your files.

There are some more different types of Transfer Protocols used in application layer like:

  • TFTP - Trivial FTP. As it is trivial, it’s like simpler version of FTP. It also uses UDP over TCP so data is less reliable but faster. Usually used when unknown parties involved.
  • SCP - Secure copy Protocol. It is just like SFTP but slightly faster.

source : https://www.quora.com/What-is-the-detailed-difference-between-FTP-and-SFTP

mv .ssh.zip ssh.zip

sudo ssh -i /users/taewon/downloads/ssh/mykeypair.pem ec2-user@ec2-18-191-183-205.us-east-2.compute.amazonaws.com

https://sarc.io/index.php/aws/520-aws-ec2-linux-10-apache-tomcat

 

AWS의 EC2 Linux 인스턴스에 10분만에 Apache Tomcat 설치하기

Technical Note 정보 stdio.h 님이 작성하신 글입니다. 카테고리: [ Amazon Web Services ] 게시됨: 29 June 2016 작성됨: 30 June 2016 최종 변경: 21 September 2019 조회수: 20749 지난 주 스터디 주제로 AWS의 EC2 서비스를 이용하여 10분만에 Linux 서버 만들기에 대해 말씀드렸습니다.  (매주 모든 분들이 하나씩 올리는 것인 줄 알았는데 저 말고는 아무도 올리지 않으셔서 조

sarc.io

 

install tomcat 

sudo yum list tomcat*

sudo yum install tomcat7-webapps.noarch

sudo service tomcat7 start

(sudo service tomcat7 end)

curl http://127.0.0.1:8080

 

 

ps -ef | grep tomcat

만약 이렇게 뜨면 

sudo -i (or sudo su)

root user로 변경해서 

 

 

맥에서 ip 확인하기

ifconfig

192.168.x.x is an ip for all networks that is connected through a router. 

 

 

sudo -i

cd /var/log/tomcat7/

service tomcat7 start

tail -f catalina.out

 

 

mysql download 

yum install mysql-server

chkconfig mysqld on

service mysqld start

mysqladmin -u root password [your_new_pwd]

mysql -uroot -p

 

**********

sudo ssh -i /Users/taewon/Downloads/ssh/MYKeyPair.pem ec2-user@ec2-18-191-183-205.us-east-2.compute.amazonaws.com

**********

 

switch java jdk

/usr/libexec/java_home -V

export JAVA_HOME=`/usr/libexec/java_home -v 1.6.0_65-b14-462`

 

 

ec2 instance(installing java 1.8 and tomcat 8, switching from java 1.7 to java 1.8)

sudo yum install java-1.8.0

sudo /usr/sbin/alternatives --config java

yum install tomcat8 tomcat8-webapps tomcat8-admin-webapps tomcat8-docs-webapp

 

 

 

 

sudo ssh -i /users/taewon/downloads/ssh_taewon/mykeypair.pem  ec2-user@ec2-54-180-92-245.ap-northeast-2.compute.amazonaws.com

http://ec2-18-191-183-205.us-east-2.compute.amazonaws.com:8080/taewonboard/

 

 

'ETC' 카테고리의 다른 글

UnsupportedClassVersionError  (0) 2020.01.29
FTP vs SFTP  (0) 2020.01.29
Apache poi(excel)  (0) 2020.01.28
01/20/20 notes(mac java dw, java download and setup)  (0) 2020.01.20
Algorithms(week3, problemset)  (0) 2020.01.06
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
@RequestMapping(value = "excelDownload")
    public void excelDownload(HttpServletResponse response) throws Exception{
        //정보를 담는 객체 
        List<BoardVO> list = boardService.selectAll();
        
        //Starting basic, Workbook for creating excel
        //Sheet with workbook
        //row and cell
        //workbook, sheet, row, cell
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("게시판");
        Row row = null;
        Cell cell = null;
        int rowNo = 0;
        
        //optional, but recommended to style your columns
        //if there are a lot of columns, different styles are required,
        //better to create a method to maintain usability of ur code
        //for me, i just needed two different type so decided to hardcode em
        
        //font for font styling
        Font font = wb.createFont();
        //cellstyle for styling your cell
        CellStyle headStyle = wb.createCellStyle();
        headStyle.setBorderTop(BorderStyle.THIN);
        headStyle.setBorderBottom(BorderStyle.THIN);
        headStyle.setBorderLeft(BorderStyle.THIN);
        headStyle.setBorderRight(BorderStyle.THIN);
        //if you want to change your background, need foreground && fillpattern!!
        headStyle.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //apply the font here
        headStyle.setFont(font);
        
        //this is for body of a table
        CellStyle bodyStyle = wb.createCellStyle();
        bodyStyle.setBorderTop(BorderStyle.THIN);
        bodyStyle.setBorderBottom(BorderStyle.THIN);
        bodyStyle.setBorderLeft(BorderStyle.THIN);
        bodyStyle.setBorderRight(BorderStyle.THIN);
        //bodyStyle.setWrapText(true);
        
        //top column 
        String[] headerString = {"게시번호""제목","작성자","작성 날짜","시작일","종료일","조회수"};
        row = sheet.createRow(rowNo++);
        for(int i = 0; i < headerString.length; i++){
            cell = row.createCell(i);
            cell.setCellStyle(headStyle);
            cell.setCellValue(headerString[i]);
            
            
        }
        
        //tried this with an array, but cant seem to find a solution 
        //prints out strings.. 
        String[] bodyString = {".getBoardid()"".getBtitle()"".getBusername()"".getBdate()"".getBfrom()"".getBto()"".getBhit()"};
        for(BoardVO vo : list){
            row = sheet.createRow(rowNo++);
//            for(int i = 0; i < bodyString.length; i++){
//                cell = row.createCell(i);
//                cell.setCellStyle(bodyStyle);
//                String temp = "vo" + bodyString[i];
//                
//                cell.setCellValue(temp);
//            }
            cell = row.createCell(0);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(vo.getBoardid());
            cell = row.createCell(1);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(vo.getBtitle());
            cell = row.createCell(2);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(vo.getBusername());
            cell = row.createCell(3);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(vo.getBdate());
            cell = row.createCell(4);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(vo.getBfrom());
            cell = row.createCell(5);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(vo.getBto());
            cell = row.createCell(6);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(vo.getBhit());
        }
        
        //set the content type and header to respond
        response.setContentType("ms-vnd/excel");
        response.setHeader("Content-Disposition""attachment;filename=test.xls");
        
        //if you want to size your columns according to text, do it after
        //data has all been inputed or it will have no effect!
        for(int i = 0; i < headerString.length; i++){
            sheet.autoSizeColumn(i);
        }
        
        //write to a workbook and close
        wb.close();
    }
}
    
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'ETC' 카테고리의 다른 글

FTP vs SFTP  (0) 2020.01.29
AWS(1/29/20 notes) 접속  (0) 2020.01.29
01/20/20 notes(mac java dw, java download and setup)  (0) 2020.01.20
Algorithms(week3, problemset)  (0) 2020.01.06
Arrays(week 2, problem set)  (0) 2019.12.30

1. Delete java from mac completely by three steps:

 

sudo rm -rf /Library/Java/*

sudo rm -rf /Library/PreferencePanes/Java*

sudo rm -rf /Library/Internet\ Plug-Ins/Java*

 

2. You can type java -version on terminal and click on more info to be directed to oracle java page.

3. I downloaded jdk 8u241 version

4. Create file on main page

 

cd 

if .bash_profile does not exist, create it by touch .bash_profile

open -e .bash_profile

export JAVA_HOME=$(/usr/libexec/java_home)

 

5. to check for java_home, echo $JAVA_HOME

 

now for download 전자정부프레임워크

1. download eclipse mars

2. go to install new software and download in order

 

1) Spring Core 3.7.3 (필수)
    http://dist.springsource.com/release/TOOLS/update/e4.4/
    Core / Spring IDE -> Spring IDE Core

 

2) UML2 Extension 5.1.2 (필수)
    http://download.eclipse.org/releases/mars/
    Modeling -> UML2 Extender SDK

 

3) Subversive SVN Connector 6.0.1 (필수)
    http://download.eclipse.org/releases/mars/
    Collaboration -> Subbersive SVN Team Provider(3.0.4)
    http://community.polarion.com/projects/subversive/download/eclipse/5.0/mars-site/
    Subversive SVN Connectors -> Subversive SVN Connectors(5.0.3) 설치
    SVNKit 1.8.12 Implementation(5.0.3) 설치

 

4) eGovFrame 3.6.0 (필수)
    http://maven.egovframe.kr:8080/update_3.6/
    필요한 플러그인 설치(전부 다 설치했음)

 

5) JUnit 4.12 (필수)
    이클립스에 내장되어있어서 별도 설치과정 필요없음

 

6) MyBatipse 1.0.23 (선택)
    http://dl.bintray.com/harawata/eclipse
    MyBatipse -> MyBatipse 설치

 

7) PMD 4.0.11 (선택)
    https://sourceforge.net/projects/pmd/files/pmd-eclipse/update-site/
    PMD for Eclipse 4 -> PMD Plug-in 설치

 

8) FindBugs 3.0.1 (선택)
    http://findbugs.cs.umd.edu/eclipse
    FindBugs -> FindBugs Feature 설치

 

9) Properties Editor 6.0.4 (선택)
    http://propedit.sourceforge.jp/eclipse/updates/
    PropertiesEditor 설치

 

10) EclEmma 2.3.3 (선택)
      http://update.eclemma.org/
      EclEmma -> EclEmma Java Code Coverage 설치

 

11) Gradle 1.0.21 (선택)
     http://download.eclipse.org/buildship/updates/e45/releases/1.0
     Buildship:Eclipse Plug-ins for Gradle -> Buildship:Eclipse Plug-ins for Gradle 설치

 

12) Developer Tools 23.0.7 / Android Connector for M2E 1.4.0(안드로이드 개발 필수)
     http://rgladwell.github.com/m2e-android/updates/
     Developer Tools 모두 설치 (Developer Tools)
     Android for Maven Eclipse -> Android for Maven Eclipse 설치 (Android Connector for M2E)



출처: https://jhlblue.tistory.com/4 [JHLBLUE]

'ETC' 카테고리의 다른 글

AWS(1/29/20 notes) 접속  (0) 2020.01.29
Apache poi(excel)  (0) 2020.01.28
Algorithms(week3, problemset)  (0) 2020.01.06
Arrays(week 2, problem set)  (0) 2019.12.30
C Programming Language(week1, problem set)  (0) 2019.12.30

1. Plurality

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <cs50.h>
#include <string.h>
 
#define MAX 9
 
typedef struct{
 
    char *name;
    int votes;
 
}candidate;
 
//array of candidates
candidate candidates[MAX];
 
//number of candidates
int candidate_count;
 
//functions
bool vote(char *name);
void print_winner();
 
int main(int argc, char *argv[]){
    //Plurality vote
        //every voter chooses one candidate
        //whichever candidate has the msot votes wins
 
    //./plurality Alice Bob Charlie
    //Number of voters : 4
    //Vote: Alice
    //Vote: Bob
    //Vote: Charlie
    //Vote: Charlie
    //Charlie
 
//2 functions
    //vote
        //look for a candidate called name.
        //if candidate found, update their vote total and return true.
        //if no candidate found, dont update any vote totals and return false
    //print_winner
        //print the name of the candidate(s) who have the most votes.
 
    //check for invalid usage
    if(argc < 2){
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }
 
    //populate array of candidates
    //check for error
    candidate_count = argc - 1;
    if(candidate_count > MAX){
        printf("Maxium number of candidates is %i\n", MAX);
        return 2;
    }
 
    for(int i = 0; i < candidate_count; i++){
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }
 
    //prints array
    /*for(int i = 0; i < candidate_counts; i++){
        printf("%i %s %i\n", i, candidates[i].name, candidates[i].votes);
    }*/
 
    //receive number of voters
    int voters = get_int("Number of voters: ");
 
    //iterate and check for invalid votes
    for(int i = 0; i < voters; i++){
        char *name = get_string("Vote: ");
        if(!vote(name)){
            printf("Invalid vote.\n");
        }
    }
 
    print_winner();
    return 0;
 
}
 
bool vote(char *name){
 
    for(int i = 0; i < candidate_count; i++){
        if(strcmp(name, candidates[i].name) == 0){
            candidates[i].votes += 1;
            return true;
        }
    }
    return false;
}
 
void print_winner(){
 
    //finds the highest votes
    int highest = 0;
    for(int i = 0; i < candidate_count; i++){
        if(candidates[i].votes > highest) highest = candidates[i].votes;
    }
 
    //prints highest voters
    for(int i = 0; i < candidate_count; i++){
        if(candidates[i].votes == highest) printf("%s\n", candidates[i].name);
    }
    return;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

2. Runoff

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#include <cs50.h>
#include <stdio.h>
#include <string.h>
 
#define MAX_VOTERS 100
#define MAX_CANDIDATES 9
 
int preferences[MAX_VOTERS][MAX_CANDIDATES];
 
typedef struct{
    char *name;
    int votes;
    bool eliminated;
}candidate;
 
candidate candidates[MAX_CANDIDATES];
 
int voter_count;
int candidate_count;
 
//Function prototypes
bool vote(int voter, int rank, char *name);
void tabulate();
bool print_winner();
int find_min();
bool is_tie(int min);
void eliminate(int min);
 
int main(int argc, char *argv[]){
    //Runoff Vote
        //Every voter ranks their preferences
        //if a candidate has a majority (more than half) of the ovtes,
        // they are the winner
        //otherwise, eliminate the candidate with the fewest votes
        //and re-run the election without them
 
    //Check for invalid usage
    if(argc < 2){
        printf("Usage: runoff [candidate...]\n");
        return 1;
    }
 
    //Populate array of candidates
    candidate_count = argc - 1;
    if(candidate_count > MAX_CANDIDATES) {
        printf("Maximum number of candidates is %i\n", MAX_CANDIDATES);
        return 2;
    }
 
    for(int i = 0; i < candidate_count; i++){
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
        candidates[i].eliminated = false;
    }
 
    //receive number of votes
    voter_count = get_int("Number of voters: ");
    if(voter_count > MAX_VOTERS){
        printf("Maximum number of voters is %i\n", MAX_VOTERS);
        return 3;
    }
 
    //keep querying for votes
    for(int i = 0; i < voter_count; i++){
        //query for each rank
        for(int j = 0; j < candidate_count; j++){
            //record vote, unless it's invalid
            char *name = get_string("Rank %i: ", j + 1);
            if(!vote(i, j, name)){
                printf("Invalid vote\n");
            }
        }
        printf("\n");
    }
 
    // Keep holding runoffs untsil winner exists
    while(true){
        // Calculate votes given remaining candidates
        tabulate();
        // Check if election has been won
        if(print_winner()){
            break;
        }
 
        int min = find_min();
        if(is_tie(min)){
            for(int i = 0; i < candidate_count; i++){
                if(!candidates[i].eliminated){
                    printf("%s\n", candidates[i].name);
                }
            }
            break;
        }
        eliminate(min);
 
        // Eliminate last-place candidates
        // If tie, everyone wins
        // Eliminate anyone with minimum number of votes
        // Reset vote counts back to zero
        for (int i = 0; i < candidate_count; i++)
        {
            candidates[i].votes = 0;
        }
    }
 
    return 0;
}
 
// Record preference if vote is valid
bool vote(int voter, int rank, char *name){
 
    bool has_candidate = false;
    //Look for a candidate called name,
    //if candidate found, update preferences so that they are the voter's
    for(int i = 0; i < candidate_count; i++){
        if(strcmp(name, candidates[i].name) == 0) {
            preferences[voter][rank] = i;
            return true;
        }
    }
 
    //if no candidate found, dont update and return false
    return false;
}
 
// Tabulate votes for non-eliminated candidates
void tabulate(void)
{
    //update vote counts for all non-eliminated candidates
    for(int i = 0; i < voter_count; i++){
        //recall that each voter votes for their heighest preference
        for(int j = 0; j < candidate_count; j++){
            //candidate who has not yet been eliminated.
            //only update vote who are still in the race
            if(!candidates[preferences[i][j]].eliminated){
                candidates[preferences[i][j]].votes += 1;
                break;
            }
        }
    }
 
    // TODO
    return;
}
 
// Print the winner of the election, if there is one
bool print_winner(void)
{
    //if any candidate has more ethan half the vote, print out their
    //their name and return true
    for(int i = 0; i < candidate_count; i++){
        if(voter_count/2 < candidates[i].votes){
            printf("%s\n", candidates[i].name);
            return true;
        }
    }
 
    //if nobody has won the election yet, return false
    return false;
}
 
// Return the minimum number of votes any remaining candidate has
int find_min(void)
{
    //return the minimum number of votes of anyone still in the elction.
    //return candidates who has not been eliminated
    int min = MAX_VOTERS;
    for(int i = 0; i < candidate_count; i++){
        if(!candidates[i].eliminated && min > candidates[i].votes)
        min = candidates[i].votes;
    }
    // TODO
    return min;
}
 
// Return true if the election is tied between all candidates, false otherwise
bool is_tie(int min)
{
    //accepts the minimum number of votes min as input.
    for(int i = 0; i < candidate_count; i++){
        if(!candidates[i].eliminated && candidates[i].votes != min){
            return false;
        }
    }
    //returns true if the election is tied between all remaining candidates
    //, and return false otherwise.
    // TODO
    return true;
}
 
// Eliminate the candidate (or candidiates) in last place
void eliminate(int min)
{
    //eliminate anyone still in the race who has the min number of votes
    //if votes are the same, should eliminate two candidates
    for(int i = 0; i < candidate_count; i++){
        if(!candidates[i].eliminated && candidates[i].votes == min){
            candidates[i].eliminated = true;
        }
    }
    // TODO
    return;
}
 
 
 
 
 
 
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

3. Tideman

COULD NOT FINISH TIDEMAN WITH MY CURRENT UNDERSTANDING OF PROGRAMMING

Will get back to it in the future

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#include <cs50.h>
#include <stdio.h>
#include <string.h>
 
// Max number of candidates
#define MAX 9
 
// preferences[i][j] is number of voters who prefer i over j
int preferences[MAX][MAX];
 
// locked[i][j] means i is locked in over j
bool locked[MAX][MAX];
 
// Each pair has a winner, loser
typedef struct
{
    int winner;
    int loser;
}
pair;
 
// Array of candidates
string candidates[MAX];
pair pairs[MAX * (MAX - 1/ 2];
 
int pair_count;
int candidate_count;
 
// Function prototypes
bool vote(int rank, string name, int ranks[]);
void record_preferences(int ranks[]);
void add_pairs(void);
void sort_pairs(void);
void lock_pairs(void);
void print_winner(void);
 
int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: tideman [candidate ...]\n");
        return 1;
    }
 
    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i] = argv[i + 1];
    }
 
    // Clear graph of locked in pairs
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            locked[i][j] = false;
        }
    }
 
    pair_count = 0;
    int voter_count = get_int("Number of voters: ");
 
    // Query for votes
    for (int i = 0; i < voter_count; i++)
    {
        // ranks[i] is voter's ith preference
        int ranks[candidate_count];
 
        // Query for each rank
        for (int j = 0; j < candidate_count; j++)
        {
            string name = get_string("Rank %i: ", j + 1);
 
            if (!vote(j, name, ranks))
            {
                printf("Invalid vote.\n");
                return 3;
            }
        }
 
        record_preferences(ranks);
 
        printf("\n");
    }
 
    add_pairs();
    sort_pairs();
    lock_pairs();
    print_winner();
    return 0;
}
 
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
    //- look for a candidate called name
    //- if candidate found, update ranks and return true. ranks[i] is the voter's ith preference.
    //- if no candidate found, dont update any ranks and return false.
    // TODO
 
    for(int i = 0; i < candidate_count; i++){
        if(strcmp(candidates[i], name) == 0){
            ranks[i] = rank;
            return true;
        }
    }
    return false;
}
 
// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
    //- update the preferences array based on the current voter's rank
    // TODO
 
    for(int i = 0; i < candidate_count; i++){
        for(int j = 0; j < candidate_count; j++){
            if(ranks[i] < ranks[j]) preferences[i][j] += 1;
        }
    }
 
    for(int i = 0; i < candidate_count; i++){
        for(int j = 0; j < candidate_count; j++){
            printf("%i\t", preferences[i][j]);
        }
        printf("\n");
    }
    return;
}
 
// Record pairs of candidates where one is preferred over the other
void add_pairs(void)
{
  //  - add each pair of candidates to pairs array if one candidate is preferred over the other.
//    - udpate global variable pair_count to be the total number of pairs
 
    for(int i = 0; i < candidate_count; i++){
        for(int j = 0; j < candidate_count; j++){
            if(preferences[i][j] > preferences[j][i]){
                pairs[pair_count].winner = i;
                pairs[pair_count].loser = j;
                pair_count += 1;
            }
            /*else if(preferences[i][j] < preferences[j][i]){
                pairs[pair_count].winner = i;
                pairs[pair_count].loser = j;
                pair_count += 1;
            }*/
 
        }
    }
 
    //before sort
    for(int i = 0; i < pair_count; i++){
        printf("pairs %ith is winner %i and loser %i\n", i, pairs[i].winner, pairs[i].loser);
    }
    printf("\n");
    // TODO
    return;
}
 
// Sort pairs in decreasing order by strength of victory
void sort_pairs(void)
{
    // TODO
    //bubble sort
    //backwards, placing the highest value first
    for(int i = 0; i < pair_count - 1; i++){
        int ifirstDiff = preferences[pairs[i].winner][pairs[i].loser];
        int isecondDiff = preferences[pairs[i].loser][pairs[i].winner];
        int iComp = ifirstDiff - isecondDiff;
 
        for(int j = i + 1; j < pair_count; j++){
            int jfirstDiff = preferences[pairs[j].winner][pairs[j].loser];
            int jsecondDiff = preferences[pairs[j].loser][pairs[j].winner];
            int jComp = jfirstDiff - jsecondDiff;
 
            if(iComp < jComp){
                pair temp = pairs[j];
                pairs[j] = pairs[i];
                pairs[i] = temp;
            }
        }
    }
 
    for(int i = 0; i < pair_count; i++){
        printf("pairs %ith is winner %i and loser %i\n", i, pairs[i].winner, pairs[i].loser);
    }
    return;
}
 
// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
    //- update locked to create the locked graph by adding all edges
    //in decreasing order of vicotry strength, as long as there is no cycle
    // TODO
    locked[pairs[0].winner][pairs[0].loser] = true;
    for(int i = 1; i < pair_count; i++){
        int a = pairs[i].winner;
        int b = pairs[i].loser;
        for(int j = i + 1; j < pair_count; j++){
            int z = pairs[j].winner;
 
            if(a > z) locked[a][b] = true;
            else break;
        }
 
    }
 
    for(int i = 0; i < candidate_count; i++){
        for(int j = 0; j < candidate_count; j++){
            printf("%s\t", locked[i][j] ? "true" : "false");
        }
        printf("\n");
    }
 
    return;
}
 
// Print the winner of the election
void print_winner(void)
{
    //-print out the winner of the election, who will be the source of the graph
    //- you may assume there may be no more than one source.
    int count = 0;
    int winner = 0;
    for(int i = 0; i < pair_count; i++){
        int temp = 0;
        for(int j = 0; j < pair_count; j++){
            if(locked[i][j]) {
                temp ++;
                if(count < temp){
                    count = temp;
                    winner = i;
                } else if (count == temp){
                    winner = i;
                }
            }
        }
    }
 
    printf("%s\n", candidates[winner]);
    // TODO
    return;
}
 
/*bool lockrecursive(int winner, int loser){
 
    bool check = true;
    if(winner < 0){
        winner = 0;
        return true;
    }
    if(loser < 0){
        loser = 0;
        return true;
    }
 
    for(int i = 0; i < winner; i++){
        if(locked[winner][i]) check = false;
    }
}*/
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'ETC' 카테고리의 다른 글

Apache poi(excel)  (0) 2020.01.28
01/20/20 notes(mac java dw, java download and setup)  (0) 2020.01.20
Arrays(week 2, problem set)  (0) 2019.12.30
C Programming Language(week1, problem set)  (0) 2019.12.30
Memory (week3)  (0) 2019.12.27

1. Readability

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#import <cs50.h>
#import <stdio.h>
#import <string.h>
#import <stdlib.h>
 
int main(int argc, char *argv[]){
    int z;
 
    if(argc <= 1 || argc >= 3){
        printf("Usage: ./caesar key\n");
        return 1;
    } else if((z = atoi(argv[1])) == 0 ){
        printf("Usage: ./caesar key\n");
        return 1;
    }
    z = atoi(argv[1]);
    char *plaintext = get_string("plaintext: ");
 
    for(int i = 0, n = strlen(plaintext); i < n; i++){
        char letter = plaintext[i];
        //this prevents converting spaces and commas
        if(letter >= 'A'){
            int temp = z;
            //prevents inputs higher than 26
            while(temp > 26){
                    temp -= 26;
            }
            //for lower case that exceeds z
            if(letter + z > 'z'){
                if(letter + temp > 'z') {
                    temp -= ('z' - letter);
                    plaintext[i] = 'a' - 1 + temp;
                } else {
                    plaintext[i] += temp;
                }
            //for capital letters that exceeds z
            } else if (letter + z > 'Z' && letter < 'a'){
                if(letter + temp > 'Z') {
                    temp -= ('Z' - letter);
                    plaintext[i] = 'A' - 1 + temp;
                } else {
                    plaintext[i] += temp;
                }
            //if it is normal, just convert
            } else {
                plaintext[i] += z;
            }
        }
 
    }
    //print vowalla
    printf("ciphertext: %s\n", plaintext);
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

2. Caesar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#import <cs50.h>
#import <stdio.h>
#import <string.h>
#import <stdlib.h>
 
int main(int argc, char *argv[]){
    int z;
 
    if(argc <= 1 || argc >= 3){
        printf("Usage: ./caesar key\n");
        return 1;
    } else if((z = atoi(argv[1])) == 0 ){
        printf("Usage: ./caesar key\n");
        return 1;
    }
    z = atoi(argv[1]);
    char *plaintext = get_string("plaintext: ");
 
    for(int i = 0, n = strlen(plaintext); i < n; i++){
        char letter = plaintext[i];
        //this prevents converting spaces and commas
        if(letter >= 'A'){
            int temp = z;
            //prevents inputs higher than 26
            while(temp > 26){
                    temp -= 26;
            }
            //for lower case that exceeds z
            if(letter + z > 'z'){
                if(letter + temp > 'z') {
                    temp -= ('z' - letter);
                    plaintext[i] = 'a' - 1 + temp;
                } else {
                    plaintext[i] += temp;
                }
            //for capital letters that exceeds z
            } else if (letter + z > 'Z' && letter < 'a'){
                if(letter + temp > 'Z') {
                    temp -= ('Z' - letter);
                    plaintext[i] = 'A' - 1 + temp;
                } else {
                    plaintext[i] += temp;
                }
            //if it is normal, just convert
            } else {
                plaintext[i] += z;
            }
        }
 
    }
    //print vowalla
    printf("ciphertext: %s\n", plaintext);
}
 
 
 

2. Substitution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
 
char *encipher(char *t, char *argv[]);
bool validate_key(char *argv[]);
 
int main(int argc, char *argv[]){
 
    //Get key O
    //validate key O
        //check key length O
        //chekc for non-alphabetic characters O
        //check for repeated characters(case-insensitive) O
    //get plaintext O
    //encipher O
        //for each alphabetic character, determine what letter it maps to O
        //preserve case O
        //leave non-alphabetic characters as-is O
    //print ciphertext O
 
    //validates key's length and invalid keys
    if(!(argc > 1 && argc < 3)){
        printf("Usage: ./substitution key\n");
        return 1;
    } else if(!(validate_key(argv))) return 1;
 
    //get plaintext
    char *= get_string("plaintext: ");
 
    //encipher & print ciphertext
    printf("ciphertext: %s\n", encipher(t, argv));
}
 
bool validate_key(char *argv[]){
    //validate key
        //check key length
        //check for non-alphabetic characters
        //check for repeated characters(case-insensitive)
    char alphabet[] = {'A','B','C','D','E','F','G','H',
                    'I','J','K','L','M','N','O','P',
                     'Q','R','S','T','U','V','W','X','Y','Z'};
 
    //sets checkRepeat to all false;
    bool checkRepeat[strlen(argv[1])];
    for(int i = 0, n = strlen(argv[1]); i < n; i++){
        checkRepeat[i] = false;
    }
 
    //checks for key's length
    if(strlen(argv[1]) != 26){
        printf("Key must contain 26 characters.\n");
        return 0;
    }
 
    //checks for repeated value or incorrect value
    for(int i = 0, n = strlen(argv[1]); i < n; i++){
        if((argv[1][i] >= 'a' && argv[1][i] <= 'z'|| (argv[1][i] >= 'A' && argv[1][i] <= 'Z')){
            for(int j = 0, m = strlen(alphabet); j < m; j++){
                if(argv[1][i] == alphabet[j] || argv[1][i] - ('a' - 'A'== alphabet[j]){
 
                    if(!checkRepeat[j]) {
                        checkRepeat[j] = true;
                        printf("it entered here on %i\n", j);
                        break;
                    }else if (checkRepeat[j]){
                        printf("Key must not contain repeated characters.\n");
                        return 0;
                    }
                }
            }
        } else {
            printf("Key must only contain alphabetic characters.\n");
            return 0;
        }
    }
 
    //converts all lower case to upper case
    for(int i = 0, n = strlen(argv[1]); i < n; i++){
        if(argv[1][i] >= 'a') argv[1][i] -= ('a' - 'A');
    }
 
    return 1;
 
}
 
char *encipher(char *t, char *argv[]){
    //encipher
        //for each alphabetic character, determine what letter it maps to
        //preserve case
        //leave non-alphabetic characters as-is
 
    //stores inputted letter placement from the alphabet
    int a = strlen(t);
    int numbers[a];
    int upperLowerDifference = 'a' - 'A';
 
    //alphabet array to find out letter placement
    char alphabet[] = {'A','B','C','D','E','F','G','H',
                        'I','J','K','L','M','N','O','P',
                         'Q','R','S','T','U','V','W','X','Y','Z'};
 
    //stores letter placement into numbers array
    for(int i = 0; i < a; i++){
        for(int j = 0, z = strlen(alphabet); j < z; j++){
            if(t[i] == alphabet[j]) {
                numbers[i] = j;
                break;
            }else if(t[i] == alphabet[j] + upperLowerDifference){
                numbers[i] = j + upperLowerDifference;
                break;
            }
        }
    }
 
    //replaces plaintext into enciphered text
    for(int i = 0; i < a; i++){
        if((t[i] >= 'a' && t[i] <= 'z'|| (t[i] >= 'A' && t[i] <= 'Z')){
            if(numbers[i] >= upperLowerDifference ) t[i] = argv[1][numbers[i] - upperLowerDifference] + upperLowerDifference;
            else t[i] = argv[1][numbers[i]];
        }
    }
 
    return t;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'ETC' 카테고리의 다른 글

01/20/20 notes(mac java dw, java download and setup)  (0) 2020.01.20
Algorithms(week3, problemset)  (0) 2020.01.06
C Programming Language(week1, problem set)  (0) 2019.12.30
Memory (week3)  (0) 2019.12.27
Arrays and Sorting Algorithms (week2)  (0) 2019.12.26

+ Recent posts