-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_2.mo
124 lines (111 loc) · 3.08 KB
/
day_2.mo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import Array "mo:base/Array";
import Char "mo:base/Char";
import Iter "mo:base/Iter";
import Nat "mo:base/Nat";
import Nat8 "mo:base/Nat8";
import Prim "mo:prim";
import Text "mo:base/Text";
import Trie "mo:base/Trie";
import TrieMap "mo:base/TrieMap";
import TrieSet "mo:base/TrieSet";
actor{
private func char_at_pos(t:Text,n:Nat): Char{
var c=0;
for(char in t.chars()){
if(c == n){
return char;
};
c += 1;
};
return '?';
};
// Challenge 1
public func nat_to_nat8(n:Nat):async Nat8{
return Nat8.fromNat(n % (255+1));
};
// Challenge 2
public func max_number_with_n_bits(n:Nat):async Nat{
var max_number:Nat = 0;
for(i in Iter.range(0,n-1)){
max_number += (2**i);
};
return max_number;
};
// Challenge 3
public func decimal_to_bits(n:Nat):async Text{
var binary:Text = "";
var num:Nat=n;
while(num > 0){
binary := Text.concat(Nat.toText((num % 2)),binary);
num /= 2;
};
return binary;
};
// Challenge 4
public func capitalize_character(c:Char):async Char{
if(Char.isUppercase(c)){
return c;
}
else{
return Char.fromNat32(65+(Char.toNat32(c)-97));
}
};
// Challenge 5
public func capitalize_text(t:Text):async Text{
return Text.map(t , Prim.charToUpper);
};
// Challenge 6
public func is_inside(t:Text,c:Char):async Bool{
for(i in t.chars()){
if(i == c){
return true;
}
};
return false;
};
// Challenge 7
public func trim_whitespace(t:Text):async Text{
return Text.trim(t, #text " ");
};
// Challenge 8
public func duplicated_character(t:Text):async Text{
for( i in Iter.range(0,t.size()-1)){
var count=0;
for(j in Iter.range(i+1,t.size()-1)){
if(char_at_pos(t,j)==char_at_pos(t,i)){
return Text.fromChar(char_at_pos(t,j))
}
}
};
return t;
};
// Challenge 9
public func size_in_bytes(t:Text):async Nat{
let text:Blob = Text.encodeUtf8(t);
var count=0;
for(val in text.vals()){
count += Nat8.toText(val).size();
};
return count;
};
// Challenge 10
public func bubble_sort(array:[Nat]):async [Nat]{
var arr:[var Nat] = Array.thaw(array);
let n:Nat = arr.size();
for(i in Iter.range(0,n-1)){
for(j in Iter.range(0,n-i-2)){
if(arr[j] > arr[j+1]){
let temp = arr[j];
arr[j]:=arr[j+1];
arr[j+1]:=temp;
}
}
};
return Array.freeze<Nat>(arr);
};
// Return the character corresponding to the unicode value n.
public func unicode_to_character(n : Nat32) : async Text {
let char : Char = Char.fromNat32(n);
return(Char.toText(char));
};
}