codewars练习记录20 js

[6 kyu] Simple Encryption #1 - Alternating Split

Implement a pseudo-encryption algorithm which given a string S and an integer N concatenates all the odd-indexed characters of S with all the even-indexed characters of S, this process should be repeated N times.

Examples:

encrypt("012345", 1) => "135024"
encrypt("012345", 2) => "135024" -> "304152"
encrypt("012345", 3) => "135024" -> "304152" -> "012345"
encrypt("01234", 1) => "13024"
encrypt("01234", 2) => "13024" -> "32104"
encrypt("01234", 3) => "13024" -> "32104" -> "20314"

Together with the encryption function, you should also implement a decryption function which reverses the process.

If the string S is an empty value or the integer N is not positive, return the first argument without changes.
翻译:
实现一个伪加密算法,给定一个字符串S和一个整数N,将S的所有奇数索引字符与S的所有偶数索引字符连接起来,这个过程应该重复N次。

与加密函数一起,您还应该实现一个解密函数,该函数可以反转过程。
如果字符串S是空值或整数N不是正数,则返回第一个参数而不进行更改。
解一:

function encrypt (text, n) {
  if (text == null) return null
  for (let k = 0; k < n; k++) {
    let odd = text.split('').filter((x, i) => i % 2 != 0)
    let even = text.split('').filter((x, i) => i % 2 == 0)
    text = odd.concat(even).join('')
  }
  return text
}

function decrypt (encryptedText, n) {
  if (!encryptedText) {
    return encryptedText
  }
  var char = encryptedText.split('')
  for (let i = 0; i < n; i++) {
    var odd = char.slice(0, char.length / 2)
    var even = char.slice(char.length / 2)
    char = []
    while (odd.length || even.length) {
      if (even.length) {
        char.push(even.shift())
      }
      if (odd.length) {
        char.push(odd.shift())
      }
    }
  }
  return char.join('')
}

解二:

function encrypt(text, n) {
  for (let i = 0; i < n; i++) {
    text = text && text.replace(/.(.|$)/g, '$1') + text.replace(/(.)./g, '$1') 
  }
  return text
}

function decrypt(text, n) {
  let l = text && text.length / 2 | 0
  for (let i = 0; i < n; i++) {
    text = text.slice(l).replace(/./g, (_, i) => _ + (i < l ? text[i] : ''))
  }
  return text
}
[6 kyu] Kebabize

Modify the kebabize function so that it converts a camel case string into a kebab case.

kebabize('camelsHaveThreeHumps') // camels-have-three-humps
kebabize('camelsHave3Humps') // camels-have-humps

翻译:
修改kebabize函数,使其将camel大小写字符串转换为kebab大小写。
解一:

function kebabize(str) {
  let newstr = str.replace(/[^a-zA-Z]/g, '') // 将所有非字母元素删掉
  for (let i = 0; i < newstr.length; i++) {
    if (newstr[i] >= 'A' && newstr[i] <= 'Z')
      newstr = newstr.replace(newstr[i], '-' + newstr[i].toLowerCase())
    else if (newstr[i] >= 'a' && newstr[i] <= 'z')
      continue
    else
      newstr = newstr.replace(newstr[i], '')
  }
  if (newstr[0] == '-') newstr = newstr.substring(1)
  return newstr
}

解二:

function kebabize(str) {
  return str.replace(/[^a-z]/ig, '').
         replace(/^[A-Z]/, c => c.toLowerCase()).
         replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
}
[6 kyu] Decipher this!

You are given a secret message you need to decipher. Here are the things you need to know to decipher it:
For each word:
the second and the last letter is switched (e.g. Hello becomes Holle)
the first letter is replaced by its character code (e.g. H becomes 72)
Note: there are no special characters used, only letters and spaces
Examples

decipherThis('72olle 103doo 100ya'); // 'Hello good day'
decipherThis('82yade 115te 103o'); // 'Ready set go'

翻译:
你会收到一条需要破译的秘密信息。以下是你需要知道的事情来破译它:
对于每个单词:
切换第二个和最后一个字母(例如Hello变成Holle)
第一个字母被其字符代码替换(例如H变为72)
注意:没有使用特殊字符,只有字母和空格
解一:

function decipherThis(str) {
  let brr = str.split(' ').map(x => x.replace(x.replace(/[^\d]/g, ''), String.fromCharCode(x.replace(/[^\d]/g, ''))))  //字符替换
  return brr.map(function (y) {  //交换位置
    let b = y.split('')
    let temp = b[1]
    b[1] = b[b.length - 1]
    b[b.length - 1] = temp
    return b.join('')
  }).join(' ')
}; 

解二:

function decipherThis(str) {
  return str.split(" ")
    .map(w =>
      w.replace(/^\d+/, c => String.fromCharCode(c))
       .replace(/^(.)(.)(.*)(.)$/, "$1$4$3$2")
    )
    .join(" ")
}
[6 kyu] A Rule of Divisibility by 13

From Wikipedia:

"A divisibility rule is a shorthand way of determining whether a given integer is divisible by a fixed divisor without performing the division, usually by examining its digits."

When you divide the successive powers of 10 by 13 you get the following remainders of the integer divisions:

1, 10, 9, 12, 3, 4 because:

10 ^ 0 ->  1 (mod 13)
10 ^ 1 -> 10 (mod 13)
10 ^ 2 ->  9 (mod 13)
10 ^ 3 -> 12 (mod 13)
10 ^ 4 ->  3 (mod 13)
10 ^ 5 ->  4 (mod 13)

Then the whole pattern repeats. Hence the following method:

Multiply

  • the right most digit of the number with the left most number in the sequence shown above,
  • the second right most digit with the second left most digit of the number in the sequence.

The cycle goes on and you sum all these products. Repeat this process until the sequence of sums is stationary.

Example:

What is the remainder when 1234567 is divided by 13?

7      6     5      4     3     2     1  (digits of 1234567 from the right)
×      ×     ×      ×     ×     ×     ×  (multiplication)
1     10     9     12     3     4     1  (the repeating sequence)

Therefore following the method we get:

7×1 + 6×10 + 5×9 + 4×12 + 3×3 + 2×4 + 1×1 = 178

We repeat the process with the number 178:

8x1 + 7x10 + 1x9 = 87

and again with 87:

7x1 + 8x10 = 87

From now on the sequence is stationary (we always get 87) and the remainder of 1234567 by 13 is the same as the remainder of 87 by 13 ( i.e 9).

Task:

Call thirt the function which processes this sequence of operations on an integer n (>=0). thirt will return the stationary number.

thirt(1234567) calculates 178, then 87, then 87 and returns 87.

thirt(321) calculates 48, 48 and returns 48
(个人理解)大意就是将例数(例如:1234567)的倒序(7654321)的每一位数和 数列1,10,9,12,3,4,1 (该数列由10的连续幂除以13取模 则取余数所得 固定的)的每一位数相乘再相加,再循环操作所得结果,直到循环前后结果相同,输出最终值
解:

function thirt(n) {
   var arr=[1,10,9,12,3,4]
   while(n>=100){
     var sum = n
     n=0
     for(let i=0;sum!=0;n=n+Math.floor(sum%10) * arr[i%6],sum=sum/10,i++);
   }
   return n
}

解:

function thirt(n) {
  const nums = [1,10,9,12,3,4]
  var sum = (''+n).split('').reverse().reduce((sum,v,i) => sum + v * nums[i%nums.length], 0)
  return sum === n ? n : thirt(sum)
}
[6 kyu] Array Helpers

This kata is designed to test your ability to extend the functionality of built-in classes. In this case, we want you to extend the built-in Array class with the following methods: square(), cube(), average(), sum(), even() and odd().

Explanation:

square() must return a copy of the array, containing all values squared
cube() must return a copy of the array, containing all values cubed
average() must return the average of all array values; on an empty array must return NaN (note: the empty array is not tested in Ruby!)
sum() must return the sum of all array values
even() must return an array of all even numbers
odd() must return an array of all odd numbers
Note: the original array must not be changed in any case!

Example

var numbers = [1, 2, 3, 4, 5];
numbers.square(); // must return [1, 4, 9, 16, 25]
numbers.cube(); // must return [1, 8, 27, 64, 125]
numbers.average(); // must return 3
numbers.sum(); // must return 15
numbers.even(); // must return [2, 4]
numbers.odd(); // must return [1, 3, 5]

翻译:
说明:
此kata旨在测试您扩展内置类功能的能力。在本例中,我们希望您使用以下方法扩展内置Array类:square()、cube()、average()、sum()、even()和odd()。
说明:
square()必须返回数组的副本,其中包含所有平方值
cube()必须返回数组的副本,其中包含所有立方值
average()必须返回所有数组值的平均值;在空数组上必须返回NaN(注意:空数组未在Ruby中测试!)
sum()必须返回所有数组值的总和
even()必须返回所有偶数的数组
odd()必须返回所有奇数的数组
注意:在任何情况下都不能更改原始数组!
解:

Object.assign(Array.prototype, {
    square() {return this.map(n => n * n);},
    cube() {return this.map(n => Math.pow(n, 3));},
    sum() {return this.reduce((p,n) => p + n, 0);},
    average() {return this.reduce((p,n) => p + n, 0) / this.length;},
    even() {return this.filter(n => !(n % 2));},
    odd() {return this.filter(n => n % 2);}
});

解:

Array.prototype.square  = function () { return this.map(function(n) { return n*n; }); }
Array.prototype.cube    = function () { return this.map(function(n) { return n*n*n; }); }
Array.prototype.average = function () { return this.sum() / this.length; }
Array.prototype.sum     = function () { return this.reduce(function(a, b) { return a + b; }, 0); }
Array.prototype.even    = function () { return this.filter(function(item) { return 0 == item % 2; }); }
Array.prototype.odd     = function () { return this.filter(function(item) { return 0 != item % 2; }); }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容