락앤락을 알고 투자한지도 약 5개월 정도가 되었다.

처음 13천원정도를 주고 샀으니... 그땐 참 싸다 생각했는데... 계속 곤두박지 만원 밑으로 쳐박힌다. 물론 이 주식은 나를 위해서 산건 아니고, 내 아들, 딸놈들 계좌로 조금씩 마련해 준것이다. 한달에 3만원씩...


그래봐야 한달에 2주정도 사줄수 있네. 2월에는 설날도 있고 해서 좀더 많이 사줄수 있었다.


어쨌든 운좋게 만원에 매수가 되었고, 지금은 12,700 원이다. 처음 13천원이였던게, 5개월지나면서 대충 평단가가 11,300원 정도. 약 10% 정도 수익이네...


내주식은 하염없이 내려만 가는데... 어쨌든. 내가 생각하는 가격이상이 오면 매도를 할것이고, 아니면 계속 추가매수 할란다. 락앤락이여. 예전의 영광을 되찾자.

'주식' 카테고리의 다른 글

LG전자  (0) 2015.07.28
한국가스공사  (0) 2015.04.08
NHN엔터테인먼트  (0) 2015.01.05
NHN엔터테인먼트  (0) 2014.12.11
nhn엔터 2014년 11월 7일 하한가  (0) 2014.11.07
by Invincible Cooler 2015. 3. 6. 17:31

1. 연차휴가는 회계연도(해당년 1월 1일) or 입사일 기준 1년 만근에 80% 이상 출근시 발생함 (사업장이 정하는것에 따라 다름)

2. 1년미만 근무 or 1년만근 이지만 80% 미만 출근인 경우 -> 1개월 만근시 다음달 연차휴가 1개 인정함

3. 해당사항은 상시근로자 5인이상일 때만 적용됨 -> 상시근로자 5인미만인경우 해당사항 없음

4. 연차는 최소 15 ~ 최대 25일임

5. 법정공휴일은 연차사용에서 포함될 수 없음 -> 다시 말하면 법정공휴일에 휴무하는것은 연차소진이 되지 않음.

6. 그외에 엄청 복잡한 상세내용이 있는데, 이해불가함. 단 같은 기준이면 사업자보다 노동자에게 유리하게 판단됨.

예를 들어서 근무가 1년이하인 경우 한달만근하면 다음달 한개의 휴가를 사용할 수 있지만, 1년후에는 이것을 제외한 연차만 발생함. 다시 말하면 연차는 지난해에 대한 올해의 보상임.

이상.

'연차휴가 및 노동법 등' 카테고리의 다른 글

연말 정산의 어려움  (1) 2016.01.22
by Invincible Cooler 2015. 3. 4. 14:51

벌써 이주식을 가지고 있은지 1년 6개월 정도가 된것 같다. 처음엔 싸다고 생각하고 지른 가격이 10만원 이상이였는데, 이상하게 계속 밑으로 하방을 하였다. 외국인의 지속적인 패대기. 그후 기관이 외인의 주식을 받는듯 하였지만, 외인의 끊임없는 패대기에 항복을 하고, 기관도 공매도 시작 6만원대까지 주식이 떨어진다. 무려 -40% 7만원이 무너질때마다 하나, 두개씩 주운 주식이 나름 수백만원이다. 그래도 처음 워낙 평단이 높아 물탄가격이 96천 정도. 1년 5개월이 이놈이 6~9만 사이를 왔다갔다 한다. 그래도 난 버틴다. 오늘 1월 5일 기점으로 95천정도 되었다. 약 -3% 정도. 이정도면 진짜 질기게 가지고 있었다. 앞으로가 문제다. 이제 본전이 왔는데, 언제까지 버텨볼까... 10만원 오면 또 밑으로 하방할 확률이 높다. 그래도 팔지는 못하겠다. 한번 2016년까지 보자.


다른건 모르겠고, 거대 기업은 뒷힘이 쎄다는 걸 항상 믿고 있으니...

'주식' 카테고리의 다른 글

한국가스공사  (0) 2015.04.08
락앤락.  (0) 2015.03.06
NHN엔터테인먼트  (0) 2014.12.11
nhn엔터 2014년 11월 7일 하한가  (0) 2014.11.07
NHN엔터테인먼트  (0) 2014.11.03
by Invincible Cooler 2015. 1. 5. 17:45

Tension between the United States and North Korea further escalatedover the weekend as Washington imposed new economic sanctions Friday against Pyongyang in retaliation for the reclusive regime’s alleged cyberattack on Sony Pictures Entertainment.

소니 픽쳐스 엔터테인먼트 관련 사이버 공격의 혐의를 받고 있는 은둔한 정권(김정은 정권이 외부와 고립이 되어 이렇게 표현한것 같다)에 대한 보복으로 워싱턴(미국의 white house)은 금요일 북한에 대해서 새로운 경제 재재를 부과함으로써 미국와 북한의 긴장감이 치솟고 있다.

The North’s Foreign Ministry responded angrily to the punitivemeasures Sundaysaying that America’s “tenacious adherence” to a hostile policy toward the North would further reinforce its will to protect its sovereignty.

북한의 외무부는 일요일 징계에 대해서 화가나서 반응하였는데, 미국의 북한에 대한 적대적 정책의 집요한 집착(계속적으로 나쁜 징계를 계속해서 이렇게 표현한것 같음)은  국권 수호의 의지를 더 강하게 하는것이라고 말하였다.(이런 미국의 징계가 북한을 고립시키는 것이 아닌, 북한을 더욱 하나로 만드는 것이라고 나름 생각하고 있음)


U.S. President Barack Obama signed an executive order Fridaywhile on vacation in Hawaiito approve sanctions against three North Korean organizations and 10 senior officials as part of his “proportional response” to the attack on Sony that produced the “Interview,” a comedy about a scheme to assassinate North Korean leader Kim Jong-un.
하와이에서 휴가중인 오바마 미국 대통령은 금요일, 소니사에서 제작을한 "인터뷰"-(북한 통치자 김정은에 대한 암살을 다룬 영화)에 대한 공격과 관련 있는 3개의 북한 조직과 10명의 수석 공무관에 대해서 제재 승인에 대해서 행정명령을 내렸다.

Announcing the decisionthe White House accused the North of carrying out “provocativedestabilizing and repressive actions and policiesparticularly its destructive and coercive cyberattack on Sony Pictures.” It also said, “Today’s actions are the first aspect of our response.” 

Seoul’s Foreign Ministry called the sanctions an “appropriate response,” reiterating that cyberattacks to damage private andcorporate interests and the openness and security of cyberspace should not be tolerated

Those sanctioned will be banned from accessing the U.S. financial system and doing any transactions with U.S. nationalsBut the largely symbolic sanctions are unlikely to further damage the economy of the heavily isolated country which is already under a series of international sanctions for its nuclear and missile tests.

The sanctions target the North’s Reconnaissance General Bureauthe country’s premier military spy agencywhich Washington and Seoul believe orchestrated a series of cyber incursions against themSeoul also blames the RGB for launching a string of fatal provocations including the 2010 torpedo attack on the corvette Cheonan that killed46 sailors

Korea Mining Development Trading Corp., in charge of the arms exportsand Korea Tangun Trading Corp., a defense research agency,have also been added to the sanctions listas well as 10 senior officialsincluding those operating in IranSyriaChinaRussia and Namibia.

Even as the FBI continues its investigation into the cyberattack against Sony Pictures Entertainmentthese steps underscore that we willemploy a broad set of tools to defend U.S. businesses and citizens,and to respond to attempts to undermine our values or threaten thenational security of the United States,” U.S. Treasury secretary JackLew said in a statement.

The sanctions came as Pyongyang has hardened its rhetoric againstthe U.S., while continuing its peace offensive toward the South andrefraining from launching its usual verbal attacks against Seoul.

The U.S. is wholly responsible for its hitherto antagonistichostilerelationship with North KoreaThe U.S. should throw away its hostilepolicy toward the North,” said a piece in Saturday’s edition of theRodong Sinmunthe daily of the North’s ruling Workers’ Party.

Should the U.S. come forward with good will while respecting oursovereignty without intervening in our internal affairswe would respondto that accordingly.” 

The two Koreas have moved closer to dialogue since the North Koreanleader demonstrated his desire to hold a “top-level meeting” with theSouth and restore cross-border ties in his New Year address.

Supporting the U.S. sanctions against the NorthSeoul appears to have reaffirmed that it would deal separately with the issues of inter-Korean cooperation and provocations such as the nuclear development and cybervandalism.

In response to Kim’s New Year’s addressSeoul reiterated that itremained open to dialogue in any formSome observers said the Northcould specify its desire for inter-Korean talks this weekwhile otherspresume that it may wait until after President Park Geun-hye deliversher New Year’s speechwhich is expected to be delivered on Jan. 12.

The upcoming impediment to inter-Korean dialogue would be theplanned annual military exercise between the U.S. and South Korea,which will begin in FebruaryThe North Korean leader has called on theallies to cancel the exercisebut the South said the “defense” drills willproceed as planned.

by Invincible Cooler 2015. 1. 5. 17:39

A non-empty zero-indexed array A consisting of N integers and sorted in a non-decreasing order is given. The leader of this array is the value that occurs in more than half of the elements of A.

 

You are given an implementation of a function:

 

class Solution { public int solution(int[] A); }

 

that, given a non-empty zero-indexed array A consisting of N integers, sorted in a non-decreasing order, returns the leader of array A. The function should return 1 if array A does not contain a leader.

 

For example, given array A consisting of ten elements such that:

 

  A[0] = 2

  A[1] = 2

  A[2] = 2

  A[3] = 2

  A[4] = 2

  A[5] = 3

  A[6] = 4

  A[7] = 4

  A[8] = 4

  A[9] = 6

the function should return 1, because the value that occurs most frequently in the array, 2, occurs five times, and 5 is not more than half of 10.

 

Given array A consisting of five elements such that:

 

  A[0] = 1

  A[1] = 1

  A[2] = 1

  A[3] = 1

  A[4] = 50

the function should return 1.

 

Unfortunately, despite the fact that the function may return expected result for the example input, there is a bug in the implementation, which may produce incorrect results for other inputs. Find the bug and correct it. You should modify at most three lines of code.

 

Assume that:

 

N is an integer within the range [1..100,000];

each element of array A is an integer within the range [0..2147483647];

array A is sorted in non-decreasing order.

Complexity:

 

expected worst-case time complexity is O(N);

expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.


initial code

int solution(int[] A) {

             int n = A.length;

             int[] L = new int[n + 1];

             L[0] = -1;

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

                    L[i + 1] = A[i];

             }

             int count = 0;

             int pos = (n + 1) / 2;

             int candidate = L[pos];

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

                    if (L[i] == candidate)

                           count = count + 1;

             }

             if (count > pos)

                    return candidate;

             return (-1);

       }


=> answer 100/100 드디어 100점이 나오다.

import java.util.*; class Solution { int solution(int[] A) { int n = A.length; int[] L = new int[n + 1]; L[0] = -1; for (int i = 0; i < n; i++) { L[i + 1] = A[i]; } int count = 0; int pos = (n + 1) / 2; int candidate = L[pos]; for (int i = 1; i <= n; i++) { if (L[i] == candidate) count = count + 1; } if (n%2==0 ? count > pos : count > pos -1) // <=========== return candidate; return (-1); } }


by Invincible Cooler 2014. 12. 16. 14:02

오늘도 열심히 해석을 해보자.


The repercussions of Korean Air’s “nut rage” incident are expected to build as Heather Cho, daughter of the airline’s chairman, faces a government summons to question her on why she caused the delay of a Korean Air flight and deplaned a flight attendant last week, the Transport Ministry said Thursday.

대한항공 "땅콩리턴" 사고에 대한 영향으로 대한항공 회장의 딸 Heather Cho는 지난주에 발생했던 왜 대한항공 비행기가 지연됐고, 승무원이 비행기에서 내려야 했는지에 대해서 정부의 심의를 받기위해 소환될것이라고, 교통부에서 목요일 말했다.



The ministry issued a notification requesting her appearance for questioning on Friday, said Lee Gwang-hee, aviation safety division director of the Ministry of Land, Infrastructure and Transport. 


교통에 관한 행정 및 이착륙, 관련 기능에 관해서 담당하고 있는 이광희씨는 교통부가 금요일에 질문을 위한 참석 요청을 조부사장에게 했다고 말했다.

Cho will appear for the questioning, the company said. 

조현아씨는 질문에 대한 답을 하기위해서 참석할것이라고 회사는 말했다.



The ministry has also asked Korean Air to supply the list of passengers on the Friday flight, with their contact information, to clarify the facts. Korean Air has yet to comply. 


관련부서는 또한 사실여부 확인을 위해서 금요일 비행기에 탑승했던 승객의 연락처를 대한항공측에서 제공해 줄것을 요청하였다. 하지만 대한항공측은 아직 동의 하지 않았다.

The authorities are urging passengers to come forward and talk about what really happened. They have finished questioning 10 Korean Air employees, including the pilot of flight KE086 and the cabin crew. 

Adding more pressure to Korean Air, the Seoul Seobu District Prosecutors’ Office on Thursday raided the airline’s Seoul and Incheon headquarters to collect documents including the black box and flight operation records of the plane in question. 


“We conducted a hasty raid as the case has drawn public attention and concerns over fabrication of evidence,” a prosecution official said. 

After analyzing the documents, the prosecutors plan to question Cho, who is suspected of violating aviation safety law and obstruction of business. 

A day before, progressive civic group the People’s Solidarity for Participatory Democracy had filed a complaint with the prosecution, claiming that Korean Air’s management has forced its employees to make false testimonies to put the blame on the chief flight attendant who was forced to leave the plane.

On Monday, news reports revealed that Cho, 40, had ordered an employee to deplane over service standards while she was traveling in first class. 

The plane, carrying 250 passengers, had to taxi back to the terminal in New York to drop off the chief flight attendant before heading for Incheon. This caused a delay of 11 minutes in the flight. 

The authorities are currently investigating whether Cho’s actions infringed aviation laws.

The key points of the investigation include whether she was shouting while on board and detailed reasons for why the employee left the plane, and why the plane had to return to the terminal.

On Tuesday, Cho stepped down from all posts at Korean Air except as executive vice president. The day after, she said she would resign from this position as well.

Korean Air’s labor union has demanded a formal apology from Cho to the employees for violating their rights. 

'영어' 카테고리의 다른 글

공부하자  (0) 2015.09.07
Zimbabwean officials: American man wanted in killing of Cecil the lion  (0) 2015.07.29
by Invincible Cooler 2014. 12. 12. 13:03

헐 27점. 시간도 중요한가 보다. 결과만 중요하다고 생각했는데...


Zero-indexed arrays A and B consisting of N non-negative integers are given. Together, they represent N real numbers, denoted as C[0], ..., C[N−1]. Elements of A represent the integer parts and the corresponding elements of B (divided by 1,000,000) represent the fractional parts of the elements of C. More formally, A[I] and B[I] represent C[I] = A[I] + B[I] / 1,000,000.


For example, consider the following arrays A and B:


  A[0] = 0 B[0] = 500,000

  A[1] = 1 B[1] = 500,000

  A[2] = 2 B[2] = 0

  A[3] = 2      B[3] = 0

  A[4] = 3 B[4] = 0

  A[5] = 5 B[5] = 20,000

They represent the following real numbers:


  C[0] = 0.5

  C[1] = 1.5

  C[2] = 2.0

  C[3] = 2.0

  C[4] = 3.0

  C[5] = 5.02

A pair of indices (P, Q) is multiplicative if 0 ≤ P < Q < N and C[P] * C[Q] ≥ C[P] + C[Q].


The above arrays yield the following multiplicative pairs:


(1, 4), because 1.5 * 3.0 = 4.5 ≥ 4.5 = 1.5 + 3.0,

(1, 5), because 1.5 * 5.02 = 7.53 ≥ 6.52 = 1.5 + 5.02,

(2, 3), because 2.0 * 2.0 = 4.0 ≥ 4.0 = 2.0 + 2.0,

(2, 4) and (3, 4), because 2.0 * 3.0 = 6.0 ≥ 5.0 = 2.0 + 3.0.

(2, 5) and (3, 5), because 2.0 * 5.02 = 10.04 ≥ 7.02 = 2.0 + 5.02.

(4, 5), because 3.0 * 5.02 = 15.06 ≥ 8.02 = 3.0 + 5.02.

Write a function:


class Solution { public int solution(int[] A, int[] B); }


that, given zero-indexed arrays A and B, each containing N non-negative integers, returns the number of multiplicative pairs of indices.


If the number of multiplicative pairs is greater than 1,000,000,000, the function should return 1,000,000,000.


For example, given:


  A[0] = 0 B[0] = 500,000

  A[1] = 1 B[1] = 500,000

  A[2] = 2 B[2] = 0

  A[3] = 2 B[3] = 0

  A[4] = 3 B[4] = 0

  A[5] = 5 B[5] = 20,000

the function should return 8, as explained above.


Assume that:


N is an integer within the range [0..100,000];

each element of array A is an integer within the range [0..1,000];

each element of array B is an integer within the range [0..999,999];

real numbers created from arrays are sorted in non-decreasing order.

Complexity:


expected worst-case time complexity is O(N);

expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.



public int solution(int A[], int B[]) {

double divider = 1000000d;


int aLength = A.length;

int bLength = B.length;

if(aLength != bLength) {

return -1;

}

if(aLength == 0 || bLength == 0) {

return -1;

}

double C[] = new double[aLength];

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

// System.out.println("C["+i+"] : " + (double)B[i] / 1000000);

C[i] = A[i] + (double)B[i] / divider;

System.out.println("C["+i+"] : " + C[i]);

}



return -1;

}

to be continue;

=> complete

public int solution(int A[], int B[]) {
double divider = 1000000d;

int aLength = A.length;
int bLength = B.length;
if(aLength != bLength) {
return -1;
}
if(aLength == 0 || bLength == 0) {
return -1;
}
double C[] = new double[aLength];
for (int i=0; i<aLength; i++) {
C[i] = A[i] + (double)B[i] / divider;
}
int count = 0;
int startIndex = -1;
do {
startIndex++;
for(int i=startIndex; i<C.length; i++) {
if(startIndex == i) {
continue;
}
double sum = C[startIndex] + C[i];
double multi = C[startIndex] * C[i];
if(multi >= sum) {
count++;
}
}
}
while(startIndex != C.length-1);

return count;
}


=<== 이건 55점짜리

몰랐던 사실인데, double 에 변수를 저장하면, 그대로 저장이 안되고 변경이 되는 수가 있다고 한다. 그래서 BigDecimal 변수를 사용해야 된다.



// you can also use imports, for example:
// import java.util.*;

// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
import java.math.*;

class Solution {
    public int solution(int[] A, int[] B) {
        int size = A.length;

		BigDecimal C[] = new BigDecimal[size];

		for (int i = 0; i < size; i++) {
			C[i] = BigDecimal.valueOf(A[i]).add(BigDecimal.valueOf((double) B[i] / 1000000d));
		}

		int count = 0;

		for (int i = 0; i < size; i++) {
			for (int j = i + 1; j < size; j++) {
				if (C[i].multiply(C[j]).compareTo(C[i].add(C[j])) >= 0) {
					count++;

					if (count > 1000_000_000) {
						return 1000_000_000;
					}
				}
			}
		}

		return count;
    }
}


by Invincible Cooler 2014. 12. 12. 11:17

이놈이 요즘 미쳤다. 장이 좋지 않은데, 꾸역꾸역 떨어지지 않고, 올라간다. 그래도 거래량에 비해선 항상 1~2% 덜올라가는 형국이다. 개미들이 무지하게 팔아치운다. 무려 1년넘게 8만원만 가면 밑으로 고꾸라 졌으니, 아직은 모른다. 또 같은 짓을 할 수 있다. 주식은 원래 남을 죽여야 내가 사는 곳이다. 상도덕이란 없다.

'주식' 카테고리의 다른 글

한국가스공사  (0) 2015.04.08
락앤락.  (0) 2015.03.06
NHN엔터테인먼트  (0) 2015.01.05
nhn엔터 2014년 11월 7일 하한가  (0) 2014.11.07
NHN엔터테인먼트  (0) 2014.11.03
by Invincible Cooler 2014. 12. 11. 09:59

A non-empty zero-indexed array A consisting of N integers and sorted in a non-decreasing order is given. The leader of this array is the value that occurs in more than half of the elements of A.

You are given an implementation of a function:

class Solution { public int solution(int[] A); }

that, given a non-empty zero-indexed array A consisting of N integers, sorted in a non-decreasing order, returns the leader of array A. The function should return −1 if array A does not contain a leader.

For example, given array A consisting of ten elements such that:

  A[0] = 2 

  A[1] = 2

  A[2] = 2

  A[3] = 2

  A[4] = 2

  A[5] = 3

  A[6] = 4

  A[7] = 4

  A[8] = 4

  A[9] = 6

the function should return −1, because the value that occurs most frequently in the array, 2, occurs five times, and 5 is not more than half of 10.


Given array A consisting of five elements such that:


  A[0] = 1

  A[1] = 1

  A[2] = 1

  A[3] = 1

  A[4] = 50

the function should return 1.


Unfortunately, despite the fact that the function may return expected result for the example input, there is a bug in the implementation, which may produce incorrect results for other inputs. Find the bug and correct it. You should modify at most three lines of code.


Assume that:


N is an integer within the range [1..100,000];

each element of array A is an integer within the range [0..2147483647];

array A is sorted in non-decreasing order.

Complexity:


expected worst-case time complexity is O(N);

expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.


위의 문제는 A라는 array에 값이 들어 있는데, 2,2,3,3,4,4 이런식으로 점점 커지는 수가 들어 있는 array이다. 이중 전체 갯수에서 같은수가 절반이 넘었을때 그때의 값을 리턴해 주고, 절반이거나 절반이 되지 않으면 -1을 리턴하라는 문제이다. 풀이보단 문제 이해가 너무 어려운 문제이다.


solution

public int solution(int A[]) {


int length = A.length;

// A 어레이의 길이가 0 이거나 1이면 -1을 리턴한다. 1개이면 절대 절반이상의 갯수를 만족할수 없다.

if (length <= 1) {

return -1;

}

// 첫번째 인자를 가장최근의 인자라고 생각할때

int lastInput = A[0];

int count = 0;

int tmpValue = -1;

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


if(lastInput == A[i]) { // 가장 마지막에 가지고 있는 값과 첫번째 값이                     //으면 카운트를 하나 올리고, 그 값을 저장하자

count++;

tmpValue = A[i];

// System.out.println("count : " + count);

}

else { // 만약 아니면 위에서 계산한 count를 계산하여 절반이상이면 

// return해주고, 아니면 count를 1로 세팅한다 (1로세팅하는 이유는 새로 하나가 추가됐기 

//때문이다

// System.out.println("count : " + count);

// System.out.println("(length/2) : " + (length/2));

if(count > (length/2)) {

return tmpValue;

}

else {

count = 1;

}

}

// 가장최근값을 가장 마지막에 저정한 값으로 넣어준다

lastInput = A[i];

System.out.println("lastInput : " + lastInput);


// 이건 마지막 놈을 체크하기 위한 루틴이다. 만약 이걸 하지 않으면 for문 //에서 else에서만 절반이 넘는지 체크를 하기 때문에 문제가 될수 있다. 예를들어 //{2,2,2,3,3,3,3,3} 이런식이면 if는 들어가지만 else에 못들어가 문제가 된다.

if(i == (length-1)) {

if(count > (length/2)) {

return tmpValue;

}

}

}

return -1;

}


'프로그래밍 > 알고리즘' 카테고리의 다른 글

BugfixingLeaderSorted  (0) 2014.12.16
CountMultiplicativePairs  (0) 2014.12.12
Min Average Two Slice by Codility  (0) 2014.12.09
by Invincible Cooler 2014. 12. 10. 17:00

문제는 아래와 같다.


A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).
For example, array A such that:

A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8

contains the following example slices:
slice (1, 2), whose average is (2 + 2) / 2 = 2;
slice (3, 4), whose average is (5 + 1) / 2 = 3;
slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.
The goal is to find the starting position of a slice whose average is minimal. Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty zero-indexed array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.
For example, given array A such that:
A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8
the function should return 1, as explained above.
Assume that:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−10,000..10,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.


처음에 이문제를 이렇게 오해해서 아래와 같이 풀었다.


public int solution(int A[]) {

int length = A.length;

if(length < 2) {

return 0;

}


int minIndex = 0;

double lastAverage = 0d;

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

   

    if(i+1 == A.length) {

    break;

    }

   

    int first = A[i];

    int second = A[i+1];

   

    if(first > second) {

    System.out.println("tmpSum : continue");

    continue;

    }


    int tmpSum = 0;

    double average = 0d;

    if(first == second) {

    average = (first+second)/2;

    System.out.println("if average : " + average);

    }

    else {

    int count = 0;

    do {

    tmpSum += first;

    first++;

    count++;

    }

    while(first <= second);

    average = (double)tmpSum/count;

   

    System.out.println("else average : " + average);

    }

    if(lastAverage == 0 || lastAverage > average) {

    lastAverage = average;

    minIndex = i;

    }

   }

   

   return minIndex;

}

어떻게 오해한것이냐면


예를 들어 int A[] = { 4, 2, 2, 5, 1, 5, 8 }; 라고하면

인접한 두개의 원소 사이에서 갯수의 합 / 카운드

다시말해서 3번째 원소 2와 4번째 원소 5는 2+3+4+5 를 해서 4개의 카운트로 나누어 평균값의 제일 작은 index로 오해를 했다. 이노무 영어가 문제다 ㅋㅋㅋ


이제 제대로 다시 풀어봐야겠다. 인접하는 두개의 원소가 아니라, 원소는 몇개가 될 수 있고, 갯수의 값의 합이구먼...


아래와 같이 수정하면 된다. 아래 내용을 잘 분석해 보면, slice가 2개 또는 3개이다. 왜 2, 3개만 적용하면되냐면, 자세한 내용은 http://codesays.com/2014/solution-to-min-avg-two-slice-by-codility/ 를 참고하면 되고, 간단하게 모든 slice는 2개 또는 3개로 나누어 진다는 것이다.

예를 들어 짝수갯수는 2로 나누어 지고, 홀수 갯수는 2로 나누어지고 마지막것이 3개라는 대충 이런개념... 아닌가? 어쨌든 결론은 2,3개의 slice이외에는 할필요가 없다는 것이다.


public int solution2(int A[]) {


int length = A.length;

if (length < 2) {

return -1;

}


if (length == 2) {

return 0;

}


int minIndex = 0;

double minAverage = 10000d;

// System.out.println("minAverage : " + minAverage);


for (int i = 0; i < length - 2; i++) {

double tmpAverage2 = (double) (A[i] + A[i + 1]) / 2;

System.out.println("2 tmpAverage : " + tmpAverage2);


if (tmpAverage2 < minAverage) {

minAverage = tmpAverage2;

minIndex = i;

}


double tmpAverage3 = (double) (A[i] + A[i + 1] + A[i + 2]) / 3;

System.out.println("3 tmpAverage : " + tmpAverage3);

if (tmpAverage3 < minAverage) {

minAverage = tmpAverage3;

minIndex = i;

}


}


return minIndex;

}


by Invincible Cooler 2014. 12. 9. 11:30
| 1 2 3 4 5 6 7 |