351

Re: Absent's Code Thread / Tech Blog

https://www.amazon.com/Algorithms-4th-R … 032157351X

Get that book. My father has it, although an old version, and it's really fucking good.

Hindsight is always 20/20.

God wrote:

A surprising amount of insight can be gleamed from sitting on the toilet. More concerning, however, is the amount of nostalgia. neutral



When in doubt, move north. God bless suomi.

Re: Absent's Code Thread / Tech Blog

I actually do have that in PDF, just haven't worked through it. Probably won't until I'm done FCC. Everyone on HN recommends it.

Re: Absent's Code Thread / Tech Blog

why not just the cracking coding interview book

sloth wrote:

Comfy does not provide challenge, challenge provides success, success provides happiness. Our world is not comfy, although we tried to make it so. Slaves of our own inventions, yada, yada. Not only on a technological level, also on a social and political level. Nothing more but apes. Apes with psychosomatic disorders.

Re: Absent's Code Thread / Tech Blog

cuz it's huge lol, and I don't really want a job at google or facebook or microsoft because I'm not really that smart kek


would probably take me a solid year to work all the way through that book


I did start it but didn't get very far because I kept starting stuff and not following through. I think the key is to just follow the fuck through with something for once. Maybe I'll look at it again idk.

Re: Absent's Code Thread / Tech Blog

Idk if I'm just tired but lmfao:

function spinalCase(str) {
  let wat = str.replace(/_/g, '');
  let spaceReg = wat.replace(/([A-Z])/g, ' $1').trim();
  let removeDoubleSpace = spaceReg.replace(/\s\s/g, ' ');
  let replace_space_with_dash = removeDoubleSpace.replace(/\s/g, '-');
  return replace_space_with_dash.toLowerCase();
  console.log(replace_space_with_dash);
}

spinalCase('This_Is_Spinal_Tap');
spinalCase("thisIsSpinalTap");
spinalCase("AllThe-small Things");
spinalCase("The_Andy_Griffith_Show");
spinalCase("Teletubbies say Eh-oh");

It fucking works though so suck my dic


edit:

function spinalCase(str) {
  let replace_underscore = str.replace(/_/g, '');
  let add_spaces = replace_underscore.replace(/([A-Z])/g, ' $1').trim();
  let replace_space_with_dash = add_spaces.replace(/\s+/g, '-');
  return replace_space_with_dash.toLowerCase();
}

spinalCase('This_Is_Spinal_Tap');
spinalCase("thisIsSpinalTap");
spinalCase("AllThe-small Things");
spinalCase("The_Andy_Griffith_Show");
spinalCase("Teletubbies say Eh-oh");

Little better I guess lol

Re: Absent's Code Thread / Tech Blog

It just doesn't work with Upper_lower

sloth wrote:

Comfy does not provide challenge, challenge provides success, success provides happiness. Our world is not comfy, although we tried to make it so. Slaves of our own inventions, yada, yada. Not only on a technological level, also on a social and political level. Nothing more but apes. Apes with psychosomatic disorders.

Re: Absent's Code Thread / Tech Blog

My embarrassingly bad and ugly code, first draft, move fast and break things version of a Piglatin algorithm:


function translatePigLatin(str) {
  let vowels = ["a", "e", "i", "o", "u"]
  let arr = str.split('');

  let lazyCheck = [];
  arr.forEach(e => {
    if (vowels.includes(e)){
      lazyCheck.push(arr[e]);
    }
  });
  if (lazyCheck.length == 0)
    return arr.join('') + "ay";  
    
  if (vowels.includes(arr[0])){
    arr.push("way");
    return arr.join('');
  }
  let constonants = [];
  for (let i = 0; i < arr.length; i++){
    if (!vowels.includes(arr[i])){
      constonants.push(arr[i]);
    }
    else
      return arr.slice(constonants.length, arr.length).join('') +
      constonants.join('') + "ay"; 
  }
}


translatePigLatin("mxrcd");

Not such a good programmer in a rush ay lol


And here's a quick'n to do a replace except if the before word has a capital it changes the capital in the replacement word to a capital or w/e:

function myReplace(str, before, after) {
  let thestr = str;
  let newBefore = before.split('');
  let newAfter = after.split('');
  if (newBefore[0] == newBefore[0].toUpperCase()){
    if (newAfter[0] != newAfter[0].toUpperCase()){
      newAfter.splice(0, 1, newAfter[0].toUpperCase());
      after = newAfter.join('');
    }
  }
  return str.replace(before, after);
}

//myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

myReplace("He is Sleeping on the couch", "Sleeping", "sitting");

I'm sure there's significantly less lazy / more efficient, less ugly ways of doing these but... Maybe I'll get around to refactoring later. I should really force myself to start using map, filter and reduce more. Don't quite have a really good grasp on that yet. Plus does js have something like a hash table? That seems like something that's fairly essential in larger scaling applications.

Re: Absent's Code Thread / Tech Blog

it's not horrible, wut. fairly straightforward to read

you can do this

arr.filter(c => vowels.includes(c)).length

but it's pretty much the same thing computationally.

you could try to do premature optimization and just look for one vowel

let vowels = ['a', 'e', 'i', 'o', 'u']
let hasVowel = 0
arr.forEach(c => if (vowels.includes(c)) { hasVowel = 1})

oh but u cant break with forEach??

maybe there's something like filter that quits on the first match, and only returns the first match or nothing



JS objects do the same thing as a hash table (though ordered?) and as a python dictonary, using strings as keys.

"In the case of Spidermonkey, objects basically have a linked list of (propname, infromation about property) pairs, until they have too many properties, when I believe they still keep the linked list (because order matters for properties in JS in practice) but add an out-of-band hashtable that maps property names to entries in the linked list." https://stackoverflow.com/questions/102 … ash-tables

if you try to use a non-primitive/non-string as a key, it just calls its toString. so if you do

let table = {}
table[[1,2,3]] = 4

it is
{"1,2,3": 4}

sloth wrote:

Comfy does not provide challenge, challenge provides success, success provides happiness. Our world is not comfy, although we tried to make it so. Slaves of our own inventions, yada, yada. Not only on a technological level, also on a social and political level. Nothing more but apes. Apes with psychosomatic disorders.

Re: Absent's Code Thread / Tech Blog

Thanks, that's pretty interesting. I remember going through some algorithms books/challenges and sometimes for complexity it was best avoid things like toString (in java anyway) or something like that if I remember correctly, so implementing algo's with a lot of built in tools won't always be possible assuming the challenge requires a certain complexity. Like you'd need to implement them without using certain conversions and without using too many arrays and/or searching or something. Idk I'm rusty and still need to study complexity a lot more.


Most of the time when I'm writing code I assume it's not optimal for some reason, like it felt superfluous to create an array and push() to it just to check if a vowel existed, which yeah I guess filter might be a good idea there. Either way it's not like iterating over an array of 5 is really gonna make much of a difference in the speed I guess. Yeah forEach has no break but I'd just use a for loop if I really wanted to "short circuit" / premature optimization or what not. Bleh I should just have more confidence or something.


edit:

function pairElement(str) {
  let arr = str.split('');
  let ret2dArr = [];
  arr.forEach(e => {
    switch(e) {
      case "G":
      ret2dArr.push(["G","C"]);
      break;
    case "C":
      ret2dArr.push(["C","G"]);
      break;
    case "A":
      ret2dArr.push(["A","T"]);
      break;
    case "T":
      ret2dArr.push(["T","A"]);
      break;
    default:
      break;
    } 
  });
  console.log(ret2dArr);
  return ret2dArr;
}

pairElement("GCG");

Leaving these in here in case I ever wanna re-study the algo section on FCC btw. I guess with this one I could've used an object of key/values and used map.


Edit: Find missing alphabet letter or w/e:

function fearNotLetter(str) {
  let arr = str.toUpperCase().split('');
  let begin = arr[0].charCodeAt();
  let end = arr[arr.length - 1].charCodeAt();
  for (let i = begin; i < end + 1; i++){
    if (!arr.includes(String.fromCharCode(i))){
      return String.fromCharCode(i).toLowerCase();
    }
  }
  return undefined;
}

fearNotLetter("abce");

I read about a girl who apparently spent like a month+ trying to figure one of these out and could never figure it out alone. Apparently a lot of people just get straight up stuck and can't get through these. I shouldn't talk shit because obviously I already have a CS degree, but... A month on something like this? Maybe it's time to go back through the earlier problems... The earlier algo's were much harder and I'm sure there'll be some more I'll get stuck on tomorrow, but if I'm stuck for more than like 30 minutes, fuck that I'm googling. Why would you not?


Edit: Didn't do this all myself, had some help via stack overflow, but it feels pretty fucking decent:

function uniteUnique(arr) {
  let theArr = []; 
  for (var i = 0; i < arguments.length; i++) {
    theArr.push(arguments[i]);
  }
  theArr = theArr.reduce((acc, val) => acc.concat(val), []);

  let seen = {};
  let answer = theArr.filter((e) => seen.hasOwnProperty(e) ? false : (seen
  [e] = true));
  return answer;
}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]); 
//should return [1, 3, 2, 5, 4].

Re: Absent's Code Thread / Tech Blog

Today's Algo's post, will periodically update until i'm done the algo's challenges for today:

Challenge: Intermediate Algorithm Scripting: Convert HTML Entities

function convertHTML(str) {
  let repAt = str.replace(/&/g, "&amp;");
  let lessThan = repAt.replace(/</g, '&lt;');
  let moreThan = lessThan.replace(/>/g, '&gt;');
  let repQuotes = moreThan.replace(/\"/g, '&quot;');
  let aposQuote = repQuotes.replace(/'/g, "&apos;");
  console.log(aposQuote);
  return aposQuote;
}

function fib(n) {
    var a = 0, b = 1, c;
    if (n < 3) {
        if (n === 0) return 0;
        return 1;
    }
    while (n > 0){
      n--;
      c = a + b, a = b, b = c;
    }
    return c;
}

function sumFibs(num) {
  if(num == 1)
    return 1;
  const even = (num) => {return num % 2 === 1;};
  let myArray = [];
  for (let i = 0; i < num + 1; i++){
    myArray.push(fib(i));
  }
  let newArr = myArray.filter(even);
  let newNewArr = newArr.filter(e => e <= num);
  let reducer = (acc, value) => acc + value;
  return newNewArr.reduce(reducer);
}

console.log(sumFibs(75025));

Didn't write all of the fib function but whatever

Re: Absent's Code Thread / Tech Blog

function sumPrimes(num) {
  // Sieve of eratosthenes
  let arr = [];
  let newArr = [];
  for (let i = 2; i <= num + 2; i++){
    arr.push(true);
  }
  for (let i = 2; i <= Math.sqrt(num); i++){
    if (arr[i]){
      for (let j = i * i; j <= num; j += i){
        arr[j] = false;
      }
    }
  }
  console.log(arr[977]);
  for(let i = 2; i <= num; i++)
  {
    if(arr[i]){
      newArr.push(i);
    }
  }
  console.log(newArr);
  let reducer = (acc, num) => acc + num;
  return newArr.reduce(reducer);
}

sumPrimes(977);

That took an excessive amount of debugging. Ended up having to change the initial for loop to start from index of 0 and add <= instead of < for all instances of < because I needed to make sure it included the 977 in the reducer method because the problem asked to include the num element in the addition. Fuck.

Re: Absent's Code Thread / Tech Blog

you should never use this brace style in JS, because of automatic semicolon insertion

  for(let i = 2; i <= num; i++)
  {

sloth wrote:

Comfy does not provide challenge, challenge provides success, success provides happiness. Our world is not comfy, although we tried to make it so. Slaves of our own inventions, yada, yada. Not only on a technological level, also on a social and political level. Nothing more but apes. Apes with psychosomatic disorders.

Re: Absent's Code Thread / Tech Blog

Weird. Will keep that in mind, though. Thanks.

Re: Absent's Code Thread / Tech Blog

Things to know: Euclidian algorithm, Sieve of Eratosthenes, Euclid's algorithm + GCD.


Anyway:

// Euclidean algorithm 
function gcd(a, b){
  let big = 0, smol = 0, k = 0;
  if (a > b){big = a; smol = b;}
  else{big = b; smol = a;}
  while (smol != 0){
    let r = big % smol;
    big = smol; smol = r;
  }
  return big;
}
// lcm(a, b) = ab/gcd(a,b))
const lcm = (a, b) => {return a * b / gcd(a,b)};

function smallestCommons(arr) {
  let newArr = [];
  let largest = 0, smallest = 0;
  if (arr[0] > arr[1]){largest = arr[0]; smallest = arr[1];}
  else{largest = arr[1]; smallest = arr[0];}
  for (let i = smallest; i < largest + 1; i++){
    newArr.push(i);
  }
  let retMe = smallest;
  newArr.forEach(e => {
    retMe = lcm(retMe, e);
  });
  return retMe;
}
smallestCommons([18, 23]);

Re: Absent's Code Thread / Tech Blog

function dropElements(arr, func) {
  let newArr = [...arr];
  for (let i = 0; i < arr.length; i++){
    if (func(arr[i])){
      return newArr;
    }
    else{
      newArr.splice(newArr.indexOf(arr[i]), 1);
    }
  }
  return newArr;
}

console.log(dropElements([1, 2, 3, 4], function(n) {return n >= 3;}));

Fairly certain there's no break you can use in a filter / map / reduce.

Re: Absent's Code Thread / Tech Blog

Idk if I 100% grasp how the spread operator is working here:

function steamrollArray(arr) {
  // I'm a steamroller, baby
  let retMe = [];
  arr.forEach(e => {
    if (Array.isArray(e)){
      retMe.push(...steamrollArray(e));
    }
    else{
      retMe.push(e);
    }
  });
  return retMe;
}

steamrollArray([[["a"]], [["b"]]]);

And why it doesn't work when applying it to (...e) instead of ...steamrollArray

Re: Absent's Code Thread / Tech Blog

loop city bitch

function binaryAgent(str) {
  let binaryArray = str.split(' ');
  let hexArray = [];
  let retArray = [];
  binaryArray.forEach(x => {
    let i = 0;
    let hexCount = 0;
    while (i < 8){
      if(x.split('').reverse()[i] == 1){
        hexCount += Math.pow(2,i);
      }
      i++;
    }
    hexArray.push(hexCount);
  });
  hexArray.forEach(hexStr => {
    retArray.push(String.fromCharCode(hexStr));
  });
  return retArray.join('');
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

I did this with zero help which is cool. Just had to remember how to convert to binary from Uni and then think of a way to implement. Not particularly hard or anything but still.

Re: Absent's Code Thread / Tech Blog

function truthCheck(collection, pre) {
  let shit = [];
  collection.filter(x => shit.push(x[pre] != undefined && x[pre] != 0 
  && x[pre] != "" && !Number.isNaN(x[pre])));
  let thing = 0;
  shit.forEach(y => {
    if(y == true)
      thing++;
  });
  return thing == shit.length;
}

truthCheck([{"single": "double"}, {"single": NaN}], "single");

bloop

Re: Absent's Code Thread / Tech Blog

function addTogether(){
  let shit = [];
  if(arguments.length == 1){
    let first = arguments[0];
    if (typeof(first) == 'number'){
      return function(newArg){
        if (typeof(newArg) != 'number')
          return undefined;
        else {return newArg + first;}
      }
    }
    else{
      return undefined;
    }
  }
  for(let i = 0; i < arguments.length; i++){
    shit.push(arguments[i]);
  }
  let checkMe = 1;
  shit.forEach(x => {
    if (typeof(x) != 'number'){
      checkMe = -1;
    }
  });
  if(checkMe == -1) return undefined;
  else return shit.reduce((acc, newstuff) => (acc + newstuff));
}

addTogether(2)([3]);
addTogether(2, "3");
addTogether(2,3);

That was painful.

Re: Absent's Code Thread / Tech Blog

var Person = function(firstAndLast) {
  let arr = firstAndLast.split(' ');
  this.getFirstName = function() {
    return arr[0];
  };
  this.getLastName = function(){
    return arr[1];
  };
  this.getFullName = function(){
    return arr[0] + " " + arr[1];
  };
    this.setFirstName = function(newFirst){
    arr.splice(0, 1, newFirst);
  };
  this.setLastName = function(newLast){
    arr.splice(1, 1, newLast);
  };
  this.setFullName = function(newFirstAndLast){
    arr = newFirstAndLast.split(' ');
  };
  
  return firstAndLast;
};

var bob = new Person('Bob Ross');

Re: Absent's Code Thread / Tech Blog

function orbitalPeriod(arr) {
  let realManArr = [];
  let realHumanArr = [];
  let retArray = [];
  arr.forEach(x => {
    realManArr.push(x.avgAlt);
    realHumanArr.push(x.name);
  }); 
  var GM = 398600.4418;
  var earthRadius = 6367.4447;
  let twoPi = 2 * Math.PI;
  for (let i = 0; i < arr.length; i++){
    let a3 = Math.pow((earthRadius + realManArr[i]),3);
    let term = a3 / GM;
    let orbitalPeriod = Math.round(twoPi * Math.sqrt(term));
    retArray.push({"name": realHumanArr[i], "orbitalPeriod": orbitalPeriod});
  }
  return retArray;
}

orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}]);

real man

Re: Absent's Code Thread / Tech Blog

Hey I'm getting pretty okay at this.

function palindrome(strorig) {
  let str = strorig.toLowerCase().replace(/[^a-z0-9]/g, "");
  let thing = str.split('');
  let thingReverse = str.split('').reverse().join('').split('');
  let j = str.length; 
  let x = false;
  let truthArray = [];
  for(let i = 0; i < str.length; i++){
    j--;
    if (thing[i] == thing[j]){
      truthArray.push(true);
    }
    else truthArray.push(false); 
  }
  if(truthArray.includes(false)) return false;
  else return true;
}


palindrome("_eye");

Not saying that's a great implementation but I'm tired as fuck and it only took me a little while to do. I think I'd fuck it up trying to white board it because I couldn't remember all the names of methods they build in but still.

Re: Absent's Code Thread / Tech Blog

function convertToRoman(num) {
  let decimalCount = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 
                      5, 4, 1];
  let romanNumerals = ["M", "CM", "D", "CD", "C", "XC", "L", 
                      "XL", "X", "IX", "V", "IV", "I"]

  let shit = [];
  let count = num;
  for(let i = 0; i < decimalCount.length; i++){
    while (decimalCount[i] <= count){
      shit.push(romanNumerals[i]);
      count -= decimalCount[i];
    }
  }
  return shit.join('');
}

console.log(convertToRoman(798));

This one fucked me up. I did not get it on my own at all. I was writing a version that would have taken FOREVER to finish writing, like every 10 I had to write another if statement or something. Then I was trying to think of a way to do it by the 100 or something, but it changes too much per thing. I couldn't even really understand the solution until I read the solution and tested it and "debugged" it because it doesn't work in a way that was intuitive to me. Kind of disappointed in my brain but okay. Whatever. Plus I was trying to use an object instead of these two arrays, but objects are apparently unordered (and it's up to the browser how to order them), and you kind of have to interpret shit backwards.


Idk. I think if I spent many frustrating days on this I would have gotten it eventually but... Fuck that.

Re: Absent's Code Thread / Tech Blog

Welp, that helped my confidence.

function rot13(str) { 
  let strArr = str.split('');
  let retMe = [];
  strArr.forEach(x => {
    let code = String.charCodeAt(x);
    if (code >= 65 && code <= 90){
      if (code <= 77){
        retMe.push(String.fromCharCode(code + 13));
      }
      else if(code >= 78){
        retMe.push(String.fromCharCode(code + 13 - 26));
      }
    }
    else retMe.push(x);
  });
  return retMe.join('');
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

Implemented Rot 13 in like 10 minutes, or less probably.

Re: Absent's Code Thread / Tech Blog

Clusterfuck, but it works:

function telephoneCheck(str) {
  let ret = true;
  if (str.length > 16){
    return false;
  }
  let numCount = 0;
  let trimStr = str.replace(/ /g, '');
  let strArr = trimStr.split('');
  strArr.forEach(x => {
    if(isNaN(x) == true && x != "-" && x != "(" && x != ")"){
      console.log(x);
      ret = false;
    }
    if (!isNaN(x)){
      numCount++;
    }
    if (strArr.includes(")") && !strArr.includes("(")) ret = false;
    if (strArr.includes("(") && !strArr.includes(")")) ret = false;
    if (strArr[strArr.length - 1] == ")") ret = false;
  });
  console.log(numCount);
  if (numCount < 10 || numCount > 11) return false;
  if (numCount == 11){
    if (strArr[0] != 1) return false;
  }
  return ret;
}

//telephoneCheck("555-555-5555");
//console.log(telephoneCheck("123**&!!asdf#"));
//telephoneCheck("1 555-555-5555");
telephoneCheck("1 555)555-5555");

ONE MORE ALGORITHM TO GO BEFORE I FINISH UP MY FUCKING 300 HOUR DATA STRUCTURE AND ALGO CERTIFICATION ayy