Skip to content

Instantly share code, notes, and snippets.

@Nevraeka
Created June 29, 2013 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nevraeka/5889710 to your computer and use it in GitHub Desktop.
Save Nevraeka/5889710 to your computer and use it in GitHub Desktop.
Some basic example code approaches and problem solving
def char_count(paragraph)
paragraph.split(%r{\s*}).count
end
def each_word_counts(paragraph)
details = {}
paragraph.split(/\s/).each { |word| details[word] = word.length }
details
end
# char_count "Zombies are coming for you"
# >> 22
# each_word_count "Zombies are coming for you!"
# >> { "Zombies" => 7, "are" => 3, "coming" => 6, "for" => 3, "you" => 3 }
/*
* Use this when
* - underscore.js is not available or a good fit for the project
* - IE8 is not a target browser
*/
function isArray(obj){
var toString = Object.prototype.toString;
return toString.call(obj) === "[object Array]";
}
function without(array1, array2){
if(isArray(array1) && isArray(array2)){
var newArray = [];
for(var ct = 0; ct < array1.length; ct++){
if(array2.indexOf(array1[ct]) === -1){ //indexOf is only a string method in IE8
newArray.push(array1[ct]);
}
}
return newArray;
} else {
return "One or both arguments of 'without' are not Arrays";
}
}
function Dragon(name){
this._name = name;
}
Dragon.prototype.name = function(){
return this._name;
}
Dragon.prototype.breathWeapon = function(){
var modifier = 0;
if(this._breathWeapon === "ice"){
modifier = 5;
}
if(this._breathWeapon === "acid"){
modifier = 7;
}
return Math.ceil(Math.random() * 6)*6 + modifier;
}
function BlackDragon(name){
this._name = name;
}
function WhiteDragon(name){
this._name = name;
}
function extendDragon(drgn){
for(key in Dragon.prototype) {
var val = Dragon.prototype[key];
if(typeof val !== "undefined"){
drgn.prototype[key] = val;
}
}
return drgn;
}
extendDragon(BlackDragon);
extendDragon(WhiteDragon);
WhiteDragon.prototype.speed = function(){
return 75 + Math.floor(Math.random()*10)*5;
}
WhiteDragon.prototype._breathWeapon = "ice";
BlackDragon.prototype.speed = function(){
return 100 + Math.ceil(Math.random() * 10)*6;
}
BlackDragon.prototype._breathWeapon = "acid";
var whiteFang = new WhiteDragon("White Fang");
var blackWing = new BlackDragon("Black Wing");
function battle(champion, challenger){
var champPower = champion.breathWeapon() + champion.speed();
var challPower = challenger.breathWeapon() + challenger.speed();
if(champPower > challPower){
return champion.name() + " has won this battle!";
} else if (challPower > champPower){
return challenger.name() + " has won this battle!";
} else {
//next round
setTimeout(battle, 0);
}
}
battle(whiteFang, blackWing);
def without(array1, array2)
array1.map { |num| num unless array2.include? num }.compact
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment