Created
July 17, 2014 15:44
-
-
Save jikeytang/27ddcd9735b798a0b62e to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140718-题目1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
请把一组有规律的单词拼接起来,规则为: | |
前一个单词的结尾应该与下一个单词的首字母相同。 | |
如: aloha, dog, arachnid, gopher, tiger, rat | |
结果为:aloha-arachnid-dog-gopher-rat-tiger. | |
PS: | |
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。 | |
```javascript | |
// you code | |
``` | |
2. 粘贴代码时请使用shift+tab,缩进前面的空白。 |
replace5
commented
Jul 17, 2014
@feng524822 的写法只有特殊情况下才有正确的结果,如果我换几个单词,马上就不行了:
good, day, yes, see
随机打乱数组, 对打乱后的数组进行校验,总会有一种情况是符合条件的。
var arr = ['aloha', 'dog', 'arachnid', 'gopher', 'tiger', 'rat'];
var newArr = null;
while(true) {
newArr = arr.sort(function () {
return Math.random() > .5 ? -1 : 1;
});
if(test(newArr)){
break;
}
}
function test(arr) {
var first = arr[0];
for(var i=1; i<arr.length; i++){
if(first[first.length-1] != arr[i][0]){
return false;
} else {
first = arr[i];
}
}
return true;
}
console.log(newArr);
我很少用 js写程式,各位常用 js,一定可以再优化
<script>
var arr = ['aloha', 'dog', 'arachnid', 'gopher', 'tiger', 'rat'];
// 印出数组
document.write('<br>数组:');
for (var i =0 ;i<arr.length;i++) {
document.write(arr[i]+', ');
}
document.write('<br>');
var txt1="";
var fun = function(arr1) {//递归方式计算
arr_length = arr1.length;
// 印出数组
//document.write('<br>数组:');
//for (var i =0 ;i<arr_length;i++) {
// document.write(arr1[i]+', ');
//}
//document.write('<br>arr.length : ' + arr.length + ', 比对字符串:' + arr1[0]);
//document.write('->'+arr1[0]); // 印出讯息予用户
txt1 = txt1 + '-' + arr1[0];
str_x = right(arr1[0],1);
for (var i =1 ;i<arr_length;i++){
str_y = left(arr1[i],1);
if (str_x==str_y){
// document.write ('<br>'+i+' '+arr1[i]+' : '+str_x+' '+ str_y);
// document.write('<br>'+i+'-'+arr1[i]); // 印出讯息予用户
Str_temp = arr1[i] // 找到字符串的元素,移动到此数组的第1个
arr1.splice(0,1); // 此数组 移除 第一个元素
arr1.splice(i-1,1); // 此数组,找到字符串的元素, 移除
arr1.unshift(Str_temp); //此数组,加入第一个是找到的字符串
return ( fun(arr1)); // 递归
}
}
document.write ('<br>=>'+txt1.substring(1,txt1.length));
}
fun(arr);
function left(str, num)
{
return str.substring(0,num)
}
function right(str, num)
{
return str.substring(str.length-num,str.length)
}
</script>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment