News:

Happy New Year! Yes, the current one, not a previous one; this is a new post, we swear!

Main Menu

[C/C++] Joe vs Ergot: Code wars!

Started by Joe, September 27, 2005, 07:26:53 PM

Previous topic - Next topic

0 Members and 2 Guests are viewing this topic.

Joe

Quote1.) Don't #include <iostream.h>, #include <iostream>.  That's standard C++.
mmk. I think that should fix the need for -Wno-deprecated too.

Quote2.) Why are you using ASCII literals (0x30, 0x31) as characters?  '0' and '1' work fine.
Oops, my attempt to do that was with double quotes.

Quote3.) Why are you using printf() in a C++ program?  Use cout.  (Unless you're formatting strings).
Uh, hehe. *fix*

Quote4.) accum = accum - sub; == accum -= sub;
Yeah, I was having trouble with that. I'll check it out again.

Quote5.) You shouldn't put programming statements on the same line as I/O (IMO), for example: cin >> accum; if (accum) dosomething(); -- I think that's ugly.
I tend not to, but its much easier to follow in that particular instance, and looks cleaner. But usually, yeah, its ugly.

Quote6.) You should have come up with a better way to do what you did in the first program.  What if your project manager wanted you to convert 32-bit numbers?  Can you imagine typing out all those literals?  Or even macros? [edit]Hrm, your third go was better, but you still could have done better with it.  Why not just cin to an int and test for 1 or 0?  (Note that my program tested for illegal values also -- what would yours do if I put in a 2 or something?)[/edit]
If I had to convert a 32-bit number, I'd edit my program to allow that. If I had intended this to be distributed (in which case I should be shot =p), I would allow that, though. If you put a 2 in my program, 2!=1 so it would mistake it for a 0.
Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


MyndFyre

Quote from: Joe[e2] on September 28, 2005, 05:21:18 PM
Quote6.) You should have come up with a better way to do what you did in the first program.  What if your project manager wanted you to convert 32-bit numbers?  Can you imagine typing out all those literals?  Or even macros? [edit]Hrm, your third go was better, but you still could have done better with it.  Why not just cin to an int and test for 1 or 0?  (Note that my program tested for illegal values also -- what would yours do if I put in a 2 or something?)[/edit]
If I had to convert a 32-bit number, I'd edit my program to allow that. If I had intended this to be distributed (in which case I should be shot =p), I would allow that, though. If you put a 2 in my program, 2!=1 so it would mistake it for a 0.
My point was this:

  cin >> i; if(i = 1) { accum = accum + 128; }
  cin >> i; if(i = 1) { accum = accum +  64; }
  cin >> i; if(i = 1) { accum = accum +  32; }
  cin >> i; if(i = 1) { accum = accum +  16; }
  cin >> i; if(i = 1) { accum = accum +   8; }
  cin >> i; if(i = 1) { accum = accum +   4; }
  cin >> i; if(i = 1) { accum = accum +   2; }
  cin >> i; if(i = 1) { accum = accum +   1; }

If you were going to do it that way, then you'd need to go back and enter the literals for every case in a 32-bit (or arbitrary-length) number.

My point was that, you should look for a better algorithm to do something like this the first time (before you code x += literals 8 times) so that you didn't have to go back to fix it.

An alternative way doing something a LOT closer to what you were doing:


inline void accumTest(int &accum, int input, int pass)
{
  if (i == 1)
    accum |= (1 << pass);
}
// then where that series of code is:
// (that's the cin >> i; if (i == 1) accum = accum + literal;)
for (int n = 7; n <= 0; n++)
{
  cin >> i;
  accumTest(&accum, i, n);
}

That's called "refactoring," or splitting up function blocks so that operations are repeated less-frequently within code blocks.

Code cleanliness: increased.  Code writing: decreased overall.
Quote from: Joe on January 23, 2011, 11:47:54 PM
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Quote from: Rule on May 26, 2009, 02:02:12 PMOur species really annoys me.

Ergot

Mynd didn't I tell you I was a horrible programmer ;D ?
Quote from: Newby on February 26, 2006, 12:16:58 AM
Who gives a damn? I fuck sheep all the time.
Quote from: rabbit on December 11, 2005, 01:05:35 PM
And yes, male both ends.  There are a couple lesbians that need a two-ended dildo...My router just refuses to wear a strap-on.
(05:55:03) JoE ThE oDD: omfg good job i got a boner thinkin bout them chinese bitches
(17:54:15) Sidoh: I love cosmetology

MyndFyre

Quote from: Ergot on September 28, 2005, 06:12:30 PM
Mynd didn't I tell you I was a horrible programmer ;D ?

Ignorance can be cured by education, but the only cure for stupidity is death.

I believe you're in the former case.  ;)
Quote from: Joe on January 23, 2011, 11:47:54 PM
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Quote from: Rule on May 26, 2009, 02:02:12 PMOur species really annoys me.

Joe

MyndFyre, not this last post, but the one just before Ergots, your sig got decapitated by Gecko. No clue what did it, but I can't see much more than the very top of your image on up.

Quote(17:29:03) [x86] Ergot: You win ;D
(17:29:11) [x86] Ergot: Roofleskates

afk church
Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


Ergot

Ooo... This summerizes my coding:
Quote
On the subject of C program indentation:

        "In My Egotistical Opinion, most people's C programs should be indented six feet downward and covered with dirt."
                -- Blair P. Houghton
Quote from: Newby on February 26, 2006, 12:16:58 AM
Who gives a damn? I fuck sheep all the time.
Quote from: rabbit on December 11, 2005, 01:05:35 PM
And yes, male both ends.  There are a couple lesbians that need a two-ended dildo...My router just refuses to wear a strap-on.
(05:55:03) JoE ThE oDD: omfg good job i got a boner thinkin bout them chinese bitches
(17:54:15) Sidoh: I love cosmetology

AntiVirus

/********************************************************/
/*                    Binary converter                  */
/*                     By Matt Fowler                   */
/*                philosopher150@yahoo.com              */
/*  converts text into binary using the division method */
/*                   through ASCII code                 */
/*compiled with the Dev-C++ compiler (www.bloodshed.net)*/
/********************************************************/

#include <iostream>
using namespace std;
#include <cstring>
#include <cstdlib>

char *entry, letter, choice[2];
int ascii, len, binary[8], total;
void prog();

int main()
{
      prog();     
      return 0;
}       
       
void prog()
{
   entry = new char[501];
   /* entry should be dynamic, otherwise a new
      string entry of 501 chars would be created
      each time function is called! 
      Talk about memory hog! */
   cout<<"Enter string to convert (up to 500 chars): ";
   cin.getline(entry, 500);
   len = strlen(entry);  /* get the number of characters in entry. */
   /* this loop is executed for each letter in the string. */
   for(int i = 0; i<len; i++)
   {
      total = 0;
      letter = entry[i]; /* store the first letter */
      ascii = letter;    /* put that letter into an int, so we can
                            see its ASCII number */
      while(ascii>0) /* This while loop converts the ASCII # into binary,
                        stores it backwards into the binary array. */
      {
         /* To get the binary code one must take the decimal number in
            question, take it and divide it by two repeatedly, save
            the remainder (which will become the binary number), save
            the whole number, divide by two, and repeat the whole
            process until 0 is reached.  This if-else statement serves
            this functionality, by getting the remainder of the ascii
            code, storing it in the array and then dividing the int
            ascii by two */
         if((ascii%2)==0)
         {
            binary[total] = 0;
            ascii = ascii/2;
            total++; /* increasing by one each time will yeild the
                        number of numbers in the array. */
         }
         else
         {
            binary[total] = 1;
            ascii = ascii/2;
            total++;
         }
      }
      total--; /* due to data type factors, the program will actually
                  add a 0 at the end of the array that is not supposed
                  to be there, decrementing total will solve this
                  problem, as that 0 will not be displayed. */
      /* this while loop displays the binary code for that letter. */
      while(total>=0)
      {
         cout<<binary[total];
         total--;
      }
   }
   delete[] entry; /* free up the memory used by entry */
   cout<<endl<<"Do again(1 = yes, 2= no)?: ";
   cin.getline(choice,3);
   if(choice[0] == '1')
      prog(); /* program is recursive, it calls itself.  It's kinda
                 like a function loop of sorts. */
   else
      exit(0); /* quits the program */ 
}

I found that at www.cplusplus.com 

Link: http://www.cplusplus.com/src/#vcpp

I played with it for awhile, it was fun. :)  But, it may help what you are doing, or give you ideas. 
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

rabbit

#include <stdio.h>

int main()
{
char *str = new char[256];
int val, pow = 1, pos = 0;

printf("input binary string followed by a \".\": ");
while(((val = getch()) != '.') || pos >= 255)
str[++pos] = val;

val = 0;

for(int i = 0; i < pos; i++)
{
if(str[i] == '.')
break;

if(str[i] == '1')
val += pow;

pow = (pow == 1) ? 2 : pow * pow;
}

printf("%ld", val);
}


Completely untested, but should work......

dynobird

#23
Here's my solution in Java :P (sorry, don't have a good c++ compiler atm, and can't install w/o dad being home.. I have no privileges... )
It's sorta long but it has good explanations.
And it doesn't let anyone flip my program out =p

/*
* Main.java
* Created on October 1, 2005, 6:17 PM
* @author Andy
*/

/*
* Binary -> Base10 Converter
*/

package binconv;

public class Main {
   
    static char[] binary;
    static String binaryStr;
   
    public static boolean isBinary() {
        for (int i = 0; i < binary.length; i++) {
            if (binary[i] != '1' && binary[i] != '0')
                return false;
        }
        return true;
    }
   
    public static void main(String[] args) {
        final int AGAIN = 1;
        final int END = 2;
        int decision;
        EasyReader in = new EasyReader(); // EasyReader and EasyWriter == best IO classes in Java!!
        System.out.println("INSTRUCTIONS:" +
                "Write a number in binary and it will be converted to base ten." +
                "Don't try to flip out my program I prevented you from writing 0 > n > 1");
       
        do { // repeat binary converter while user wants to
            do { // if user gives non-binary number, repeat
                System.out.println("Binary number: ");
                binaryStr = in.readLine();
                binary = binaryStr.toCharArray();
            }
            while(!isBinary());

            int digits = binary.length;
            int accum = 0;
            int add = 1; // the value of 2^n that i will add

            for (int i = 0; i < digits; i++)
                if (i > 0)
                    add = add * 2;
            for (int j = 0; j < digits; j++) {
                if (binary[j] == '1')
                    accum += add;
                add = add / 2;
            }
         
            System.out.println("Binary: " + binaryStr + " = Base 10: " + accum);
            do { // if user doesn't give a valid answer, repeat
                System.out.println("Again? 1. Yes 2. No");
                decision = in.readInt();
            }
            while (decision != AGAIN && decision != END);
        }
        while (decision == AGAIN);
    }
}

Sidoh

Quote from: dynobird on October 01, 2005, 06:30:45 PM
It's sorta long but it has good explanations.
I'm listening.  This thread is too on-topic!  Let's change that.  :)

Joe

Well Sidoh, its hard to take a programming discussion off-topic when the only people who can understand a word we're saying are programmers who wouldn't want to take this off-topic. On a side note, so we don't go off-topic..

joe@JoeMomma:~/dev/cpp/helloworld $ ./binconv-rev && ./binconv
Enter decimal number:
125
125 = 01111101b
Enter binary digits:
01111101
01111101b = 125


Thanks to iago's C++ binary bot, I figured out strings.
Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


Ergot

Nice lol. LIBERATE THE SOURCE! It's for me to study ;S
Quote from: Newby on February 26, 2006, 12:16:58 AM
Who gives a damn? I fuck sheep all the time.
Quote from: rabbit on December 11, 2005, 01:05:35 PM
And yes, male both ends.  There are a couple lesbians that need a two-ended dildo...My router just refuses to wear a strap-on.
(05:55:03) JoE ThE oDD: omfg good job i got a boner thinkin bout them chinese bitches
(17:54:15) Sidoh: I love cosmetology

Joe

#27
// C++ binary->decimal converter
// Author: Joe[e2]

#include <iostream.h>
#include <stdio.h>
using namespace std;

int main() {
  string binary;
  int accum = 0;
  int add = 255;

  printf("Enter binary digits:\n");
  cin >> binary;
  add = 128;
  for(int i = 0; i < 8; i++) {
    if(binary.substr(i, 1) == "1") { accum = accum + add; }
    add = add / 2;
  }

  cout << binary << "b = " << accum << "\n";
  return 0;
}


That makes a horrible asumption that the string's length is always 8, but it also handles the error of it being more than 8, by only using the first 8. I don't know how C++ would handle me trying, say, binary[999] when it only goes up to 7. Asuming it will return an 0x00 (which isn't an 0x31), it will test as a "0".

EDIT -
joe@JoeMomma:~/dev/cpp/helloworld $ ./binconv
Enter binary digits:
10
Aborted

I didn't code that anywhere. Runtime error?
Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


rabbit

Stop using stdio and iostream.  You're only meant to use ONE.

drka