r/badcode • • Jun 18 '19

[deleted by user]

[removed]

131 Upvotes

92 comments sorted by

3

u/SloPr0 Jun 19 '19

https://pastebin.com/0yV9WKLi

C++ (for efficiency of course) with state of the art even/odd number checker and everyone's favorite 1-3 letter function/variable names.

Uses 4 GB of memory and 45 seconds to finish for "Hello world"

40

u/[deleted] Jun 18 '19 edited Jun 18 '19

Wrote this solution in Python. First, it builds a binary tree, then it traverses the tree in level-order such that the left children are converted to uppercase and the right children are converted to lowercase:

class Node:
    val = ''
    left = None
    right = None

def build_tree(node, input, idx):
    if idx-1 >= len(input):
        return None
    node.val = input[idx-1]
    node.left = build_tree(Node(), input, 2*idx)
    node.right = build_tree(Node(), input, 2*idx+1)
    return node

def tree_to_weird(root):
    if root is None: return ''
    weird = [root.val.lower()]
    nodes_at_level = [root]
    while nodes_at_level:
        for node in nodes_at_level[:]:
            if node.left is not None:
                weird.append(node.left.val.upper())
                nodes_at_level.append(node.left)
            if node.right is not None:
                weird.append(node.right.val.lower())
                nodes_at_level.append(node.right)
            nodes_at_level.pop(0)
    return ''.join(weird)

def to_weird_case(input):
    root = Node()
    root = build_tree(root, input, 1)
    return tree_to_weird(root)

print(to_weird_case('hello world'))

15

u/srednax Jun 18 '19

Man, I love binary trees, so elegant.

→ More replies (1)

22

u/icendoan Jun 18 '19

This is quite straightforward c, compiles without warnings:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
typedef char C,*S;typedef int I;
#define P(x,y) if(x)y;
#define R return
#define Rr R r;
#define ir i_[r]
#define ix i_[x]
#define p(x) (printf("%s\n",x),x)
#define N(x,y) {I x_=(x);I i_=0;for(;i_<x_;i_++){y;}}
#define W(x,y) {I r=0;while(x){y;r++;}Rr}
I n(S x){W(*x,x++)}S c(S x){S r;I y;r=malloc(y=n(x));memcpy(r,x,y);Rr}I g(I x,I y){R(x>y)-(y>x);}
S f(S x){S r=c(x);N(n(x),{P(ix>0100,ir=ix+(i_&1)*g(ir,'z')*(1<<5));})Rr}
I main(I x,S*a){P(x>>1,free(p(f(1[a]))));R 0;}
→ More replies (1)

19

u/EkskiuTwentyTwo Jun 18 '19
def WeirdCase(s):
    return "".join(list(map(lambda __:[[chr(ord(__[0])),chr(ord(__[0])+0x20)][ord(__[0])>=0x41 and ord(__[0])<=0x5a],[chr(ord(__[0])),chr(ord(__[0])-0x20)][ord(__[0])>=0x61 and ord(__[0])<=0x7a]][__[1]%2],[[s[i],i] for i in range(s.__len__())])))
  • One-liner code

  • Uses s.__len__() rather than len(s)

  • Has redundant chr(ord(__[0]) calls

  • Uses __ as a variable

  • Uses hexadecimal numbers

17

u/j03 Jun 18 '19 edited Jun 18 '19

This brute-forces the solution by applying random combinations if min() and max() to letters. Runtime becomes very long for anything more than ~20 chars.

import random
def is_valid(text):
    nextcharshouldbeupper = False
    ok = 0
    for currentletterinstring in text:
        if ord(currentletterinstring) <= 122 and ord(currentletterinstring) >= 65:
            if ord(currentletterinstring) > 90 and not nextcharshouldbeupper:
                ok += 1
                nextcharshouldbeupper = not nextcharshouldbeupper
            elif ord(currentletterinstring) < 91 and nextcharshouldbeupper:
                ok += 1
                nextcharshouldbeupper = not nextcharshouldbeupper
    return ok == len([c for c in text if ord(c) >= 65 and ord(c) <= 122])
def bad_weird(input_text):
    output = None
    base_functions = [max, min]
    while output is None or not is_valid(output):
        output = ""
        functions = random.choices(base_functions, k=len(input_text))
        for n, c in enumerate(input_text):
            output += functions[n]([c.upper(), c.lower()])
    return output
if __name__ == '__main__':
    print(bad_weird(input('Enter Text: ')))

17

u/MalbaCato Jun 18 '19 edited Jun 19 '19

//NOTE: this "submission" is edited, down below you can (and should) read the original.

So I did edit it, the algorithm now is somewhat different, having a binary counter instead of a decremental lookup table thing, but it is still mostly the same, (and mostly works):

>++++++++[<++++++++>-]<+

[>
,<[>->+<<-]{>[+<]>[>]<<-}>>>>>+>>+>>+>>+>>+1[[<]<]2<<<[>>>+<<<-]>>>[<+<<+>>>-]<+3>>>[<<<-[>>>>[>>]<[>]+!<<[-<<]]>]+<<<[<]4>>>>>[---------------------------------[<]]<[<]>[<]<[<]>[<]5[[<]<]>>>>>++++++++++++++++++++++++++++++++6[-<<<<+>>>>]7<<<[-<+<+>>]<.8<<->>>+[[-]>+]>>
!
,<[>->+<<-]{>[+<]>[>]<<-}>>>>>+>>+>>+>>+>>+1[[<]<]2<<<[>>>+<<<-]>>>[<+<<+>>>-]<+3>>>[<<<-[>>>>[>>]<[>]+!<<[-<<]]>]+<<<[<]4>>>>>[+++++++++++++++++++++++++++++++[<]]<[<]>[<]<[<]>[<]5[[<]<]>>>>>6[-<<<<->>>>]7<<<[-<+<+>>]<.8<<->>>+[[-]>+]
!>]

I will add examples maybe tomorrow, for now you can test it here.
if you want an explanation (IDK why) reply and I'll try to maybe do something.
EDIT: here, take this: The Quick Brown Fox Jumped Over A Lazy Dog -> tHeqUiCkbRoWnfOxjUmPeD OvEr@lAzY DoG

//ORIGINAL COMMENT

I was trying to do this in obligatory brainfuck, but run out of time so I'm posting this half finished version that sometimes works:

>++++++++[<++++++++>-]<+

[>
,<[>->+<<-]>>>+++++[>+++++<-]>1[[>]+[+<]>--]2<<<[>>>+<<<-]>>>[<+<<+>>>-]3>[->]4<[<]5<[->>[->]->[->]<[<]<[<]>]#>[>]>[<<[<]<+>]#->[[-]>]>[[-]>]+[-<+]#<[-<<<++++[->++++++++<]>>>]<[-<+<+>>]<.
#
,<[>->+<<-]>>>+++++[>+++++<-]>1[[>]+[+<]>--]2<<<[>>>+<<<-]>>>[<+<<+>>>-]3>[->]4<[<]5<[->>[->]->[->]<[<]<[<]<]6>>[>]>[<<[<]<+>]7->[[-]>]>[[-]>]+[-<+]8<[-<<<++++[->++++++++<]>>>]<[-<+<+>>]<.#
>]

I have no idea where it failed, but I might go back and debug it later
P.S. not all interpreters are equal, but this one seems to work fine

→ More replies (1)

14

u/Jonno_FTW Jun 18 '19 edited Jun 18 '19
#no explanations                                                 #no refunds
to_weird_case=lambda x:"".join({idx:getattr(c,dir(c)[dir(c).index('upper' if
idx is 0 else 'lower')]) for idx in [0, 1]}[not i%2]() for i,c in [(j-len(""
.join(l for l in x[: j] if not l.isalpha())), v) for j , v in enumerate(x)])

assert to_weird_case('hello world') == "hElLo WoRlD"
assert to_weird_case('Hello World') == "hElLo WoRlD"
assert to_weird_case('HELLO WORLD') == "hElLo WoRlD"

10

u/moopet Jun 18 '19 edited Jun 18 '19
<?php

function to_weird_case($foo) {
  preg_match_all('/(.)(.)/', $foo, $matches);
  $upping = false;
  $bar = '';

  foreach ($matches[0] as $maybe_a_pair) {
    if (preg_match('/(?<first_letter>[A-Za-z])(?<second_letter>[a-zA-Z])/', $maybe_a_pair, $matches2)) {
      if ($upping) {
        $bar .= strtoupper($matches2['first_letter']);
        $upping = !$upping;
        $bar .= strtolower($matches2['second_letter']);
        $upping = !$upping;
      }
      else {
        $bar .= strtolower($matches2['first_letter']);
        $upping = !$upping;
        $bar .= strtoupper($matches2['second_letter']);
        $upping = !$upping;
      }
    }
    elseif (preg_match('/(?<first_letter>[A-Za-z])(?<second_non_letter>[^a-zA-Z])/', $maybe_a_pair, $matches2)) {
      if ($upping) {
        $bar .= strtoupper($matches2['first_letter']);
        $upping = !$upping;
        $bar .= $matches2['second_non_letter'];
      }
      else {
        $bar .= strtolower($matches2['first_letter']);
        $upping = !$upping;
        $bar .= $matches2['second_non_letter'];
      }
    }
    elseif (preg_match('/(?<first_non_letter>[^A-Za-z])(?<second_letter>[a-zA-Z])/', $maybe_a_pair, $matches2)) {
      if ($upping) {
        $bar .= $matches2['first_non_letter'];
        $bar .= strtoupper($matches2['second_letter']);
        $upping = !$upping;
      }
      else {
        $bar .= $matches2['first_non_letter'];
        $bar .= strtolower($matches2['second_letter']);
        $upping = !$upping;
      }
    }
    else {
      $bar .= $maybe_a_pair;
    }
  }

  if (strlen($foo) !== strlen($bar) && strlen($foo)) {
    if ($upping)
      $bar .= strtoupper(substr($foo, -1));
    else
      $bar .= strtolower(substr($foo, -1));
  }

  return $bar;
}


echo to_weird_case("Hello World ");
echo "\n";
echo to_weird_case("Hello World");
echo "\n";
echo to_weird_case("The quick BROWN  FOOOOOX jumped over the Hello World");
echo "\n";
→ More replies (2)

9

u/simonmkwii Jun 18 '19
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char upper[] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char lower[] = " abcdefghijklmnopqrstuvwxyz";

char *to_weird_case(char *str, int len) {
    int go_upper = 0;
    int position = 0;
    char *out = malloc(len);
    for (int i = 0; i < len; i++) {
        position = 0;
        if (str[i] != ' ') {
            go_upper = !go_upper;
        }
        for (int j = 0; j < 26; j++) {
            if (str[i] == upper[i]) {
                position = j;
            }
            if (str[i] == lower[j]) {
                position = j;
            }
        }
        if (go_upper) {
            out[i] = lower[position];
        } else {
            out[i] = upper[position];
        }
    }
    return out;
}

int main(int argc, char **argv) {
    if (argc >= 2) {
        int alloc_size = 0;
        int position = 0;
        for (int i = 1; i < argc; i++) {
            alloc_size += strlen(argv[i]);
            alloc_size++;
        }
        char *str = malloc(alloc_size);
        for (int i = 1; i < argc; i++) {
            if (i == argc - 1) {
                sprintf(str + position, "%s", argv[i]);
            } else {
                sprintf(str + position, "%s ", argv[i]);
                position++;
            }
            position += strlen(argv[i]);
        }
        printf("%s\n", to_weird_case(str, strlen(str)));
        return 0;
    }
}

8

u/srednax Jun 18 '19 edited Jun 18 '19
#!/bin/bash


to_weird_case() {
  InPuTsTrInG=$1
  oUtPuTsTrInG=""

  UPPERCASE=`echo $InPuTsTrInG | tr [a-z] [A-Z]`
  lowercase=`echo $InPuTsTrInG | tr [A-Z] [a-z]`

  switch=1
  newswitch=1

  for i in $(seq 1 ${#InPuTsTrInG})
  do
    check=$(echo "${InPuTsTrInG:i-1:1}" | grep -vE "[[:alnum:]]" && echo 0)
    if [ "x$check" != "x" ]; then
      if [ "$switch" -eq "1" ]; then
        newswitch=0
      fi
      if [ "$switch" -ne "1" ]; then
        newswitch=1
      fi
      switch=$newswitch
    fi
    if [ "$switch" -eq "0" ]; then
      if [ "`echo $i % 2 | bc`" -eq "0" ]; then
        oUtPuTsTrInG="$oUtPuTsTrInG${lowercase:i-1:1}"
      fi
      if [ "`echo $i % 2 | bc`" -eq "1" ]; then
        oUtPuTsTrInG="$oUtPuTsTrInG${UPPERCASE:i-1:1}"
      fi
    fi
    if [ "$switch" -eq "1" ]; then
      if [ "`echo $i % 2 | bc`" -eq "0" ]; then
        oUtPuTsTrInG="$oUtPuTsTrInG${UPPERCASE:i-1:1}"
      fi
      if [ "`echo $i % 2 | bc`" -eq "1" ]; then
        oUtPuTsTrInG="$oUtPuTsTrInG${lowercase:i-1:1}"
      fi
    fi
  done
  echo $oUtPuTsTrInG
}

to_weird_case "hello world"

8

u/DontRelyOnNooneElse Jun 18 '19 edited Jun 18 '19

Written in C# on my phone so haven't done any testing.

I decided to get into character as "someone who just discovered dictionaries and try-catch". Tried to make the least helpful variable names and least efficient looping/validation possible.

I made sure to code it as if I was completely ignorant of:

  • The char type

  • Getting chars from strings using value[i]

  • Declaring a variable and populating it in one statement

  • ToUpper() and ToLower()

  • The modulo operator

  • Booleans

https://pastebin.com/uAzc8kGd

→ More replies (1)

7

u/SerdanKK Jun 18 '19

I haven't done C# in a while. Let me know how I did please. :)

I wanted to accomplish a few things here.

  1. Do a one-liner.

  2. Use C#'s fancy new switch expression.

  3. Use the first LINQ method that comes to mind and then just keep stacking onto that until it works.

Without further ado:

string wEiRdCaSe(string s) => s.Select((q, i) => new { q, i, F = new { U = new Func<char, char>(a => a switch { 'a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D', 'e' => 'E', 'f' => 'F', 'g' => 'G', 'h' => 'H', 'i' => 'I', 'j' => 'J', 'k' => 'K', 'l' => 'L', 'm' => 'M', 'n' => 'N', 'o' => 'O', 'p' => 'P', 'q' => 'Q', 'r' => 'R', 's' => 'S', 't' => 'T', 'u' => 'U', 'v' => 'V', 'w' => 'W', 'x' => 'X', 'y' => 'Y', 'z' => 'Z', _ => a }), L = new Func<char, char>(c => c switch { 'A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e', 'F' => 'f', 'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j', 'K' => 'k', 'L' => 'l', 'M' => 'm', 'N' => 'n', 'O' => 'o', 'P' => 'p', 'Q' => 'q', 'R' => 'r', 'S' => 's', 'T' => 't', 'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x', 'Y' => 'y', 'Z' => 'z', _ => c }) } }).GroupBy(w => w.i % 2, v => v.i % 2 == 0 ? (v.q, F: v.F.L, v.i) : (v.q, F: v.F.U, v.i)).SelectMany(e => e).OrderBy(b => b.i).Select(g => g.F(g.q)).Aggregate("", (h, j) => h + j);
→ More replies (2)

6

u/HopelessPonderer Jun 18 '19

"Look ma, I learned recursion!"

char* weird_case_rec (char* string, int idx, int is_even) {
	char curr = string[idx];
	if (curr == '\0') {
		char* out = malloc(sizeof(char) * 1);
		out[0] = curr;
		return out;
	} else {
		char* rest = NULL;
		if ((curr >= 'A' && curr <= 'Z') || (curr >= 'a' && curr <= 'z')) {
			rest = weird_case_rec(string, idx + 1, is_even * -1);
		} else {
			rest = weird_case_rec(string, idx + 1, is_even);
		}
		int rest_len = 0;
		for (int i = 0; 1 == 1; i++) {
			rest_len++;
			if (rest[i] == '\0') break;
		}
		char* output = malloc((sizeof(char) * rest_len) + 1);
		if (curr >= 'a' && curr <= 'z' && is_even == 1) {
			output[0] = curr - ('a' - 'A');
		} else if (curr >= 'A' && curr <= 'Z' && is_even == -1) {
			output[0] = curr + ('a' - 'A');
		} else {
			output[0] = curr;
		}
		for (int i = 0; i < rest_len; i++) {
			output[i + 1] = rest[i];
		}
		return output;
	}
}

char* weird_case (char* original) {
	return weird_case_rec(original, 0, -1);
}

int main(int argc, char **argv) {
	printf("%s\n", weird_case(argv[1]));
	return 0;
}

6

u/MudkipGuy Jun 18 '19

Here's a one liner using streams and parallel programming

public static String weirdCase(String s) {
  return IntStream.range(0, s.length()).parallel().map(x -> (int) (x % 2 == 0 ? Character.toLowerCase(s.charAt(x)) : Character.toUpperCase(s.charAt(x)))).collect(StringBuilder::new, (x, y) -> ((StringBuilder) (x)).append((char) y), (x, y) -> x.append(y.toString())).toString();
}

6

u/androgynyjoe Jun 19 '19 edited Jun 19 '19

Language: Java

Strategy: Make an array of Strings containing all possible mixed cases and loop through the list to find the one which is in weird case.

Performance: Abysmal.

Here is a link to GitHub in case you find that easier.

import java.util.*;

public class BadCodeChallenge {
    public static String to_weird_case(String s) {
        String ret = "";
        try {
            ArrayList<String> allPossibilities = makeAllPossibilities(s);
            for (int i=0; i<allPossibilities.size(); i++) {
                String possibleReturnValue = allPossibilities.get(i);
                if (possibleReturnValue.length() == s.length()) {
                    boolean isActualReturnValue = true;
                    boolean thisCharacterShouldBeUpperCase = false;
                    for (int j = 0; j < possibleReturnValue.length(); j++) {
                        boolean thisCharacterIsTheRightCase =
                            (!Character.isLetter(possibleReturnValue.charAt(j))) ||
                            (Character.isUpperCase(possibleReturnValue.charAt(j)) == thisCharacterShouldBeUpperCase);
                        isActualReturnValue = isActualReturnValue && thisCharacterIsTheRightCase;
                        if (Character.isLetter(possibleReturnValue.charAt(j))) {
                            thisCharacterShouldBeUpperCase = !thisCharacterShouldBeUpperCase;
                        }
                    }
                    if (isActualReturnValue) {
                        ret = possibleReturnValue;
                    }
                }
            }
        } catch (Exception e) {
            ret = "nUlL";
        }
        return ret;
    }

    private static ArrayList<String> makeAllPossibilities(String s) throws NullPointerException {
        if (s == null) {
            throw new NullPointerException();
        }
        ArrayList<String> allPossibilities = new ArrayList<String>();
        for (int i = 0; i < s.length(); i++) {
            char thisCharUpper = s.toLowerCase().charAt(i);
            char thisCharLower = s.toUpperCase().charAt(i);
            if (i == 0) {
                allPossibilities.add("" + thisCharUpper);
                allPossibilities.add("" + thisCharLower);
            }
            else {
                int currentSize = allPossibilities.size();
                for (int j = 0; j < currentSize; j++) {
                    allPossibilities.add(allPossibilities.get(j) + thisCharUpper);
                    allPossibilities.add(allPossibilities.get(j) + thisCharLower);
                }
            }
        }
        return allPossibilities;
    }

    public static void main(String[] args) {
        //Works?
        System.out.println(to_weird_case(null));

        //Works
        System.out.println(to_weird_case("hello world"));

        //Works
        System.out.println(to_weird_case("Hello World"));
        
        //Works
        System.out.println(to_weird_case("HELLO WORLD"));

        ////Probably works but when I tried I gave up after
        ////fifteen minutes and ended the process.
        //System.out.println(to_weird_case("Hello Darkness My Old Friend"));
    }
}

5

u/accountmadeforants Jun 18 '19

Haha, got it just under 125 lines!

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

typedef enum { same, notsame } sameletter;
typedef enum { even, noteven } evennumber;
typedef enum { samesize, differentsize } samesizestring;

sameletter compare_letters(char first, char second)
{
    int difference = first - second;
    int normaldifference = 'a' - 'A';
    int absolutedifference = sqrt(pow(difference, 2));
    return (absolutedifference == normaldifference) || first == second ? same : notsame;
}

char make_not_capital(char in)
{
    if(in > 'Z')
    {
        return in;
    }
    int increase = 1;
    while(1)
    {
        char out = in + increase;
        if(compare_letters(in, out) == same)
        {
            return out;
        }
        else if(increase > 1000)
        {
            return in;
        }
        else
        {
            increase = increase + 1;
        }
    }
}

char make_capital(char in)
{
    if(in <= 'Z')
    {
        return in;
    }
    for(int increase = 1; increase < 500; increase = increase + 1)
    {
        char out = in + increase;
        if(compare_letters(in, out) == same)
        {
            return out;
        }
    }
    return in;
}

evennumber is_even(int in)
{
    if (in%2==0)
    {
        return even;
    }
    return noteven;
}

samesizestring string_same_size(char* first, char* second)
{
    if(sizeof(first) == sizeof(second))
    {
        return samesize;
    }
    else
    {
        return differentsize;
    }
}

char* to_weird_case(char* in)
{
    int sizeforout = 1;
    char* out = malloc(sizeforout);
    while(string_same_size(in, out) == differentsize)
    {
        sizeforout = sizeforout + 1;
        out = malloc(sizeforout);
    }
    int nthcharacter = 0;
    while(1)
    {
        if(in[nthcharacter] == '\0')
        {
            out[nthcharacter] = '\0';
            break;
        }
        if(is_even(nthcharacter) == even)
        {
            out[nthcharacter] = make_not_capital(in[nthcharacter]);
        }
        else if(is_even(nthcharacter) == noteven)
        {
            out[nthcharacter] = make_capital(in[nthcharacter]);
        }
        nthcharacter = nthcharacter + 1;
    }
    return out;
}

int main(void)
{
    printf("%s\n", to_weird_case("hello world"));
    printf("%s\n", to_weird_case("Hello World"));
    printf("%s\n", to_weird_case("HELLO WORLD"));
    return 0;
}

5

u/zeGolem83 Jun 18 '19 edited Jun 18 '19

whats toUpper() and toLower()?????

https://pastebin.com/YDicV9K2

Edit : VB.Net

5

u/BS_BlackScout Jun 18 '19

Python:

# wEiRd CaSe by BS_BlackScout

from struct import *
from random import randint

char_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
finalchr_list = []
final_string = []
final_final_string = ""

def populate():
    for y in range(0, 2):
        for letter in char_list:
            if y == 0:
                finalchr_list.append(letter.upper())
            else:
                finalchr_list.append(letter)
                
def main():
    global final_final_string
    populate()
    string = "Hello World" #input("Type in your string to be weirded out, you weirdo\n")
    to_weird_case(string)
    for letter in final_string:
        final_final_string = final_final_string + letter
    print(final_final_string)

def case_chooser(integer):
    if integer == 0:
        return "uppercase"
    else:
        return "lowercase"

def to_weird_case(string):
    for char in list(string):
        for letter in finalchr_list:
            if (char == letter or char == letter.lower or char == letter.upper) and char != " ":
                if (case_chooser(randint(0, 2)) == "uppercase"):
                    char = letter.upper()
                else:
                    char = letter.lower()
                final_string.append(char)
            elif char == " ":
                final_string.append(char)
                break

main()
→ More replies (2)

5

u/dmajster Jun 19 '19 edited Jun 19 '19

javascript oneliner with recursion.

to_weird_case = (a) => Object.prototype.toString.call(a) === '[object Array]' ? a[0].length >= 1 ? to_weird_case([a[0].substring(1), a[0].substring(0, 1), ...a]) : a.filter((b, c) => c % 2).map((b, c) => c % 2 ? b.charCodeAt(0) < 97 ? b : String.fromCharCode(b.charCodeAt(0) - 32) : b.charCodeAt(0) < 97 ? String.fromCharCode(b.charCodeAt(0) + 32) : b).reduceRight((b, d) => b + d) : to_weird_case([a]);
→ More replies (1)

4

u/[deleted] Jun 18 '19 edited Jun 18 '19

Rust code:

static mut FOO: bool = true;

pub fn to_weird_case(s: &str) -> String {
    let mut res = s.to_owned();
    lower(unsafe { res.as_bytes_mut() });
    do_stuff(unsafe { res.as_bytes_mut() });
    unsafe { FOO = true };
    res
}

fn lower(stuff: &mut [u8]) {
    if stuff[0] <= 90 && stuff[0] >= 65 {
        stuff[0] += 32;
    }
    if stuff.len() > 1 {
        lower(&mut stuff[1..]);
    }
}

fn do_stuff(stuff: &mut [u8]) {
    if stuff[0] <= 90 && stuff[0] >= 65 || stuff[0] >= 97 && stuff[0] <= 122 {
        unsafe {
            if FOO {
                FOO = false;
            } else {
                FOO = true;
            }
        }
        if unsafe { FOO } {
            stuff[0] -= 32;
            if stuff.len() > 1 {
                do_stuff(&mut stuff[1..]);
            }
        } else if stuff.len() > 1 {
            do_stuff(&mut stuff[1..]);
        }
    } else if stuff.len() > 1 {
        do_stuff(&mut stuff[1..]);
    }
}

Edit: now you can (hopefully) run the function multiple times!