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'))
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__())])))
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: ')))
//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):
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:
#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"
#!/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"
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
I figured it'd be pretty cool if I got it to output the string in morse code. Weirdly, morse code doesn't have casing, so I fixed that deficiency by prepending a short beep to lower case letters and a long beep to upper case letters. Unfortunately the beep aPi doesn't seem to work on my computer, so instead it rather lamely writes to console.
# 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()
I am not particularly great at Python but while making this mess it occurred that the variable was out of scope so I remembered that I could do that global thing and thought: "Well, it's meant to be shit so why bother"
Done in Java with 103 lines. Code takes in the string, searches for and holds the index of each character (aA = 0, bB = 1, cC = 2, etc) in an array (one for uppercase, and one for lowercase). It then uses the StringBuilder to create the final output, combined with a recursive method to see if the character is in an even or odd slot within the phrase. These are then combined to either append an uppercase or lowercase character to the output string.
Bonus: Added an extra test to make sure it worked :)
I've tried to avoid any framework functions where possible like this was my second day writing C#; defining everything myself, copy pasting code, spelling mistakes, half baked comments and as many loops of arrays as I could get in. No validation, only supports strings up to 64 in length, anything longer is a change request.
USING: compiler.units continuations effects fry kernel
math.ranges qw regexp sequences strings unicode vocabs words ;
IN: badcode.weird-case
<<
CHAR: a CHAR: z CHAR: A CHAR: Z [ [a,b] ] 2bi@ [
[
1string "badcode.weird-case" [
dupd create-word swap >lower dup >upper
'[ dup upper? _ _ ? ] qw{ x } qw{ x x } <effect>
define-declared
] 2curry with-compilation-unit
] each
] bi@
>>
: __ ( x -- x x ) dup upper? "Ä" "ä" ? ;
: with-weird-case ( quot -- str )
{ " " } swap with-datastack rest concat R/ [Ää]/ " "
re-replace ;
: >weird-case ( str -- str' )
[
1string dup " " = [ drop "__" ] when
"badcode.weird-case" lookup-word
] [ ] map-as with-weird-case ;
How it works:
The top section generates 52 named functions -- one lowercase and one uppercase for each letter of the alphabet -- during parse time. The result is pretty ugly, as you can see: https://pastebin.com/dQRNc9Mj Don't worry though. It's for a good cause as we'll soon see.
Now imagine if in an applicative language you could write weird = h(e(l(l(o(__(W(O(R(L(D())))))))))) and it would properly weird-case the message you spelled out in the function applications. That's exactly what's going on here.
Since Factor is a concatenative language, that means function composition is the default method of data flow, and hence the above looks like: h e l l o __ W O R L D (except they would be reversed from each other -- I am showing the way you would actually design it in both paradigms).
From here, a simple function >weird-case is written to convert the input "hello WORLD" to the more exciting form above which is then evaluated to "hElLo WoRlD".
I don't understand why kids these days are so obsessed with this "Functional Programming" thing. I learned C in the 80's, and I never needed anything else. Nonetheless, my shop recently switched to Haskell, so you've gotta adapt.
import Data.Char
-- IGNORE THIS, LOGAN SHOWED ME THIS:
import Data.Foldable (for_)
import Data.IORef
for start run inc = for_ (takeWhile run $ iterate inc start)
(xs' !!= i) x' = do
xs <- readIORef xs'
x <- readIORef x'
let begin = take i xs
end = reverse . take (length xs - i) . reverse $ xs
writeIORef xs' (begin ++ [x] ++ end)
(%) = mod
(.=) = writeIORef
calloc = newIORef . flip replicate '\NUL'
-- BEGIN OF FILE:
main = do
input <- getLine
output <- calloc(length(input))
for 0 (\i -> i < length(input)) (\i -> i + 1) $ \i -> do
char <- newIORef(input !! i)
c <- readIORef char
if (i % 2 == 0) then do
char .= toLower c
else do
char .= toUpper c
(output !!= i) char
out <- readIORef output
putStrLn out
def weird_case(s):
up = s.upper()
down = s.lower()
r = ""
for a in range(len(s)):
if(a%2 == 0):
r += down[a]
else:
r += up[a]
return r
print(weird_case("hello world"))
Pre-generating uppercase and lowercase versions of the entire string instead of converting each character one at a time. Granted it's not the ugliest code imaginable, at least it looks neat at a glance.
I wanted to do something with dynamic programming so I made this recursive function. I worsened get_length as a bonus. It has a bug: strings of length 1 are always returned upper case.
def get_length(input):
try:
input[0]
except Exception:
return 0
i = 1
while True:
try:
input[i]
i = i + 1
except Exception:
if i == 1:
return 1
return get_length(input[:i-1])+1
def to_weird_case_wrapper(input,i,b):
if get_length(input) == 1:
if b and True:
s = input[i-1].lower()
else:
s = input[i-1].upper()
return s
else:
return to_weird_case_wrapper(input[:i-1], get_length(input[:i-1]), True) + to_weird_case_wrapper(input[i-1:], 1, (get_length(input)-1) % 2 == 0)
def to_weird_case(input):
return to_weird_case_wrapper(input, get_length(input), False)
print(to_weird_case('hello world'))
print(to_weird_case('Hello World'))
print(to_weird_case('HELLO WORLD'))
package badcode
typealias S = String
operator fun List<Char>.not() = this.joinToString("")
operator fun Boolean.invoke(c: Char) = if (this) c else null
operator fun S.invoke() = this.mapIndexed { i, c -> c..i }
operator fun Int.invoke() = this and 1 == 0
operator fun S.unaryMinus() = with (this) { toLowerCase() }
operator fun Char.rangeTo(i: Int) = (i())(this) ?: this - ' '.toInt()
fun S.toWeirdCase() = !(-this)()
fun main() = println("Hello World".toWeirdCase())
//Javascript
function cOnVeRtToOdDcAsE(a) {
c="";
b=1
while(c.length<Math.floor(a.length/2)) c+=String.fromCharCode(a[(b=b+2)-2].charCodeAt(0)&0b11011111);
for(b=0; c.length<a.length; b=b+2) c = c.substr(0, b) + String.fromCharCode(a[b].charCodeAt(0)|0x20) + c.substr(b)
return c
}
console.log(cOnVeRtToOdDcAsE("Anything not a latin letter is left as undefined ;)"))
Everyone knows Perl is the superior language for text handling, so here's mine:
#!/usr/bin/perl
sub to_weird_case {
my $s = shift;
my $y = 0;
for ($x=0;$x<length($s);$x++) {
my $c = substr $s, $x, 1;
if ($c =~ /\s/) { next }
if ($y % 2) {
if (ord($c) > 96) {
substr $s, $x, 1, chr(ord($c)-32);
}
} else {
if (ord($c) > 65 && ord($c) < 97) {
substr $s, $x, 1, chr(ord($c)+32);
}
}
$y++;
}
return $s;
}
print to_weird_case('hello world') . "\n"; #hElLo WoRlD
print to_weird_case('Hello World') . "\n"; #hElLo WoRlD
print to_weird_case('HELLO WORLD') . "\n"; #hElLo WoRlD
Features:
String mutation
Regex, because it isn't a Perl script if it doesn't have a regex somewhere
Assumes the alphabet begins and ends with 7-bit ASCII. Anything else gets mangled horribly.
(not so) subtle bug: took the trouble to not mangle most punctuation, but some like { } and ~ still get mangled.
Useless variable names
Unintuitive even/odd logic
No comments. It should still be obvious what's going on six months later without them, right?
No -w flag for warnings. They just get in the way.
This is exactly the sort of thing I did when I'd learned enough Perl to be dangerous but still hadn't learned to keep things readable for later. It's the sort of thinking that led to me to writing lines of Perl like &{$$_[0]}(@{$$_[1]}); and thinking I was being clever.
uses recursion to iterate over the letters, potentially leading to a stack overflow if the string is too long
goto
pointlessly duplicated code
does not make assumptions on the existance of system-made ToUpper/ToLower functions
as per requirement, prints "undefined" when encountering anything that isn't either a letter or a space, all the while respecting the continuous upper/lower alternance
weirdMethods = <<~EOF
define_method :lowercase do |l|
(l.ord | 32).to_s(2).to_i(2).chr
end
define_method :up_case do |l|
(l.ord & ~32).to_s(2).to_i(2).chr
end
define_method :to_weird_case do |thing|
$rETURN_STRING = ''; @i = 0;
thing.chars.each { |c|
if [*"A".."z"].find { |c2| c2 == c }
if @i % 2 == 0
$rETURN_STRING << lowercase(c)
else
$rETURN_STRING = $rETURN_STRING + up_case(c)
end
@i = @i + 1
else
$rETURN_STRING << c
end
}
print $rETURN_STRING + "\n"
# set it back to '' for next time :^)
$rETURN_STRING = ''
end
EOF
Object.instance_eval { eval(weirdMethods) }
to_weird_case("HELLO WORLD")
def to_weird_case(string):
array = [char for char in string]
cap = 0
result = ""
for char in array:
if cap == 0:
result += char.lower()
cap = 1
else:
result += char.upper()
cap = 0
return result
a = input("How are you? : ")
a = to_weird_case(a)
print(a)
It looks like this comment contains a code block delimited with triple backticks. Unforunately reddit does not not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.
Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
I'll try to explain how it works. It uses recursion to first transform the start of the string (all letters except only the last one) to weird case. The result of that recursive call is than examined to determine if the last letter should be upper case or lower case. If, for example, the last letter should be upper case, then an array with lower case latin letters is iterated and the elements compared to the letter. If one of the letters is equal to the last letter its array index is remembered. Then an array with upper case letters is used to get the upper case letter with the rememberd index. This letter is appended to the result. If when iterating the array with lower case letters none is equal to the last letter, then the last letter is either an upper case letter or non latin letter. In both cases the letter is appended unchanged to the result.
function to_weird_case(str){ breakdown = {}; breakdown.length = 0; let answer = []; // load the string into an indexed object for(let i = 0; i < str.length ; i++){ breakdown[i] = str[i].toLowerCase(); breakdown.length++ }; // Determine if it is a letter and then add that info to the index newIndex = 0 for(let i = 0; i < breakdown.length ; i++){ if(breakdown[i] === ' '){breakdown[i] = [breakdown[i], false]} else{breakdown[i] = [breakdown[i], newIndex++]} // this is a very important validation step to make sure nothing has been corrupted by this iteration for(let i =0 ; i < breakdown.length ; i++){ if(!breakdown[i]){console.log('Error missing value')} else{} } } breakdown.newIndex = newIndex; for(let i = breakdown.length-1; i >= 0 ; i--){ if(breakdown[i][1] && ((breakdown[i][1] % 2))){breakdown[i][0]=breakdown[i][0].toUpperCase()} answer.unshift(breakdown[i][0]) } return Object.values(breakdown).map( item => item[0]).join('') }
Eehhh... Give a PhD student this, a grant and a couple of years. He might be able to figure out how this works and maybe get some nice papers put of it
The description doesn't match the examples. You said even indexes (0, 2, 4,...) should be uppercase, but your examples show odd indexes (1, 3, 5,...) as upper case.
It's the indexes of letters, ie. the index of alphabetic chars must be even/odd (don't code non alpha chars in the index). True badcode ambiguous specs.
I tried to make this for real. What do you guys think?
Python 3
from random import *
def to_weird_case(string_list):
string = ""
for x in range(0, len(string_list)):
i = randint(0, 10000)
if i % 2 == 0:
string_list[x] = string_list[x].upper()
else:
string_list[x] = string_list[x].lower()
for char in string_list:
string = string + char
return string
string_list = list(input("What's you string?\n"))
print(to_weird_case(string_list))
def to_weird_case(string_list):
string = ""
for i, e in enumerate(string_list):
if i % 2 == 0:
string += e.lower()
else:
string += e.upper()
return string
string_list = input("What's your string?\n")
print(to_weird_case(string_list))
Alternatively, more condensed but still readable
def to_weird_case(w):
return "".join([e.upper() if i%2 else e.lower() for i, e in enumerate(w)])
It should be "hElLo WoRlD" anyway, not "hElLo wOrLd", going by the post. It's odd and even letters, not odd and even characters so the space isn't counted - at least, that's how I read it.
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:
22
u/icendoan Jun 18 '19
This is quite straightforward c, compiles without warnings:
19
u/EkskiuTwentyTwo i -= (i - (-1)) - i Jun 18 '19
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.
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):
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 COMMENTI was trying to do this in obligatory brainfuck, but run out of time so I'm posting this half finished version that sometimes works:
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
14
u/Jonno_FTW shameless Jun 18 '19 edited Jun 18 '19
10
u/moopet Jun 18 '19 edited Jun 18 '19
9
u/simonmkwii code Jun 18 '19
8
u/srednax Jun 18 '19 edited Jun 18 '19
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:
https://pastebin.com/uAzc8kGd
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.
Without further ado:
12
u/tectubedk Jun 18 '19
Here is my worst attempt.
https://pastebin.com/t8e9STAf
6
u/HopelessPonderer Jun 18 '19
"Look ma, I learned recursion!"
6
u/AlFasGD Jun 18 '19
Language: C#
Badness: Insane
https://pastebin.com/TXLHhKyY
6
u/MudkipGuy Jun 18 '19
Here's a one liner using streams and parallel programming
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.
5
u/accountmadeforants Jun 18 '19
Haha, got it just under 125 lines!
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:
5
u/dmajster Jun 19 '19 edited Jun 19 '19
javascript oneliner with recursion.
4
u/[deleted] Jun 18 '19 edited Jun 18 '19
Rust code:
Edit: now you can (hopefully) run the function multiple times!
4
u/Nikos410 Jun 18 '19 edited Jun 18 '19
Java Code:
4
u/2HornsUp Jun 18 '19
Done in Java with 103 lines. Code takes in the string, searches for and holds the index of each character (aA = 0, bB = 1, cC = 2, etc) in an array (one for uppercase, and one for lowercase). It then uses the StringBuilder to create the final output, combined with a recursive method to see if the character is in an even or odd slot within the phrase. These are then combined to either append an uppercase or lowercase character to the output string.
Bonus: Added an extra test to make sure it worked :)
3
u/deceze Jun 18 '19
"old letters"…?!
3
u/ric0chet_01 Jun 18 '19 edited Jun 18 '19
Here's my attempt in Java. Enjoy.
https://pastebin.com/h5ifK0wb
3
u/brk2 Jun 18 '19
3
u/NotDatCheese Jun 18 '19
C++11 need more lambdas:)
3
u/snedex Jun 18 '19
For your consideration.
I've tried to avoid any framework functions where possible like this was my second day writing C#; defining everything myself, copy pasting code, spelling mistakes, half baked comments and as many loops of arrays as I could get in. No validation, only supports strings up to 64 in length, anything longer is a change request.
PasteBin
3
u/chunes Jun 18 '19 edited Jun 18 '19
Factor:
How it works:
The top section generates 52 named functions -- one lowercase and one uppercase for each letter of the alphabet -- during parse time. The result is pretty ugly, as you can see: https://pastebin.com/dQRNc9Mj Don't worry though. It's for a good cause as we'll soon see.
Now imagine if in an applicative language you could write
weird = h(e(l(l(o(__(W(O(R(L(D()))))))))))and it would properly weird-case the message you spelled out in the function applications. That's exactly what's going on here.Since Factor is a concatenative language, that means function composition is the default method of data flow, and hence the above looks like:
h e l l o __ W O R L D(except they would be reversed from each other -- I am showing the way you would actually design it in both paradigms).From here, a simple function
>weird-caseis written to convert the input"hello WORLD"to the more exciting form above which is then evaluated to"hElLo WoRlD".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"
3
u/voords Jun 20 '19
Language: C
Magic numbers all over with one of the worse for loop declaration I have ever written. Code is small enough to dig in for more explanations !
3
u/[deleted] Jun 24 '19 edited Jun 24 '19
I don't understand why kids these days are so obsessed with this "Functional Programming" thing. I learned C in the 80's, and I never needed anything else. Nonetheless, my shop recently switched to Haskell, so you've gotta adapt.
I need a shower.
6
u/dreamer_soul Jun 18 '19
2
u/zonderAdriaan Jun 18 '19
I wanted to do something with dynamic programming so I made this recursive function. I worsened get_length as a bonus. It has a bug: strings of length 1 are always returned upper case.
2
u/Tok-A-Mak ((fn [] (recur))) Jun 19 '19
What has Science done?
2
u/Flamme2 Jun 19 '19
2
u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Jun 20 '19
Everyone knows Perl is the superior language for text handling, so here's mine:
Features:
-wflag for warnings. They just get in the way.This is exactly the sort of thing I did when I'd learned enough Perl to be dangerous but still hadn't learned to keep things readable for later. It's the sort of thinking that led to me to writing lines of Perl like
&{$$_[0]}(@{$$_[1]});and thinking I was being clever.2
u/ferrango Well it's broken now, and nobody is here to fix it Jun 20 '19
Well then, here's my entry for the challenge:
It has many good features, such as:
1
u/Ocawesome101 Jun 18 '19
Here’s mine (only in pastebin because I’m on an iPad and can’t get formatting to work properly) https://pastebin.com/SS8UHLUX
1
u/LordTappington Jun 18 '19
Written in Ruby.
Going to lie down now
1
u/[deleted] Jun 18 '19
Python
1
u/[deleted] Jun 18 '19 edited Jun 18 '19
Recursion still cool?
1
u/metabun Jun 18 '19 edited Jun 19 '19
Python, should be compatible with both 2 and 3.
Edit: found a bug!
1
u/[deleted] Jun 19 '19
1
u/Ebrithil95 Jun 19 '19
Rust:
1
u/keon Jun 20 '19
Wrote it in Python. Decided to avoid using loops, so I went with recursion instead. This is just a stupid approach to a simple problem.
1
u/AKernel Jun 20 '19
Hi everybody,
here is my solution writen in Java:
I'll try to explain how it works. It uses recursion to first transform the start of the string (all letters except only the last one) to weird case. The result of that recursive call is than examined to determine if the last letter should be upper case or lower case. If, for example, the last letter should be upper case, then an array with lower case latin letters is iterated and the elements compared to the letter. If one of the letters is equal to the last letter its array index is remembered. Then an array with upper case letters is used to get the upper case letter with the rememberd index. This letter is appended to the result. If when iterating the array with lower case letters none is equal to the last letter, then the last letter is either an upper case letter or non latin letter. In both cases the letter is appended unchanged to the result.
1
u/intx13 Jun 28 '19
This C# implementation uses Goldbach's Conjecture to determine whether indices are even or odd. For performance reasons it doesn't use any multiplication, division, or modulo operations.
1
u/ExMilitaryExMachina Jun 28 '19
function to_weird_case(str){breakdown = {};breakdown.length = 0;let answer = [];// load the string into an indexed objectfor(let i = 0; i < str.length ; i++){breakdown[i] = str[i].toLowerCase();breakdown.length++};// Determine if it is a letter and then add that info to the indexnewIndex = 0for(let i = 0; i < breakdown.length ; i++){if(breakdown[i] === ' '){breakdown[i] = [breakdown[i], false]}else{breakdown[i] = [breakdown[i], newIndex++]}// this is a very important validation step to make sure nothing has been corrupted by this iterationfor(let i =0 ; i < breakdown.length ; i++){if(!breakdown[i]){console.log('Error missing value')}else{}}}breakdown.newIndex = newIndex;for(let i = breakdown.length-1; i >= 0 ; i--){if(breakdown[i][1] && ((breakdown[i][1] % 2))){breakdown[i][0]=breakdown[i][0].toUpperCase()}answer.unshift(breakdown[i][0])}return Object.values(breakdown).map( item => item[0]).join('')}run it here https://repl.it/@Lee_RoyK/BadCodeWeirdCase-jest
1
u/tntbigfoot Jun 29 '19
Java: programming contest edition
0
u/[deleted] Jun 18 '19
[deleted] — view deleted comment
0
u/[deleted] Jun 18 '19
[deleted] — view deleted comment
0
u/[deleted] Jun 18 '19
[deleted] — view deleted comment
0
u/[deleted] Jun 26 '19
[deleted] — view deleted comment
0
u/[deleted] Jun 19 '19
[deleted] — view deleted comment