Open Side Menu Go to the Top
Register
Programming homework and newbie help thread Programming homework and newbie help thread

10-10-2015 , 05:53 AM
Disclaimer: I've never written a word of Ruby. I'm going to talk about things from a general OO programming point of view. Some terminology may vary in Ruby.

The initialize method in Ruby is an example of a constructor, which is a method called when an instance of a class is instantiated. If you do not include a constructor, the compiler creates one called a default constructor. In Ruby this would be:

Quote:
def initialize()
end
However, if you write your own constructor, the compiler stops including the default one. The reason is that you may not want your class to be able to be created without initializing it. For instance, if you have a Circle class, you might want to prevent people creating an instance of it without specifying a radius. Circle gotta have a radius.

So I assume what you want in Ruby is this (someone correct me if I'm wrong):

Code:
class Person
  attr_accessor :name
  attr_accessor :age

  def initialize()
  end

  def initialize(newage, newname)
    @age = newage
    @name = newname
  end

  def display
    puts "I am aged #{@age} and my name is #{@name}"
  end
end
Note that in my usual language, C#, creating an instance with the default constructor and then calling display() would throw a NullReferenceException because @age and @name have not been set. No idea what happens in Ruby.
Programming homework and newbie help thread Quote
10-10-2015 , 10:05 AM
When you use the initialize method, it seems you must always pass the right amount of arguments to it when creating a new instance. So the following works.

Code:
class Person

  attr_accessor :gender


  def initialize(name, age)
    @name = name
    @age = age
  end

  def display
    puts "Aged #{@age} and named #{@name}"
  end
end



p1 = Person.new('Tim', '21')
p1.display


p3 = Person.new('' , '')
p3.gender = "male"
puts p3.gender




I suspect I'm missing the point of the excercise though conidering the question again: ( or maybe not?)
Question 4:
Create a class named person with a name and an age.
Use the initialize() method.
Use attr_accessor to create the get and set methods.
Programming homework and newbie help thread Quote
10-10-2015 , 10:13 AM
Quote:
Originally Posted by mackeleven
When you use the initialize method, it seems you must always pass the right amount of arguments to it when creating a new instance.
I mean... yeah. That goes for any method call. But there neednt be only one initialize method. Have you covered method overloading yet?
Programming homework and newbie help thread Quote
10-10-2015 , 10:24 AM
No. Although the course is moving hella fast. I should know html, javascript, Java, Ruby on Rails, C# asp.net, css just a month in lol (coming from an engineering background that had C and assembly)
Programming homework and newbie help thread Quote
10-10-2015 , 11:26 AM
Ok I have found this works which might be more like it
Code:
class Person

  attr_accessor :new_name
  attr_accessor :new_age

   def initialize(name = "Mike", age = "35")
    @name = name
    @age = age
   end

  def display
    puts "Aged #{@age} Named #{@name}"
  end
end



p1 = Person.new('Tim', '21')
p1.display


p2 = Person.new
p2.display

p3 = Person.new
p3.new_name = "Max"
p3.new_age = "25"
puts ("Aged #{p3.new_age} Named #{p3.new_name}")
output:
Aged 21 Named Tim
Aged 35 Named Mike
Aged 25 Named Max
Programming homework and newbie help thread Quote
10-12-2015 , 12:29 PM
I've been learning C from the K&R book for the past few months. To pull it all together, I decided to write a program that has (part of) the same functionality as one of the commands in my favorite data and statistics program.

Ended up being a headache, but I learned a lot in doing so. Does it make me a masochist if I like coding in C?

If anybody cares to take a look at the code, I would really appreciate hearing ways to improve. The print_table function in particular seems wonky and there must be a better way to implement that.

Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXLENGTH 20
#define ROWS 21
#define CHARS 256
#define LINES 5
#define DEL 127
#define MEMBERS 14
#define FORMAT "  %-24s%15s    %-19s%15s\n"

typedef struct  {
    unsigned long n;
    char s[MAXLENGTH];
} cell;

struct filestats {
    cell counts[CHARS];
    cell windows;
    cell mac;
    cell unix;
    cell ctl;
    cell extctl;
    cell uc;
    cell lc;
    cell digit;
    cell special;
    cell extended;
    cell filesize;
    cell lengths[LINES];
    cell lmin;
    cell lmax;
    cell lnum;
    cell eoleof;
    char * format;
};

struct row {
    char * a; 
    char * b; 
    char * c; 
    char * d;
};

int count_chars(FILE *, struct filestats *);
int other_stats(struct filestats *);
void create_strings(struct filestats *);
int print_table(struct filestats *);

int main(int argc, char *argv[])
{
    struct filestats stats = {0};
    FILE *fp;
    
    if (argc == 1) {
        printf("invalid file specification\n");
        return 1;
    }
    
    if ((fp = fopen(*++argv, "rb")) == NULL) {
        printf("hexdump: can't open %s\n", *argv);
        return 1;
    } else {
        count_chars(fp, &stats);
        fclose(fp);
        other_stats(&stats);
        create_strings(&stats);
        print_table(&stats);
    }
    return 0;
}

int count_chars(FILE *fp, struct filestats *stats)
{
    char c, prev = '\0';
    int len = 1, line = 0;
    
    while ((c = (char) getc(fp)) != EOF) {
        ++stats->counts[(unsigned char) c].n;
        if (c != '\n' && c != '\r')
            ++len;
        else if (prev == '\r' && c == '\n')
            ++stats->windows.n;
        else {
            if (line <= LINES) {
                stats->lengths[line++].n = len;
            }
            if (len < stats->lmin.n || stats->lmin.n == 0)
                stats->lmin.n = len;
            if (len > stats->lmax.n)
                stats->lmax.n = len;
            len = 1;
        }
        prev = c;
    }
    stats->eoleof.n = (prev =='\r' || prev == '\n');
    strncpy(stats->eoleof.s, stats->eoleof.n ? "yes" : "no", MAXLENGTH);
    return 0;
}

int other_stats(struct filestats *stats)
{
    int i;
    char c;
    unsigned long count;
    
    for (i = 0; i < CHARS; ++i) {
        count = stats->counts[i].n;
        c = (char) i;
        stats->filesize.n += count;
        if (i > 0 && i < 32 && i != '\n' && i != '\r'  && i != '\t')
            stats->ctl.n += count;
        else if ((i >= 128 && i <= 159) || i == 255)
            stats->extctl.n += count;
        else if (isupper(c))
            stats->uc.n += count;
        else if (islower(c))
            stats->lc.n += count;
        else if (isdigit(c))
            stats->digit.n += count;
        else if (isgraph(c) && i != ',')
            stats->special.n += count;
        else if (i >= 160 && i <= 254)
            stats->extended.n += count;
    }
    stats->mac.n = stats->counts['\r'].n - stats->windows.n;
    stats->unix.n = stats->counts['\n'].n - stats->windows.n;
    stats->lnum.n = stats->windows.n + stats->mac.n + stats->unix.n;
    if (stats->ctl.n + stats->extctl.n + stats->counts['\0'].n //
        + stats->counts[DEL].n)
        stats->format = "BINARY";
    else
        stats->format = ((stats->extended.n) ? "EXTENDED ASCII" : "ASCII");
    return 0;
}

void convert(cell *);

void create_strings(struct filestats* st)
{
    int i;
    cell *members[] = {
        &st->windows, &st->mac, &st->unix, &st->ctl, &st->extctl, &st->uc, 
        &st->lc, &st->digit, &st->special, &st->extended, &st->filesize, 
        &st->lmin, &st->lmax, &st->lnum
    };
    
    for (i = 0; i < CHARS; ++i)
        convert(&st->counts[i]);
    for (i = 0; i < LINES; ++ i) {
        convert(&st->lengths[i]);
        if (!st->lengths[i].n)
            strncpy(st->lengths[i].s, ".", MAXLENGTH);
    }
    for (i = 0; i < MEMBERS; ++ i)
        convert(members[i]);
}

void itoa(unsigned long, char *);
void reverse(char *);
void add_commas(char *);

void convert(cell * x)
{
    itoa(x->n, x->s);
    add_commas(x->s);
}

int print_table(struct filestats* st)
{
    struct row *r, table[ROWS] = {
        "Line-end characters", "", "Line length (tab=1)", "",
        "  \\r\\n         (Windows)", st->windows.s, "  minimum", st->lmin.s,
        "  \\r by itself (Mac)", st->mac.s, "  maximum", st->lmax.s,
        "  \\n by itself (Unix)", st->unix.s, "", "",
        "Space/separator characte", "rs             ", "Number of lines", //
            st->lnum.s,
        "  [blank]", st->counts[' '].s, "  EOL at EOF?", st->eoleof.s,
        "  [tab]", st->counts['\t'].s, "", "",
        "  [comma] (,)", st->counts[','].s, "Length of first 5 l", //
            "ines           ",
        "Control characters", "", "  Line 1", st->lengths[0].s,
        "  binary 0", st->counts['\0'].s, "  Line 2", st->lengths[1].s,
        "  CTL excl. \\r, \\n, \\t", st->ctl.s, "  Line 3", st->lengths[2].s,
        "  DEL", st->counts[DEL].s, "  Line 4", st->lengths[3].s,
        "  Extended (128-159,255)", st->extctl.s, "  Line 5", st->lengths[4].s,
        "ASCII printable", "", "", "",
        "  A-Z", st->uc.s, "", "",
        "  a-z", st->lc.s, "File format", st->format,
        "  0-9", st->digit.s, "", "",
        "  Special (!@#$ etc.)", st->special.s, "", "",
        "  Extended (160-254)", st->extended.s, "", "",
        "", "---------------", "", "",
        "Total", st->filesize.s, "", ""
    };
    int i;
    char *string_b[16], *string_c[18];
    
    printf("\n");
    for (i = 0; i < ROWS; ++i) {
        r = &table[i];
        printf(FORMAT, r->a, r->b, r->c, r->d);
    }
}

void itoa(unsigned long n, char * s)
{
    char * i = s;
    
    do {
        *i++ = n % 10 + '0';
    } while ((n /= 10) > 0);
    *i = '\0';
    reverse(s);
}

void reverse(char * s)
{
    int c;
    char *j;
    
    for (j = s+strlen(s)-1; s < j; s++, j--)
        c = *s, *s = *j, *j = c;
}

void add_commas(char * s)
{
    int commas, i;
    commas = (strlen(s) - 1) / 3;
    
    for (s += strlen(s), i = 0; commas > 0; --s, ++i) {
        *(s + commas) = *s;
        if (i > 0 && !(i % 3))
            *(s - 1 + commas--) = ',';
    }
}
Here is what the output looks like when you run the program on the source file.

Code:
  Line-end characters                        Line length (tab=1)               
    \r\n         (Windows)            236      minimum                        1
    \r by itself (Mac)                  0      maximum                       74
    \n by itself (Unix)                 0                                      
  Space/separator characters                 Number of lines                236
    [blank]                           662      EOL at EOF?                  yes
    [tab]                             276                                      
    [comma] (,)                       130    Length of first 5 lines           
  Control characters                           Line 1                        19
    binary 0                            0      Line 2                        19
    CTL excl. \r, \n, \t                0      Line 3                        20
    DEL                                 0      Line 4                        21
    Extended (128-159,255)              0      Line 5                        16
  ASCII printable                                                              
    A-Z                               204                                      
    a-z                             2,549    File format                  ASCII
    0-9                               107                                      
    Special (!@#$ etc.)             1,210                                      
    Extended (160-254)                  0                                      
                          ---------------                                      
  Total                             5,610
Programming homework and newbie help thread Quote
10-13-2015 , 06:50 PM
finally made a coderbytes account just to keep track of progress on problems there

do the first question as a warmup, reverse a string

write the code, test it twice, submit it - all test cases incorrect.

WTF?

Change it slightly so maybe it does what they want a little more closely. All test cases incorrect.

Okay....

Check one of the top rated answers for the problem, it's almost exactly a carbon copy of what I wrote to begin with.

ffs, this place

edit

just tried copy+pasting other code that got a perfect score. When I submit it, I get them all wrong.

Fun times.

Last edited by Roonil Wazlib; 10-13-2015 at 07:03 PM.
Programming homework and newbie help thread Quote
10-14-2015 , 05:48 AM
Roonil,

change your avatar back!
Programming homework and newbie help thread Quote
10-14-2015 , 09:43 AM
No! I like gun dog!

Also,

Solved their char shift problem. Score of zero ldo. Check one of the top rated submissions and it's actually wrong. Doesn't handle caps properly the way mine does.

So, apparently being right isn't always a good thing for coderbytes.

Time to find a new place to practice algorithms.
Programming homework and newbie help thread Quote
10-14-2015 , 10:01 AM
Atta boy!
Programming homework and newbie help thread Quote
10-14-2015 , 01:19 PM
Quick dumb question


Am I correct in assuming that
Horizontal scalability means how well ur system performs when u add more cores/threads(logical units). To the existing system

And vertical scalability means how well ur system performs when handling a larger data set?

When investigating vertical scalability do I have to keep the number of cores/threads constant?(seems counter intuitive)

Also, I kinda know the factors affecting horizontal scalability like amdahl's law etc

But what are the factors affecting vertical scalability??
Programming homework and newbie help thread Quote
10-14-2015 , 03:45 PM
sorry 1 more dumb question, how do u determine the memory footprint of a program or maybe just a loop??

is there a program that does it for you??
Programming homework and newbie help thread Quote
10-14-2015 , 06:38 PM
Quote:
Originally Posted by CyberShark93
sorry 1 more dumb question, how do u determine the memory footprint of a program or maybe just a loop??

is there a program that does it for you??
google "memory profiler" for whatever platform you're running.
Programming homework and newbie help thread Quote
10-15-2015 , 12:34 AM
Quote:
Originally Posted by CyberShark93
Quick dumb question


Am I correct in assuming that
Horizontal scalability means how well ur system performs when u add more cores/threads(logical units). To the existing system

And vertical scalability means how well ur system performs when handling a larger data set?

When investigating vertical scalability do I have to keep the number of cores/threads constant?(seems counter intuitive)

Also, I kinda know the factors affecting horizontal scalability like amdahl's law etc

But what are the factors affecting vertical scalability??
I think you are a little confused about this.

Horizontal and Vertical Scaling
Quote:
To scale horizontally (or scale out) means to add more nodes to a system, such as adding a new computer to a distributed software application. An example might involve scaling out from one Web server system to three. As computer prices have dropped and performance continues to increase, high-performance computing applications such as seismic analysis and biotechnology workloads have adopted low-cost "commodity" systems for tasks that once would have required supercomputers. System architects may configure hundreds of small computers in a cluster to obtain aggregate computing power that often exceeds that of computers based on a single traditional processor. The development of high-performance interconnects such as Gigabit Ethernet, InfiniBand and Myrinet further fueled this model. Such growth has led to demand for software that allows efficient management and maintenance of multiple nodes, as well as hardware such as shared data storage with much higher I/O performance. Size scalability is the maximum number of processors that a system can accommodate.[4]
To scale vertically (or scale up) means to add resources to a single node in a system, typically involving the addition of CPUs or memory to a single computer. Such vertical scaling of existing systems also enables them to use virtualization technology more effectively, as it provides more resources for the hosted set of operating system and application modules to share. Taking advantage of such resources can also be called "scaling up", such as expanding the number of Apache daemon processes currently running. Application scalability refers to the improved performance of running applications on a scaled-up version of the system.[4]
There are tradeoffs between the two models. Larger numbers of computers means increased management complexity, as well as a more complex programming model and issues such as throughput and latency between nodes; also, some applications do not lend themselves to a distributed computing model. In the past, the price difference between the two models has favored "scale up" computing for those applications that fit its paradigm, but recent advances in virtualization technology have blurred that advantage, since deploying a new virtual system over a hypervisor (where possible) is almost always less expensive than actually buying and installing a real one.[dubious ] Configuring an existing idle system has always been less expensive than buying, installing, and configuring a new one, regardless of the model.
Programming homework and newbie help thread Quote
10-15-2015 , 12:38 AM
@econophile - gave a quick look see at your code. I need to copy it and look at it to give you a decent critique.
Programming homework and newbie help thread Quote
10-15-2015 , 08:36 AM
I looked at it super briefly. My impression was it was an unfortunate project because it was irreducibly messy. Not a lot of simplification to be done on a project where the idea is to do a billion different things depending on a million different possibilities.
Programming homework and newbie help thread Quote
10-15-2015 , 10:07 AM
Quote:
Originally Posted by adios
I think you are a little confused about this.

Horizontal and Vertical Scaling
Okay I understand now, so when investigating scalability i don't have to investigate input size at all right?
Programming homework and newbie help thread Quote
10-15-2015 , 06:32 PM
i'm analysing parallel performance, and these are the results that I got, a lot of it doesn't make sense =(
Code:
Threads                 Elapsed time(s)               CPU time(s)            Speed up          Efficiency(%)
1(Serial)                 211.7                              211.2                       1                        100
1(set threads=1)     229.2                              228.6                       0.92                    92
2                           118.1                              235.7                       1.79                    89.5
3                           87                                   259.7                       2.43                    81
4                           62.5                                249.3                       3.39                    84.5
5                           53.6                                267.5                       3.95                    79
6                           45.2                                270.5                       4.68                    78
8                           35.9                                286.3                       5.9                      73.2
12                         29.7                                355.1                       7.13                     60
16                         26.5                                427                          7.99                     50
first of all i don't understand why the efficiency increase at threads=4? (i timed it like 10 times), can any1 think of a reason why this might happen??

according to my profiler the serial part of my program is negligible compared to the parallel part(<0.1%, since we are required to time pretty much only the parallel part), the thing is pretty embarrassingly parallel.so according to Amdahl’s law my efficiency shouldn't decrease this quickly?

regarding parallel overheads:
PO(single thread)= time(single)/time(serial) - 1 = 10%

case threads = 2:

time(2threads)= (parallelportion/2 + 1- parallelportion + Paralleloverhead*2)*time(serial)
118 = (1/2 + 2*PO)*211
PO = 3%

and parallel overhead decreases as thread increases which makes sense, but now the efficiency drop doesn't make sense



so confused, please help =)
Programming homework and newbie help thread Quote
10-16-2015 , 05:14 AM
Quote:
Originally Posted by CyberShark93
...first of all i don't understand why the efficiency increase at threads=4? (i timed it like 10 times), can any1 think of a reason why this might happen??
Your system has 4 cores or 2 cores with hyper-threading. The OS manages a thread pool that essentially allocates a thread per core/hyper-thread. Once you go beyond 4 threads there are contention issues on at least one core.


Quote:
according to my profiler the serial part of my program is negligible compared to the parallel part(<0.1%, since we are required to time pretty much only the parallel part), the thing is pretty embarrassingly parallel.so according to Amdahl’s law my efficiency shouldn't decrease this quickly?

regarding parallel overheads:
PO(single thread)= time(single)/time(serial) - 1 = 10%

case threads = 2:

time(2threads)= (parallelportion/2 + 1- parallelportion + Paralleloverhead*2)*time(serial)
118 = (1/2 + 2*PO)*211
PO = 3%

and parallel overhead decreases as thread increases which makes sense, but now the efficiency drop doesn't make sense



so confused, please help =)
Not sure what you mean about efficiency drop. I just don't understand your table I guess and what all the columns mean.
Programming homework and newbie help thread Quote
10-16-2015 , 08:59 AM
Quote:
Originally Posted by adios
Your system has 4 cores or 2 cores with hyper-threading. The OS manages a thread pool that essentially allocates a thread per core/hyper-thread. Once you go beyond 4 threads there are contention issues on at least one core.




Not sure what you mean about efficiency drop. I just don't understand your table I guess and what all the columns mean.
By efficiency I mean:

Speed up/number of threads
Programming homework and newbie help thread Quote
10-16-2015 , 05:25 PM
Always have ways of doing things differently clanking around the back of the ol' noodle. Wanted to play around with fizzbuzz and came up with this.

Not entirely sure it's an improvement over checking for 3, 5, and 15 separately, but at least it's different than how I'd normally do it, I think.

Code:
public static String fizzBuzz(int x) {
        String fizz = "";
        if (x % 3 == 0)
            fizz += "Fizz";
        if (x % 5 == 0)
            return fizz += "Buzz\n";
        else
            return fizz.equals("") ? fizz += x + "\n" : (fizz += "\n");        
    }
Programming homework and newbie help thread Quote
10-16-2015 , 11:08 PM
Lots of digital ink has been written on the "idea" behind "fizzbuzz." One camp says do it however and move on to the next. Another camp says, "but they also want you to see that 3 and 5 are part of 15, what if they also want to add mod 2 = baz, mod 7 = bar, mod 11 = foo, mod 13 = yum, and so on? You really want to be checking all of those cases by hand?" Of course, camp two would then say there is a better way even, etc etc etc
Programming homework and newbie help thread Quote
10-17-2015 , 03:43 AM
I secretly think that fizzbuzz is designed to screen for OCD tendencies and not programming competency.
Programming homework and newbie help thread Quote
10-17-2015 , 06:21 AM
Quote:
Originally Posted by CyberShark93
By efficiency I mean:

Speed up/number of threads
Well there is a number of threads for a process where you will get max performance due to the way an OS manages their thread pools in that they tend to assign threads to use unused cores. So if you have 4 cores (2 cores with hyper-threading) you will tend to get max parrallelism from 4 threads. With 8 cores it would be 8 threads and so on.
Programming homework and newbie help thread Quote
10-17-2015 , 10:35 PM
Quote:
Originally Posted by Wolfram
I secretly think that fizzbuzz is designed to screen for OCD tendencies and not programming competency.
I suppose it is a good way to figure out what the interviewer is like as well. Write the most obnoxiously "wrong" version you can think of see the reaction.
Programming homework and newbie help thread Quote

      
m