[04.17.22] Codewars
9629 ワード
Detect Pangram
Description
A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog"is a pangram, because it uses the letters A-Z at least once (case is irrelevant).
Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation.
My answer
function isPangram(string){
const alphabet = 'abcdefghijklmnopqrstuvwsyz';
const testStr = string.toLowerCase();
for(let i = 0; i < alphabet.length; i++) {
if (testStr.indexOf(alphabet[i]) === -1) {
return false;
}
}
return true;
}
Other solutions
function isPangram(string){
string = string.toLowerCase();
return "abcdefghijklmnopqrstuvwxyz".split("").every(function(x){
return string.indexOf(x) !== -1;
});
}
function isPangram(string){
return 'abcdefghijklmnopqrstuvwxyz'
.split('')
.every((x) => string.toLowerCase().includes(x));
}
function isPangram(string){
return (string.match(/([a-z])(?!.*\1)/ig) || []).length === 26;
}
Wrap up
every function
array.every(callbackFn, thisArg)
Parameters
callbackFn
function isPangram(string){
const alphabet = 'abcdefghijklmnopqrstuvwsyz';
const testStr = string.toLowerCase();
for(let i = 0; i < alphabet.length; i++) {
if (testStr.indexOf(alphabet[i]) === -1) {
return false;
}
}
return true;
}
function isPangram(string){
string = string.toLowerCase();
return "abcdefghijklmnopqrstuvwxyz".split("").every(function(x){
return string.indexOf(x) !== -1;
});
}
function isPangram(string){
return 'abcdefghijklmnopqrstuvwxyz'
.split('')
.every((x) => string.toLowerCase().includes(x));
}
function isPangram(string){
return (string.match(/([a-z])(?!.*\1)/ig) || []).length === 26;
}
array.every(callbackFn, thisArg)
The current element being processed in the array
The index of the current element being processed in the array
The array every was called upon.
A value to use as this when executing callbackFn
Return value
true if the callbackFn function returns a truthy value for every array element. Otherwise, false.
Examples
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
const isSubset = (array1, array2) => array2.every(element => array1.includes(element));
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6])); // true
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7])); // false
[12, 5, 8, 130, 44].every(x => x >= 10); // false
[12, 54, 18, 130, 44].every(x => x >= 10); // true
// ---------------
// Modifying items
// ---------------
let arr = [1, 2, 3, 4];
arr.every( (elem, index, arr) => {
arr[index+1] -= 1
console.log(`[${arr}][${index}] -> ${elem}`)
return elem < 2
})
// Loop runs for 3 iterations, but would
// have run 2 iterations without any modification
//
// 1st iteration: [1,1,3,4][0] -> 1
// 2nd iteration: [1,1,2,4][1] -> 1
// 3rd iteration: [1,1,2,3][2] -> 2
// ---------------
// Appending items
// ---------------
arr = [1, 2, 3];
arr.every( (elem, index, arr) => {
arr.push('new')
console.log(`[${arr}][${index}] -> ${elem}`)
return elem < 4
})
// Loop runs for 3 iterations, even after appending new items
//
// 1st iteration: [1, 2, 3, new][0] -> 1
// 2nd iteration: [1, 2, 3, new, new][1] -> 2
// 3rd iteration: [1, 2, 3, new, new, new][2] -> 3
// ---------------
// Deleting items
// ---------------
arr = [1, 2, 3, 4];
arr.every( (elem, index, arr) => {
arr.pop()
console.log(`[${arr}][${index}] -> ${elem}`)
return elem < 4
})
// Loop runs for 2 iterations only, as the remaining
// items are `pop()`ed off
//
// 1st iteration: [1,2,3][0] -> 1
// 2nd iteration: [1,2][1] -> 2
source: mdn web docs Your order, please
Description
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
Examples
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
My answer
function order(words){
const regex = /\d/g;
let test = words.split(' ').sort(function(a,b) {
return a.match(regex) - b.match(regex);
})
return test.join(' ');
}
Other solutions
function order(words){
var array = words.split(' ');
var sortedArray = [];
for(i = 0; i <= array.length; i++) {
for(j = 0; j < array.length; j++) {
if(array[j].indexOf(i) >= 0) {
sortedArray.push(array[j]);
}
}
}
return sortedArray.join(' ');
}
function order(words){
// ...
return words && words.split(' ')
.map(word => word.match(/\d/) + word)
.sort()
.map(word => word.slice(1))
.join(' ');
}
Wrap up
match function
If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec().
If you need to know if a string matches a regular expression RegExp, use RegExp.test().
If you only want the first match found, you might want to use RegExp.exec() instead.
If you want to obtain capture groups and the global flag is set, you need to use RegExp.exec() or String.prototype.matchAll() instead.match(regexp)
Return value
An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.
If the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.
if the g flag is not used, only the first complete match and its related capturing groups are returned. In this case, the returned item will have additional properties as described below.
Examples
const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const regexp = /[A-E]/gi;
const matches_array = str.match(regexp);
console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const capturingRegex = /(?<animal>fox|cat) jumps over/;
const found = paragraph.match(capturingRegex);
console.log(found.groups); // {animal: "fox"}
const str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.",
str2 = "My grandfather is 65 years old and My grandmother is 63 years old.",
str3 = "The contract was declared null and void.";
str1.match("number"); // "number" is a string. returns ["number"]
str1.match(NaN); // the type of NaN is the number. returns ["NaN"]
str1.match(Infinity); // the type of Infinity is the number. returns ["Infinity"]
str1.match(+Infinity); // returns ["Infinity"]
str1.match(-Infinity); // returns ["-Infinity"]
str2.match(65); // returns ["65"]
str2.match(+65); // A number with a positive sign. returns ["65"]
str3.match(null); // returns ["null"]
source: mdn web docs
Unique In Order
Description
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:
uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3]) == [1,2,3]
My answer
var uniqueInOrder=function(iterable){
let result = [];
let paramArray = Array.isArray(iterable) ? iterable : iterable.split('');
for (let i = 0; i < paramArray.length; i++) {
if (paramArray[i] != paramArray[i+1]) {
result.push(paramArray[i]);
}
}
return result;
}
Other solutions
function uniqueInOrder(it) {
var result = []
var last
for (var i = 0; i < it.length; i++) {
if (it[i] !== last) {
result.push(last = it[i])
}
}
return result
}
var uniqueInOrder=function(iterable){
return [...iterable].filter((a, i) => a !== iterable[i-1])
}
Reference
この問題について([04.17.22] Codewars), 我々は、より多くの情報をここで見つけました
https://velog.io/@jay_jykim91/04.17.22-Codewars
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
function order(words){
const regex = /\d/g;
let test = words.split(' ').sort(function(a,b) {
return a.match(regex) - b.match(regex);
})
return test.join(' ');
}
function order(words){
var array = words.split(' ');
var sortedArray = [];
for(i = 0; i <= array.length; i++) {
for(j = 0; j < array.length; j++) {
if(array[j].indexOf(i) >= 0) {
sortedArray.push(array[j]);
}
}
}
return sortedArray.join(' ');
}
function order(words){
// ...
return words && words.split(' ')
.map(word => word.match(/\d/) + word)
.sort()
.map(word => word.slice(1))
.join(' ');
}
match(regexp)
const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const regexp = /[A-E]/gi;
const matches_array = str.match(regexp);
console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const capturingRegex = /(?<animal>fox|cat) jumps over/;
const found = paragraph.match(capturingRegex);
console.log(found.groups); // {animal: "fox"}
const str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.",
str2 = "My grandfather is 65 years old and My grandmother is 63 years old.",
str3 = "The contract was declared null and void.";
str1.match("number"); // "number" is a string. returns ["number"]
str1.match(NaN); // the type of NaN is the number. returns ["NaN"]
str1.match(Infinity); // the type of Infinity is the number. returns ["Infinity"]
str1.match(+Infinity); // returns ["Infinity"]
str1.match(-Infinity); // returns ["-Infinity"]
str2.match(65); // returns ["65"]
str2.match(+65); // A number with a positive sign. returns ["65"]
str3.match(null); // returns ["null"]
Description
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:
uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3]) == [1,2,3]
My answer
var uniqueInOrder=function(iterable){
let result = [];
let paramArray = Array.isArray(iterable) ? iterable : iterable.split('');
for (let i = 0; i < paramArray.length; i++) {
if (paramArray[i] != paramArray[i+1]) {
result.push(paramArray[i]);
}
}
return result;
}
Other solutions
function uniqueInOrder(it) {
var result = []
var last
for (var i = 0; i < it.length; i++) {
if (it[i] !== last) {
result.push(last = it[i])
}
}
return result
}
var uniqueInOrder=function(iterable){
return [...iterable].filter((a, i) => a !== iterable[i-1])
}
Reference
この問題について([04.17.22] Codewars), 我々は、より多くの情報をここで見つけました https://velog.io/@jay_jykim91/04.17.22-Codewarsテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol