다각형과 점

 

입력으로 하나의 직교 다각형(모든 변이 x축 혹은 y축과 평행한 다각형)의 또 하나의 점 p가 주어질 때 그 점이 다각형의 내부에 있는지

외부에 있는지 판단하는 프로그램을 작성하라

 

입력 형식의 예 시계방향으로 꼭지점의 좌표가 주어짐

8 // 꼭지점의 개수

0 0 //첫번째 꼭지점 x,y 좌표

16 0

16 18

10 18

10 6

6 6

6  12

0 12 //마지막 꼭지점의 x,y 좌표

7 7 //테스트할 점 p의 좌표


내부 / 외부 검사

 

점에서 시작하여 한 방향으로 무한히 뻗어가는 아무 직선이나 하나 그어서

그것이 다각형의 변과 짝수 번 교차하면 외부, 홀수번 교차하면 내부에 있다.

 

문제는 그은 직선이 겹치게된다면 ???

꼭지점의 좌표값은 모두 짝수, 검사할 점 좌표값은 홀수로 가정한다.

 

package section2;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code10 {

	public static void main(String[] args) {
		
		try {
			Scanner in = new Scanner(new File("data.txt"));
			int n = in.nextInt();
			OrthPolygon thePolygon = new OrthPolygon(n);
			for(int i =0; i<n; i++)
				thePolygon.addVertex(in.nextInt(),in.nextInt());
			Mypoint2 thePoint = new Mypoint2(in.nextInt(),in.nextInt());
			in.close();
			if(thePolygon.contains(thePoint))
				System.out.println("Yes");
			else
				System.out.println("No");
		}catch(FileNotFoundException e) {
			System.out.println("No data file exists");
			System.exit(1);
		}

	}

}

 

메인 함수 클래스!

 

package section2;

public class OrthLine {
	public Mypoint2 u;
	public Mypoint2 v;
	
	public OrthLine(Mypoint2 p, Mypoint2 q){
		u =p;
		v= q;
		if(p.x>q.x || p.x==q.x && p.y>q.y)
			swap();
	}
	
	private void swap() {
		Mypoint2 tmp = u;
		u =v;
		v=tmp;
	}
	
	public OrthLine(int x, int y, int x1, int y1){
		u =new Mypoint2(x,y);
		v = new Mypoint2(x1,y1);
	}
	
	public boolean isVertical() {
		return (u.x == v.x);
	}
	
	public boolean intersects(OrthLine other) {
		if(isVertical() && !other.isVertical()) {
			return(other.u.x < u.x && other.v.x > u.x && u.y <other.u.y && v.y > other.u.y);
		}
		else if(!isVertical() && other.isVertical()) {
			return(other.u.y < u.y && other.v.y > u.y && u.x < other.u.x &&v.x > other.u.x);
		}
		else
			return false;
	}
}

선분 클래스

 

package section2;

public class OrthPolygon {
	public int n;
	public Mypoint2 [] vertices;
	
	public OrthPolygon(int k) {
		n=0;
		vertices = new Mypoint2[k];
	}
	public void addVertex(int x, int y) {
		vertices[n++] = new Mypoint2(x,y);
	}
	
	public int maxX() {
		int max = vertices[0].x;
		for(int i =0;i <n;i++) {
			if(vertices[i].x>max)
				max =vertices[i].x;
		}
		return max;
	}
	
	public boolean contains(Mypoint2 p) {
		OrthLine arrow = new OrthLine(p, new Mypoint2(maxX()+1,p.y));
		int count =0;
		for(int i =0;i<n;i++) {
			OrthLine edge = new OrthLine(vertices[i], vertices[(i+1)%n]);
			if(arrow.intersects(edge))
				count++;
		}
		return (count % 2 == 1);
	}
}

직교 다각형 클래스 

 

기하학 적인 프로젝트를 할때마다 뭔가 어렵지만 종이에 그려가며

하니 조금 수월 하였다 이부분에대해서는 아직 이해가 덜되어 

계속 읽어보며 이해를 더 해야할 것같다!!

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

static 그리고 public 2  (0) 2021.06.28
static 그리고 public 1  (0) 2021.06.28
메서드와 생성자 2  (0) 2021.06.24
메서드와 생성자 1  (0) 2021.06.23
클래스 ,객체, 참조변수 5  (0) 2021.06.23

생성자

 

클래스 안에 그 클래스와 동일한 이름을 가지며 return 타입이 없는 특별한 메서드를 둘 수 있는데

이것을 생성자 라고 부른다.

 

생성자는 new 명령으로 객체가 생성될때 자동으로 실행된다. 주 목적은 객체의 데이터

필드의 값을 초기화하는 것이다.

 

생성자가 반드시 매개변수를 받아야하는 것은 아니다.

 

package section2;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code09 {

	static MyRectangle2[] rects = new MyRectangle2[100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		try {
			Scanner in = new Scanner(new File("data.txt"));
			
			while(in.hasNext()) {
			rects[n++] = new MyRectangle2(in.nextInt(),in.nextInt(),in.nextInt(),in.nextInt());
			}
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("no data file");
			System.exit(1);
		}
		bubbleSort();
	
		for(int i =0;i<n;i++) 
			System.out.println(rects[i].toString());
		}
	
		private static void bubbleSort() {
			for(int i = n-1;i>0;i--) {
				for(int j =0; j<i; j++) {
					if(rects[j].calArea() > rects[j+1].calArea()) {
						MyRectangle2 tmp = rects[j];
						rects[j] = rects[j+1];
						rects[j+1] = tmp;
					}
				}
			}
		}
}


 

package section2;

public class Mypoint2 {
	public int x;
	public int y;
	
	public Mypoint2(int x, int y) {
		this.x = x;
		this.y = y;
	}
}
package section2;

public class MyRectangle2 {
	public Mypoint2 lu;
	public int width;
	public int height;
	
	public MyRectangle2(int x, int y, int w, int h) {
		lu = new Mypoint2(x,y);
		width =w;
		height = h;
	}
	public int calArea() {
		return width * height;
	}
	
	public String toString() {
		return "("+lu.x + ","+ lu.y +")"+ width + " " + height;
	}
}

생성자를 이용해서 저번 code5를 수정해보았다.

 

어떤 이유때문에 사각형 하나를 표현할때 꼭지점의 좌표와 높이 너비를 이용해 표현하지 않고

대각 방향에 두 꼭지점의 좌표를 이용한다고 했을때

수정이 필요하다!

 

이전 코드였다면 표현방법을 바꿧을뿐인데

그 클래스와 다른클래스 까지 다 바꿔야만 한다.

 

지금은 해당 클래스만 바꾸면 되지만 

메인함수 클래스에서는 대부분 어떠한 것도 바꿀 필요가 없게된다!!

 

어찌되었건 코드의 수정이 적어진다!

응집도를 높이고 결합도가 높아지게 하기 위함이다

 

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

static 그리고 public 1  (0) 2021.06.28
메서드와 생성자 3  (0) 2021.06.24
메서드와 생성자 1  (0) 2021.06.23
클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 4  (0) 2021.06.22

이번 시간에는 

진짜 애플리케이션에서 DB연동을 하여 

애플리케이션에 기존 메모리가 아닌 DB에 쿼리를

날려 데이터를 관리하는 것을 해보았다.

 

발전 과정을 알아보기위해

옛날 방식으로 해보았다.!

 

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	implementation 'org.springframework.boot:spring-boot-starter-jdbc'
	runtimeOnly 'com.h2database:h2'
}

일단 build.gradle 파일에 dependencies에 

JDBC , H2 관련 라이브러리를 추가해준다.

 

spring.datasource.url=jdbc:h2:tcp://localhost/~/test 
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa

또한

resources/application.properties 이곳에

스프링 부트 데이터베이스 연결설정을 추가해준다.

 

이렇게 되면 데이터베이스에 접근하기 위한 준비가 다 되었다.

 

이제 JDBC API를 가지고 개발을 해보았다.

package hello.hellospring.repository; import hello.hellospring.domain.Member;
import org.springframework.jdbc.datasource.DataSourceUtils;
import javax.sql.DataSource; 
import java.sql.*;
import java.util.ArrayList;

import java.util.List; 
import java.util.Optional;
public class JdbcMemberRepository implements MemberRepository {
    private final DataSource dataSource;
    public JdbcMemberRepository(DataSource dataSource)
    { this.dataSource = dataSource;
    }
    @Override
    public Member save(Member member) {
        String sql = "insert into member(name) values(?)";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql,
                    Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, member.getName());
            pstmt.executeUpdate();
            rs = pstmt.getGeneratedKeys();
            if (rs.next()) { member.setId(rs.getLong(1));
            } else {
                throw new SQLException("id 조회 실패");
            }
            return member;
        } catch (Exception e) {
            throw new IllegalStateException(e);
        } finally {
            close(conn, pstmt, rs);

        } }
    @Override
    public Optional<Member> findById(Long id) {
        String sql = "select * from member where id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql); pstmt.setLong(1, id);
            rs = pstmt.executeQuery();
            if(rs.next()) {
                Member member = new Member(); member.setId(rs.getLong("id")); member.setName(rs.getString("name")); return Optional.of(member);
            } else {
                return Optional.empty();
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        } finally {
            close(conn, pstmt, rs);
        } }
    @Override
    public List<Member> findAll() {
        String sql = "select * from member";

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            List<Member> members = new ArrayList<>(); while(rs.next()) {
                Member member = new Member(); member.setId(rs.getLong("id")); member.setName(rs.getString("name")); members.add(member);
            }
            return members;
        } catch (Exception e) {
            throw new IllegalStateException(e);
        } finally {
            close(conn, pstmt, rs);
        }
    }
    @Override
    public Optional<Member> findByName(String name) {
        String sql = "select * from member where name = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql); pstmt.setString(1, name);

            rs = pstmt.executeQuery();
            if(rs.next()) {
                Member member = new Member(); member.setId(rs.getLong("id")); member.setName(rs.getString("name")); return Optional.of(member);
            }
            return Optional.empty(); } catch (Exception e) {
            throw new IllegalStateException(e);
        } finally {
            close(conn, pstmt, rs);
        }
    }
    private Connection getConnection() {
        return DataSourceUtils.getConnection(dataSource);
    }
    private void close(Connection conn, PreparedStatement pstmt, ResultSet rs)
    {
        try {
            if (rs != null) {
                rs.close(); }
        } catch (SQLException e) { e.printStackTrace();
        } try {
        if (pstmt != null) { pstmt.close();
        }
    } catch (SQLException e) {
        e.printStackTrace(); }
        try {
            if (conn != null) {

                close(conn);
            }
        } catch (SQLException e) { e.printStackTrace();
        } }
    private void close(Connection conn) throws SQLException { DataSourceUtils.releaseConnection(conn, dataSource);
    } }

 

package hello.hellospring;

import hello.hellospring.repository.JdbcMemberRepository;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import hello.hellospring.service.MemberService;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class SpringConfig {
    
    private DataSource dataSource;
    
    public SpringConfig(DataSource dataSource){
        this.dataSource = dataSource;
    }
    
    @Bean
    public MemberService memberService(){
        return new MemberService(memberRepository());
    }

    @Bean
    public MemberRepository memberRepository(){
        //return new MemoryMemberRepository();
        return new JdbcMemberRepository(dataSource);
    }
}

기존에 MemoryMemberRepository() 를 반환하던것을

JdbcMemberRepository에 dataSource를 넣어주는 것 만으로

db를 이용하게끔 바꾸는 것이 가능해졌다. 다른 코드는 건들지 않고 

 jdbc연동 클래스 하나와 설정 파일 변경을 하였는데 치환하는 것이 가능하였다!

 

정상적으로 들어가는지 확인!

 

사실 중요한 것은 스프링을 왜쓰냐?

객체지향적인 설계가 왜 좋은가? 

다형성을 활용! 인터페이스를 두고 구현체를 바꿔 끼우기를 

굉장히 편리하게 되도록 스프링컨테이너가 지원을 해주기 때문!

의존성 주입 덕분에 편리하게 가능하다. 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/lecture/49594?tab=note&speed=0.75

MemberService는 MemberRepository를 의존하고 있고

MemberRepository는 구현체로 MemoryMemberRepository 와 JdbcMemberRepository가 있다.

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/lecture/49594?tab=note&speed=0.75

기존에는 memory를 스프링빈으로 등록했다면 이것을 빼고

jdbc를 등록하였다.

 

이것을 개방 폐쇄 원칙이라고 한다. 정보처리기사 공부할때 나왔던 내용이다.

SOLID 에 개방-폐쇄 원칙 이란 

확장에는 열려있고, 수정에는 닫혀있다

스프링의 DI를 사용하면 '기존 코드를 전혀 손대지 않고, 설정만으로 구현 클래스를 변경 할 수있다.'

 

'웹프로그래밍 > Spring 입문' 카테고리의 다른 글

18. 스프링 JDBC Template  (0) 2021.06.29
17. 스프링 통합 테스트  (0) 2021.06.29
15. H2 데이터베이스 설치  (0) 2021.06.24
14. 회원 웹 기능 - 조회  (0) 2021.06.24
13. 회원 웹 기능 - 등록  (0) 2021.06.23

스프링 DB 접근 기술에 대하여 알아보았다.

 

이전 시간에는 메모리에 있기에 서버가 내려가면 데이터가 사라지게된다!

실무에서는 데이터베이스에 데이터를 저장하고 관리한다 

그것을 위해 H2라는 프로그램을 설치 해보았다.

 

 

그리고 테이블을 생성하였다!

crete table Member
(
         id   bigint generated by default as identity,
         name varchar(255),
         primary key (id)
);

id 타입은  bidint 타입이다. (자바에서의 Long) 

generated by default as identity 값을 세팅하지 않고 인서트하게되면

자동으로 값을 채워주게 된다.

pk는 id이다.

 

'웹프로그래밍 > Spring 입문' 카테고리의 다른 글

17. 스프링 통합 테스트  (0) 2021.06.29
16. 순수 JDBC  (0) 2021.06.24
14. 회원 웹 기능 - 조회  (0) 2021.06.24
13. 회원 웹 기능 - 등록  (0) 2021.06.23
12. 회원 웹기능 - 홈 화면 추가  (0) 2021.06.23

조회 하는 기능까지 구현하였다!

 

package hello.hellospring.controller;

import hello.hellospring.domain.Member;
import hello.hellospring.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
public class MemberController {


    private final MemberService memberService;

    @Autowired
    public MemberController(MemberService memberService){
        this.memberService = memberService;
    }

    @GetMapping("/members/new")
    public String createForm(){
        return "members/createMemberForm";
    }

    @PostMapping("/members/new")
    public String create(MemberForm form){
        Member member = new Member();
        member.setName(form.getName());

        memberService.join(member);

        return "redirect:/";
    }

    @GetMapping("/members")
    public String list(Model model){
        List<Member> members = memberService.findMembers();
        model.addAttribute("members",members);
        return "members/memberList";
    }

 

"/members" 를 GetMapping으로 주고

Member형식의 리스트 members를 만들어 findMembers()를 쓰게되면 멤버를

다 가져올 수 있게 된다.

members자체를 모델에 담아서 화면에 넘기고

members/memberList를 반환한다!

 

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>

<div class="container">
  <div>
    <table>
      <thead>
      <tr>
        <th>#</th>
        <th>이름</th>
      </tr>
      </thead>
      <tbody>
      <tr th:each="member : ${members}">
        <td th:text="${member.id}"></td>
        <td th:text="${member.name}"></td>
      </tr>
      </tbody>
    </table>
  </div>
</div> <!-- /container -->
</body>
</html>

th:each 는 루프문이다.! 첫번째 객체를 꺼내와서

id name을 꺼내와서 출력한다. 이때 getId , getName을 이용해서

프로퍼티 방식으로 꺼내오게된다.

 

가입 후 조회기능을 하니 이렇게 조회된 화면을 확인할 수 있었다.

 

<!DOCTYPE HTML>
<html> <body>
<div class="container">
  <div>
    <table>
      <thead>
      <tr>
        <th>#</th>
        <th>이름</th> </tr>
      </thead>
      <tbody>
      <tr>
        <td>1</td>
        <td>이재혁</td> </tr>
      </tbody>
    </table>
  </div>
</div> <!-- /container -->
</body>
</html>
 

크롬의 페이지 소스보는 기능을 사용하여 

살펴 보니

타임리프 문법이 있던 곳이 랜더링 되어 있는 것을 

확인할 수 있었다!

 

현재는 데이터가 메모리에 있기때문에 서버를 내렸다가 다시 키게되면

데이터가 다 지워지게된다. 그렇기에 해결 방안에 대하여

다음 포스트에 정리할 예정이다.

 

이번시간에는 회원 등록을 해보았다.

 

package hello.hellospring.controller;

import hello.hellospring.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MemberController {


    private final MemberService memberService;

    @Autowired
    public MemberController(MemberService memberService){
        this.memberService = memberService;
    }

    @GetMapping("/members/new")
    public String createForm(){
        return "members/createMemberForm";
    }
}

기존에 만들어 놨던 MemberController에 

/members/new 를 매핑으로 사용하는 creatForm을

만들었다. members/createMemberForm을 반환하게된다!

 

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">

  <form action="/members/new" method="post">
    <div class="form-group">
    <label for="name">이름</label>
    <input type="text" id="name" name="name" placeholder="이름을 입력하세요">
  </div>
    <button type="submit">등록</button>
  </form>

</div> <!-- /container -->
</body>
</html>

members디렉터리를 만들고 그 하위에 createMemberForm.html을 

만들었다. input type태그를 사용하여 

이름을 입력받고 등록버튼을 누르면 서버로 값이 전달되게 된다.

 

그 다음으로는 넘어온 값을 받아서 실제 회원가입을 할 수 있게끔 만들었다.

package hello.hellospring.controller;

public class MemberForm {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

먼저 MemberForm 이라는 클래스를 만들고 Getter and Setter를 만들어준다 

이유는 받아온 값을 매칭시켜줄 클래스를 만들어야하기 때문이다!

 

package hello.hellospring.controller;

import hello.hellospring.domain.Member;
import hello.hellospring.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MemberController {


    private final MemberService memberService;

    @Autowired
    public MemberController(MemberService memberService){
        this.memberService = memberService;
    }

    @GetMapping("/members/new")
    public String createForm(){
        return "members/createMemberForm";
    }

    @PostMapping("/members/new")
    public String create(MemberForm form){
        Member member = new Member();
        member.setName(form.getName());

        memberService.join(member);

        return "redirect:/";
    }
}

그런 다음 @PostMapping으로 create를 만들었다.

 

-createForm()

먼저 회원가입을 누르면 members/new로 들어온다

이때는 Get방식이다 단지 members/createMemberForm 을 뿌려주는것뿐이다.

createMemberForm 에 이름을 넣고 등록버튼을 누르면 Post 방식으로 넘어온다!!

 

PostMapping은 데이터를 폼 ?같은것에 넣고 전달할때 쓰인다.

Get은 조회할때 쓰인다

url은 같지만 Post냐 Get이냐 에 따라 다르게 매핑이 가능한다.

 

등록버튼이 눌러지면 Post매핑인 create()가 동작한다.!

-create()

이때 MemberForm 의 name에 데이터 값이 들어오게된다.

(스프링이 createMemberForm.html에 있는 

input type에 name을 보고 넣어주게된다.)

스프링이 setName()을 통해서 값을 넣어주게되고

 

나는 getName을 이용하여 member 객체에 name값을 

넘겨준다!

 

그리고 join을 이용하여 가입하고

 

redirect 를 이용하여 " / "를 다시 요청한다.!

웹 MVC 개발

 

MemberController를 이용하여 

회원등록 , 회원조회 하는 것을 만들어 보았다.

 

package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(){
        return "home";
    }
}

HomeController 를 생성하고 

@GetMapping에 "/" 값을 주면 

localhost:8080 주소창에 입력하면

home.html을 리턴한다.!

 

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"> <body>
<div class="container">
  <div>
    <h1>Hello Spring</h1> <p>회원 기능</p>
    <p>
      <a href="/members/new">회원 가입</a> <a href="/members">회원 목록</a>
    </p> </div>
</div> <!-- /container -->
</body>
</html>

 templates하위에 home.html을 생성한다!

회원 가입을 누르면 /members/new 로 이동하고

회원 목록을 누르면 /members로 이동하는 html코드이다.

 

그런데!

이전에 분명 아무것도 없으면 웰컴페이지인 index.html 로가는데 

 

우선순위가 있다는것! 

HomeController에 매핑된 것이 있기때문에 그것을 먼저 실행한다!

 

클래스 라는 것은 관련있는 데이터들을 하나의 단위로 묶어두기 위한 것이다.

하지만 이것이 전부가 아니다.

서로 관련있는 데이터들 뿐 아니라, 그 데이타와 관련이 깊은 메서드 까지도 함께 묶어둘 수 있다.

이렇게 함으로써 코드의 응집도를 높이고 결합도를 낮출 수 있다.

 

객체란 ?

 

객체지향 프로그래밍에서 객체란 " 데이터 " + " 메서드 " 이다. 데이터는 객체의 정적 속성을

표현하고 메서드는 객체의 기능을 표현한다.

 

그렇다면 전의 예제의 함수들을 옮겨보겠다!

package section2;

public class Polynomial2 {
	
	public char name; //다항식의 이름
	public int nTerms = 0; // 항의 개수
	public Term2[] terms; //항들의 배열
	
	public int calcPolynomial(int x) {
		int result = 0;
		
		for (int i =0; i< nTerms; i++) {
			result += (terms[i].calTerm(x));
			}
		return result;
	}

	public void printPolynomial() {
		for(int i =0; i<nTerms; i++) {
			terms[i].printTerm();
			System.out.print("+");
		}
		System.out.println();
		
	}
	
	public void addTerm(int c, int e) {
		int index = findTerm(e);
		if(index != -1) {
				terms[index].coef += c;
		}
		else {
			int i = nTerms-1;
			while(i >= 0 && terms[i].exp < e) {
				terms[i+1] = terms[i];
				i--;
			}
			terms[i+1] = new Term2();
			terms[i+1].coef = c;
			terms[i+1].exp =e;
			nTerms++;
		}
	}

	public int findTerm(int e) {
		for(int i=0;i<nTerms && terms[i].exp >=e ;i++) {
			if(terms[i].exp ==e) {
				return i;
			}
		}
		return -1;
	}
}

    다항 클래스

package section2;

public class Term2 {
	
	public int coef;//계수
	public int exp;//차수
	
	public int calTerm(int x) {
		return (int)(coef * Math.pow(x, exp));
	}
	
	public void printTerm() {
		System.out.print(coef + "x^" +exp);
	}
}

항 클래스

package section2;

import java.util.Scanner;

public class code7{

	static Polynomial2 polys[] = new Polynomial2 [100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		Scanner kb = new Scanner(System.in);
		while(true) {
			System.out.print("$ ");
			String command = kb.next();
			if(command.equals("create")) {
				char name = kb.next().charAt(0);
				polys[n] = new Polynomial2();
				polys[n].terms = new Term2[100];
				polys[n].name = name;
				polys[n].nTerms = 0;
				n++;
			}
			else if(command.equals("add")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int c = kb.nextInt();
					int e = kb.nextInt();
					polys[index].addTerm(c,e);
					
				}
				
			}
			else if(command.equals("calc")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int x = kb.nextInt();
					int result = polys[index].calcPolynomial(x);
					System.out.println(result);
				}
				
			}
			else if(command.equals("print")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					polys[index].printPolynomial();
				}

			}
			else if(command.equals("exit")) {
				break;
			}
		}
		
		kb.close();

	}

	private static int find(char name) {
		for(int i =0;i<n;i++) {
			if(polys[i].name == name) {
				return i;
			}
		}
		return -1;
	}

}

메인 클래스

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

메서드와 생성자 3  (0) 2021.06.24
메서드와 생성자 2  (0) 2021.06.24
클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 4  (0) 2021.06.22
클래스, 객체, 참조변수 3  (0) 2021.06.22

다항함수

 

다항함수는 항들의 합이며, 항은 계수와 지수에 의해서 정의된다. 계수는 0이 아닌 정수이고

지수는 음이 아닌 정수라고 가정한다.

 

프로그램 실행 예

$ create f // f=0을 정의한다.

$ add f 2 3 // f(x)에 2x3승 을 더한다. 따라서 f(x) = 2x3이 된다.

$ add f -1 1 // f(x) = 2x3 -x

$ calc f 2 // x=2일때 f의 값을 출력한다.

$ print f // 차수에 관한 내림차순으로 정렬하여 출력한다.

$ create g // 다른 다항함수 g를 정의한다.

$ exit //종료

 

처음에는 어떤 자료구조를 만들어 

다항함수를 표현할것인가??

 

항 들이 모여서 다항함수를 만든다!

 

package section1;

public class Term {
	
	public int coef;//계수
	public int exp;//차수
}

계수와 차수를 가지는 항 클래스 생성

 

package section1;

public class Polynomial {
	
	public char name; //다항식의 이름
	public int nTerms; // 항의 개수
	public Term[] terms; //항들의 배열
}

 

다항 클래스 생성

 

package section1;

import java.util.Scanner;

public class code6 {

	static Polynomial polys[] = new Polynomial [100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		Scanner kb = new Scanner(System.in);
		while(true) {
			System.out.print("$ ");
			String command = kb.next();
			if(command.equals("create")) {
				char name = kb.next().charAt(0);
				
				polys[n] = new Polynomial();
				polys[n].terms = new Term[100];
				polys[n].name = name;
				polys[n].nTerms = 0;
				n++;
			}
			else if(command.equals("add")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int c = kb.nextInt();
					int e = kb.nextInt();
					addTerm(polys[index], c,e);
					
				}
				
			}
			else if(command.equals("calc")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					int x = kb.nextInt();
					int result = calcPolynomial(polys[index], x);
					System.out.println(result);
				}
				
			}
			else if(command.equals("print")) {
				char name = kb.next().charAt(0);
				int index = find(name);
				if(index==-1) {
					System.out.println("No such Polynomial exist");
				}
				else {
					printPolynomial(polys[index]);
				}

			}
			else if(command.equals("exit")) {
				break;
			}
		}
		
		kb.close();

	}

	private static int calcPolynomial(Polynomial p, int x) {
		int result = 0;
		
		for (int i =0; i<p.nTerms; i++) {
			result += calTerm(p.terms[i], x);
			}
		return result;
	}

	private static int calTerm(Term term, int x) {
		return (int)(term.coef * Math.pow(x, term.exp));
	}

	private static void printPolynomial(Polynomial p) {
		for(int i =0; i<p.nTerms; i++) {
			printTerm(p.terms[i]);
			System.out.print("+");
		}
		System.out.println();
		
	}

	private static void printTerm(Term term) {
		System.out.print(term.coef + "x^" +term.exp);
		
	}

	private static void addTerm(Polynomial p, int c, int e) {
		int index = findTerm(p,e);
		if(index != -1) {
			p.terms[index].coef += c;
		}
		else {
			int i = p.nTerms-1;
			while(i >= 0 && p.terms[i].exp < e) {
				p.terms[i+1] = p.terms[i];
				i--;
			}
			p.terms[i+1] = new Term();
			p.terms[i+1].coef = c;
			p.terms[i+1].exp =e;
			p.nTerms++;
		}
	}

	private static int findTerm(Polynomial p, int e) {
		for(int i=0;i<p.nTerms && p.terms[i].exp >=e ;i++) {
			if(p.terms[i].exp ==e) {
				return i;
			}
		}
		return -1;
	}

	private static int find(char name) {
		for(int i =0;i<n;i++) {
			if(polys[i].name == name) {
				return i;
			}
		}
		return -1;
	}

}

디테일한 완성도가 떨어지는 코드라서 몇 가지 수정해야할 부분을 수정할 예정이다.

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

메서드와 생성자 2  (0) 2021.06.24
메서드와 생성자 1  (0) 2021.06.23
클래스, 객체, 참조변수 4  (0) 2021.06.22
클래스, 객체, 참조변수 3  (0) 2021.06.22
클래스, 객체, 참조변수 2  (0) 2021.06.21

평면상에 좌표축에 평행한 n개의 직사각형에 과한 데이터를 입력 받은 후 면적이 작은 것부터 큰 것 순으로 정렬하여

출력하는 프로그램을 작성하라

 

입력 파일의 형식: 

0 1 2 4

1 4 7 8

4 3 12 9

8 18 11 30

5 10 6 11

 

맨 앞 두정수가 좌상단의 꼭지점 좌표!

세번째 정수는 너비

네번째는 높이이다.

 

package section1;

public class Mypoint1 {
	public int x;
	public int y;
}

좌표를 저장하는 클래스

package section1;

public class MyRectangle1 {
	public Mypoint1 lu;
	public int width;
	public int height;
}

사각형 정보를 저장할 클래스

 

 

 

package section1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code05 {

	static MyRectangle1[] rects = new MyRectangle1[100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		try {
			Scanner in = new Scanner(new File("data.txt"));
			
			while(in.hasNext()) {
			rects[n] = new MyRectangle1();
			rects[n].lu= new Mypoint1();
			rects[n].lu.x = in.nextInt();
			rects[n].lu.y = in.nextInt();
			rects[n].width = in.nextInt();
			rects[n].height = in.nextInt();
			n++;
			}
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("no data file");
			System.exit(1);
		}
		bubbleSort();
	
		for(int i =0;i<n;i++) 
			System.out.println(rects[i].lu.x + " "+ rects[i].lu.y + " "+rects[i].width + " " + rects[i].height);
		}
		private static void bubbleSort() {
			for(int i = n-1;i>0;i--) {
				for(int j =0; j<i; j++) {
					if(calArea(rects[j]) > calArea(rects[j+1])) {
						MyRectangle1 tmp = rects[j];
						rects[j] = rects[j+1];
						rects[j+1] = tmp;
					}
				}
			}
		}
		public static int calArea(MyRectangle1 r) {
			return r.width * r.height;
		}
}


 항상 객체안에 내용을 건들때 자꾸 new로 생성을 해주고 건들어야한다는 것을 

까먹는다.. 객체 안에 객체가 들어있기때문에 

rects[n] = new MyRectangle1();
rects[n].lu= new Mypoint1();

이부분에서 약간 애를 먹었다.

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

메서드와 생성자 1  (0) 2021.06.23
클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 3  (0) 2021.06.22
클래스, 객체, 참조변수 2  (0) 2021.06.21
클래스 , 객체, 참조변수 1  (0) 2021.06.21

+ Recent posts