FCC编程题之中级算法篇(上)
介绍
FCC: 全称为freeCodeCamp,是一个非盈利性的、面向全世界的编程练习网站。这次的算法题来源于FCC的中级算法题。
FCC中级算法篇共分为(上)、(中)、(下)三篇。每篇各介绍7道算法题。每道算法题都会介绍相应的思路和详细的解答过程。
目录
- 1. Sum All Numbers in a Range
- 2. Diff Two Arrays
- 3. Roman Numberal Converter
- 4. Where art thou
- 5. Search and Replace
- 6. Pig Latin
- 7. DNA Pairing
1. Sum All Numbers in a Range
We'll pass you an array of two numbers. Return the sum of those two numbers and all numbers between them.
The lowest number will not always come first.
Here are some helpful links:
- Math.max()
- Math.min()
- Array.prototype.reduce()
方法 1
由题意可知,只需将最小值赋予i,最大值赋予len,然后再迭代相加即可得到答案。
function sumAll(arr) {
let sum = 0;
for (let i = Math.min(arr[0], arr[1]), len = Math.max(arr[0], arr[1]); i <= len; i++) {
sum += i;
}
return sum;
}
方法 2
利用数学的等差公式直接解答。
Sn = n * (a1 + an) / 2
function sumAll(arr) {
return (arr[0] + arr[1]) * (Math.abs(arr[1] - arr[0]) + 1) / 2;
}
2. Diff Two Arrays
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
Here are some helpful links:
- Comparison Operators
- Array.prototype.slice()
- Array.prototype.filter()
- Array.prototype.indexOf()
- Array.prototype.concat()
这里用到了filter()、indexOf()和concat()两个方法。
其中,filter()方法是一个过滤器,其会对调用filter()方法的数组的每一个值调用一次回调函数,利用其中回调函数返回值为true的值创建一个新数组。
indexOf()方法接受一个参数,在数组中查找并返回该参数的下标,如果没找到,则返回-1。
concat()方法用于合并数组。
思路
利用
indexOf()方法判断数组中的值是否存在于另一个数组。利用
filter()方法对数组中的每一个值调用回调函数进行判断,回调函数里使用了indexOf()方法。利用
concat()方法将两个过滤后的数组合并为一个新数组。
function diffArray(arr1, arr2) {
return arr1.filter((val) => {
return arr2.indexOf(val) === -1; // 对arr1数组进行过滤,去掉在arr2数组中存在的值
}).concat(arr2.filter((val) => { // 对arr2数组进行过滤,然后合并两个数组
return arr1.indexOf(val) === -1;
}));
}
3. Roman Numberal Converter
Convert the given number into a roman numeral.
All roman numerals answers should be provided in upper-case.
Here are some helpful links:
- Roman Numerals
- Array.prototype.splice()
- Array.prototype.indexOf()
- Array.prototype.join()
由帮助栏的Roman Numerals可知,罗马数字有三个特征:
- 某些数由特殊的符号来表示

同一个符号不应在一行内连续出现4次及以上,例如IIII
如果一个数出现在特定的数的符号之前则减,之后则加
- 例如:IV = V - I = 5 - 1 = 4
- 例如:VI = V + I = 5 + 1 = 6
- 例如:3999 = 3000 + 900 + 90 + 9 = MMM + CM + XC + IX
思路
创建两个数组,分别用来存储
有特殊符号的数字和与之对应的罗马数字。由第三个特性可知,用
待转换的数字减去比之小的数字中的最大的数字,重复此过程,直到待转换的数字为0,即可得到对应的罗马数字。
function convertToRoman(num) {
// 创建两个数组,分别存储数字和与之对应的罗马数字
const numArr = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
const romArr = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M'];
let str = '';
let i = numArr.length - 1;
while (i >= 0) {
// 当待转换数字比 i 下标数字大时,重复该过程
while (num >= numArr[i]) {
num -= numArr[i]; // 减小数字
str += romArr[i]; // 增加减小数字对应的罗马数字
}
i--;
}
return str;
}
4. Where art thou
Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument). Each property and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], and the second argument is { last: "Capulet" }, then you must return the third object from the array (the first argument), because it contains the property and its value, that was passed on as the second argument.
Here are some helpful links:
- Global Object
- Object.prototype.hasOwnProperty()
- Object.keys()
hasOwnProperty()方法判断调用该方法的对象是否有检测的属性。
keys()方法返回参数对象的可枚举属性的字符串数组。
思路
利用
hasOwnProperty()判断是否有指定的属性。利用
===判断对象的值是否相等。利用
filter()方法过滤数组。
function whatIsInAName(collection, source) {
// 取得source的属性
let keys = Object.keys(source);
return collection.filter((val) => {
// 遍历source的属性数组,如果collection不存在该属性或对应的属性的值不一致,则返回fasle
for (let i in keys) {
if (!val.hasOwnProperty(keys[i]) || val[keys[i]] !== source[keys[i]]) {
return false;
}
}
return true;
});
}
5. Search and Replace
Perform a search and replace on the sentence using the arguments provided and return the new sentence.
First argument is the sentence to perform the search and replace on.
Second argument is the word that you will be replacing (before).
Third argument is what you will be replacing the second argument with (after).
NOTE: Preserve the case of the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog"
Here are some helpful links:
- Array.prototype.splice()
- String.prototype.replace()
- Array.prototype.join()
replace()方法用于替换字符串文本并返回一个替换完成后的新字符串。
slice()方法用于提取字符串的一部分,并返回提取的部分。如果没有第二个参数来指定结束位置,则一直取到字符串末尾。
思路
判断要替换的文本的首字母是否是大写,如果是,则把替换用的文本的首字母也变为大写。
利用
replace()方法替换文本。
function myReplace(str, before, after) {
// 判断要替换的文本的首字母是否是大写
if (before[0] === before[0].toUpperCase()) {
after = after[0].toUpperCase() + after.slice(1);
}
return str.replace(before, after);
}
6. Pig Latin
Translate the provided string to pig latin.
Pig Latin takes the first consonant (or consonant cluster) of an English word, moves it to the end of the word and suffixes an "ay".
If a word begins with a vowel you just add "way" to the end.
Input strings are guaranteed to be English words in all lowercase.
Here are some helpful links:
- Array.prototype.indexOf()
- Array.prototype.push()
- Array.prototype.join()
- String.prototype.substr()
- String.prototype.split()
元音字母共有5个:a、e、i、o、u。
split()方法接受一个参数作为分隔符,然后把字符串分割为一个数组。如果只想取得字符串的值而不改变字符串,可以使用[]来取值。
substr()方法返回一个由指定位置开始,长度为指定个数的字符串,如果没有指定提取字符的个数,则一直取到字符串末尾。
思路
利用
indexOf()方法判断字符串中第一个元音字母的下标index。如果
index等于0,说明字符串以元音字母开头,直接在末尾加上way。如果不相等,则重组字符串,并在末尾加上ay。
function translatePigLatin(str) {
const arr = ['a', 'e', 'i', 'o', 'u'];
let index = 0;
for (let i in str) {
if (arr.indexOf(str[i]) > -1) {
index = i;
break;
}
}
// 隐式类型转换
return index == 0 ? str + 'way' : str.slice(index) + str.substr(0, index) + 'ay';
}
7. DNA Pairing
The DNA strand is missing the pairing element. Take each character, get its pair, and return the results as a 2d array.
Base pairs are a pair of AT and CG. Match the missing element to the provided character.
Return the provided character as the first element in each array.
For example, for the input GCG, return [["G", "C"], ["C","G"],["G", "C"]]
The character and its pair are paired up in an array, and all the arrays are grouped into one encapsulating array.
Here are some helpful links:
- Array.prototype.push()
- String.prototype.split()
DNA碱基配对即A对T、C对G。
map()方法创建一个新数组,其元素为回调函数返回的值。
思路
创建两个数组,分别存储['A', 'T', 'C', 'G']和['T', 'A', 'G', 'C']。
利用
split()方法分割数组为单个字符数组。利用
map()方法对单个字符数组中的每个元素调用回调函数。
function pairElement(str) {
const arr1 = ['A', 'T', 'C', 'G'];
const arr2 = ['T', 'A', 'G', 'C'];
return str.split('').map((val)=>{
return [val, arr2[arr1.indexOf(val)]];
});
}
此文也发表在了我的简书上。
如果你对某题有更好的解决方法,请务必在评论区指出,谢谢。
FCC编程题之中级算法篇(上)的更多相关文章
- FCC编程题之中级算法篇(下)
介绍 本篇是"FCC编程题之中级算法篇"系列的最后一篇 这期完结后,下期开始写高级算法,每篇一题 目录 1. Smallest Common Multiple 2. Finders ...
- FCC编程题之中级算法篇(中)
介绍 接着上次的中级算法题 目录 1. Missing letters 2. Boo who 3. Sorted Union 4. Convert HTML Entities 5. Spinal Ta ...
- java学习之第五章编程题示例(初学篇)
/* Animal.java */ package animal; public abstract class Animal { public abstract void cry(); public ...
- FCC上的javascript算法题之中级篇
FCC中的javascript中级算法题解答 中级算法的题目中用到了很多js的知识点,比如迭代,闭包,以及对json数据的使用等等,现在将自己中级算法的解答思路整理出来供大家参考讨论.欢迎大家提出新的 ...
- C算法编程题(四)上三角
前言 上一篇<C算法编程题(三)画表格> 上几篇说的都是根据要求输出一些字符.图案等,今天就再说一个“上三角”,有点类似于第二篇说的正螺旋,输出的字符少了,但是逻辑稍微复杂了点. 程序描述 ...
- fcc的中级算法题
核心提示:这是网上开源编程学习项目FCC的javascript中级编程题(Intermediate Algorithm Scripting(50 hours)),一共20题.建议时间是50个小时,对于 ...
- FCC中级算法(上)
在学习FCC中级算法这一块,自己遇到了很多问题,通过RSA也慢慢把问题解决了,发现每一个问题都会有很多的解决思路,因此把自己想到的一些思路记录到这里. 1. Sum All Numbers in a ...
- 算法是什么我记不住,But i do it my way. 解一道滴滴出行秋招编程题。
只因在今日头条刷到一篇文章,我就这样伤害我自己,手贱. 刷头条看到一篇文章写的滴滴出行2017秋招编程题,后来发现原文在这里http://www.cnblogs.com/SHERO-Vae/p/588 ...
- C算法编程题(七)购物
前言 上一篇<C算法编程题(六)串的处理> 有些朋友看过我写的这个算法编程题系列,都说你写的不是什么算法,也不是什么C++,大家也给我提出用一些C++特性去实现问题更方便些,在这里谢谢大家 ...
随机推荐
- DirectUI界面编程(二)绘制一个按钮
上节介绍了使用源码方式构建Duilib应用的项目配置,并创建了一个最简单的基于Duilib库的窗口,细心的读者会发现,当我们点击窗口的关闭按钮时,应用并没有真的退出,因为我们并没有对窗口事件进行处理, ...
- soapUI检查webServices接口的方法以及对自动触发线程的查询
这几天需要熟悉接口传输过来的数据,因此会用到soapUI,但是没结果这个工具,然后百度了下,结合了下,下面是我对webservice在soapUI的展现: 1:其实说白了,就是我们不知道从接口里传输过 ...
- 树莓派使用samba
tips:打算利用树莓派做局域网内的文件共享服务器, 实测发现树莓派挂载一个硬盘比较合适,挂载多个硬盘则会出现供电不足而挂载失败, 即使利用外置供电接入多个硬盘实测效果也不好,树莓派在IO上无法处理多 ...
- luoguP2742 【模板】二维凸包 / [USACO5.1]圈奶牛 二维凸包
我们知道,纵坐标最小的点一定在凸包上(如果有多个,那它们都会被取到) 随便找一个纵坐标最小的点,将其他所有点按照这个点为原点极角排序,我们发现极角大的会在极角小的后面加入(感性认知一下) 考虑新(加入 ...
- 路飞学城Python-Day24(practise)
本章总结 练习题 什么是C/S架构? C指的是client(客户端软件),S指的是Server(服务端软件)
- HDU 1047 Integer Inquiry( 高精度加法水 )
链接:传送门 思路:高精度水题 /************************************************************************* > File ...
- BZOJ 4012 [HNOI2015]开店 (树分治+二分)
题目大意: 给你一棵树,边有边权,点有点权,有很多次询问,求点权$\in[l,r]$的所有节点到某点$x$的距离之和,强制在线 感觉这个题应该放在动态点分之前做= = 套路方法和动态点分是一样的 每次 ...
- Linux 进程及作业管理
进程简介: 内核的功用:进程管理.文件系统.网络功能.内存管理.驱动程序.安全功能 进程(Process):什么是进程,进程是程序的执行实例,即运行中的程序,同时也是程序的一个副本:程序是放置于磁 ...
- Python破解Wifi密码思路
一.前言说明 本机运行环境:系统环境Win10,运行环境Python3.6,运行工具Pycharm 需要Python的包有:pywifi 这是一种暴力破解wifi的模式,需要的时间比较长,本文主要提供 ...
- 新建Eclipse工作空间,复制原有的配置(转)
方法一: File->Switch workspace->Other...,按下图选择 只复制简单的配置,如cvs之类的信息是不会复制的. 方法二: 在方法一的基础上做如下操作 将新建的w ...