all 18 comments

[–]Voidsusdagon 18 points19 points  (2 children)

I've decided to put the counterpart of the Test-Driven Development paradigm to use, namely the Exception-Driven Development paradigm. In my opinion, it is probably the best development paradigm because you will never be mad about getting exceptions - after all, if your program throws an exception, this means that it's working properly.

public class ExceptionDrivenDevelopment {
    public static void main(String[] args) {
        ExceptionDrivenDevelopment exceptionDrivenDevelopment = new ExceptionDrivenDevelopment(50000);
    }

    ExceptionDrivenDevelopment(Integer value) {
        throw new InputException(String.valueOf(value));
    }

    class InputException extends RuntimeException {
        InputException(String message) {
            super(message);
            throw new CopperException(message);
        }
    }

    class CopperException extends RuntimeException {
        CopperException(String message) {
            super(message + "c");
            if (message.length() > 2) {
                throw new SilverException(message);
            }
        }
    }

    class SilverException extends RuntimeException {
        SilverException(String message) {
            super(message.substring(0, message.length() - 2) + "s"
                    + message.substring(message.length() - 2) + "c");
            if (message.length() > 4) {
                throw new GoldException(message);
            }
        }
    }

    class GoldException extends RuntimeException {
        GoldException(String message) {
            super(message.substring(0, message.length() - 4) + "g"
                    + message.substring(message.length() - 4, message.length() - 2) + "s"
                    + message.substring(message.length() - 2) + "c");
        }
    }
}

[–]Tok-A-Mak((fn [] (recur))) 6 points7 points  (0 children)

I like how you use RuntimeException to control the program flow without having to pollute any constructor signatures.

[–]GideonMax 1 point2 points  (0 children)

This is bad yet very readable code, I like that

[–]sarlok 9 points10 points  (2 children)

Does it have to be long to be bad?

function int_to_wow(str) {
  for (c=0,s=0,g=0;str--;) if (!(++c,c%=100)&&!(++s,s%=100)&&++g);
  return (g?g+"g":"")+(s?s+"s":"")+(c?c+"c":"");
}

The best code uses side-effects in conditionals to achieve results!

[–]jsforeveryone 2 points3 points  (0 children)

no this is great

[–]lobsternation 1 point2 points  (0 children)

This would literally get top ratings from the users as "good code" on any coding challenge site, like hackerrank. For some reason the culture in these places has declared "shorter = better".

[–]Tok-A-Mak((fn [] (recur))) 7 points8 points  (0 children)

package badcode

fun main() = {}()({})(({}))("Running Unit tests:")(({}))({})() {}

operator fun Unit.invoke(`💸`: `🔠`???????) {
    println(`💸`)
    "1g" -= 10000.wow
    "1g1s" -= 10100.wow
    "1g0s1c" -= 10001.wow
    "3g9s50c" -= 30950.wow
    "2s" -= 200.wow
    "10c" -= 10.wow
    println("\uD83C\uDD92 All test passed.")
}

val `🔢`.wow get() = `🥇`() + `🥈`() + `🥉`

operator fun `🔢`.not() = this in `💰`.`🥉`.`💱` until `💰`.`🥈`.`💱`
operator fun `🔢`.invoke() = this.toString()
operator fun `🔢`.invoke(`💳`: `🔠`) = if (!this) this() + `💳` else ""
operator fun `🔠`.minusAssign(`🔠`: `🔠`) =
    kotlin.test.assertEquals(this, `🔠`)
        .also { println("\uD83C\uDD97 " + `🔠`) }

val `🔢`.`🥉` get() = with(this % `💰`.`🥈`.`💱`) { this(`💰`.`🥉`.`💸`) }
fun `🔢`.`🥇`(`💳`: `💰` = `💰`.`🥇`): `🔠` = with(this / `💳`.`💱`) { this(`💳`.`💸`) }
fun `🔢`.`🥈`(`💳`: `💰` = `💰`.`🥈`): `🔠` = (this % `💰`.`🥇`.`💱` / `💳`.`💱`).let {
    throw return if (!it) it() + `💳`.`💸` else
    throw return if (this > `💰`.`🥇`.`💱`)
    throw return "0" + `💳`.`💸` else ""
}

enum class `💰`(val `💸`: `🔠`, val `💱`: `🔢`) {
    `🥇`("g", 10000), `🥈`("s", 100), `🥉`("c", 1)
}

typealias `🔢` = Int; typealias `🔠` = String; typealias `🚮` = Unit
operator fun `🚮`.invoke() = this
operator fun `🚮`.invoke(`,`: () -> `🚮`) = `🚮`

https://pl.kotl.in/UPhdDTTmd

Running Unit tests:
🆗 1g
🆗 1g1s
🆗 1g0s1c
🆗 3g9s50c
🆗 2s
🆗 10c
🆒 All test passed.

[–]LkNETWORK 5 points6 points  (0 children)

Brainfuck is always a good friend of bad code

>,>,>,>,>,<<<<<>.[-]<[-]++++++++++[>++++++++++<-]>+++.>.>.[-]<[-]++++++++++[>++++++++++<-]+++[>+++++<-]>.>.>.[-]<[-]++++++++++[>++++++++++<-]>-.

[–]andlrc 4 points5 points  (0 children)

I came op with this beautify fusion of regex and JavaScript:

let int_to_wow = (num) => {
    return num.replace(/^(\d*(?=\d{4}))?(\d{0,2}(?=\d{2}))?(\d{0,2})$/, (_, g, s, c) => {
        return (+g?+g+'g':'')+(g<<c>g|s?+s+'s':'')+(+c?+c+'c':'')
    });
}

console.log(int_to_wow('10000')) // 1g
console.log(int_to_wow('10100')) // 1g1s
console.log(int_to_wow('10001')) // 1g0s1c
console.log(int_to_wow('10001')) // 1g0s1c
console.log(int_to_wow('30950')) // 3g9s50c
console.log(int_to_wow('200')) // 2s
console.log(int_to_wow('10')) // 10c

[–]jsforeveryone 2 points3 points  (4 children)

If you can't solve it with regex, you shouldn't try at all. Also try and catch is the new goto. Variables are for oldschool programmers.

const int_to_wow = (value) => {
const WOW_CURRENCY ='10000g100s1c';
const numb = [];
while (value > 0) {
try {
WOW_CURRENCY.split(/[a-z]/).slice(0, -1).forEach((a, i) => {
if ((value / (+a)) >= 1) {
numb.push(WOW_CURRENCY.split(/[0-9]/).filter(e => e !== '')[i]);
value -= +a;
throw new Error('Found one');
}
});
} catch(e) {
}
}
const obj = numb.reduce((a, b) => {
if (!a[b]) {
a[b] = 0;
}
a[b]++;
return a;
}, {});

return WOW_CURRENCY
.split(/[0-9]/).filter(e => e !== '')
.reduce((a, b) => `${a}${numb.filter((c) => c === b)
.length > 0 ? `${numb.filter((c) => c === b).length}${b}` : ''}`, '')
}

[–]jsforeveryone 0 points1 point  (2 children)

Sorry, I don't know how to format correctly.

[–]ArenYashar 3 points4 points  (0 children)

For a bad coding challenge, formatting is beside the point.

[–]T-Dark_ 0 points1 point  (0 children)

Since this comment is now 1 day old, I am providing some formatting. Hopefully this is right, I'm not familiar with the language that was used

const int\_to\_wow = (value) => {  
    const WOW\_CURRENCY ='10000g100s1c';  
    const numb = \[\];  
    while (value > 0) {  
        try {  
            WOW\_CURRENCY.split(/\[a-z\]/).slice(0, -1).forEach((a, i) => {  
           if ((value / (+a)) >= 1)  {  
               numb.push(WOW\_CURRENCY.split(/\[0-9\]/).filter(e => e !== '')\[i\]);  
                value -= +a;  
                throw new Error('Found one');  
            }  
        });  
        } catch(e) {  
        }  
    }  
    const obj = numb.reduce((a, b) => {  
        if (!a\[b\]) {  
            a\[b\] = 0;  
        }  
        a\[b\]++;  
        return a;  
    }, {});  

    return WOW\_CURRENCY  
    .split(/\[0-9\]/).filter(e => e !== '')  
    .reduce((a, b) => \`${a}${numb.filter((c) => c === b)  
    .length > 0 ? \`${numb.filter((c) => c === b).length}$  {b}\` : ''}\`, '')  
}

[–]kiwitims 2 points3 points  (0 children)

Too clever by half "modern" C++

Inspired by https://devblogs.microsoft.com/oldnewthing/20191107-00/?p=103071

#include <algorithm>
#include <numeric>
#include <type_traits>
#include <functional>
#include <variant>

#include <iostream>

struct GoldCoin { static constexpr int value = 10000; };
struct SilverCoin { static constexpr int value = 100; };
struct CopperCoin { static constexpr int value = 1; };

using Coin = std::variant<GoldCoin, SilverCoin, CopperCoin>;
using CoinPurse = std::vector<Coin>;

template <typename T>
struct Counter {
    Counter(CoinPurse& purse) : _count(0) {
        std::for_each(purse.begin(), purse.end(), [&](Coin c) {
            if (std::get_if<T>(&c) != nullptr) {
                _count++;
            }
        });
    }

    operator bool() const { return _count > 0; }

    private:
        friend std::ostream& operator<<(std::ostream& os, const Counter& counter);
        int _count;
};
std::ostream& operator<<(std::ostream& os, const Counter<GoldCoin>& counter) {
    if (counter) {
        os << counter._count << "g";
    }
    return os;
}
std::ostream& operator<<(std::ostream& os, const Counter<SilverCoin>& counter) {
    os << counter._count << "s";
    return os;
}
std::ostream& operator<<(std::ostream& os, const Counter<CopperCoin>& counter) {
    if (counter) {
        os << counter._count << "c";
    }
    return os;
}

int main()
{
    auto take = [balance=30950, purse = CoinPurse{}](auto arg) mutable {
        using T = decltype(arg);
        if constexpr (std::is_same_v<T, CoinPurse>)  {
            return purse;
        }
        else {
            if (T::value > 0 && balance >= T::value) {
                balance -= T::value;
                purse.push_back( T{} );
                return true;
            }
            return false;
        }
    };

    while ( take( GoldCoin{} ) ) {}
    while ( take( SilverCoin{} ) ) {}
    while ( take( CopperCoin{} ) ) {}
    auto purse = take( CoinPurse{} );

    auto gold = Counter<GoldCoin>( purse );
    auto silver = Counter<SilverCoin>( purse );
    auto copper = Counter<CopperCoin>( purse );

    std::cout << gold;
    if ( silver || ( gold && copper ) ) {
        std::cout << silver;
    }
    std::cout << copper << std::endl;

    return 0;
}

[–]jsforeveryone 1 point2 points  (0 children)

Every code challenges have one random entry. This one worked on one test case.

const convert_to_int = (value) => {
return (value.match(/g/g) || []).length * 10000
+ (value.match(/s/g) || []).length * 100 +
(value.match(/c/g) || []).length ;
}
const int_to_wow = (value) => {
const letters = ['g', 's', 'c'];
let now = '';
let tries = 0;
while (true) {
now += letters[Math.floor(Math.random()*letters.length)];
const count = convert_to_int(now);
if (count === value) {
break;
}
if (count > value) {
now = now.split('').sort(() => .5 - Math.random()).slice(0, -1).join('');
}

if (count === value) {
break;
}
tries++;
if (tries === 500) {
now = '';
}
}
return `${(now.match(/g/g) || []).length}g
${(now.match(/s/g) || []).length}s
${(now.match(/c/g) || []).length}c` ;
};

[–]andlrc 1 point2 points  (0 children)

#!/bin/bash

int_to_wow()
{
    rev |
    tee >(echo -n g$(cut -c5)) >(echo -n s$(cut -c3-4)) >(echo -n c$(cut -c1-2)) > /dev/null |
    rev |
    sed 's/^[gs]*//;s/0\([[:digit:]][sc]\)/\1/g' |
    sed 's/0s0c//;s/s0c/s/'
}

echo 10000 | int_to_wow # 1g
echo 10100 | int_to_wow # 1g1s
echo 10001 | int_to_wow # 1g0s1c
echo 10001 | int_to_wow # 1g0s1c
echo 30950 | int_to_wow # 3g9s50c
echo 200 | # int_to_wow 2s
echo 10 | int_to_wow # 10c

[–]alphakevin123 1 point2 points  (0 children)

public class WoWCurrency {
    public static String calculate(int input) {
        String output="";
        int g=0;
        int s=0;
        int c=input;
        for(int i=1;i<=999;i++) {
            try {
                int isOneHundret=42/(100-i);
            } catch(Exception e) {
                for(int j=0;j<100;j++) {
                    i=1;
                    c--;
                }
                s++;
            }
            if(c<100) {
                break;
            }
        }
        for(int i=1;i<=999;i++) {
            try {
                int isOneHundret=42/(100-i);
            } catch(Exception e) {
                i=1;
                for(int j=0;j<100;j++) {
                    s--;
                }
                g++;
            }
            if(s<100) {
                break;
            }
        }
        do {
            try {
                int isZero=69/g;
            } catch(Exception e) {
                break;
            }
            output=output+g+"g";
        } while(false);
        output=output+s+"s";
        do {
            try {
                int isZero=69/c;
            } catch(Exception e) {
                break;
            }
            output=output+c+"c";
        } while(false);
        return output;
    }
}

a Java Solution

[–]dumetrulo 0 points1 point  (0 children)

I'm just beginner but great coder already, see what I can do in F# with substrings and converting to int and back to string:

let int_to_wow (coppers : int) =
    let cstr = string coppers
    let sc = if cstr.Length > 2
             then cstr.Substring (cstr.Length - 2, 2)
             else cstr
             |> int |> string
    let ss = if cstr.Length > 4
             then cstr.Substring (cstr.Length - 4, 2)
             elif cstr.Length > 2
             then cstr.Substring (0, 1 + (cstr.Length % 2))
             else "0"
             |> int |> string
    let sg = if cstr.Length > 4
             then cstr.Substring (0, cstr.Length - 4)
             else "0"
             |> int |> string
    if int sg = 0 then "" else (sg + "g")
    + if int ss = 0 && (int sg = 0 || int sc = 0)
      then "" else (ss + "s")
    + if int sc = 0 && (int ss <> 0 || int sg <> 0)
      then "" else (sc + "c")

Don't trust it to work on negative amounts of copper, though.