728x90

주어진 두수 사이의 수 중 약수의 개수가 짝수이면 더하고 홀수이면 빼서 결과값 반환 

 

public int solution(int left, int right) {

int answer = 0;

for (int i = left; i <= right; i++) {

if(primeNum(i)%2==0) {

answer+=i;

}else {

answer-=i;

}

}

return answer;

}

 

public int primeNum(int num) {

int count=0;

for (int i = 1; i*i <= num; i++) {

if(i*i==num)count++;

else if(num%i==0)count+=2;

}

return count;

}

단순하게 약수의 개수를 구해서 계산했다. 

 

그런데 약수를 구하는 primeNum을 보면 

i*i==num 

즉 제곱수인 경우는 1만 더하고 아니면 전부 2를 더해서 짝수이다. 

 

즉 제곱수만 빼고 나머지는 다 더하면 된다. 

 

public int solution2(int left, int right) {

int answer = 0;

for (int i = left; i <= right; i++) {

if(i%Math.sqrt(i)==0) {

answer-=i;

}else {

answer+=i;

}

}

return answer;

}

728x90

현재 순위대로 선수 배열이 주어지고 

callings 배열이 주어진다. 

해설진은 앞 선수를 한명 추월할 때마다 한번씩 calling하고 calling 순서대로 담은 배열이 callings 이다.

경기가 끝났을때 선수를 순위대로 담은 배열을 반환 

 

처음엔 순서가 있어서 ArrayList의 indexOf로 쉽게 찾을 수 있을 줄 알았는데 

indexOf도 결국 선형검색을 수행하기 때문에 이중포문과 별 차이가 없어서 시간초과된다. 

 

이름이 불리기 때문에 Map으로 하려고 했는데 

처음엔 map으로 이름 찾는건 좋은데 순서를 바꾸고 순서가 바뀐 map을 다시 배열로 변경하는 작업도 까다로워

결국 시간초과되었다. 

 

해결방법은 생각보다 간단했다.

public String[] solution(String[] players, String[] callings) {

int n = players.length;

HashMap<String, Integer> rank = new HashMap<>();

 

for (int i = 0; i < n; i++) {

rank.put(players[i], i);

}

 

for (String calling : callings) {

int i = rank.get(calling);

String temp = players[i - 1];

players[i - 1] = players[i];

players[i] = temp;

 

rank.put(players[i - 1], i - 1);

rank.put(players[i], i);

}

 

return players;

}

랭크맵으로 다시 선수 순위 배열을 만드는게 아니라 랭크맵은 순위를 참조하기만 하고 players를 조작해 반환한다. 

 

 

 

 맵을 선수 이름으로 순위를 찾는 맵과 순위로 선수 이름을 찾는 맵을 만드는 방법도 있다. 

같은 내용을 키와 값만 바꿔서 두개의 맵을 만들어 사용하는건 다른데서도 쓸 수 있지 않을까싶어 만들어보았다. 

public String[] solution2(String[] players, String[] callings) {

String[] answer = new String[players.length];

Map<String,Integer> a = new HashMap<String, Integer>();

Map<Integer,String> b = new HashMap<Integer,String>();

for (int i = 0; i < players.length; i++) {

a.put(players[i],i);

b.put(i, players[i]);

}

for (int i = 0; i < callings.length; i++) {

int callingsRank = a.get(callings[i]);

a.replace(callings[i],callingsRank-1);

String prev = b.get(callingsRank-1);

b.replace(callingsRank-1, callings[i]);

a.replace(prev, callingsRank);

b.replace(callingsRank, prev);

}

for (int i = 0; i < a.size(); i++) {

answer[i]=b.get(i);

}

return answer;

}

 

 

'Java > Coding Test' 카테고리의 다른 글

성격 유형 검사하기 문제풀이  (0) 2023.09.25
약수의 개수와 덧셈 문제풀이  (0) 2023.09.24
공원 산책 문제풀이  (0) 2023.09.24
신고 결과 받기 문제풀이  (0) 2023.09.23
소수찾기 문제풀이  (0) 2023.09.18
728x90

문자열 배열로 시작지점S, 장애물X이 표시된 공원 ex){"SOO","OOX","OOO"},

문자열 배열로 "E 1"과 같이 이동방향+공백+이동거리가 주어진 이동 명령 ex){"E 1","S 1"}이 주어질 때 

길이 없거나 가는 길에 장애물이 있는 경우 명령을 무시하고 다음 명령을 수행한다면 

최종 도착지를 int[]로 반환

public int[] solution(String[] park, String[] routes) {

int[] position= new int[2];//S 찾아서 바꿔줘

for (int i = 0; i < park.length; i++) {//시작위치 설정

if(park[i].contains("S")) {

position[0] = i;

position[1] = park[i].indexOf("S");

break;

}

}

int[][] parkArr = new int[park.length][park[0].length()];

for (int i = 0; i < parkArr.length; i++) {

for (int j = 0; j < parkArr[0].length; j++) {

if(park[i].charAt(j)=='X')parkArr[i][j]=1;

}//park 정수행렬로 변경

}

for (int i = 0; i < routes.length; i++) {

if(isPossible(parkArr,position,routes[i]))position=move(position,routes[i]);

}

return position;

}

public boolean isPossible(int[][] parkArr, int[] position, String route) {

String direction = route.split(" ")[0];

int distance = Integer.valueOf(route.split(" ")[1]);

//장애물이 있는지, 길이 있는지

if(direction.equals("E")) {

if(position[1]+distance>parkArr[0].length-1)return false;

for (int i = 1; i <= distance; i++) {

if(parkArr[position[0]][position[1]+i]==1)return false;

}

}else if(direction.equals("W")) {

if(position[1]-distance<0)return false;

for (int i = 1; i <= distance; i++) {

if(parkArr[position[0]][position[1]-i]==1)return false;

}

}else if(direction.equals("N")) {

if(position[0]-distance<0)return false;

for (int i = 1; i <= distance; i++) {

if(parkArr[position[0]-i][position[1]]==1)return false;

}

}else if(direction.equals("S")) {

if(position[0]+distance>parkArr.length-1)return false;

for (int i = 1; i <= distance; i++) {

if(parkArr[position[0]+i][position[1]]==1)return false;

}

}

 

 

return true;

}

public int[] move(int[] position,String route) {

String direction = route.split(" ")[0];

String distance = route.split(" ")[1];

if(direction.equals("E")) {

position[1]+=Integer.valueOf(distance);

}else if(direction.equals("W")) {

position[1]-=Integer.valueOf(distance);

}else if(direction.equals("N")) {

position[0]-=Integer.valueOf(distance);

}else if(direction.equals("S")) {

position[0]+=Integer.valueOf(distance);

}

return position;

}

isPossible 로 이동 가능한지 확인 후 move로 이동을 수행한다. 

String 배열로 주어진 park는 핸들링하기 편하게 int[][] 로 행렬로 바꾸어 준다. 

 

isPossible은 길이 있는지, 있다면 가는 길에 장애물이 있는지 확인하여야 한다. 

 

'Java > Coding Test' 카테고리의 다른 글

약수의 개수와 덧셈 문제풀이  (0) 2023.09.24
달리기 경주 문제풀이  (0) 2023.09.24
신고 결과 받기 문제풀이  (0) 2023.09.23
소수찾기 문제풀이  (0) 2023.09.18
소인수분해 문제풀이  (0) 2023.09.18
728x90

function addJavaScript(jsFilePath){

var headElement = document.getElementsByTagName('head')[0];

var newScriptElement = document.createElement('script');

newScriptElement.setAttribute('type','module');

newScriptElement.setAttribute('src',jsFilePath);

headElement.appendChild(newScriptElement);

}

addJavaScript('js/app.js');

addJavaScript('js/request.js');

addJavaScript('js/request-url.js');

 

html 파일에서 include.js만 추가하고

<script src="js/ref/guest_js_include.js" type="text/javascript"></script>

 

include.js 내에서 

추가할 모듈을 추가한다. 

'Javascript' 카테고리의 다른 글

Intersection Observer 무한스크롤 구현하기  (0) 2023.11.24
SPA AJAX Request With JQuery  (0) 2023.09.25
AJAX using JQuery  (0) 2023.09.24
JQuery event  (0) 2023.09.23
Javascript this  (0) 2023.09.23
728x90

-form을 이용한 jQuery AJAX 요청

$('#f').on('submit',function(e){

/*let parameter1=$('#f').serialize();

console.log(parameter1);*/

let parameter2 = $(e.target).serialize();

let jsonArray = $(e.target).serializeArray();

 

e.preventDefault();

});

form.on('submit',function) 

form에 submit 이벤트 리스너 등록 

 

>form의 input parameters (json data) 생성

 

++('#f') 폼으로 접근하는것은 권장하지 않는다. 

이벤트가 발생한 event target으로 접근 

 

let parameter2 = $(e.target).serialize();

serialize() 함수 => property=value&property=value&... 형식으로 data 생성 

 

let jsonArray = $(e.target).serializeArray();

serializeArray() 함수 =>json 배열 형태로 data 생성

 

++element의 속성값 접근하기 

//attribute set

$('#p_image').attr('src','icon1.png');

//attribute get

console.log($('#p_image').attr('src'));

attr('attributeName'[,value])

 

++폼 태그의 입력값에 접근할 때

console.log("1.$('#id').attr('value') [x]:"+$('#id').attr('value'));

console.log("1.$('#id').val() [o]:"+$('#id').val());

attr('value') value 속성의 값에 접근하는 방법은 사용하지 않는다. 

val() 함수를 사용하면 DOM 생성 이후 동적으로 변하는 value 값을 읽을 수 있다. 

 

 

>jQuery AJAX 요청

 

$.ajax(url[, settings])

settings type = plainObject == json == { url:xx, setting1:xx, setting2:xx...}

 

ㅁ settings

 

method: type(String) default('GET')

Http요청 보낼 방식

 

contentType: type(boolean or String) default('application/x-www-form-urlencoded; charset=UTF-8')

서버로 데이터를 보낼 때 데이터의 타입 : multipart/form-data, text/plain...

 

data: type(plainObject or String or Array) default({})

서버로 보낼 데이터 

body를 가질 수 없는 requestMethod(GET) 의 경우 data가 URL에 붙여진다.

 

dataType: type(String) default(jquery가 xml, json, script, html 중 적절한 타입을 찾아 설정, 보통 json) 

서버로부터 받은 응답의 데이터 타입 

 

timeout: type(number) default(0) 

number ms 만큼 timeout 한 후에야 send 된다. 

 

statusCode: type(PlainObject==json) default({})

응답의 상태 코드

요청이 성공적으로 이루어지면 success callback 

3xx(redirect)를 포함한 4xx,5xx(error) 발생시 error callback 

$.ajax({

statusCode: {

404: function() {

alert( "page not found" );

}

}

});

404 코드일때 function() 실행 

 

 

beforeSend: type(function(jqxhr,settings{})

요청 전 실행될 함수

 

success: type(function(data, textStatus, jqxhr))

요청 성공시 실행될 함수

 

error: type(function(jqxhr,textStatus,errorThrown))

error 발생시 실행될 함수

 

complete: type(function(jqxhr, textStatus))

success, error callback 함수가 실행된 이후 실행될 함수

 

 

 

$.ajax({

url:`01.ajaxRequestPOST/${idStr}`,

method:`POST`,

data: parameter 또는 jsonArray,

contentType:'application/json;charset=UTF-8',

dataType:'json',

success:function(responseJsonObject){

...

},

});

 

>prevent default submit

e.preventDefault();

 

 

GET 방식 AJAX 요청 예제 

$('#id').keyup(function (e) {

let idStr = $(e.target).val();

if (idStr.trim() == '') return;

 

$.ajax({

url: `01.ajaxRequestGET/${idStr}`,

method: `GET`,

data: {},

contentType: 'application/json;charset=UTF-8',

dataType: 'json',

success: function (responseJsonObject) {

if (responseJsonObject.status == 1) {

$('#msg').html(responseJsonObject.msg).css('color', 'green');

} else if (responseJsonObject.status == 2) {

$('#msg').html(responseJsonObject.msg).css('color', 'orange');

}

},

error: function (xhr, textStatus) {

alert('error!!' + textStatus);

}

})

});

keyup 이벤트가 발생할 때 입력된 값을 받고 ajax 요청을 한다. url로 id를 맵핑하기 때문에 data가 필요없다.

 

POST 방식 AJAX 요청 예제

$.ajax({

url:`01.ajaxRequestPOST/${idStr}`,

method:`POST`,

data:{},

contentType:'application/json;charset=UTF-8',

dataType:'json',

beforeSend:function(){

$('#msg').html('<img src="loading.gif" width="20px" height="20px/>');

},

success:function(responseJsonObject){

if(responseJsonObject.status==1){

$('#msg').html(responseJsonObject.msg).css('color','green');

}else if(responseJsonObject.status==2){

$('#msg').html(responseJsonObject.msg).css('color','orange');

}

},

error:function(xhr,textStatus){

alert('error!!'+textStatus);

}

});

beforeSend 함수도 만들어주어 send 직전부터 response를 받을때까지 실행할 함수를 등록

 

setInterval 함수를 이용하여 정해진 시간 간격마다 AJAX 요청 실행 

$(function(){

setInterval(function(){

$.ajax({

url:'04.newsTitlesJSON',

method:'GET',

dataType:'json',

success:function(responseJsonObject){

let html= `<ul>`;

$.each(responseJsonObject.data,function(i,newsJsonObject){

 

html+=`<li>${newsJsonObject.title}[${newsJsonObject.company}]${newsJsonObject.date}</li><br>`;

 

});

html+=`</ul>`;

$('#newsDiv').html(html);

}

});

},1000);

})

 

 

 

 

jQuery API document

https://api.jquery.com/jquery.ajax/

 

jQuery.ajax() | jQuery API Documentation

Description: Perform an asynchronous HTTP (Ajax) request. The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available

api.jquery.com

 

'Javascript' 카테고리의 다른 글

SPA AJAX Request With JQuery  (0) 2023.09.25
js 모듈 의존성 줄이기  (0) 2023.09.24
JQuery event  (0) 2023.09.23
Javascript this  (0) 2023.09.23
JQuery effect  (0) 2023.09.22
728x90

 

$(function() {

$('td').click(function(e){

console.log("event[표준객체]:"+e);

console.log("e.target[표준객체]:"+e.target);

console.log(e.target.firstChild.nodeValue);

console.log("this :"+this);

console.log(this.firstChild.nodeValue);

console.log("e.target[표준객체]--> jQuery객체의 text메소드 호출:"+$(e.target).text());

});

});

$(function); ==> window onload 시 function 등록 

 

javascript 표준객체에서는 jQuery의 함수를 사용할 수 없다.

jQuery 의 함수를 사용하려면 $()로 객체를 Wrapper 객체로 만들어주어야 한다. 

 

$('td').click(function); ==> td태그의 click 이벤트 리스너에 function 등록 

 

e = 발생 이벤트 

e.target = 이벤트가 발생한 객체

$(e.target) = 이벤트가 발생한 객체의 랩퍼 객체 

 

 

$('#txtInput').keyup(function(e){

console.log("key:"+e.key);

console.log("keyCode:"+e.keyCode);//ASCIIcode

$('#txtKeyCode').val(`${e.key}[${e.keyCode}]`);

});

키 이벤트의 프로퍼티 key, keyCode

 

key = 입력한 키

keyCode = 입력한 키의 아스키코드

 

key는 문자 뿐만아니라 enter, spacebar, shift, 등 모든 키를 받는다. 

 

$('').val() == Element.value 

val(); = get

val(param); = set param in element.value

 

 

$().text() == element.innerText

$().html() == element.innerHTML

$(e.target).html('jQuery에서 제공하는 Event 핸들링 메소드'+ ++clickCount);

 

$('#mouseArea').on('mouseenter mouseleave',function(){

if(e.type=='mouseenter'){

enterCount++;

}else if(e.type=='mouseleave'){

leaveCount++;

}

});

 

.on() 이벤트 바인딩 함수

지금까지 나온 .click(), .keyup() 등은 특정 이벤트를 지정하여 그 이벤트에 대해서만 처리하는 리스너를 만드는데

.on() 함수는 어떤 타입의 이벤트라도 처리할 수 있고, 여러 이벤트를 처리할 수도 있다.

 

위 예제는 mouseenter 또는 mouseleave 이벤트가 발생하면 실행할 함수를 정의했는데 e.type으로  이벤트의 타입을 

구분하고 각 이벤트마다 다른 처리를 하였다. 

 

on(event, [childSelector, data,] function) 

event와 event를 처리할 function이 필수 인자 

특정 자식객체에게만 접근할 때는 childSelector, function을 수행하는데 필요한  data가 있다면 data를 추가로 입력할 수 있다.

$('#btnAdd').click(function(){

let item_no =$('li').length;

$('ul').append(`<li>list item ${item_no}</li>`);

});

$('ul').on('click','li',function(e){

alert($(e.target).text());

});

 

버튼을 클릭하면 ul 자식으로 li객체가 생성된다. 

li객체는 최초 로딩때는 존재하지 않다가 ul 객체에 이벤트가 발생하면 동적으로 생성되는 객체이다. 

이렇게 동적으로 생성되는 객체에 이벤트 리스너를 등록하려면 on함수를 사용한다. 

$('ul').on('click','li',function(e){...});

ul객체에 click 이벤트를 등록함과 동시에 그 자식 li도 click 이벤트를 등록한다. 

 

 

일회용 이벤트 리스너 만들기

one() 함수 사용

$('li').one('click',function(e){

alert($(e.target).text());

});

한번 이벤트를 처리하고 나면 이벤트 리스너를 삭제하여 더이상 이벤트를 처리하지 않는다.

 

 

'Javascript' 카테고리의 다른 글

js 모듈 의존성 줄이기  (0) 2023.09.24
AJAX using JQuery  (0) 2023.09.24
Javascript this  (0) 2023.09.23
JQuery effect  (0) 2023.09.22
JQuery 입문  (1) 2023.09.22
728x90

자바스크립트에서 this 는 다른 언어와 다르게 작동한다.

this는 함수를 호출한 방법에 따라 다르게 결정된다.

 

let obj1={

'no':1,

'func1':function(){

console.log('obj1.func1 -->this:'+this.no);

}

}

obj1.func1();//1

ob1의 func1을 실행하면 obj1의 no인 1을 반환한다. 

 

let obj2={

'no':2,

'func2':function(){

console.log('obj2.func2 -->this:'+this.no);

}

}

 

this를 다른 문맥으로 옮기려면 call이나 apply 함수를 사용

obj1.func1.call(obj2);

--------func.call(obj1)----------
obj1.func1 -->this:2

obj2.func2.apply(obj1);

--------func.apply(obj1)----------
 obj2.func2 -->this:1

 

obj1.func1.call(window);

obj1.func1 -->this:undefined

 

this를 처음 호출 함수의 this로 고정 시키려면 bind 함수 사용 (바인드가 여러번 중첩되면 처음 적용된 바인드가 마지막까지 적용된다)

 

function f(){

return this.a;

}

var g = f.bind({ a: "bindedFirst" });

console.log(g()); // bindedFirst

 

var h = g.bind({ a: "bindedSecond" }); // bind는 한 번만 동작

console.log(h()); // bindedFirst

g(): bindedFirst
h(): bindedFirst

 

이벤트 리스너에서 this는 currentTarget

 

$('td').click(function(e){

console.log("this :"+this);

});

this   :[object HTMLTableCellElement]

  

'Javascript' 카테고리의 다른 글

AJAX using JQuery  (0) 2023.09.24
JQuery event  (0) 2023.09.23
JQuery effect  (0) 2023.09.22
JQuery 입문  (1) 2023.09.22
JQuery 이해하기  (0) 2023.09.22
728x90

유저 아이디 배열과 "신고자 피신고자" 배열, 제재 대상 기준 횟수가 주어질때 ,

신고자가 신고한 유저가 제재 대상이 되면 신고자에게 메일을 보내고

이때 신고자가 받은 메일의 개수를 담은 배열을 반환  

public int[] solution(String[] id_list, String[] report, int k) {

int[] answer = new int[id_list.length];

Map<String,Set<String>> reportedMap = new HashMap<String,Set<String>>();//K:신고당한사람 V:신고한사람SET

ArrayList<String> id = new ArrayList<String>();//answer에 저장할때 index를 알아내기 위해 id_list와 같은 순서로 add

for (int i = 0; i < id_list.length; i++) {

id.add(id_list[i]);

}

for(int i=0; i<report.length;i++){

Set<String> thoseReporting = reportedMap.getOrDefault(report[i].split(" ")[1],new HashSet<String>());//신고한사람SET

thoseReporting.add(report[i].split(" ")[0]);

reportedMap.put(report[i].split(" ")[1],thoseReporting);

}

Set<String> reportedSet = reportedMap.keySet();

for (Iterator iterator = reportedSet.iterator(); iterator.hasNext();) {

String string = (String) iterator.next();

Set<String> a = reportedMap.get(string);

if(a.size()>=k) {

for (Iterator iterator2 = a.iterator(); iterator2.hasNext();) {

String string2 = (String) iterator2.next();

answer[id.indexOf(string2)]++;

}

}

}

return answer;

}

 

다른사람 풀이를 보는데   객체 지향으로 푼 사람이 있었다. 

class User{

String name;

HashSet<String> reportList;

HashSet<String> reportedList;

public User(String name){

this.name = name;

reportList = new HashSet<>();

reportedList = new HashSet<>();

}

}

유저 객체는

본인 이름과 

본인이 신고한 사람 set, 본인을 신고한 사람 set을 가지고 있다.   

public int[] solution2(String[] id_list, String[] report, int k) {

int[] answer = new int[id_list.length];

ArrayList<User> users = new ArrayList<>();

HashMap<String, Integer> suspendedList = new HashMap<>(); // <이름>

HashMap<String, Integer> idIdx = new HashMap<String, Integer>(); // <이름, 해당 이름의 User 클래스 idx>

int idx = 0;

 

for (String name : id_list) {

idIdx.put(name, idx++);

users.add(new User(name));

}

 

for (String re : report) {

String[] str = re.split(" ");

users.get(idIdx.get(str[0])).reportList.add(str[1]);//신고가 한번 발생하면 신고 당한사람과 신고한 사람의리스트 모두 갱신 

users.get(idIdx.get(str[1])).reportedList.add(str[0]);

}

 

for (User user : users) {

if (user.reportedList.size() >= k)//신고당한 횟수가 k번 이상이면

suspendedList.put(user.name, 1);//제재리스트에 유저이름을 올린다.

}

 

for (User user : users) {

for (String nameReport : user.reportList) {

if (suspendedList.get(nameReport) != null) {//제재 대상에 이름이있다면 

answer[idIdx.get(user.name)]++;//그 이름으로 index 찾아서 answer증가

}

 

}

}

return answer;

 

}

'Java > Coding Test' 카테고리의 다른 글

달리기 경주 문제풀이  (0) 2023.09.24
공원 산책 문제풀이  (0) 2023.09.24
소수찾기 문제풀이  (0) 2023.09.18
소인수분해 문제풀이  (0) 2023.09.18
치킨 쿠폰 문제풀이  (0) 2023.09.17

+ Recent posts