圖說演算法使用JavaScript(四)

3-7題目:將句中或片語單字反轉 Reverse Words
給定一個短句,將句子中的每一個單字的字母順序反轉,請注意,是句子中的每個單字,以字做為單位進行字母順序反轉。

JS     reverse_word.js

const change = str =>{
	const answer = [];

	str.split(" ").forEach(word =>{ //注意""有空格
		let temp = "";  //注意""沒空格
		for(let i = word.length-1; i>=0; i--){
			temp +=word[i];
		}
	answer.push(temp);
	});

	return answer.join(" "); //注意""有空格
};

console.log("原來句子:");
console.log("The greatest test of courage on earth is to bear defeat without losing heart.");
console.log("句子中每個單字都反轉:");
console.log(change("The greatest test of courage on earth is to bear defeat without losing heart."));

PHP        reverse_word.php

$my_str="The greatest test of courage on earth is to bear defeat without losing heart.";

function my_reverse ($str){

  $my_arr = explode(" ", $str);
  $len = count($my_arr);
  $i = 0;
  while ($i<=$len-1){
    $t_str[]=strrev($my_arr[$i]);
    $i++;
  }

  $my_re=join(" ",$t_str);
  return $my_re;
}

$my_re = my_reverse($my_str);

echo $my_str."<br>";
echo $my_re;
使用函數:
explode()
count()
join() 或 implode() 把陣列元素组合成的字符串。
strre() 反轉字串
3-8題目:首字大寫 Capitalization
給定一個短句,將句子中的每一個單字的第一個字母轉為大寫,請注意,是每句子中的每一個單字,以字做為單位進行首字大寫轉換。

JS       capitalization.htm

const bigletter = sentence => {
	const words = []; //宣告words陣列

	for (let word of sentence.split(""))
		words.push(word[0].toUpperCase() + word.slice(1));

	return words.join("");
};

console.log("原來的句子");
console.log("Genius is an infinite capacity for taking pains.");
console.log("首字大寫的句子:");
console.log(bigletter("Genius is an infinite capacity for taking pains."));

PHP          capitalization.php  

$my_str="Genius is an infinite capacity for taking pains.";
function my_bigletter ($str){
	$my_arr = explode(" ",$str);
	$my_len = count($my_arr);
	$t_big = array();
	$i = 0;
	
	while ($i<=$my_len-1){
		array_push($t_big, ucfirst($my_arr[$i]));
		$i++;
	}
	
	$f_big = implode(" ", $t_big);
	return $f_big; 
}

$f_bigletter=my_bigletter($my_str);
echo $f_bigletter;
使用函數
explode()
count()
array_push() 将一个或多个元素插入陣列的尾端
implode()
3-9平均值 Mean
給定一個數字組,計算平均值,例如給定的陣列[1,2,3],則回傳平均值為2.0。這支程式可以利用Javascript的reduce()方法,它能將陣列中每項元素(由左至右)傳入回呼函式,將陣列化為單一值。

JS        mean.js

const stat1 = [2,8,7,6,5,6,4];
const stat2 = [9,2,8,7,6,5,6,4];
const reducer = (accu, currentValue) => accu + currentValue;
//2,8,7,6,5,6,4
console.log("第1組原始資料");
console.log("[2,8,7,6,5,6,4]");
console.log(stat1.reduce(reducer)/stat1.length);
//9,2,8,7,6,5,6,4
console.log("第2組原始資料");
console.log("[9,2,8,7,6,5,6,4]");
console.log(stat2.reduce(reducer)/stat2.length);

PHP        mean.php

$my_arr_1=array(2,8,7,6,5,6,4);
$my_arr_2=array(9,2,8,7,6,5,6,4);
echo "數字陣列1:";
print_r($my_arr_1);
echo "<br>";
echo "數字陣列2:";
print_r($my_arr_2);
echo "<br>";
function get_mean ($my_arr){
$len = count($my_arr);$total = array_sum($my_arr);
$mean = $total/$len;return $mean;
}
$my_mean_1 = get_mean($my_arr_1);
$my_mean_2 = get_mean($my_arr_2);
echo "my_mean_1=".$my_mean_1."<br>";
echo "my_mean_2=".$my_mean_2."<br>";
使用函數
count()
array_sum() 計算陣列元素值的總和
3-10回傳給定總和的數值序對 Two Sum
這個函數會傳入兩個引數,第一個引數是一個包含多個數字的整數值,第二個引數為給定的總和值(sum),該函數會回傳所有加總起來會等於給定總和的所有數值序對,這個數值序對內的數字可以多次使用。例如給定的第一個引數為[1,2,2,3,4],給定的第二個引數為數值4,則陣列中的3及1加總結果為4。另一種狀況,陣列中的2及2加總結果為4,則回傳的結果值為[[2,2],[3,1]]。

JS          two_sum.js

const twototal = (num, total) =>{
	const subpair = [];
	const ans = [];
      for (let a of num) {
		const b = total -a;
		if (ans.indexOf(b) !== -1){
			subpair.push([a,b]);
		}
		ans.push(a);
	}
	return subpair;
}
console.log ("第1組原始資料");
console.log ("twototal([1,2,2,3,4], 4)=");
console.log (twototal([1,2,2,3,4], 4));
console.log ("第2組原始資料");
console.log ("twototal([2,3,5,1,5,1,3,4], 6)=");
console.log (twototal([2,3,5,1,5,3,4], 6));
Array.prototype.indexOf() 找出元素索引值的陣列indexOf()
Array.prototype.push() 會將一或多個的值,加入至一個陣列中

PHP          two_sum.php

$arr_1 =array (2,3,5,1,5,1,3,4);
function get_two_sum($arr, $num){
$t_arr = array();
$ans = array();
$len = count($arr);
$i=0;
	while ($i <=$len-1){
		$b = $num - $arr[$i];
		$arr_slice = array_slice($arr, $i+1);
		if (in_array($b, $arr_slice) == true){
			$ans[]=array($arr[$i], $b);
		}
		$i++;
	}
	return $ans;
}
$my_two_sum = get_two_sum($arr_1, 6);
print_r($my_two_sum);
使用函數
count()
arr_slice($arr,$num) 函數切割 $arr陣列、$num從多少開始切
in_array($val,$arr) 在函數中尋找是否有值

圖說演算法使用JavaScript(三)

3-4題目:最常出現的字母
撰寫一個函數,傳入引數為一個字串,其輸出的結果會將該字串中出現頻率最高的字母輸出。

JS     max_character.htm

const my_max = str =>{
	const words = {};  //You can create a const object

	for (let ch of str)
		words[ch] = words[ch]+1 || 1;

	let counter = 0;
	let most = null;

	for (let ch in words) {
		if (words[ch] > counter){
			counter = words[ch];
			most = ch;
		}
	}
	return most;
};
console.log(my_max("tomorrow"));

PHP    max_character.php

//$my_str="不要在你的智慧中夾雜著傲慢。不要使你的謙虛新缺乏智慧。";
$my_str="Hello World! 你好世界!";
//$my_str="我為人人,人人為我";
//$my_str="gooddoog";
echo "原來的字串:".$my_str."<br>";

function mb_str_split($str){
	//不分中英字串都可以切成陣列
	return preg_split('/(?<!^)(?!$)/u',$str);
}

function get_most_str($str){

	$arr = mb_str_split($str);    //切字串成陣列
	$len = count ($arr);
	$my_count = 0;
	
	for ($i=0 ; $i<=$len-1; $i++){
		
		$str_count=substr_count($str,$arr[$i]);
		//計算出現次數
		if ($str_count>$my_count){

			$my_count=$str_count;
			$most = $arr[$i];
		}
	}

	return [$most,$my_count];
}

$most_str= get_most_str($my_str);
echo "最大數為".$most_str[0]."=".$most_str[1]."<br>";
使用函數:
substr_count() 計算子字串在字串中出現的次數
3-5題目:判斷兩字是否相同 Anagrams
這個函數的功能是給定兩個包含相同數量的字母的單字或片語,並進行判斷所傳入的單字或片語是否相同的檢查函數。

JS   anagrams.js

const  compare = str =>{

	const table ={}; //宣告一個table物件

	for (let char of str.replace(/\w/g, "").toLowerCase())
		table[char] = table[char]+1 || 1;

	return table;
};

const anagrams = (strA, strB) =>{
	const charA = compare(strA);
	const charB = compare(strB);

	if (Object.keys(charA).length !==Object.keys(charB).length)
		return false;

	for (let char in charA)
		if (charA[char] !== charB[char]) return false;

	return true;
};

console.log(anagrams("happy birthday", "happy birthday"));
console.log(anagrams("happyy birthday", "hhappy birthday"));
說明:
str.replace(/\w/g,"").toLowerCase();
\w 包含數字字母與底線,等同於[A-Za-z0-9_]      出處

PHP     anagrams.php

$my_str_1="happy birthday";
//$my_str_1="大家好";
$my_str_2="hhhappybirthday";
//$my_str_2="happy birthday";

echo "字串_1:".$my_str_1."<br>";
echo "字串_2:".$my_str_2."<br>";

function mb_str_split($str){
	//不分中英字串都可以切成陣列
	return preg_split('/(?<!^)(?!$)/u',$str);
}

/*
$str_1_ar = mb_str_split($my_str_1);
$str_2_ar = mb_str_split($my_str_2);

$str_len_1 = count ($str_1_ar);
$str_len_2 = count ($str_2_ar);
$flag =($str_len_1 != $str_len_2) ;	
$i=0;
if($flag==1){
	echo "這兩個長度不同<br>";

}else{
	
  while ($i<= $str_len_1-1){

  		$flag2=strcmp($str_1_ar[$i],$str_2_ar[$i]);
	    
	    if($flag2==1){
	    	echo "這兩個字母不同<br>";
	    	break;
	    }
	      $i++;
	}
}
*/
function my_anagrams ($str1, $str2){

	$str_1_ar = mb_str_split($str1);
  $str_2_ar = mb_str_split($str2);
  $str_len_1 = count ($str_1_ar);
  $str_len_2 = count ($str_2_ar);
  $flag1 =($str_len_1 != $str_len_2) ;
  $i=0;	
  $msg1="這兩個長度相同<br>";
  $msg2="這兩個字母相同<br>";

  if($flag1==1){
	  $msg1="這兩個長度不同<br>";
	  $msg2="這兩個字母不同<br>";
  }
  else{
  	 while ($i<= $str_len_1-1){

  		$flag2=strcmp($str_1_ar[$i],$str_2_ar[$i]);
	    
	    if($flag2==1){
	    	$msg2="這兩個字母不同<br>";
	    }
	      $i++;
		}//while
   
  }//elseif
	
  return [$msg1,$msg2];

}//function

$my_msg = my_anagrams($my_str_1,$my_str_2);

echo $my_msg[0];
echo $my_msg[1];
函數使用:
strcmp(str1,str2) 比較兩個字串(對大小寫敏感)
3-6題目:反向陣列  Reverse Array
將給定的陣列中的元素,由前往後排列方式,變更成由後往前的排列順序。例如給定原陣列的內容值為[1,2,3,4],則所撰寫的這個函數會回傳[4,3,2,1]‵.

JS      reverse.js

const rev1 = dim =>{
	for (let i=0; i <dim.length /2; i++){
		const temp = dim[i];
		dim[i] = dim[dim.length-1-i];
		dim[dim.length-1-i]=temp;
	}
	return dim;
};

const rev2 = dim =>{
	for (let i=0; i<dim.length/2; i++) {
		[dim[i], dim[dim.length-1-i]] = [
			dim[dim.length-1-i], dim[i]
		];
	}
	return dim;
};

console.log("['a','e','i','o','u']反向陣列:",rev1(['a','e','i','o','u']));
console.log("[2,4,6,8,10]反向陣列:",rev2([2,4,6,8,10]));

PHPh      reverse.php

$my_arr_1=array("a","e","i","o","u");
$my_arr_2=array(2,4,6,8,10);
//$my_str_2="happy birthday";

echo "陣列_1:";
print_r($my_arr_1);
echo "<br>";
echo "陣列_2:";
print_r($my_arr_2);

$re_arr_1 = array_reverse($my_arr_1);
$re_arr_2 = array_reverse($my_arr_2);

echo "<br>";
echo "反陣列_1:";
print_r($re_arr_1);
echo "<br>";
echo "反陣列_2:";
print_r($re_arr_2);
函數使用:
array_reverse($arr) 以相反的順序傳回數組