Skip to content

Commit 7b64e34

Browse files
committed
added trivia algos
1 parent 8372206 commit 7b64e34

File tree

2 files changed

+120
-0
lines changed

2 files changed

+120
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
/**
4+
* Function will sort array using a predicate index
5+
*/
6+
7+
function index_sort(array &$sort, int $idx): array{
8+
9+
try{
10+
11+
if(empty($sort) || count($sort) == 0){
12+
13+
throw new \Exception("Invalid array, please check array and try again");
14+
15+
}
16+
17+
uasort($sort, function($val_1, $val_2) use($idx) {
18+
19+
if(!ctype_alpha($val_1) || !ctype_alpha($val_2)){
20+
21+
return null;
22+
23+
}
24+
25+
if(substr($val_1, $idx) > substr($val_2, $idx)){
26+
27+
return 1;
28+
29+
}else if( substr($val_1, $idx) < substr($val_2, $idx) ){
30+
31+
return -1;
32+
33+
}
34+
35+
return null;
36+
37+
});
38+
39+
return $sort;
40+
41+
}catch(\Exception $e){
42+
43+
exit($e->getMessage());
44+
echo "\n\n";
45+
46+
}
47+
48+
}
49+
50+
$arr = ['orange', 'banana', 'apple','carrot', 'collard', 'pea'];
51+
52+
$sorted = index_sort($arr, 2);
53+
54+
foreach($sorted as $val){
55+
56+
echo $val . " ";
57+
58+
}
59+
60+
echo "\n\n";
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
/**
4+
* Function will sort array using last char in string
5+
*/
6+
7+
function sort_last_char(array &$usort): array{
8+
9+
try{
10+
11+
if(empty($usort) || count($usort) == 0){
12+
13+
throw new \Exception("Invalid array, please check array and try agaian");
14+
15+
}
16+
17+
uasort($usort,function($val_1, $val_2) {
18+
19+
if(!ctype_alpha($val_1) || !ctype_alpha($val_2)){
20+
21+
return null;
22+
23+
}
24+
25+
if(substr($val_1,-1) > substr($val_2,-1)){
26+
27+
return 1;
28+
29+
}else if(substr($val_1,-1) < substr($val_2,-1)){
30+
31+
return -1;
32+
33+
}
34+
35+
return null;
36+
37+
});
38+
39+
return $usort;
40+
41+
}catch(\Exception $e){
42+
43+
exit($e->getMessage());
44+
echo "\n\n\n\n";
45+
46+
}
47+
48+
}
49+
50+
$arr = ['orange', 'banana', 'apple','carrot', 'collard', 'pea'];
51+
52+
$sorted_arr = sort_last_char($arr);
53+
54+
foreach($sorted_arr as $val){
55+
56+
echo $val . " ";
57+
58+
}
59+
60+
echo "\n\n\n\n";

0 commit comments

Comments
 (0)