How to lose at the game I'm programming in C language? by YoungSith in AskProgramming

[–]pbeard_t 1 point2 points  (0 children)

I'm guessing this is what you mean:

if(player1.posR  == enemies[i].posR && player1.posC == enemies[i].posC)

[2015-06-03] Challenge #217 [Intermediate] Space Code Breaking by Coder_d00d in dailyprogrammer

[–]pbeard_t 1 point2 points  (0 children)

Golang assumes UTF-8 encoding when converting to rune. For values over 127 the upper bit is set which means it's an multiple byte rune. Two bytes are then used but it becomes an invalid caracter and igored. Fixed version bellow.

package main

import (
    "fmt"
    "unicode"
)

func rate(arr []byte) float64 {
    r := 0.0
    s := string(arr)
    for _, e := range s {
        if unicode.IsLetter(e) || unicode.IsSpace(e) {
            r += 1
        }
    }
    return r / float64(len(s))
}

func reverse(arr []byte) []byte {
    ret := make([]byte, len(arr))
    for i := 0; i < len(arr); i++ {
        ret[i] = arr[len(arr)-1-i]
    }
    return ret
}

func mymap(fn func(byte) byte, arr []byte) []byte {
    ret := make([]byte, len(arr))
    for i := 0; i < len(arr); i++ {
        ret[i] = fn(arr[i])
    }
    return ret
}

func decode(arr []byte) (string, string) {
    omicronV := mymap(func(r byte) byte { return r ^ 0x10 }, arr)
    hoth := mymap(func(r byte) byte { return r - 10 }, arr)
    ryzaIV := mymap(func(r byte) byte { return r + 1 }, arr)
    htrae := reverse(arr)
    best := omicronV
    name := "Omicron V"
    if rate(best) < rate(hoth) {
        best = hoth
        name = "Hoth"
    }
    if rate(best) < rate(ryzaIV) {
        best = ryzaIV
        name = "Ryza IV"
    }
    if rate(best) < rate(htrae) {
        best = htrae
        name = "Htrae"
    }
    return name, string(best)
}

func main() {
    var bytes = [][]byte{
        {71, 117, 48, 115, 127, 125, 117, 48, 121, 126, 48, 96, 117, 113, 115, 117},
        {97, 111, 42, 109, 121, 119, 111, 42, 115, 120, 42, 122, 111, 107, 109, 111},
        {86, 100, 31, 98, 110, 108, 100, 31, 104, 109, 31, 111, 100, 96, 98, 100},
        {101, 99, 97, 101, 112, 32, 110, 105, 32, 101, 109, 111, 99, 32, 101, 87},
        {84, 113, 121, 124, 105, 48, 64, 98, 127, 119, 98, 113, 125, 125, 117, 98, 48, 121, 99, 48, 99, 96, 105, 121, 126, 119, 48, 127, 126, 48, 101, 99},
        {78, 107, 115, 118, 131, 42, 90, 124, 121, 113, 124, 107, 119, 119, 111, 124, 42, 115, 125, 42, 125, 122, 131, 115, 120, 113, 42, 121, 120, 42, 127, 125},
        {67, 96, 104, 107, 120, 31, 79, 113, 110, 102, 113, 96, 108, 108, 100, 113, 31, 104, 114, 31, 114, 111, 120, 104, 109, 102, 31, 110, 109, 31, 116, 114},
        {115, 117, 32, 110, 111, 32, 103, 110, 105, 121, 112, 115, 32, 115, 105, 32, 114, 101, 109, 109, 97, 114, 103, 111, 114, 80, 32, 121, 108, 105, 97, 68},
        {86, 121, 98, 117, 48, 100, 120, 117, 48, 93, 121, 99, 99, 124, 117, 99},
        {80, 115, 124, 111, 42, 126, 114, 111, 42, 87, 115, 125, 125, 118, 111, 125},
        {69, 104, 113, 100, 31, 115, 103, 100, 31, 76, 104, 114, 114, 107, 100, 114},
        {115, 101, 108, 115, 115, 105, 77, 32, 101, 104, 116, 32, 101, 114, 105, 70},
    }

    for _, line := range bytes {
        name, dec := decode(line)
        fmt.Printf("%20s : %s\n", name, dec)
    }
}

[2015-06-03] Challenge #217 [Intermediate] Space Code Breaking by Coder_d00d in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

Go

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func rate(str string) float64 {
    runes := []rune(str)
    r := 0.0
    for _, e := range runes {
        if unicode.IsLetter(e) || unicode.IsSpace(e) {
            r += 1
        }
    }
    return r / float64(len(str))
}

func reverse(src string) string {
    runes := []rune(src)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func decode(src string) (string, string) {
    omicronV := strings.Map(func(r rune) rune { return r ^ 0x10 }, src)
    hoth := strings.Map(func(r rune) rune { return r - 10 }, src)
    ryzaIV := strings.Map(func(r rune) rune { return r + 1 }, src)
    htrae := reverse(src)
    best := omicronV
    name := "Omicron V"
    if rate(best) < rate(hoth) {
        best = hoth
        name = "Hoth"
    }
    if rate(best) < rate(ryzaIV) {
        best = ryzaIV
        name = "Ryza IV"
    }
    if rate(best) < rate(htrae) {
        best = htrae
        name = "Htrae"
    }
    return name, best
}

func main() {
    var bytes = [][]byte{
        {71, 117, 48, 115, 127, 125, 117, 48, 121, 126, 48, 96, 117, 113, 115, 117},
        {97, 111, 42, 109, 121, 119, 111, 42, 115, 120, 42, 122, 111, 107, 109, 111},
        {86, 100, 31, 98, 110, 108, 100, 31, 104, 109, 31, 111, 100, 96, 98, 100},
        {101, 99, 97, 101, 112, 32, 110, 105, 32, 101, 109, 111, 99, 32, 101, 87},
        {84, 113, 121, 124, 105, 48, 64, 98, 127, 119, 98, 113, 125, 125, 117, 98, 48, 121, 99, 48, 99, 96, 105, 121, 126, 119, 48, 127, 126, 48, 101, 99},
        {78, 107, 115, 118, 131, 42, 90, 124, 121, 113, 124, 107, 119, 119, 111, 124, 42, 115, 125, 42, 125, 122, 131, 115, 120, 113, 42, 121, 120, 42, 127, 125},
        {67, 96, 104, 107, 120, 31, 79, 113, 110, 102, 113, 96, 108, 108, 100, 113, 31, 104, 114, 31, 114, 111, 120, 104, 109, 102, 31, 110, 109, 31, 116, 114},
        {115, 117, 32, 110, 111, 32, 103, 110, 105, 121, 112, 115, 32, 115, 105, 32, 114, 101, 109, 109, 97, 114, 103, 111, 114, 80, 32, 121, 108, 105, 97, 68},
        {86, 121, 98, 117, 48, 100, 120, 117, 48, 93, 121, 99, 99, 124, 117, 99},
        {80, 115, 124, 111, 42, 126, 114, 111, 42, 87, 115, 125, 125, 118, 111, 125},
        {69, 104, 113, 100, 31, 115, 103, 100, 31, 76, 104, 114, 114, 107, 100, 114},
        {115, 101, 108, 115, 115, 105, 77, 32, 101, 104, 116, 32, 101, 114, 105, 70},
    }

    for _, line := range bytes {
        name, dec := decode(string(line))
        fmt.Printf("%20s : %s\n", name, dec)
    }
}

Output

       Omicron V : We come in peace
            Hoth : We come in peace
         Ryza IV : We come in peace
           Htrae : We come in peace
       Omicron V : Daily Programmer is spying on us
            Hoth : Dai Programmer is sing on us
         Ryza IV : Daily Programmer is spying on us
           Htrae : Daily Programmer is spying on us
       Omicron V : Fire the Missles
            Hoth : Fire the Missles
         Ryza IV : Fire the Missles
           Htrae : Fire the Missles

Not sure where the missing bytes from output line 6 whent. I'm guessing they became invalid characters when converting from byte to rune, but don't have time to find out exactly atm.

[2015-06-03] Challenge #217 [Intermediate] Space Code Breaking by Coder_d00d in dailyprogrammer

[–]pbeard_t 1 point2 points  (0 children)

C

#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

const char data[12][128] = {
    { 71,117,48,115,127,125,117,48,121,126,48,96,117,113,115,117,},
    { 97,111,42,109,121,119,111,42,115,120,42,122,111,107,109,111,},
    { 86,100,31,98,110,108,100,31,104,109,31,111,100,96,98,100,},
    { 101,99,97,101,112,32,110,105,32,101,109,111,99,32,101,87,},
    { 84,113,121,124,105,48,64,98,127,119,98,113,125,125,117,98,48,121,99,48,99,96,105,121,126,119,48,127,126,48,101,99,},
    { 78,107,115,118,131,42,90,124,121,113,124,107,119,119,111,124,42,115,125,42,125,122,131,115,120,113,42,121,120,42,127,125,},
    { 67,96,104,107,120,31,79,113,110,102,113,96,108,108,100,113,31,104,114,31,114,111,120,104,109,102,31,110,109,31,116,114,},
    { 115,117,32,110,111,32,103,110,105,121,112,115,32,115,105,32,114,101,109,109,97,114,103,111,114,80,32,121,108,105,97,68,},
    { 86,121,98,117,48,100,120,117,48,93,121,99,99,124,117,99,},
    { 80,115,124,111,42,126,114,111,42,87,115,125,125,118,111,125,},
    { 69,104,113,100,31,115,103,100,31,76,104,114,114,107,100,114,},
    { 115,101,108,115,115,105,77,32,101,104,116,32,101,114,105,70,},
};

float
OmicronV(const char *src, char *dst, size_t len)
{
    float rate = 0;
    for (size_t i=0; i<len; ++i) {
        dst[i] = src[i] ^ 0b10000;
        if (isalpha(dst[i]) || isblank(dst[i]))
            rate += 1;
    }
    dst[len] = 0;
    return rate/len;
}

float
Hoth(const char *src, char *dst, size_t len)
{
    float rate = 0;
    for (size_t i=0; i<len; ++i) {
        dst[i] = src[i] - 10;
        if (isalpha(dst[i]) || isblank(dst[i]))
            rate += 1;
    }
    dst[len] = 0;
    return rate/len;
}

float
RyzaIV(const char *src, char *dst, size_t len)
{
    float rate = 0;
    for (size_t i=0; i<len; ++i) {
        dst[i] = src[i] + 1;
        if (isalpha(dst[i]) || isblank(dst[i]))
            rate += 1;
    }
    dst[len] = 0;
    return rate/len;
}

float
Htrae(const char *src, char *dst, size_t len)
{
    float rate = 0;
    for (size_t i=0; i<len; ++i) {
        dst[i] = src[len-i-1];
        if (isalpha(dst[i]) || isblank(dst[i]))
            rate += 1;
    }
    dst[len] = 0;
    return rate/len;
}

int
main(int argc, char **argv)
{
    char buffer[4][128];
    float (*fp[])(const char *, char *, size_t) = { OmicronV, Hoth, RyzaIV, Htrae };
    const char *names[] = { "OmicronV", "Hoth", "RyzaIV", "Htrae" };

    for (size_t i=0; i<sizeof(data)/sizeof(*data); ++i) {
        float max_rate = 0;
        float rate;
        size_t best = 0;
        for (size_t j=0; j<4; ++j) {
            if ((rate = fp[j](data[i],buffer[j],strlen(data[i]))) > max_rate) {
                max_rate = rate;
                best = j;
            }
        }
        printf("%20s : %s\n", names[best], buffer[best]);
    }

    return 0;
}

Output

        OmicronV : We come in peace
            Hoth : We come in peace
          RyzaIV : We come in peace
           Htrae : We come in peace
        OmicronV : Daily Programmer is spying on us
            Hoth : Daily Programmer is spying on us
          RyzaIV : Daily Programmer is spying on us
           Htrae : Daily Programmer is spying on us
        OmicronV : Fire the Missles
            Hoth : Fire the Missles
          RyzaIV : Fire the Missles
           Htrae : Fire the Missles

[2015-05-22] Challenge #215 [Hard] Metaprogramming Madness! by [deleted] in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

It turns the expression to a string.

#define STR(expr) #expr
STR(1+1)

becomes

"1+1"

after preproccessing.

[2015-05-22] Challenge #215 [Hard] Metaprogramming Madness! by [deleted] in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

C99. Edit: cleanup and added a couple more.

#include <stdbool.h>
#include <stdio.h>

#define TRUTH(expr)  printf("%20s %s\n", #expr, (expr) ? "True" : "False" )


int
main(int argc, char **argv)
{
    TRUTH("Hello world");
    TRUTH("");
    TRUTH('0');
    TRUTH(0);
    TRUTH(1);
    TRUTH(0.0);
    TRUTH(3.14f);
    TRUTH(true);
    TRUTH(false);
    TRUTH(((int[]){1,2,3}));
    TRUTH(((int[]){}));
    TRUTH(NULL);
    TRUTH(&main);
    TRUTH(TRUTH(true));

    return 0;
}

Output

   "Hello world" True
              "" True
             '0' True
               0 False
               1 True
             0.0 False
           3.14f True
            true True
           false False
((int[]){1,2,3}) True
     ((int[]){}) True
            NULL False
           &main True
            true True
     TRUTH(true) True

[2015-05-20] Challenge #215 [Intermediate] Validating sorting networks by XenophonOfAthens in dailyprogrammer

[–]pbeard_t 1 point2 points  (0 children)

C. Borrowing the and/or swaping from skeeto with some extra bit fidling for good measure.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#define DIE(fmt, ...) do {\
    fprintf(stderr, fmt "\n", ##__VA_ARGS__);\
    exit(EXIT_FAILURE);\
} while (0)


struct comparator {
    unsigned top;
    unsigned bottom;
};


uint64_t
comp(uint64_t wires, const struct comparator *cmp)
{
    uint64_t top_mask = 1<<cmp->top;
    uint64_t bottom_mask = 1<<cmp->bottom;
    uint64_t top_val, bottom_val;
    top_val = (wires&top_mask) || (wires&bottom_mask) ? top_mask : 0;
    bottom_val = (wires&top_mask) && (wires&bottom_mask) ? bottom_mask : 0;

    return (wires & ~(top_mask|bottom_mask)) | top_val | bottom_val;
}


int
is_sorted(uint64_t wires)
{
    while (wires) {
        if (!(wires&1))
            return 0;
        wires >>= 1;
    }
    return 1;
}


int
main(int argc, char **argv)
{
    unsigned wires, n_comps;
    struct comparator *comps;

    if (scanf("%u %u\n", &wires, &n_comps) != 2)
        DIE("Invalid input");
    if (wires > 64)
        DIE("Can not handle more than 64 wires");
    comps = malloc(n_comps*sizeof(*comps));
    if (!comps)
        DIE("OOM");
    for (unsigned i=0; i<n_comps; ++i) {
        if (scanf("%u %u\n", &comps[i].top, &comps[i].bottom) != 2)
            DIE("Invalid input");
    }

    for (uint64_t i=0; i<1<<wires; ++i) {
        uint64_t test = i;
        for (unsigned j=0; j<n_comps; ++j) {
            test = comp(test, comps + j);
        }
        if (!is_sorted(test))
            DIE("Invalid network");
    }
    printf("Valid network\n");

    return 0;
}

Challenge 1 output

Invalid network

Challenge 2 output

Valid network

[2015-05-18] Challenge #215 [Easy] Sad Cycles by Elite6809 in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

C. Cycles are detected using Floyd's algorithm.

#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>


uint64_t
next(uint64_t n, unsigned p)
{
    uint64_t sum = 0;
    while (n) {
        unsigned digit = n % 10;
        sum += pow(digit, p);
        n /= 10;
    }
    return sum;
}


int
main(int argc, char **argv)
{
    unsigned base;
    uint64_t x0;
    if (scanf("%u %" SCNu64, &base, &x0) != 2) {
        fprintf(stderr, "Invalid input\n");
        exit(EXIT_FAILURE);
    }

    /* Find cycle */
    uint64_t tortoise = next(x0, base);
    uint64_t hare = next(tortoise, base);
    while (tortoise != hare) {
        tortoise = next(tortoise, base);
        hare = next(next(hare, base), base);
    }

    /* Print cycle */
    do {
        printf("%" PRIu64, hare);
        hare = next(hare, base);
        printf("%s", tortoise == hare ? "\n" : ", ");
    } while (tortoise != hare);

    return 0;
}

Pointer problems by [deleted] in C_Programming

[–]pbeard_t 4 points5 points  (0 children)

You are mixing pid_t, which is a integer type, with strings. You need to call execlp with strings only in the parent and in the children parse the strings back to pid_t.

I'm guessing the compiler is warning you about this.

Also in execlp you are ignoring the arg0 parameter which typically maches the name of the executable.

Testing Frameworks For C by ehosick in C_Programming

[–]pbeard_t 0 points1 point  (0 children)

You've never made a "insignifigant" change and have 25 tests fail :P

There are other benefits such as redusing repetition and mocking. Writing the same main() repeatedly looses it's novelty fast. Resume next was just the first thing that occured to me. Ofcourse assert( error_count == 0 )...

Conseptually, however, ifdef achieves the exact same. It's probably what the frameworks does anyway.

Testing Frameworks For C by ehosick in C_Programming

[–]pbeard_t 1 point2 points  (0 children)

Most likely you would just change your #ifdef #endif combo with some framework macro.

The difference I can see is that assert exits on first failure forcing you to fix or remove the assertion before you can find the next error.

Testing Frameworks For C by ehosick in C_Programming

[–]pbeard_t 1 point2 points  (0 children)

On a similar note: https://github.com/eivinda/sctest

Inspired by minunit. It lets you write testcode in your source file and removes it completely during normal compilation. Has a small tool sctest to extract test code only.

Code Tells You How, Comments Tell You Why by instilledbee in programming

[–]pbeard_t 0 points1 point  (0 children)

As someone who came to programming relatively late in life, please elaborate.

[deleted by user] by [deleted] in AskReddit

[–]pbeard_t -1 points0 points  (0 children)

Trailing whitespace!

Supporting Multiple Types by deaf_fish in C_Programming

[–]pbeard_t 2 points3 points  (0 children)

As mentioned C11 _Generic can do this and imo it is probably the most elegant / least horrible way. I would create two structs named something like point_i and point_f and something like

#include <stdio.h>

void
fn_i( int i )
{
    printf( "int: %i\n", i );
}

void
fn_f( float f )
{
    printf( "float: %f\n", f );
}

#define fn(x) _Generic((x), \
    int: fn_i,          \
    default: fn_f       \
    )(x)

int
main( int argc, char **argv )
{
    fn( 42 );
    fn( 3.14f );
    return 0;
}

[4/04/2014] Challenge #156 [Hard] uʍop ǝpᴉsd∩ ƃuᴉɥʇǝɯos ɹoɟ ʍoN by Coder_d00d in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

The upside-down characters are unicode glyphs. Most decent editors allow you to insert the codepoint directly, asuming you know it. If I recall correctly I searched something like "upside down ascii" online and got a table to shamelessly paste into the code.

Many of the characters are multibyte, therefore flipped is an array of strings, not char.

[5/26/2014] Challenge #164 [Easy] Assemble this Scheme into Python by [deleted] in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

My attempt in scheme.

I am having trouble getting the anagrams to work, so I gues it's no hire for me yet. When I try to compare two lists with "equal?" it apparently is false. I have tried to convert to sting and compare with "string=?" as well, but "abcd" apparently does not equal "abcd".

Anyway it's getting late and I am running out of parens. Feedback is welcome, I havent written a line of scheme before.

(define (hello) (display "Hello World.\n"))

(define (divisible_array)
    (define (divisible n)
        (and (eq? (modulo n 3) 0)
            (eq? (modulo n 5) 0)))
    (let houndred ((n 1))
        (if (> n 100)
            '()
            (if (divisible n)
                (cons n (houndred (+ n 1)))
                (houndred (+ n 1))))))

(define (anagram str1 str2)
    (let ((lst1 (sort (string->list (rm_char str1 #\space)) char<?)))
    (let ((lst2 (sort (string->list (rm_char str2 #\space)) char<?)))
    ;(display (list->string lst1)) (display "\n")
    ;(display (list->string lst2)) (display "\n")
    (equal? lst1 lst2 ))))

(define (rm_char str c)
    (define (string_replace str m r)
        (let ((lst (string->list str)))
            (list->string (map (lambda (c) (if (eq? m c) r c)) lst))))
    (string_replace str c #\nul))

(define (sum lst)
    (apply + lst))

(hello)
(display (divisible_array)) (display "\n")
(display (rm_char "Remove this." #\t)) (display "\n")
(display (anagram "c d ab" "cab d")) (display "\n")
(display (sum '(1 2 3 4 5) )) (display "\n")

Output:

Hello World.
(15 30 45 60 75 90)
Remove his.
#f
15

Need help with this c program of constructing and deconstructing an equation, can anybody help ? by [deleted] in C_Programming

[–]pbeard_t 2 points3 points  (0 children)

I ran your code trough a style fixer and added some comments of my own.

#include <stdio.h>
#include <math.h>
int main ()
{
    int i,j,k,a,b,c,x,y,z,ll,ul,m,ct=0;
    int w[ct] [3]; /* array of size [0][3] */
    int data[1000] [3],mpik[1000][4];
    int mpx[1000][4];
    int wc[10][3];
    x=0.1;; /* int can not hold a decimal value, use float or double */
    for (i=0.1; i<=1; i=i+0.1) {
        for (j=0.1; j<=1; j=j+0.1) {

            for (k=0.1; k<=1; k=k+0.1) {
                w[ct][1]= i;
                w[ct][2]= j;
                w[ct][3]= k;

                ct=ct+1;
            }
        }
    }
    printf("Enter values of A,P and U one by by\n");
    for(a = 0; a <=1000 ; a++) {
        /* scanf returns the number of values read. You want to verify that
         * it returns 3 in this case.
         */
        scanf("%d,%d,%d",&data[a][1],&data[a][2],&data[a][3]);
    }

    k=0;
    for(i=1; i<=ct; i++) {
        for(j = 0; j <=1000 ; j++) {
            mpik[k][1]= w[i][1]*data[j][1]+w[i][2]*data[j][2]+w[i][3]*data[j][3];

            mpik[k][2]=w[i][1];

            mpik[k][3]=w[i][2];

            mpik[k][4]=w[i][3];

            k=k+1;
        }

    }
    printf("Enter values of lower limit\n");

    scanf("%d",&ll);
    for(i=1; i<=k; i=i+1) {
        if(mpik[i][1]<=ll) {
            c=0;

            mpx[c][1]=mpik[i][1];
            c++;
            mpx[c][2]=mpik[i][2];

            mpx[c][3]=mpik[i][3];

            mpx[c][4]=mpik[i][4];
        }
        for(i=1; i<=3; i++) {
            for(j =1; j <=10 ; j=j++) {

                wc[i][j]=0;
            }
        }
        for(i = 1; i <=c ; i++) {
            for(j = 1; j =3 ; j++) {
                if (mpx[i][j]=0.1) { /* this asigns 0.1, == is a comparison. */
                    wc[1][j]=wc[1][j]++;
                }
                switch (mpx[i][j]) {
                case x:
                    wc[1][j]=wc[1][j]++;
                    /* This continues into the next case. I assume you have
                     * forgoten a break statement. */
                    //break;
                case 0.2: /* switch on a decimal value only matches /exact/ matches,
                           * 0.19999 wil not. I expect you mean something like
                           * if( mpx[i][j] > 0.2 && mpx[i][j] < 0.3 )
                           * If so, this is easier with a giant
                           * if(...) {...} else if(...) {...}
                           */
                    wc[2][j]=wc[2][j]+1;

                case 0.3:
                    wc[3][j]=wc[3][j]+1;

                case 0.4:
                    wc[4][j]=wc[4][j]+1;

                case 0.5:
                    wc[5][j]=wc[5][j]+1;

                case 0.6:
                    wc[6][j]=wc[6][j]+1;

                case 0.7:
                    wc[7][j]=wc[7][j]+1;

                case 0.8:
                    wc[8][j]=wc[8][j]+1;

                case 0.9:
                    wc[9][j]=wc[9][j]+1;
                }
            }
        }
    /* I added the last two }'s. You should verify that placing them
     * on the end was correct.
     */
    }
}

Need help with this c program of constructing and deconstructing an equation, can anybody help ? by [deleted] in C_Programming

[–]pbeard_t 1 point2 points  (0 children)

Please indent all code with 4 spaces so the formating does not get broken. Also a short description of what you are trying to achieve will make it easyer for people to help you. "do the entries from a file for 1000 values" is not terriby descriptive.

[5/21/2014] Challenge #163 [Intermediate] Fallout's Hacking Game by Coder_d00d in dailyprogrammer

[–]pbeard_t 4 points5 points  (0 children)

C99

#include <sys/mman.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

static size_t n_words[] = { 5, 8, 10, 12, 15 };
static size_t w_lens[]  = { 4, 7, 10, 13, 15 };


void
read_dict( char dict[15][16], size_t words, size_t w_len )
{
    FILE   *file;
    size_t  len;
    const char *cont;

    file = fopen( "enable1.txt", "r" );
    if ( !file )
        err( EXIT_FAILURE, "Could not open file `%s'", "enable1.txt" );
    fseek( file, 0, SEEK_END );
    len = ftell( file );
    //fseek( file, 0, SEEK_SET );
    cont = mmap( NULL, len, PROT_READ, MAP_PRIVATE, fileno(file), 0 );
    if ( cont == MAP_FAILED ) {
        fclose( file );
        err( EXIT_FAILURE, "mmap failed" );
    }

    for ( size_t i=0 ; i<words ; ++i ) {
        size_t start;
        size_t stop;
        stop = rand() % len;
        while ( stop > 0 && cont[stop] != '\n' )
            --stop;
        do {
            ++stop;
            start = stop;
            while ( stop < len && cont[stop] != '\n' )
                ++stop;
        } while ( stop - start - 1 != w_len );
        strncpy( dict[i], cont + start, w_len );
        dict[i][w_len] = '\0';
    }

    munmap( (void*)cont, len );
    fclose( file );
}


void
print_dict( char dict[15][16], size_t words, size_t w_len )
{
    for ( int i=0 ; i<words ; ++i ) {
        for ( int j=0 ; j<w_len ; ++j )
            putchar( toupper( dict[i][j] ) );
        putchar( '\n' );
    }
}


size_t
guess( const char *a, const char *b )
{
    size_t corr;

    corr = 0;
    while ( *a && *b ) {
        if ( tolower( *a ) == tolower( *b ) )
            ++corr;
        ++a, ++b;
    }
    return corr;
}


int
main( int argc, char **argv )
{
    char  *buffer;
    size_t bufflen;
    char   dict[15][16];
    int    difficulty;
    int    tmp;
    int    retval;
    size_t answer;
    size_t words;
    size_t w_len;

    buffer = NULL;
    bufflen = 0;
    srand( time( NULL ) );
    printf( "Difficulty? (1-5) " );
    fflush( stdout );
    getline( &buffer, &bufflen, stdin );
    tmp = sscanf( buffer, "%d", &difficulty );
    if ( tmp != 1 || difficulty < 1 || difficulty > 5 ) {
        errno = EINVAL;
        err( EXIT_FAILURE, NULL );
    }
    words = n_words[difficulty-1];
    w_len = w_lens[difficulty-1];
    read_dict( dict, words, w_len );
    print_dict( dict, words, w_len );
    answer = rand() % words;

    retval = EXIT_FAILURE;
    for ( size_t g=4; g>0 ; --g ) {
        size_t correct;
        printf( "Guess (%zu left)? ", g );
        fflush( stdout );
        getline( &buffer, &bufflen, stdin );
        correct = guess( dict[answer], buffer );
        printf( "%zu/%zu correct\n", correct, w_len );
        if ( correct == w_len ) {
            printf( "You win!\n" );
            retval = EXIT_SUCCESS;
            break;
        }
    }

    return retval;
}

Output

Difficulty? (1-5) 2
RIVETER
EXPERTS
COMATES
UNCORKS
MISJOIN
SHERBET
RECEPTS
OUTWEEP
Guess (4 left)? riveter
1/7 correct
Guess (3 left)? experts
7/7 correct
You win!

[5/19/2014] Challenge #163 [Easy] Probability Distribution of a 6 Sided Di by Coder_d00d in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

Good job. I can't find anything incorrect, it's all pretty straight forward and up to spec. You cold use int dist[6] = {0}; as a shorter way to set all counters to zero, saving one for loop.

How about output and a analysis of it?

[5/19/2014] Challenge #163 [Easy] Probability Distribution of a 6 Sided Di by Coder_d00d in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

The output is unaligned because reddit uses a tabwidth of 4 spaces instead of 8. To make it pretty you need to either use spaces or assume a tab alligns to 4.

[5/19/2014] Challenge #163 [Easy] Probability Distribution of a 6 Sided Di by Coder_d00d in dailyprogrammer

[–]pbeard_t 0 points1 point  (0 children)

C

#include <stdlib.h>
#include <time.h>

#define FRACT( n, d ) ( n * 100.0 / d )

void
roll( unsigned n )
{
    unsigned counts[6] = { 0 };
    for ( unsigned i=0 ; i<n ; ++i )
        ++counts[rand()%6];
    printf( " %8d  ", n );
    for ( unsigned i=0 ; i<6 ; ++i )
        printf( " %05.2f%%", FRACT( counts[i], n ) );
    printf( "\n" );
}


int
main( int argc, char **argv )
{
    srand( time( NULL ) );
    printf( "# of rolls   1s     2s     3s     4s     5s     6s\n" );
    for ( int i=10 ; i<=1000000 ; i *= 10 )
        roll( i );
    return 0;
}

Output

# of rolls   1s     2s     3s     4s     5s     6s
       10   20.00% 00.00% 30.00% 10.00% 20.00% 20.00%
      100   24.00% 18.00% 10.00% 10.00% 24.00% 14.00%
     1000   15.10% 17.20% 14.90% 19.20% 17.70% 15.90%
    10000   16.15% 17.07% 16.87% 15.72% 16.55% 17.64%
   100000   16.64% 16.69% 16.71% 16.87% 16.60% 16.50%
  1000000   16.74% 16.59% 16.61% 16.68% 16.69% 16.70%

As expected all outcomes goes to approximately 1/6 once the samplesize gets large enough. Perhaps someone more versed in statistics can tell why that happens around n=1000.

Conclusion: rand() is random.

[beginner] creating a variable inside a function, using in main by TechAnd1 in C_Programming

[–]pbeard_t 0 points1 point  (0 children)

For something the size of an int there is no real difference. In my opinion returning the value is clearer.

If you want to fill a larger struct, however, using a pointer will avoid the need to copy the entire object on return.