Jump to content

The under 100 line challenge!

fletch to 99

Caesar Cipher encryption program:) 62 lines! Encrypt, decrypt and brute force! Made in Python.

 

MaxKeySize = 26 #defines max key, sets the value of MaxKeySize to 25 print ("Welcome to the Caesar Cipher Converter made by the amazing Ben Johnson!.")#welcome messagedef getMode():    while True:#function to get the mode that the user wants to use        print('Encrypt, decrypt or brute force?' "Valid inputs are: encrypt, decrypt, brute, e, d, b")        mode = input().lower() #converts the mode to lower case before validating        if mode in 'encrypt e decrypt d brute b'.split(): #validation             return mode #returns mode        else:             print('Enter either "encrypt" or "e" or "decrypt" or "d" or "brute" or "b".') #will only be printed if user enters an invalid input def getMessage(): #function to get message    print('Enter your message:')#print    return input()#returns the users message to the function def getKey(): #function to get the offset key    key = 0     while True: #while loop for validation        print('Enter the key number (1-%s)' % (MaxKeySize))        key = int(input())        if (key >= 1 and key <= MaxKeySize):            return key def getTranslatedMessage(mode, message, key): #function to get the encrypted message    if mode[0] == 'd': #decrypt        key = -key #-key from ascii equivalent    translated = ''     for symbol in message: #        if symbol.isalpha():#            num = ord(symbol)#            num += key# this code is to encrypt the message, as it converts each symbol to ascii using ord() command and then adds the key             if symbol.isupper():                if num > ord('Z'):                    num -= 26                elif num < ord('A'):                    num += 26            elif symbol.islower():                if num > ord('z'):                    num -= 26                elif num < ord('a'):                    num += 26 #this code and above is to make sure there are no mistakes, as it stops errors with a's and z's etc             translated += chr(num)        else:            translated += symbol    return translated mode = getMode()message = getMessage()if mode[0] != 'b': #brute force        key = getKey()  print('Your translated text is:')if mode[0] != 'b':    print(getTranslatedMessage(mode, message, key))else:     for key in range(1, MaxKeySize + 1): #for loop to use brute force to decrypt        print(key, getTranslatedMessage('decrypt', message, key))
Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Factorial of a number :P

its in c#.net

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test{    class Program    {        static void Main(string[] args)        {            char reRun;            do            {                double x;                Console.WriteLine("\r\n\r\nEnter number:");                x = double.Parse(Console.ReadLine());                Console.WriteLine("Factorial of {0} = {1}", x, CalculateFactorial(x, --x));                Console.WriteLine("\r\n\r\nDo you want to re-run? (y to rerun/any other char to exit)");                reRun = Console.ReadKey().KeyChar;            }            while (reRun.ToString().ToLower() == "y");        }        private static double CalculateFactorial(double x1, double x2)        {            x1 = x1 * x2;            if (x2 > 1)                x1 = CalculateFactorial(x1, --x2);            return x1;        }    }}

Desktop:

CPU : i5 4440 | Motherboard : Gigabyte B85M-D3H | RAM : Kingstone HyperX blu 4GB x2 | GPU : Asus R9 280X DC II Top [RIP 2017] | PSU : Corsair VS 550W | Display(s) : Dell S2240L | Mouse : Logitech G400s | Operating System : Windows 7 64bit

 

Laptop:

Acer Predator Helios 300 (CPU: Intel Core i5 7300HQ | GPU: GTX 1050ti | RAM: 16GB RAM | Operating System: Windows 10 64bit)

Link to comment
Share on other sites

Link to post
Share on other sites

Couldn't quite get this one down to 100 lines without making it even more unreadable than it already is. It's an EverQuest Wizard translocate bot that reads chat and ports people to where ever they say. It was a bit rushed so it definitely isn't what I would call good code but here it is anyway.
 

import time, ctypes, win32gui, subprocess, osfrom SendKeys import sendKeysfrom datetime import datetimePAUSE = 0.005OOC_DELAY = 2 * 60logPath = "C:\\games\\EverQuest\\Logs\\eqlog_Translocator_beta.txt"mods = []spells = [[['commonlands','common','commons','commonland'],['tox','toxx','toxxulia'],['nek','nektulos'],['nro','ro'],['fay','gfay','faydark','greater'],['cazic'],['combine','dread','dreadland','dreadlands','dl'],['nkarana','north']],[['wkarana','west']]]timeOfLastOOC = datetime(2010, 1, 1)lastDest = NonelastSpellSet = -1def findDest(dest):    for spellset in range(0, len(spells)):        for spellgroup in range(0, len(spells[spellset])):            for spell in range(0, len(spells[spellset][spellgroup])):                if dest == spells[spellset][spellgroup][spell]:                    return spellset, spellgroup    return Nonedef parseLine(line):    global timeOfLastOOC    line = line.lower()    if "tells you," in line:        line = line.replace("'", "")        line = line.split(" ")[5:]        if len(line) < 4:            return        if line[3] == "help":            sendInput("\n/tell {0} commands are \"list\", \"port <destination>\"\n".format(line[0]))        elif line[3] == "list":            for spellSet in spells:                sendInput("\n/tell {} {}\n".format(line[0], ' '.join([s[0] for s in spellSet])))        elif line[3] == "port" or line[3] == "load" and len(line) >= 5:            if line[4] == "list":                for spellSet in spells:                    sendInput("\n/tell {} {}\n".format(line[0], ' '.join([s[0] for s in spellSet])))            else:                port(line[0], line[4], True if line[3] == "port" else False)        elif line[3] == "say" and line[0] in mods:            sendInput("'{}\n".format(' '.join(line[4:])))        elif line[3] == "tell" and line[0] in mods:            sendInput("\n/tell {} {}\n".format(line[4], ' '.join(line[5:])))        elif line[3] == "mimic" and line[0] in mods:            sendInput("\n{}\n".format(' '.join(line[4:])))        elif findDest(line[3]):            port(line[0], line[3], True)        elif line[3] != "sorry,":            sendInput("\n/tell {} {}\n".format(line[0], "Unknown command."))    elif "'hail, translocator'" in line:        currentTime = datetime.now()        if (currentTime - timeOfLastOOC).total_seconds() > OOC_DELAY:            sendInput("8")            timeOfLastOOC = currentTimedef port(target, dest, cast):    spell = findDest(dest)    castPort(target, spell[0], spell[1], cast) if spell else sendInput("\n/tell {} {}\n".format(target, "Unknown destination."))def castPort(target, spellSet, spell, cast):    global lastSpellSet, lastDest    if spellSet != lastSpellSet:        sendInput("\n/mem port{0}\n".format(spellSet+1), 0.05)        sendInput("\n/tell {0} loading spells\n".format(target), 12)    if cast:        if spell == lastDest:            time.sleep(2)        lastDest = spell        sendInput("\n/target {0}\n".format(target), .5)        sendInput("\n/cast {0}\n".format(spell+1), 1)        sendInput("\n/cast {0}\n".format(spell+1), 1)        sendInput("\n/cast {0}\n".format(spell+1), .05)        sendInput("\n/tell {0} casting port to {1}\n".format(target, spells[spellSet][spell][0]), 8)        sendInput("{ESC}", .25)    lastSpellSet = spellSet    def getWindowHandle():    windows = []    def enumHandler(hwnd, lParam):        if win32gui.IsWindowVisible(hwnd):            if 'EverQuest' in win32gui.GetWindowText(hwnd):                windows.append(hwnd)    win32gui.EnumWindows(enumHandler, None)    return None if len(windows) == 0 else windows[0]def sendInput(msg, delay=0.0):    sendKeys(msg, with_spaces=True, with_newlines=True, pause=PAUSE)    if delay > 0:        time.sleep(delay)if __name__ == "__main__":    hwnd = getWindowHandle()    if not hwnd:        proc = subprocess.Popen('c:\\games\\EverQuest\\launchpad.exe')        time.sleep(10)        ctypes.windll.user32.SetCursorPos(1200, 700)        time.sleep(.05)        ctypes.windll.user32.mouse_event(0x2, 0, 0, 0, 0)        time.sleep(0.05)        ctypes.windll.user32.mouse_event(0x4, 0, 0, 0, 0)        time.sleep(15)        sendInput("\n", 20)        sendInput("\n", 25)        proc.kill()        hwnd = getWindowHandle()    s = os.stat(logPath, follow_symlinks=True)    logSize = s.st_size    port('none', 'combine', False)    while True:        with open(logPath, 'r') as log:            newLogSize = log.seek(0, 2)            log.seek(logSize)            logSize = newLogSize            for line in log.read().split("\n"):                parseLine(line)        time.sleep(.5)

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

I wish I could, but I don't have any ideas.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

I can make the most useful program in 1 line. Remove all white spaces ^-^.

You would have a problem if you was using Python.

Link to comment
Share on other sites

Link to post
Share on other sites

Random compliment generator with weather (substitute your values as necessary):

<html><head><meta http-equiv="refresh" content="3600"> <!-- Refresh every 15 minutes --><meta charset="utf-8"></head><body><script language="JavaScript"> var name = ""var compliment = [  "Looking good.",  "Hello, Handsome.",  "Hello, Beautiful.",  "Have a great day.",  "I like your shirt.",  "That looks nice on you.",  "I disagree with anyone who disagrees with you.",  "Have you been working out?",  "Take a break; you've earned it.",  "I support all of your decisions.",  ":)",  "You look perfect.",	"Your shoes are untied. Made you look.",	"Don't worry. You'll do great.",	"The Force is strong with you.",	"Happy Holidays"];var i = Math.floor(Math.random()*compliment.length)var element = compliment[i];var myDate = new Date(); /* hour is before noon */if ( myDate.getHours() < 12 )  { 	document.write("<table border=0 width=1800>")	document.write(" <tr>")	document.write(" <td width=100% align=center>")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")    document.write("Good Morning " + name + " " +  element + "<br />" ); 	document.write("Today's date and time is: " + myDate); } else  /* Hour is from noon to 5pm (actually to 5:59 pm) */if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) { 	document.write("<table border=0 width=1800>")	document.write(" <tr>")	document.write(" <td width=100% align=center>")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")    document.write("Good Afternoon " name + "<br />" );	document.write("Today's date and time is: " + myDate); } else  /* the hour is after 5pm, so it is between 6pm and midnight */if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) {     document.write("<table border=0 width=1800>")	document.write(" <tr>")	document.write(" <td width=100% align=center>")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("<br />")	document.write("Have a good night " + name + " " + element + "<br />"); 	document.write("Today's date and time is: " + myDate);} else  /* the hour is not between 0 and 24, so something is wrong */{     document.write("I'm not sure what time it is!"); }</script><br /><br /><br /><br /><iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%" src="http://forecast.io/embed/#lat=41.7013889&lon=-71.1555556&name=Fall River"> </iframe></body></html>
Link to comment
Share on other sites

Link to post
Share on other sites

Just a console version of Conway's Game of Life. I wrote it to get my feet wet with C#, because the place I'm interning at uses C#.

using System;using System.Collections;using System.Threading;namespace GameOfLife {    class Program  {        static void Main() {            bool reset = false, exit = false; // loop conditionals            BitArray world = new BitArray(24 * 75), nextW = new BitArray(24 * 75); // storage for live/dead cells            Random random = new Random(); // used in initializing world randomly            Console.WriteLine("Welcome to Conway's Game of Life!\n\nControls:\n\n    Reset World:\t\tR\n\n    Exit Application:\t\tEsc");            Console.WriteLine("\n\n\nPress Enter to Begin!"); // greeting/ instructions            Console.ReadLine(); // Pause to keep instructions on screen until user is ready            while (!exit) { // Esc hasn't been pressed                for (int i = 0; i < 24; i++) {                    for (int j = 0; j < 75; j++) {                        if (random.Next(0, 5) == 0) world.Set(i*75 + j, true);                        else world.Set(i * 75 + j, false);                    }                } // One in Five chance of live cell                printWorld(world); // display initial generation                Thread.Sleep(100); // wait 100 mS                while(!reset && !exit) { // neither exit nor reset flag has been raised                    for (int i = 0; i < 24; i++) {                        for (int j = 0; j < 75; j++) {                            if ((world.Get(i * 75 + j) && (getNeighbors(world, i, j) == 2)) || (getNeighbors(world, i, j) == 3)) nextW.Set(i * 75 + j, true);                            else nextW.Set(i * 75 + j, false);                        }                    } // If Neighbors N = 2 and cell is currently living, cell lives. Else if N = 3, cell lives. Else cell dies.                    for (int i = 0; i < 24; i++) {                        for (int j = 0; j < 75; j++)                            world.Set(i*75 + j, nextW.Get(i*75 + j));                    } // pass new generation values into displayed array (will become old generation)                    printWorld(world); // display new generation                    Thread.Sleep(100); // wait 100 mS                    if (Console.KeyAvailable) {                        var key = Console.ReadKey(true).Key;                        if (key == ConsoleKey.R) reset = true;                        else if (key == ConsoleKey.Escape) exit = true;                    } // if key pressed, check to see if its a key we care about, and update flags accordingly                }                reset = false; // in case r was pressed, resets the reset flag to false            }        }        static void printWorld(BitArray world) {            string newS = ""; // used because old image persisted without first writing to string            for (int i = 0; i < 24; i++) {                for (int j = 0; j < 75; j++) {                    if (world.Get(i*75 + j)) newS += "#"; else newS += " ";                }                newS += "\n";            }            Console.Clear(); // used for same reason as newS            Console.Write(newS); // update console image        }        static int getNeighbors(BitArray world, int i, int j) {            // i and j assumed to be within bounds. OK for self-contained program and functions, not for library/ group code.            int neighbors = 0;            if (i + 1 < 24) { // top row y val ok                if ((j + 1 < 75) && world.Get((i+1)*75 + j+1)) neighbors++;                if (world.Get((i+1)*75 + j)) neighbors++;                if ((j - 1 >= 0) && world.Get((i+1)*75 + j-1)) neighbors++;            }            if ((j + 1 < 75) && world.Get(i*75 + j+1)) neighbors++;            if ((j - 1 >= 0) && world.Get(i*75 + j-1)) neighbors++;            if (i - 1 >= 0) { // bottom row y val ok                if ((j + 1 < 75) && world.Get((i-1)*75 + j+1)) neighbors++;                if (world.Get((i-1)*75 + j)) neighbors++;                if ((j - 1 >= 0) && world.Get((i-1)*75 + j-1)) neighbors++;            }            return neighbors; // each neighbor checked, returns number of living cells        }    }}

CPU - FX 8320 @ 4.8 GHz

| MoBo - Sabertooth 990FX | GPU - XFX Radeon HD 7870 GHz Ed. @ 1.075 GHz | CPU Cooler - H100 | RAM - 16 GB Dual Channel Vengeance @ 1600 MHz (didn't care to push these...) | OS - Windows 8 Pro | Storage - OCZ Vertex 3 (120 GB Boot), Samsung 830 Pro 64 GB, WD Black 1 TB, some random 320 GB from a laptop | PSU - CM Silent Hybrid Pro 850W (MDPC Sleeving) | Case - 800D | Monitors - ASUS V238H/ X Star DP2710LED | Mouse - M90 Keyboard - CM Quickfire Rapid w/ custom key caps

"When life gives you lemons, Don't make lemonade, make life take the lemons back!" - Cave Johnson, CEO

Link to comment
Share on other sites

Link to post
Share on other sites

I wanna do this, but idk what to make

Make snake for the console window.

CPU - FX 8320 @ 4.8 GHz

| MoBo - Sabertooth 990FX | GPU - XFX Radeon HD 7870 GHz Ed. @ 1.075 GHz | CPU Cooler - H100 | RAM - 16 GB Dual Channel Vengeance @ 1600 MHz (didn't care to push these...) | OS - Windows 8 Pro | Storage - OCZ Vertex 3 (120 GB Boot), Samsung 830 Pro 64 GB, WD Black 1 TB, some random 320 GB from a laptop | PSU - CM Silent Hybrid Pro 850W (MDPC Sleeving) | Case - 800D | Monitors - ASUS V238H/ X Star DP2710LED | Mouse - M90 Keyboard - CM Quickfire Rapid w/ custom key caps

"When life gives you lemons, Don't make lemonade, make life take the lemons back!" - Cave Johnson, CEO

Link to comment
Share on other sites

Link to post
Share on other sites

I don't know a lot outside of a little hands-on experience with Batch programming, but I have a VBS file that runs a batch that I have in the Task Scheduler to clear out my temporary files on my Windows 8.1 laptop. Unfortunately, I'm still looking for a way to delete the folders that are also created in the Temp areas that I don't need, since they are not deleted during this.

 

The VBS allows me to run the batch file in silent mode. My results after a lot of testing and guessing are below. The Task Scheduler is set to run the VBS at log in, then restart every so often so that I can do things without issues that could come up if the temp was cleared, but also so that my temp files that I don't need get cleared out and don't slow down my computer.

 

Here are the contents that I have in my VBS Script:

 

Set WshShell = CreateObject("WScript.Shell")WshShell.Run chr(34) & "C:\ProgramPath\CleanTemp.bat" & chr(34), OSet WshShell = Nothing

 

Here is the contents of the batch that was mentioned in the VBS:

 

@Echo off
del /S /Q "%temp%\*.*"
del /S /Q "C:\Windows\temp\*.*"
del /S /Q "C:\Windows\Prefetch\*"

 

Link to comment
Share on other sites

Link to post
Share on other sites

Does 100 lines include usings and namespaces and such, is it just user code or all code in the document?

Failed to load signature. Error 404 - Witty comment not found

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

You're missing quite a lot of semicolons AND a string concatenation at line 63 ;)

Unfortunately JS doesn't need semicolons.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

I officially have made the best js program ever. Javascript will never become any more useful or informative in any way.

 

Let history remember today. The day where Javascript became self aware.

window.ever=!![];this.js = 'insane'function nothing(){}for(;ever;){  do{nothing()}  while(js === "insane")}
Link to comment
Share on other sites

Link to post
Share on other sites

...

 

TL;DR: Never use floating point values for arithmetic when you'll need to compare them. This is why any (decent) programming teacher will tell you never to use floating point variables to handle things like bank balances. Most of them don't know why, but it's still good advice. :)

 

 

 

"Never" and "always" are so final. Integral values can be represented exactly in IEEE format (up to the precision of the mantissa), so you could store bank balances in cents (a.k.a "fixed point" arithmetic).  But in general, comparisons are fine as long as you understand what is going on. I've witnessed so many otherwise smart programmers say really stupid things about floating-point (examples: "there is no floating point compare instruction on the CPU" (it's called FCOM by the way), or "floating point numbers are not exact, so they can't be compared"). Is it just math anxiety? I think the problem is conflating computer arithmetic with real world arithmetic. For me, it helps to view computer arithmetic as just a bit-twiddling API independent of actual mathematics. In this API view you can compare values for equality, you can get deterministic results, and you can successfully write numerical code. You just have to understand what the functions do - as you would with any other API. This is definitely an area needing more attention.  David Eberly was working on a book covering all aspects of computer arithmetic a few years ago, but his publisher canceled the project fearing there wouldn't be enough demand.  How sad.

Link to comment
Share on other sites

Link to post
Share on other sites

 

I don't know a lot outside of a little hands-on experience with Batch programming, but I have a VBS file that runs a batch that I have in the Task Scheduler to clear out my temporary files on my Windows 8.1 laptop. Unfortunately, I'm still looking for a way to delete the folders that are also created in the Temp areas that I don't need, since they are not deleted during this.

 

The VBS allows me to run the batch file in silent mode. My results after a lot of testing and guessing are below. The Task Scheduler is set to run the VBS at log in, then restart every so often so that I can do things without issues that could come up if the temp was cleared, but also so that my temp files that I don't need get cleared out and don't slow down my computer.

 

Set WshShell = CreateObject("WScript.Shell")WshShell.Run chr(34) & "C:\ProgramPath\CleanTemp.bat" & chr(34), OSet WshShell = Nothing

Here is the contents of the batch that was mentioned in the VBS:

@[member='Echo'] offdel /S /Q "%temp%\*"del /S /Q "%temp%\*.*"del /S /Q "C:\Windows\temp\*"del /S /Q "C:\Windows\temp\*.*"del /S /Q "C:\Windows\Prefetch\*"del /S /Q "C:\Windows\Prefetch\*.*"

 

Highly experienced in batch scripter here

Unfortunately you cannot Delete folders without knowing their specific names inside a folder without some fancy coding which I can provide but a much nicer way if you want is to simply use RMDIR to delete the entire temp folder and just make it again.

Also you don't need the del bit if you delete the entire directory.

RMDIR /S /Q "%temp%\"MKDIR "%temp%" :: If the %temp% thing doesn't work do "mkdir "%appdata%\Local\Temp\"

A riddle wrapped in an enigma , shot to the moon and made in China

Link to comment
Share on other sites

Link to post
Share on other sites

Just a small browser-based javascript Rock, Paper, Scissors game I made in some spare time. Not the best or really any practical use besides passing time, but just saw this contest and decided to post it. :P

var userChoice = prompt("Do you choose rock, paper or scissors?");var computerChoice = Math.random();if (computerChoice < 0.34) {	computerChoice = "rock";} else if(computerChoice <= 0.67) {	computerChoice = "paper";} else {	computerChoice = "scissors";} console.log("Computer: " + computerChoice);var compare = function(choice1, choice2) {    if (choice1 === choice2) {        return "The result is a tie!"    } else if (choice1 === "rock") {        if (choice2 === "scissors") {            return "Rock wins";        } else {            return "paper wins";        };    } else if (choice1 === "paper") {        if (choice2 === "rock") {            return "paper wins";        } else {            return "scissors wins"        };    } else if (choice1 === "scissors") {        if (choice2 === "rock") {            return "rock wins";        } else {            return "scissors wins";        };    };};compare(userChoice, computerChoice);

  Christian 

 

Use the following style specs in your sig to spread the LTT revolution!

Rig Specs:

Screeninator: Gigabyte GeForce GTX960

Powermathingy: Corsair CX600W

Stickiminator: 2x G.Skill ARES 4GB DDR3-1866

Procrastinator: AMD FX-8350 @4.1GHz 1.3V

Holdametalicizor: DIYPC Gamemax-BK

Noisoundacreator: Cyber Acoustics CA-3072 (loudamagargle) Onn Wireless FM Radio Headset (earamagargle)

Attachamathingy: ASRock 990FX Extreme9

Remembrerthing: Western Digital 1TB Blue, Western Digital 40GB Blue

Flat-Colorful-Thing: Acer K272HL

See-A-Move-O: Logitech Hyperion Fury G402

ButtonBoard: Cooler Master CMSTORM Devastator Blue

Talkamagargle: Blue Snowball Ice

 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Basically i was bored today and decided to take a look at Ruby. After reading up on the fundamentals i decided to take this challenge upon myself; make something useful in less than 100 lines.

 

I failed. I decided to make a calculator using the shunting-yard algorithm in order to solve more advanced equations. It is working brilliantly, but by the time i got it to work, the code was 125 lines (minus 12 "readability" lines = 113 lines, still too many).

 

I know this is not very object-oriented, and thus i am not taking advantage of the brilliance of the ruby programming language, but never mind that.

Any inputs on compressing the below code would be greatly appreciated - i want this to fit into this challenge!

def isLeftAssoc(func)	leftassoc = [true, true, true, true, false]	return leftassoc[func]enddef getPrecedence(func)	precedence = [2, 2, 3, 3, 4]	return precedence[func]enddef plus(n1, n2)	return n1 + n2enddef minus(n1, n2)	return n1 - n2enddef multiply(n1, n2)	return n1 * n2enddef divide(n1, n2)	return n1 / n2enddef power(n1, n2)	return n1 ** n2enddef getOperator(str)	case str	when "+"		return 0	when "-"		return 1	when "*"		return 2	when "/"		return 3	when "^"		return 4	when "("		return 5	when ")"		return 6	else		puts "error: " + str	endenddef tokenize(formula)	startpos = 0	endpos = 0	tokens = []	formula.each_char do |i|		if (i >= '0' && i <= '9') || i == '.'			endpos += 1		else			if endpos != startpos				tokens.push(formula[startpos..endpos-1].to_f)			end			tokens.push(getOperator(formula[endpos]))			endpos += 1			startpos = endpos		end	end	tokens.push(formula[startpos..endpos-1].to_f)end def reversePolishNotation(tokens, output, startpos = 0)	stack = []	i = startpos	until i == tokens.length		if tokens[i].class == Float			output.push(tokens[i])		elsif tokens[i].class == Fixnum			if tokens[i] == 5 # (				i += reversePolishNotation(tokens, output, i+1)				i += 1			elsif tokens[i] == 6 # )				while stack.length > 0					output.push(stack.pop())				end				return i - startpos			else				while (stack[stack.length-1].class == Fixnum) && ((isLeftAssoc(tokens[i]) && getPrecedence(stack[stack.length-1]) >= getPrecedence(tokens[i]) || (!isLeftAssoc(tokens[i]) && getPrecedence(stack[stack.length-1]) > getPrecedence(tokens[i]))))					output.push(stack.pop())				end				stack.push(tokens[i])			end		end		i += 1	end	while stack.length > 0		output.push(stack.pop())	end	return i - startposenddef calculateRPN(output)	function = [method(:plus), method(:minus), method(:multiply), method(:divide), method(:power)]	i = 0	while output.length > 1		if output[i].class == Fixnum			output[i-2] = function[output[i]].call(output[i-2], output[i-1])			output.slice!(i-1, 2)			i -= 2		end		i += 1	end	return outputendprint "Please input formula: "formula = gets.chompformula = formula.delete(" ") # remove spacesformula = formula.delete(",") # remove thousand separatorstokens = []output = []tokens = tokenize(formula)reversePolishNotation(tokens, output)puts calculateRPN(output)
Link to comment
Share on other sites

Link to post
Share on other sites

I'm making a program to automatically set up the Windows 10 privacy settings. It's functional, but not feature complete!

Github link

Link to comment
Share on other sites

Link to post
Share on other sites

Basically i was bored today and decided to take a look at Ruby. After reading up on the fundamentals i decided to take this challenge upon myself; make something useful in less than 100 lines.

 

I failed. I decided to make a calculator using the shunting-yard algorithm in order to solve more advanced equations. It is working brilliantly, but by the time i got it to work, the code was 125 lines (minus 12 "readability" lines = 113 lines, still too many).

 

I know this is not very object-oriented, and thus i am not taking advantage of the brilliance of the ruby programming language, but never mind that.

Any inputs on compressing the below code would be greatly appreciated - i want this to fit into this challenge!

 

 

I don't know Ruby, but you could save a few lines by making multiple variable declarations in one line like so

Source: http://stackoverflow.com/questions/14410340/assigning-multiple-variables-to-the-same-value-in-one-line

 

You can combine the removal of spaces and thousand separators into one line I believe. See documentation at http://ruby-doc.org/core-2.0.0/String.html#method-i-delete

 

I think it might be something like this (again, I don't know Ruby)

I think one of those 2 should work.

 

Also not sure if you need to declare tokens to an empty array near the end.

def isLeftAssoc(func)	leftassoc = [true, true, true, true, false]	return leftassoc[func]enddef getPrecedence(func)	precedence = [2, 2, 3, 3, 4]	return precedence[func]enddef plus(n1, n2)	return n1 + n2enddef minus(n1, n2)	return n1 - n2enddef multiply(n1, n2)	return n1 * n2enddef divide(n1, n2)	return n1 / n2enddef power(n1, n2)	return n1 ** n2enddef getOperator(str)	case str	when "+"		return 0	when "-"		return 1	when "*"		return 2	when "/"		return 3	when "^"		return 4	when "("		return 5	when ")"		return 6	else		puts "error: " + str	endenddef tokenize(formula)	startpos = 0	endpos = 0	tokens = []	formula.each_char do |i|		if (i >= '0' && i <= '9') || i == '.'			endpos += 1		else			if endpos != startpos				tokens.push(formula[startpos..endpos-1].to_f)			end			tokens.push(getOperator(formula[endpos]))			endpos += 1			startpos = endpos		end	end	tokens.push(formula[startpos..endpos-1].to_f)end def reversePolishNotation(tokens, output, startpos = 0)	stack = []	i = startpos	until i == tokens.length		if tokens[i].class == Float			output.push(tokens[i])		elsif tokens[i].class == Fixnum			if tokens[i] == 5 # (				i += reversePolishNotation(tokens, output, i+1)				i += 1			elsif tokens[i] == 6 # )				while stack.length > 0					output.push(stack.pop())				end				return i - startpos			else				while (stack[stack.length-1].class == Fixnum) && ((isLeftAssoc(tokens[i]) && getPrecedence(stack[stack.length-1]) >= getPrecedence(tokens[i]) || (!isLeftAssoc(tokens[i]) && getPrecedence(stack[stack.length-1]) > getPrecedence(tokens[i]))))					output.push(stack.pop())				end				stack.push(tokens[i])			end		end		i += 1	end	while stack.length > 0		output.push(stack.pop())	end	return i - startposenddef calculateRPN(output)	function = [method(:plus), method(:minus), method(:multiply), method(:divide), method(:power)]	i = 0	while output.length > 1		if output[i].class == Fixnum			output[i-2] = function[output[i]].call(output[i-2], output[i-1])			output.slice!(i-1, 2)			i -= 2		end		i += 1	end	return outputendprint "Please input formula: "formula = gets.chompformula = formula.delete(" ") # remove spacesformula = formula.delete(",") # remove thousand separatorstokens = []output = []tokens = tokenize(formula)reversePolishNotation(tokens, output)puts calculateRPN(output)
a, b = 0, 0
variableName.delete(" ,")variableName.delete(" ").delete(",")
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×