madbernard: a long angled pier (Default)
Just did a Coderbyte challenge that was, "given an array of numbers that could be positive or negative but which will not include 0, return 'Arithmetic' for arrays where there's the same distance between all the numbers, 'Geometric' for arrays where there's the same multiple between all the numbers, and -1 for everything else." My answer isn't the best it could possibly be (I feel that I'm using Math.abs poorly, and I should have taken a moment more to make the reduce part bring back the biggest number in the difference array... averages can be deceiving), but looking at answers from unnamed other people, several of them don't even work. This one only compares the gap in numbers of the first two and last two in the array:
function ArithGeo(arr) { 
  var isArithmetic=(arr[1]-arr[0]==arr[arr.length-1]-arr[arr.length-2]);
  var isGeometric=(arr[1]/arr[0]==arr[arr.length-1]/arr[arr.length-2]);
  // code goes here  
  if(!isArithmetic&&!isGeometric){//is not special
    return -1;
  }else{
    return (isArithmetic)?'Arithmetic':'Geometric';
  }
}
It can be defeated with [1,2,45,99,100]. I saw this same pattern three times in like six answers I looked over. Interesting to catch stuff that the tests don't. When I started this post I was feeling a cheerful about not being at the bottom of the heap, but now I'm a bit sad. Anyway, here's my answer. Tell me about better ways of checking that every number in an array is the same... I could have done another for loop, "if difference array [i] !== difference array [0] return false"...
function ArithGeo(arr) { 
  var geo = [];
  var arith = [];
  for (var i = 0; i < arr.length - 1; i++) {
    geo.push(Math.abs(arr[i + 1] / arr[i]));
    arith.push(Math.abs(arr[i + 1] - arr[i]));
  }
  var sumGeo = geo.reduce(function(prev, curr){
    return prev + curr;
  });
  var sumArith = arith.reduce(function(prev, curr){
    return prev + curr;
  });
  if (sumGeo / geo.length === geo[0]) {return 'Geometric';}
  if (sumArith / arith.length === arith[0]) {return 'Arithmetic';}
  return -1; 
}
madbernard: a long angled pier (Default)
Here's one I thought would be simple, which wasn't. The problem is, "return a count of all the vowels (not y) in a string." I thought I'd use regex.exec to capture an array of vowels and find the length of the array... But it only ever returned length 2. I see in the Mozilla Developer Network info page that RexExp.length is 2, but I don't know why I'm getting that here. Can someone troubleshoot?
function VowelCount(str) { 
  var re = /([aeiou])/ig;
  var arr = re.exec(str);
  console.log(arr);
  return arr.length; 
}

console.log(VowelCount('moooo'));
So I pivoted to for loops and came up with this,
function VowelCount(str) { 
  var re = /[aeiou]/i;
  var count = 0;
  for (var i = 0; i < str.length; i++) {
    if (re.test(str.charAt(i))) {
      count += 1;
      console.log(i);
  }
  return count; 
}
This also took some troubleshooting, since the count was wrong when I was using the 'g' flag in the regex. I'm also not sure why that was. Other people I looked at also had mangled looking answers, though of course Matt Larsh has something good,
function VowelCount(str) { 
  var vowels = str.match(/[aeiou]/g);
  return vowels.length;
}
Looks like I need to bone up on str.match.
madbernard: a long angled pier (Default)
Challenge 5 was, given a number between 1 and 1000, add up all the numbers inclusive in that set. Obviously I could repurpose Matt Larsh's recursive function to do this, so I did so, and it worked first try. Woo! Though, no one else seems to be doing +=. I wonder if this would be super wrong if I wasn't recursing and thus seeing it only once each function call? Or do they just like num + SimpleAdding(stuff)?
function SimpleAdding(num) {
  if (num === 1) {
    return 1;  
  }
  else {
    return num += SimpleAdding(num - 1);
  }      
}
Challenge 6 was one I hadn't yet solved in Free Code Camp: Capitalize every word in a string. I abandoned a couple different paths while trying for speed, and eventually came up with this answer that seems cludgy:
function LetterCapitalize(str) { 
  var foo = str.split('');
  var bar = [];
  bar.push(foo[0].toUpperCase());
  for(var i = 1; i < foo.length; i++) {
    if (foo[i - 1] === ' ') {
      bar.push(foo[i].toUpperCase());
    }
    else {
      bar.push(foo[i]);
    }    
  }
  console.log(bar.join(''));
  return bar.join('');
}
LetterCapitalize('to see how to enter arguments in JavaScript');
I tried replacing the space in the if statement with /\s/ and that didn't work, nor did /\s/g; I'm not sure why not.

One of my abandoned paths was to do a str.replace(regex, function) but I wasn't getting the function to work... So I was super curious to see what Matt Larsh did, and sure enough he did something cool:
function LetterCapitalize(str) { 
  return str.replace(/\b[a-z]/g,function(c){return c.toUpperCase()});
}
That "\b" was something I thought should exist, but didn't find: the signal for "match a word boundary". I just tried /\b\w/g and that works, too; I suppose his way is better, though, since it limits the capitalization to only things that we absolutely know need capitalizing. Unless if \w includes accented letters and other slightly less usual things? My RegEx skillz are not yet l33t and m4d.
madbernard: a long angled pier (Default)
The next Free Code Camp exercise is to find the length of the longest word in a string (and all of their test strings are free of anything but letters and single spaces). Good points: I had no trouble getting the shape of the solution, and split totally worked great. Actually doing the proper syntax for Reduce required a lot of searching, though, and eventually I basically copied a bit from this webpage about getting comfy with arrays. I should work through that website sometime... Most of the failed reduce trials I don't have copies of, but one that I don't understand is that when I had a 0 in the place I thought was for initial value, right after the anonymous function and before the console.log error-catching readout, here: }, 0);
console.log(foo.length);
what I got out of the function was only 0. Baffling. Below is code that works. :)

function findLongestWord(str) {
var words = str.split(' ');
var foo = words.reduce(function(prevWord, thisWord){
if (thisWord.length > prevWord.length) {
return thisWord;
}
else {
return prevWord;
}
});
console.log(foo.length);
return foo.length;
}

findLongestWord('The quick brown fox jumped over the lazy dog');
madbernard: a long angled pier (Default)
So, 4 was trivial, which was great: make a function that factorializes numbers. Like, 5! is 1 * 2 * 3 * 4 * 5 = 120.

function factorialize(num) {
for (var i = (num - 1); i > 0; i--) {
num *= i;
}
return num;
}

factorialize(5);

But 5... I feel like I shouldn't have to make my own function that takes an array and jams it all into a single string without commas separating the bits. But the concat stuff I was looking at in the Mozilla Developer Network wasn't working that way (even though their example shows it should. So baffled).

And I feel like there must be some way to not declare like 7 variables... But I couldn't figure out how to chain these methods/functions. Anyway: here it is, a function that checks if a statement is a palindrome (ignoring all the non-letter things! The RegEx stuff was honestly fun learning).

function reverseString(str) {
var reverseStr = '';
for (var i = str.length - 1; i > -1; i--){
reverseStr += str[i];
}
return reverseStr;
}

function arrToRevStr(arr) {
var str = '';
for (var i = arr.length - 1; i > -1; i--){
str += arr[i];
}
return str;
}

function palindrome(str) {
var cleanStrArray = /(\w)/g.exec(str);
var cleanStr = arrToRevStr(cleanStrArray);
var cleanStrLow = cleanStr.toLowerCase();

var reverseStr = reverseString(str);
var cleanReverseStrArray = /(\w)/g.exec(reverseStr);
var cleanReverseStr = arrToRevStr(cleanReverseStrArray);
var cleanReverseStrLow = cleanReverseStr.toLowerCase();

if (cleanStrLow == cleanReverseStrLow) {return true;}
else {return false;}
}

palindrome("eye");
madbernard: a long angled pier (Default)
I feel like I've reversed a string before... I vaguely remember something about halving the length and swapping things around the middle. But this time, when Free Code Camp asked for it as their very first JavaScript coding exercise, I just looped through the entire thing. Woooo!

function reverseString(str) {
var reverseStr = '';
for (var i = str.length - 1; i > -1; i--){
reverseStr += str[i];
console.log(reverseStr);
}
return reverseStr;
}

reverseString('hello');

At first I had just defined the reverseString variable as "var reverseStr;", and the readout I was getting from that console.log in the loop was "NaNo" "NaNol" etc. Second debugging step, when I made the start point of the loop i = str.length - 1 instead of i = str.length, I got "undefinedo" "undefinedol" "undefinedoll" etc. So in the first case it was trying to add the nothing in "hello"[5] to NaN, since why, the sensible programming language thinks, would I be trying to use an addition operator, +, on anything but a number? I'm not sure why trying to add "o" worked; I suppose JavaScript decided that the o it was getting meant that it should be adding to a string or object or some non-number thing, but that string or object or whatever wasn't defined. It's nice that when it failed at adding it relapsed to concatenating.

...I suspect this is a terrible implementation of reversing a string. Any takers?

The Free Code Camp at this point suggests I should be pairing, and a nice guy in the chat room linked me up with a copy of Screenhero (they've joined Slack and are not taking new signups unless someone already inside invites you in), which they suggest is good for being able to remotely cowork and see everything on another screen... Another guy in the chat suggested coderpad.io or another .io solution instead, as less dangerous and better functioning. What do people think, re: screen sharing programs?
madbernard: a long angled pier (Default)
I'm grimly slogging through the Javascript track of Codecademy again. Ticking off the boxes for Free Code Camp. The "address book" bit with Bill Gates etc was particularly annoying. Did they ever explain For/In loops? Every other thing Codecademy does is massively slow and information sparse, and then suddenly they expect you to know For/In?

But! Plus side, the people behind the Free Code Camp Twitter account let me know they're building their own Javascript course, so someday Codecademy will be back in its own box for people who are happy with how it works!

Also, I've been taking breaks by reading the massive "What is Code" article at Bloomberg that was going around a few weeks back. It pointed out a quirk in Javascript that I hadn't seen elsewhere, which you can recreate right now (in at least Chrome and Firefox)... F12 to get the Developer Tools open, go to the Console tab, type in 0.2 + 0.4, hit enter. Answer: 0.6000000000000001

I found this page that explains Floating Point errors in Javascript. The upshot is, the computer stores decimal fractions as binary fractions, and sometimes there's no exact match, so it uses the closest binary fraction it has. And you get around this by rounding. I wonder if this is something that people who code JS for a living do all the time?
madbernard: a long angled pier (Default)
I've been through the first few chapters of the Aquent Gymnasium Javascript Foundations course, but that's momentarily on hold due to the Grim Flash Bugs of Hacking Team... Before that, I had some fun learning how to screw around with developer tools: F12 toggles the modern update of "view source", where you can look if webpages you visit have scripts that log things to the console, look at the scripts and how they're written, interesting stuff like that.

Around the 4th I had the idea that it would be fun to make a program that would show you the layout of the stars on the American flag (the star area is called the "union", apparently) once we added Puerto Rico as a state... And for any number of states, really. My thought was to use the brute-force ability of programs, find every rectangle that contains the right number of stars (like, for 9: 1x9, 4+5, 3x3, 5+4, 9x1) and then compare their proportions to the proportions of the union, and I got all the sub bits working. However, I've gotten hung up on the math, and looping, that breaks the number of stars into possible rectangles. I need something that will return an array of every grouping that adds to the correct number of stars, where the groupings are an even number of rows of length "X" plus any number of rows of length "X-1". (The flag has, in the past, looked like an I-beam).

A friend of mine at Amazon pointed out this online thing for learning to code Javascript, Free Code Camp. The idea is that once you know just enough to be useful, you start being of use by coding actual projects for nonprofits that sign up with them; and then you have a portfolio of work to use to get a job. Sounds pretty great, though today I hit the JQuery section and it popped me over to Codecademy... I did that last year, when it was Code Year ("Learn to code in a year!"), and it's not my style. It takes minutes of cutting and pasting at their direction to be able to shake out a bit of actual information, and they rarely explain the reasons behind anything. I vastly prefer just reading everything at once and having more freedom to build a thing...

But I know much more about CSS, now, so woo!
madbernard: a long angled pier (Default)
People on Amazon and elsewhere seem to agree that they do not grok the Table example, so I was curious to get to it. I also don't read it on first pass. I didn't read the squirrel/phi example last chapter, though, either... This one doesn't seem deeper in the weeds than that, at first pass.

I don't understand polymorphism. Inheritance seems simple, but that may be because I vaguely remember that CodeAcademy Javascript, which I did a year ago, hit that hard. Polymorphism seems like it might be like cell biology... Like, many proteins have zinc fingers, structures that hold out a metal ion to interface with other proteins structures. When you see one, you have an idea what that protein/program is going to be up to. But that's just a guess.

Right now I don't understand something fundamental about wording in Javascript... Like, "line" seemed important in his example, but searching the page, it just suddenly appears in the TextCell constructor. I think it's drawing from the array/object inputs, but I need to track down how. For my own code I suspect I'll be doing a ton of veryLongWordyThingThatExplainsBetter, for awhile.
madbernard: a long angled pier (Default)
There I was on Eloquent Javascript's problem 5.4, http://eloquentjavascript.net/05_higher_order.html#h_jr7hZiuR7+

The for loop seemed simple, but what I came up with wasn't processing "isNaN" as a function.

var every = function (array, compare) {
for (var i = 0; i < array.length; i++) {
if (array.i !== compare)
return false;
else return true;
}
};

console.log(every([NaN, NaN, NaN], isNaN));
// → should be true, but was showing as false
console.log(every([NaN, NaN, 4], isNaN));
// → false


Putting the "compare" in the if condition in () parentheses (because I had a memory that some form of parentheses would make javascript try to find the value of a thing... Thinking about this, that was probably a memory from getting values of keys, done with [], which in this case I believe would flag "compare" as an array) didn't fix it. Trying for != to allow for type conversion didn't fix it.

I looked at the hints, and they didn't talk about making functions do their thing; they talked about setting up the loop like "forEach". I took an abortive stab at redoing the loop to use forEach... This didn't run, and the linter in JSBin was sad about my use of break. (I'm still not sure what's up with break.)

function every (array) {
array.forEach(function(compare) {
if (array !== compare) {
break;
}
else return true;
});
return false;
}


I tabbed over to the annotated book: https://docs.google.com/document/d/1aa2-HtUglQrAps31s4LdTPVsiFb1BxhyjZolxeezzcI/edit?_escaped_fragment_=#!
Predicate functions were never defined in the book so I’ll quickly explain them here.

A predicate function is a function that returns true or false based on some condition. In this problem, we’re using isNaN(testValue), which returns true if testValue is NaN (remember this means not a number), and false otherwise.

Huh. At first that seemed a bit unfair, a new unexplained type of function. But then, a closer reading would have indicated that the compare thing had to be a function; and I'd even previously went back to the appearance of isNaN in Eloquent Javascript and managed to whizz past the part where it was summoned into action like so, isNan("some thing").

The working answer,
var every = function (array, compare) {
for (var i = 0; i < array.length; i++) {
if (!compare(array[i]))
return false;
}
return true;
};

And "some" is trivial from there.

May 2016

S M T W T F S
1234567
8910 11121314
15161718192021
22232425262728
293031    

Syndicate

RSS Atom

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 22nd, 2017 11:59 am
Powered by Dreamwidth Studios