Author Topic: [C/C++] Joe vs Ergot: Code wars!  (Read 24168 times)

0 Members and 2 Guests are viewing this topic.

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #15 on: September 28, 2005, 05:21:18 pm »
Quote
1.) Don't #include <iostream.h>, #include <iostream>.  That's standard C++.
mmk. I think that should fix the need for -Wno-deprecated too.

Quote
2.) 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.

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

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

Quote
5.) 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.

Quote
6.) 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.
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline MyndFyre

  • Boticulator Extraordinaire
  • x86
  • Hero Member
  • *****
  • Posts: 4540
  • The wait is over.
    • View Profile
    • JinxBot :: the evolution in boticulation
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #16 on: September 28, 2005, 05:46:14 pm »
Quote
6.) 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:
Code: [Select]
  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:

Code: [Select]
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.
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Our species really annoys me.

Offline Ergot

  • 吴立峰 ^_^ !
  • x86
  • Hero Member
  • *****
  • Posts: 3724
  • I steal bandwidth. p_o
    • View Profile
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #17 on: September 28, 2005, 06:12:30 pm »
Mynd didn't I tell you I was a horrible programmer ;D ?
Who gives a damn? I fuck sheep all the time.
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

Offline MyndFyre

  • Boticulator Extraordinaire
  • x86
  • Hero Member
  • *****
  • Posts: 4540
  • The wait is over.
    • View Profile
    • JinxBot :: the evolution in boticulation
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #18 on: September 28, 2005, 06:49:46 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.  ;)
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Our species really annoys me.

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #19 on: September 28, 2005, 07:02:04 pm »
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
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline Ergot

  • 吴立峰 ^_^ !
  • x86
  • Hero Member
  • *****
  • Posts: 3724
  • I steal bandwidth. p_o
    • View Profile
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #20 on: September 28, 2005, 09:11:54 pm »
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
Who gives a damn? I fuck sheep all the time.
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

Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #21 on: September 29, 2005, 12:32:55 pm »
Code: [Select]
/********************************************************/
/*                    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

Offline rabbit

  • x86
  • Hero Member
  • *****
  • Posts: 8092
  • I speak for the entire clan (except Joe)
    • View Profile
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #22 on: September 29, 2005, 07:08:06 pm »
Code: [Select]
#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......

Offline dynobird

  • Newbie
  • *
  • Posts: 26
  • I'm new here!
    • View Profile
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #23 on: October 01, 2005, 06:30:45 pm »
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
Code: [Select]
/*
 * 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);
    }
}
« Last Edit: October 01, 2005, 06:42:02 pm by dynobird »

Offline Sidoh

  • x86
  • Hero Member
  • *****
  • Posts: 17634
  • MHNATY ~~~~~
    • View Profile
    • sidoh
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #24 on: October 01, 2005, 06:38:05 pm »
It's sorta long but it has good explanations.
I'm listening.  This thread is too on-topic!  Let's change that.  :)

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #25 on: October 01, 2005, 11:34:17 pm »
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.
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline Ergot

  • 吴立峰 ^_^ !
  • x86
  • Hero Member
  • *****
  • Posts: 3724
  • I steal bandwidth. p_o
    • View Profile
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #26 on: October 01, 2005, 11:48:49 pm »
Nice lol. LIBERATE THE SOURCE! It's for me to study ;S
Who gives a damn? I fuck sheep all the time.
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

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #27 on: October 02, 2005, 02:09:40 am »
Code: [Select]
// 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?
« Last Edit: October 02, 2005, 02:13:28 am by Joe[e2] »
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline rabbit

  • x86
  • Hero Member
  • *****
  • Posts: 8092
  • I speak for the entire clan (except Joe)
    • View Profile
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #28 on: October 02, 2005, 02:25:49 pm »
Stop using stdio and iostream.  You're only meant to use ONE.

Offline drka

  • ffdshow > in_mp3.dll
  • Full Member
  • ***
  • Posts: 330
    • View Profile
Re: [C/C++] Joe vs Ergot: Code wars!
« Reply #29 on: October 02, 2005, 02:28:35 pm »
i think scanf() works like cin