728x90

✨ Array의 모든 index에 값을 한 번에 채워주거나, 원하는 구간만큼 값을 채워줄 수 있는 helper method

(e.g., arr.fill(false) or arr.fill(0, 2, 4)) 왼쪽처럼 Array의 모든 값을 false로 채우거나, index 2부터 3까지 0을 채워줄 수 있다.
(Array.prototype.slice()와 마찬가지로 구간을 지정할 때, end-1까지 진행된다는 점을 명심하자)

💻Example Code

const arr = [ 1, 2, 3, 4, 5, 6 ];

console.log( arr.fill(0, 1, 3) );

실행 결과(index 1부터 3까지 지정했지만, 2까지 변한 것을 볼 수 있다)

😋 매우 큰 Array의 값을 한 번에 초기화 해줄 때, 또는 원하는 index 구간만큼 값을 바꿔줄 때 매우 유용하다.
백준 4673번 셀프 넘버(Self Number)문제를 풀 때 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

 

Array.prototype.fill()

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
728x90

Code

최종 제출 코드
기존 제출 코드

😢 무언가 원초적인 방법으로 풀었던 문제, 어떻게 풀어 나갈지에 대한 고민을 조금 했다.

😊 기존 제출 Solution) array를 선언하고, 모든 index 값을 0으로 초기화해준 후 Self Number가 아니라면 해당 index에 1을 넣어주었다.
그리고 마지막에 for loop의 i를 이용해 array[i]의 값이 1이 아니라면(=Self Number라면) Self Number인 i를 출력하도록 했다.

[추가] 최종 제출 Solution)
while loop 안에서 각 자릿수 나눠주기 + 나눠준 값 더하기를 진행하여 코드의 복잡도를 줄여줬다. 또한 시간도 더 빨라졌다.
그리고  배열 10000개 만큼 false로 채워주고, 셀프 넘버가 아니라면 true로 변경시켜주었다. 따라서 false로 남아있다면 그건 셀프 넘버다.


각 자릿수를 구하는 것은 매우 원초적인 방법으로 진행했다.
54321인 다섯 자리를 기준으로 설명하자면,
parseInt( 54321/10000 )(=5.4321)은 5
parseInt( (54321%10000) / 1000 )(=4.321)은 4
parseInt( (54321%1000) / 100 )(=3.21)은 3
parseInt( (54321%100) / 10 )(=2.1)은 2
54321 % 10 은 1
아래 Full Code에는 위의 자릿수 나누는 방식을, 다른 방법으로 접근한 Code가 있다.

✔ while loop을 이용한 자릿수 나누고, 바로 더하기

let temp = 나눌값;
let sum = temp;

while( 0 > temp){
sum += temp%10;
temp = parseInt(temp/10); }

또한, 다른 사람들이 푼 풀이가 매우 흥미로워서 그 방법들도 함께 연습했다. 세상에는 대단한 사람들이 참 많다.

Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)

// Self Number
 
// 4th Solution
 
const n = 10000;
const isSelfNum = new Array(n + 1);
isSelfNum.fill(true);
 
function d(n) {
const N = n.toString().split('');
 
return n + N.reduce((acc, num) => (acc += +num), 0);
}
 
for (let i = 1; i <= n; i++) {
isSelfNum[d(i)] = false;
}
 
for (let i = 1; i <= n; i++) {
if (isSelfNum[i]) {
console.log(i);
}
}
 
// 3rd Solution
 
// function d(n) {
// let temp = n;
// let sum = temp;
 
// while (temp > 0) {
// sum += temp % 10;
// temp = parseInt(temp / 10);
// }
 
// return sum;
// }
 
// const N = 10000;
// const selfNumCheckArr = new Array(N);
// selfNumCheckArr.fill(false);
 
// for (let i = 1; i <= N; i++) {
// selfNumCheckArr[d(i)] = true;
// if (!selfNumCheckArr[i]) {
// console.log(i);
// }
// }
 
// 1st solution
 
// const N = 10000;
// let arr = [];
 
// for (let i = 0; i <= N; i++) {
// d(i);
// }
 
// function d(n) {
// if (n < 10) {
// arr[n + n] = 1;
// } else if (n < 100) {
// arr[n + parseInt(n / 10) + (n % 10)] = 1;
// } else if (n < 1000) {
// arr[n + parseInt(n / 100) + parseInt((n % 100) / 10) + (n % 10)] = 1;
// } else if (n < 10000) {
// arr[
// n +
// parseInt(n / 1000) +
// parseInt((n % 1000) / 100) +
// parseInt((n % 100) / 10) +
// (n % 10)
// ] = 1;
// } else {
// arr[
// n +
// parseInt(n / 10000) +
// parseInt((n % 10000) / 1000) +
// parseInt((n % 1000) / 100) +
// parseInt((n % 100) / 10) +
// (n % 10)
// ] = 1;
// }
// }
 
// for (let i = 1; i <= N; i++) {
// if (!(arr[i] === 1)) {
// console.log(i);
// }
// }
 
// 2nd solution(string - array[index])
 
// const N = 10000;
// const arr = [];
 
// for (let i = 0; i <= N; i++) {
// arr[i] = 0;
// }
 
// for (let i = 1; i <= N; i++) {
// d(i);
// }
 
// function d(n) {
// const str = n.toString();
 
// if (n < 10) {
// arr[n + n] = 1;
// } else if (n < 100) {
// arr[n + parseInt(str[0]) + parseInt(str[1])] = 1;
// } else if (n < 1000) {
// arr[n + parseInt(str[0]) + parseInt(str[1]) + parseInt(str[2])] = 1;
// } else if (n < 10000) {
// arr[
// n +
// parseInt(str[0]) +
// parseInt(str[1]) +
// parseInt(str[2]) +
// parseInt(str[3])
// ] = 1;
// } else {
// arr[
// n +
// parseInt(str[0]) +
// parseInt(str[1]) +
// parseInt(str[2]) +
// parseInt(str[3]) +
// parseInt(str[4])
// ];
// }
// }
 
// for (let i = 1; i <= N; i++) {
// if (arr[i] === 0) {
// console.log(i);
// }
// }
728x90

✨ pattern과 맞는 String을 교체해주는 helper method

(e.g., str.replace('dog', 'cat')) 왼쪽처럼 dog을 cat으로 교체하는 것이 가능하다.
간단하게 설명하자면,
첫 번째 parameter에는 RegExp(Regular Expressions) 또는 String을 넣을 수 있고(즉, 찾을 pattern)
두 번째 parameter에는 새로 넣을 new string을 넣을 수 있다(즉, 새로 넣을 replacement)

💻Example Code

1) 간단한 단어 교체

const str = 'Hi there!';
const afterReplace = str.replace('Hi', 'Hello');

console.log(afterReplace);

실행 결과(Hi가 Hello로 교체된 것을 볼 수 있다)

2) RegExp를 이용한 교체(alphabet만 남기기)

const strTwo = 'Hi! there~@!';
const afterReplaceTwo = strTwo.replace(/[^\w]/g, '');

console.log(afterReplaceTwo);

실행 결과(특수문자, 공백이 제거된 것을 볼 수 있다)

📌replace(/[^\w]/g, '')를 자세히 살펴보겠다.
1. RegExp의 시작과 끝은 /(slash)
2. []는 []안에 어느 것이라도 매치된다면 이라는 뜻이다. (다시 알아볼 필요가 있음)
3. ^ 는 무효화 시킨다는 뜻이다(반전이라고 생각하면 될듯하다)
4. \w은 글자와 숫자(alphanumeric)를 뜻한다.
5. g는 global이라는 뜻. 한 번 매치되어도 끝까지 매치되는 것을 찾게 한다.

즉, [^\w]을 이용해 글자와 숫자 이외의 모든 문자는 제거한다. 라고 보면 편하다.

😋 Anagrams(철자를 바꾼 말) Algorithm에서 공백, 구두점 그리고 특수문자를 제거하기 위해 사용하였다.
Regular Expressions은 문자열을 다루기에 매우 유용하다. 어렵기 때문에 하나씩 차근차근 쌓아가는 것이 필요하다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

 

String.prototype.replace()

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

 

RegExp

The RegExp constructor creates a regular expression object for matching text with a pattern.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

 

Regular expressions

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), search

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
728x90

✨ object의 keys 또는 values를 array로 반환하는 helper method

💻Example Code

const obj = { a: 'something', b: 2, c: 3 };

console.log( Object.keys(obj) );
console.log( Object.values(obj) );

실행 결과(keys와 values가 array로 반환되는 것을 볼 수 있다)

😋 Anagrams(철자를 바꾼 말) Algorithm 에서 같은 종류의 철자가 사용되었는지 확인할 때 유용하게 사용하였다.
(Algorithm 카테고리의 Anagrams Algorithm 문제에서 확인 가능하다)
이 외에도 다양한 곳에서 사용 가능하다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

 

Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

 

Object.values()

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
728x90

Q. 주어진 array를 주어진 size만큼 잘라서 sub array로 넣어라.

--- Examples
chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/master/completed_exercises/chunk/index.js

😢 undefined 개념, 배열의 마지막 index를 지정하는 방법 그리고 slice를 활용하는 방법을 몰라서 많이 고민했다.

😊 Solution 1)
주어진 array 값을 for ... of를 통해 element로 하나씩 가져오고, 새로운 chunk array가 비어(undefined)있거나 size만큼 꽉차면 새로운 sub array를 push하고, 그게 아니라면 chunk array의 마지막 index sub array에 element를 push하여 해결한다.

Solution 2)
index를 size만큼 쌓아올리는 index 변수를 선언하여, slice(index, index + size); index += size; 를 while loop안에서 반복해준다. 그렇게하면 주어진 길이만큼 slice하여 sub array로 push할 수 있다.

✔ undefined 이용

!undefined는 true

✔ slice(begin, end)

시작부터 끝 전 index까지 array를 잘라준다.
(자세한 내용은 helper method 카테고리에서 확인 가능하다)

Full Code

function chunk(array, size) {
const chunked = [];
let index = 0;
 
while (index < array.length) {
chunked.push(array.slice(index, index + size));
index += size;
}
 
return chunked;
}
 
// function chunk(array, size) {
// const chunked = [];
//
// for (let element of array) {
// const last = chunked[chunked.length - 1];
//
// if (!last || last.length === size) {
// chunked.push([element]);
// } else {
// last.push(element);
// }
// }
//
// return chunked;
// }
728x90

https://www.acmicpc.net/problem/4344

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/54592b15a8664302e6d2c812440edabf9b417013

😢 5분 정도 고민하고, 코드로 하나씩 정리해 나가면서 금방 풀 수 있었던 문제

😊 전체 Test Case를 반복할 수 있는 for loop을 가장 바깥에서 돌리고, 중첩 첫 번째 for loop에서 점수를 모두 더해준 후 평균을 구한다. 그리고 중첩 두 번째 for loop에서 평균보다 높은 인원수를 구하고 비율을 계산해주고 출력한다.
평균을 어떻게 구할지, 평균을 넘는 인원은 몇명인지, 비율을 구하는 공식은 무엇인지 먼저 정리하고 풀어나가면 금방 해결할 수 있다.

Full Code

// 1st Solution
 
// For submit
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
const input = [
'5',
'5 50 50 70 80 100',
'7 100 95 90 80 70 60 50',
'3 70 90 80',
'3 70 90 81',
'9 100 99 98 97 96 95 94 93 91'
];
 
const C = parseInt(input[0]);
 
for (let i = 1; i <= C; i++) {
const NAndGradeArr = input[i].trim().split(' ');
let totalGrade = 0;
let avg = 0;
let counter = 0;
let proportion = 0;
for (let j = 1; j <= parseInt(NAndGradeArr[0]); j++) {
totalGrade += parseInt(NAndGradeArr[j]);
}
 
avg = totalGrade / parseInt(NAndGradeArr[0]);
 
for (let k = 1; k <= parseInt(NAndGradeArr[0]); k++) {
if (parseInt(NAndGradeArr[k]) > avg) {
counter++;
}
}
 
proportion = (counter / parseInt(NAndGradeArr[0])) * 100;
console.log(proportion.toFixed(3) + '%');
}
// 비율 구하는 공식 : 비교량 / 기준량 * 100 (2 / 5 * 100)
 
// other solution (좀 특이해서 참고해보았다)
 
// var a = require('fs')
// .readFileSync('/dev/stdin')
// .toString()
// .match(/[^\r\n]+/g)
// .slice(1),
// b = a.map(function(x) {
// return x.split(' ');
// }),
// c = [],
// e = [];
// for (var i = 0; i <= b.length - 1; i++) {
// c.push(
// b[i].reduce(function(pre, cur) {
// return parseInt(pre) + parseInt(cur);
// }) /
// b[i][0] -
// 1
// );
 
// e.push(
// b[i].slice(1).filter(function(x) {
// return x > c[i];
// })
// );
 
// console.log(((e[i].length / b[i][0]) * 100).toFixed(3) + '%');
// }
728x90

✨ 문자 또는 숫자를 순서대로 정렬할 때 사용하는 helper method

(e.g., strArr.sort() or numArr.sort((a, b) => a - b)) 문자를 sort 할 때, 10이 넘어가는 숫자를 sort할 때, 왼쪽처럼 사용법이 다르다.
Numbers는 Strings으로 변환되기 때문에, Unicode order에 따라 80이 9보다 앞에 위치한다.

💻Example Code

const strArr = [ 'c', 'b', 'a' ];
const numArr = [ 3, 33, 2, 22, 1, 11 ];

console.log( strArr.sort() );
console.log( numArr.sort() ); // For Example
console.log( numArr.sort((a,b) => a - b) );

실행 결과( 2번째 결과는 Number를 그냥 sort() 했을 때 결과이다)

😋 Anagrams(철자 순서를 바꾼 말) Algorithm에서 유용하게 사용 가능하며, 다양한 상황에서 사용 가능하다.

✔ sort((a, b) => a - b)로 숫자가 정렬되는 것을 Test 해보자

const numArr = [ 3, 2, 1, 11, 22 ,33 ];

function compare(a, b) {
console.log('a:'+a);
console.log('b:'+b);
return a - b; }

a가 b보다 작아서 negative가 나오는 경우 a는 b보다 낮은 숫자의 index를 갖고, 0은 변화 없음, 0보다 크면 a는 b보다 높은 index를 갖게 되는 식으로 정렬된다. 아마 선택 정렬(Selection Sort)과 비슷한 방식이 아닐까 생각해본다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

 

Array.prototype.sort()

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
728x90

✨ String의 알파벳을 대문자(toUpperCase()) 또는 소문자(toLowerCase())로 바꿔주는 helper method

(e.g., str.toLowerCase() or str.toUpperCase()) 왼쪽처럼 String 변수에 helper method를 붙여 사용한다.

💻Example Code

const strOne = 'abc';
const strTwo = 'ABC';

console.log( strOne.toUpperCase() );
console.log( strTwo.toLowerCase() );

실행 결과(소문자는 대문자로, 대문자는 소문자로 바뀐 걸 볼 수 있다)

😋 Anagrams(철자 순서를 바꾼 말)와 Vowels(모음 찾기) Algorithm 에서 유용하게 사용했다. 다양한 곳에서 활용이 가능하다.
활용된 내용은 위의 알고리즘 문제를 참고하시면 좋습니다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase

 

String.prototype.toLowerCase()

The toLowerCase() method returns the calling string value converted to lower case.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

 

String.prototype.toUpperCase()

The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24
728x90

Q. 주어진 2개의 String이 서로 Anagrams인지 확인하라 (Anagram - 철자 순서만 다르고, 같은 개수의 알파벳)
(단, 대문자, 공백 그리고 구두점은 제외한다)

--- Examples
anagrams('rail safety', 'fairy tales') --> True
anagrams('RAIL! SAFETY!', 'fairy tales') --> True
anagrams('Hi there', 'Bye there') --> False

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/2cf4631c1d09e038f0bf9827b710812d078c4023

😢 RegExp, Object.keys().length 스킬을 사용하게 될지 예상하기 힘들었다.

😊 Solution 1)
Map을 생성해주는 function을 만들고, Object.keys().length를 이용해 사용된 철자의 종류가 동일한지 확인하고, for ... in을 이용해 사용된 철자의 개수가 동일한지 확인하여 문제를 해결한다.
Solution 2)
순서를 정렬하는 function을 만들고, 그 결과가 서로 같은지 확인하는 방법을 이용해 문제를 해결한다.

위의 2가지 방법에서 가장 중요한 것은 replace(/[^\w]/g, '')을 이용해 대문자, 공백 그리고 구두점을 제거해주는 것이다.

✔ replace(/[^\w]/g, '')

알파벳 외 문자를 제거한다.

✔ toLowerCase()

대문자를 소문자로 바꿔준다

✔ split('')

String을 separator기준으로 Array로 나눠서 저장해준다

✔ sort()

Array의 순서를 UTF-16 기준으로 정렬해준다

✔ join()

Array를 separator기준으로 String으로 합쳐준다

✔ Object.keys()

Object의 key만 Array 형식으로 받아볼 수 있다. 따라서 옆에 .length를 사용해 길이를 받아볼 수 있다

 

Full Code

function anagrams(stringA, stringB) {
return cleanString(stringA) === cleanString(stringB);
}
 
function cleanString(str) {
return str
.replace(/[^\w]/g, '')
.toLowerCase()
.split('')
.sort()
.join('');
}
 
// function anagrams(stringA, stringB) {
// const aCharMap = buildCharMap(stringA);
// const bCharMap = buildCharMap(stringB);
//
// if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
// return false;
// }
//
// for (let char in aCharMap) {
// if (aCharMap[char] !== bCharMap[char]) {
// return false;
// }
// }
//
// return true;
// }
//
// function buildCharMap(str) {
// const charMap = {};
//
// for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
// charMap[char] = charMap[char] + 1 || 1;
// }
//
// return charMap;
// }
728x90

https://www.acmicpc.net/problem/8958

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/f1fa3910361f1978f2443cba1df1b851b055da38

😢 이번 문제는 꽤나 고민을 했다. 첫 풀이 때는, 중첩 for loop을 2번이나 써서 '1. 점수를 얻어내고 2. 점수를 계산하여' 출력 하였다. 
하지만 2번째 풀이에서(위의 코드)는 중첩 for loop 한 번으로 점수를 얻음과 동시에 출력하였다. 중첩 for loop을 한 개나 없앴다는 것에 만족한다. 대략 30분 정도 걸렸던 것 같다. 혼자 못 풀 문제는 아니었다.

😊 첫 번째 for {}안에 점수를 표시할 counter와 점수를 더할 eachSum을 선언하였다. 그리고 두 번째 for {}안에서 배열의 해당 index가 O라면 counter를 증가하며 eachSum에 계속 더하였고, X라면 counter가 다시 1로 시작하도록 초기화하였다.
두 번째 for {}이 끝난 후 한 줄의 OX점수를 합한 eachSum을 출력해주었다.

Full Code

 

// 1st Solution (submitted)
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// For local test
 
const input = [
'5',
'OOXXOXXOOO',
'OOXXOOXXOO',
'OXOXOXOXOXOXOX',
'OOOOOOOOOO',
'OOOOXOOOOXOOOOX'
];
 
// 2nd Solution
 
const N = parseInt(input[0]);
 
for (let i = 1; i <= N; i++) {
let counter = 1;
let eachSum = 0;
for (let j = 0; j < input[i].length; j++) {
if (input[i][j] === 'O') {
eachSum += counter;
counter++;
} else {
counter = 1;
}
}
console.log(eachSum);
}
 
// 1st Solution
 
// const N = parseInt(input[0]);
// const result = [];
// let idx = 0;
 
// for (let i = 1; i <= N; i++) {
// let counter = 0;
// for (let j = 0; j < input[i].length; j++) {
// if (input[i][j] === 'O') {
// counter++;
// result.push(counter);
// } else {
// counter = 0;
// result.push(counter);
// }
// }
// }
 
// for (let i = 1; i <= N; i++) {
// let eachSum = 0;
// for (let j = 0; j < input[i].length; j++) {
// eachSum += result[idx];
// idx++;
// }
// console.log(eachSum);
// }
 
// other solution
 
// const N = parseInt(input[0]);
 
// for (let i = 0; i < N; i++) {
// let eachO = String(input[i + 1]).split('X');
// let sum = 0;
// for (let j = 0; j < eachO.length; j++) {
// for (let k = 1; k <= String(eachO[j]).length; k++) {
// sum += k;
// }
// }
// console.log(sum);
// }

+ Recent posts