Programmig exercises
Reverse Word
function reverseWords(message){
var words = [];
for( var i = 0 , size_message = message.length ; i < size_message ; i++ ){
var tmp_word = "";
while( message[i] !== " " && i < size_message){
tmp_word += message[i];
i++;
}
words.push(tmp_word);
}
var result = "";
for( var i = words.length-1; i >=0 ; i-- ){
result = result + words[i] + " ";
}
return result;
}
const message = [ 'c', 'a', 'k', 'e', ' ',
'p', 'o', 'u', 'n', 'd', ' ',
's', 't', 'e', 'a', 'l' ];
reverseWords(message);
Largest element in a stack
class Stack {
constructor() {
// Initialize an empty array
this.items = [];
}
// Push a new item to the last index
push(item) {
this.items.push(item);
}
// Remove the last item
pop() {
// If the stack is empty, return null
// (It would also be reasonable to throw an exception)
if (!this.items.length) {
return null;
}
return this.items.pop();
}
at(i){
return this.items[i];
}
size(){
return this.items.length;
}
// See what the last item is
peek() {
if (!this.items.length) {
return null;
}
return this.items[this.items.length - 1];
}
}
class MaxStack {
constructor(){
this.stack1 = new Stack();
console.log("init MaxStack");
}
push(item){
this.stack1.push(item);
}
getMax(){
let max_number = Number.NEGATIVE_INFINITY;
for(var i=0,max_n = this.stack1.size() ; i < max_n ; i++ ){
if( this.stack1.at(i) > max_number ){
max_number = this.stack1.at(i);
}
}
return max_number;
}
}
let maxStack1 = new MaxStack();
maxStack1.push(3);
maxStack1.push(300);
maxStack1.push(1);
maxStack1.push(102);
maxStack1.push(2);
console.log( maxStack1.getMax() );
Programmig excercises
By Irving Norehem Llamas Covarrubias
Programmig excercises
- 211