Jump to content

The under 100 line challenge!

fletch to 99
11 minutes ago, straight_stewie said:

As an aside, I think that the pattern that the "original recipe" C# compiler and Roslyn uses is that void methods return a void object (the CTS BCL has a type System.Void), and then calls a POP instruction, which throws away the void object.

Btw, I see you're new. Welcome to the forum :) One of the things we do is quote someone when replying to them. (highlight text in their reply and a quote button pops up). This gives them a notification that you've responded. Had I not been subscribed to this thread I would have never known that you replied.

Thank you! And I don't know what CLR does that when loading void object onto the stack and popping it, I've checked up on Mono source code and discovered that they didn't even bother with the loading onto stack for Void structure in C# and a lot of people seems to mention that System.Void is only for reflection purpose.

 

And yep, I've just joined up recently and pretty much searching for a new community to discuss programming basically. Thank you for the warm welcome. :)

Link to comment
Share on other sites

Link to post
Share on other sites

28 minutes ago, FreeDev said:

Thank you! And I don't know what CLR does that when loading void object onto the stack and popping it, I've checked up on Mono source code and discovered that they didn't even bother with the loading onto stack for Void structure in C# and a lot of people seems to mention that System.Void is only for reflection purpose.

I just checked. In release mode Roslyn doesn't have void methods return anything. In Debug mode it does.

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

That is really interesting, I never have heard of it being done before. That is something new to learn about today. Thank you. :D

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

Here's one of my apps (I often use it for docker images to handle health-checks)

It performs either TCP or UDP connection to target host and port and exits with either 0 (for success) or 1, 2 for error

https://github.com/UnAfraid/go-health-check

 

Just 72 lines but when i made it that wasn't even the goal

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...
 
Disp "Enter x1 for V1:"
Input A
Disp "Enter x2 for V1:"
Input B
Disp "Enter x3 for V1:"
Input C
Disp "Enter x1 for V2:"
Input D
Disp "Enter x2 for V2:"
Input E
Disp "Enter x3 for V2:"
Input F
ClrHome
(B*F)-(C*E)->G
(C*D)-(A*F)->H
(A*E)-(B*D)->I
Disp G,H,I

Program for calculator TI-83Plus to calculate the cross-product of two vectors 

for(var i = 0; i<= 1/0; i++) {
	alert("Look, i am like while(true){}");
}

1/0 != Error; 1/0 == ∞

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...

Geoblocking EU users (so you won't have to bother about the GDPR) in five lines of PHP code:

$disallowed_countries = ["BE", "BG", "CZ", "DK", "DE", "EE", "IE", "EL", "ES", "FR", "HR", "IT", "CY", "LV", "LT", "LU", "HU", "MT", "NL", "AT", "PL", "PT", "RO", "SI", "SK", "FI", "SE", "UK"];
$ip = $_SERVER["REMOTE_ADDR"];
if (in_array(geoip_country_code_by_name($ip), $disallowed_countries)) {
    die("Your country does not want you to be here.");
}

 

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace PokeballBot
{
    public partial class Form1 : Form
    {
        bool running = false;

        public Form1() => InitializeComponent();

        void button1_Click(object sender, EventArgs e)
        {
            running = !running;
            button1.Text = running ? "Stop" : "Start";
        }

        void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (running)
            {
                Bitmap screenshot = ScreenshotPokeball;
                Point ball = GetLoc(Color.FromArgb(201, 60, 76), screenshot);
                Point pika = GetLoc(Color.FromArgb(248, 208, 80), screenshot);
                pictureBox1.Image = screenshot;
                if (ball.X != -1 && ball.Y != -1 && pika.X != -1 && pika.Y != -1)
                    if (pika.X < ball.X)
                        KeyboardPress(68, 7);
                    else if (pika.Y > ball.Y)
                        KeyboardPress(87, 26);
                    else if (pika.X > ball.X)
                        KeyboardPress(65, 4);
                    else if (pika.Y < ball.Y)
                        KeyboardPress(83, 22);
            }
            Invalidate(false);
            Update();
        }

        Point GetLoc(Color c, Bitmap croppedGameScreen)
        {
            for (int x = 0; x < croppedGameScreen.Width; x++)
                for (int y = 0; y < croppedGameScreen.Height; y++)
                    if (AreAboutEqual(c, croppedGameScreen.GetPixel(x, y)))
                        return new Point(x / 16, y / 16);
            return new Point(-1, -1);
        }

        bool AreAboutEqual(Color f, Color s) => f.R - 10 < s.R && f.R + 10 > s.R && f.G - 10 < s.G && f.G + 10 > s.G && f.B - 10 < s.B && f.B + 10 > s.B;

        static Bitmap ScreenshotPokeball
        {
            get
            {
                Rect rect = new Rect();
                GetWindowRect(Process.GetProcessesByName("Pokeball").ToArray()[0].MainWindowHandle, ref rect);
                Bitmap bmp = new Bitmap(160, 160, PixelFormat.Format24bppRgb);
                Graphics.FromImage(bmp).CopyFromScreen(rect.left + 19, rect.top + 42, 0, 0, new Size(160, 160), CopyPixelOperation.SourceCopy);
                return bmp;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        struct Rect
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        static void KeyboardPress(byte vk, byte sc)
        {
            keybd_event(vk, sc, 0, 0);
            keybd_event(vk, sc, 2, 0);
        }

        [DllImport("user32.dll")]
        static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
    }
}

Combined with some some windows forms its a pretty nice bot for this game.

PokeballBot.exe

~chrissx aka. that crazy german dude

A bad website

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...

Recently I had a situation where one of our clients was typing a message our server needed to handle.  While processing the message through a web service we use, we kept getting an improper XML format error.  Unfortunately the error was super generic, and didn't provide any information as to where the problem actually was.  Made sure all special characters were properly escaped or removed, there were no hidden character, even made sure there were no new line characters, although I knew that shouldn't be the issue. 

 

Finally I noticed two words in the message:  weren't and don't, and that the apostrophe didn't look right.

What it ended up being was that for some reason the client's keyboard was not setup to output the ordinary single quote, instead it used a different version of it that required unicode.  The message is being transmitted as ASCII (it's not critical, but it avoid a lot of other problems).

 

Now handling that one character was easy enough;  I just added the code to replace it with a standard single quote, but it did bring to my attention that there were other characters that could prove problematic as well, and I wanted to find a simple and elegant way to handle them.

 

Regex to the rescue, per usual:

This little gem ended up doing pretty much everything I needed

[^ -~]

This will select any character that is not a printable ascii character, and you can then replace it with space, or empty string, or whatever you want.

 

I actually wasn't sure if the character ranges worked this way, but I had a hunch so I decided to test it.  Previously I had assumed that when you specified a range, it was only for alphanumeric characters, since they have a defined order.  So you could only do a-z, b-j,0-9,4-5, etc

It turns out the way the ranges actually works is by comparing them as their respective ASCII/Unicode Integer values, similar to how in C/C++ code, you can test if a number is an integer by comparing it like so

int isdigit(char c)
{
    if((c >= '0' && c <= '9')
    {
         return 1;
    }
    else
    {
         return 0;
    }                       
}

I know I'm not the first person to discover this, but I've never seen someone mention that it works this way, so I thought it worth mentioning.

 

Link to comment
Share on other sites

Link to post
Share on other sites

 

52 minutes ago, JacobFW said:

Regex to the rescue, per usual:

not to sound critical given I have 0 idea what your codebase is like, but it sounds like you are missing some cross layer validation (i.e. a system on the client side that does the data creation so that it's always sent with the right encoding/format/schema etc, and can let the user know something is incorrect before sending the data over the wire).

I know regex fixed it this time, but that seems more like a bandaid fix than a robust solution. not having a standardized client/server interface might cause more headache down the road.

 

Again, no idea who your users are or what your code is like and I have no idea what domain context you might have, just thought i'd throw my probably unwanted 2 cents in.

Gaming build:

CPU: i7-7700k (5.0ghz, 1.312v)

GPU(s): Asus Strix 1080ti OC (~2063mhz)

Memory: 32GB (4x8) DDR4 G.Skill TridentZ RGB 3000mhz

Motherboard: Asus Prime z270-AR

PSU: Seasonic Prime Titanium 850W

Cooler: Custom water loop (420mm rad + 360mm rad)

Case: Be quiet! Dark base pro 900 (silver)
Primary storage: Samsung 960 evo m.2 SSD (500gb)

Secondary storage: Samsung 850 evo SSD (250gb)

 

Server build:

OS: Ubuntu server 16.04 LTS (though will probably upgrade to 17.04 for better ryzen support)

CPU: Ryzen R7 1700x

Memory: Ballistix Sport LT 16GB

Motherboard: Asrock B350 m4 pro

PSU: Corsair CX550M

Cooler: Cooler master hyper 212 evo

Storage: 2TB WD Red x1, 128gb OCZ SSD for OS

Case: HAF 932 adv

 

Link to comment
Share on other sites

Link to post
Share on other sites

35 minutes ago, reniat said:

 

not to sound critical given I have 0 idea what your codebase is like, but it sounds like you are missing some cross layer validation (i.e. a system on the client side that does the data creation so that it's always sent with the right encoding/format/schema etc, and can let the user know something is incorrect before sending the data over the wire).

I know regex fixed it this time, but that seems more like a bandaid fix than a robust solution. not having a standardized client/server interface might cause more headache down the road.

 

Again, no idea who your users are or what your code is like and I have no idea what domain context you might have, just thought i'd throw my probably unwanted 2 cents in.

Fair point.  A lot of it however is outside of my control, and to my knowledge most of the formal solutions require integrating the code everywhere it's needed.

Link to comment
Share on other sites

Link to post
Share on other sites

17 hours ago, JacobFW said:

Fair point.  A lot of it however is outside of my control, and to my knowledge most of the formal solutions require integrating the code everywhere it's needed.

Just make sure at the very least you are sanitizing your input if security is a concern. Theres a big potential for code injection depending on what consumes the data being passed.

Gaming build:

CPU: i7-7700k (5.0ghz, 1.312v)

GPU(s): Asus Strix 1080ti OC (~2063mhz)

Memory: 32GB (4x8) DDR4 G.Skill TridentZ RGB 3000mhz

Motherboard: Asus Prime z270-AR

PSU: Seasonic Prime Titanium 850W

Cooler: Custom water loop (420mm rad + 360mm rad)

Case: Be quiet! Dark base pro 900 (silver)
Primary storage: Samsung 960 evo m.2 SSD (500gb)

Secondary storage: Samsung 850 evo SSD (250gb)

 

Server build:

OS: Ubuntu server 16.04 LTS (though will probably upgrade to 17.04 for better ryzen support)

CPU: Ryzen R7 1700x

Memory: Ballistix Sport LT 16GB

Motherboard: Asrock B350 m4 pro

PSU: Corsair CX550M

Cooler: Cooler master hyper 212 evo

Storage: 2TB WD Red x1, 128gb OCZ SSD for OS

Case: HAF 932 adv

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

print("Remember to do under 100 line code chalinge!")

Link to comment
Share on other sites

Link to post
Share on other sites

Here is my code

A small bifid cipher encoder/decoder

if it doesn't work fr some reason plsss reply or comment or whatever u r supposed to do

[code]
import java.io.*;
public class Bifid_cypher {
    public static void main(String[] args) throws IOException {
        InputStreamReader red = (new InputStreamReader(System.in));
        BufferedReader in = new BufferedReader(red);
        System.out.println("Enter 1 to encrypt");
        System.out.println("Enter 2 to decrypt");
        int opt = Integer.parseInt(in.readLine());
        if (opt == 1)
        {
            char a[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            char c[][] = new char[5][5];
            char c1[] = new char[25];
            int x = 0;
            while (x <25)
            {
                int r= (int)(Math.random()*(25));//RANDOMISATION CODE
                char random=a[r];
                boolean b = true;
                for (int j = 0; j < x; j++)//FILTERING MATCHING ELEMENTS AND FILLING
                {
                    if(random==c1[j])
                    {
                        b = false;
                        break;
                    }
                }
                if (b==true)
                {
                    c1[x]=random;
                    x += 1;
                }
            }
            for(int j=0;j<25;j++)//1D TO 2D CONVERSION
            {
                if(j%5==0)
                {
                    System.out.print("\n");
                }
                c[((j)/5)][((j)%5)]=c1[j];
                System.out.print(c1[j]);
            }
            System.out.println("\n"+"enter the message");//ASK FOR THE INPUT
            String s=in.readLine();
            int e1[]=new int[s.length()*2];
            for(int i=0;i<s.length();i++)//ENCRYPTION STAGE
            {
                for(int j=0;j<5;j++)
                {
                    for(int k=0;k<5;k++)
                    {
                        if(s.charAt(i)=='J')
                        {
                            if('I'==c[j][k])
                            {
                                e1[i]=j;
                                e1[i+s.length()]=k;
                            }
                        }
                        else if(s.charAt(i)==c[j][k])
                        {
                            e1[i]=j;
                            e1[i+s.length()]=k;
                        }
                    }
                }
            }
            String output="";
            for(int i=0;i<s.length();i++)
            {
                output+=c[e1[i*2]][e1[i*2+1]];
            }
            System.out.println("\n"+"the encrypted code");
            System.out.print(output);
        }
        if(opt==2)
        {
            System.out.println("enter the encryption key");
            String s2[]=new String[5];
            for(int i=0;i<5;i++)
                s2[i]=in.readLine();
            System.out.println("enter the message");
            String msg=in.readLine();
            int e2[]=new int[msg.length()*2];
            for(int i=0;i<msg.length();i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    for (int k = 0; k < 5; k++)
                    {
                        if(msg.charAt(i)==s2[j].charAt(k))
                        {
                            e2[i*2]=j;
                            e2[i*2+1]=k;
                        }
                    }
                }
            }
            System.out.println();
            String output="";
            for(int i=0;i<msg.length();i++)
            {
                output+=s2[e2[i]].charAt(e2[i+msg.length()]);
            }
            System.out.println("\n"+"the decrypted code");
            System.out.print(output);
        }
    }
}

[ /code]
Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Hi everyone!

 

As my first project, getting comfortable with Python, I wrote this roman numeral to normal number converter!

 

It came out to 77 lines ;)

 

def calculatenumeral(str):
    roman_numeral = str
    ron_list = list(str)
    ron_list_worth = list(str)
    position_in_ron = 0
    ron_equals = 0
    i = 0

    for letter in roman_numeral:
        ron_list[position_in_ron] = letter

        if letter == roman_numerals[0]:
            ron_list_worth[position_in_ron] = 1

        if letter == roman_numerals[1]:
            ron_list_worth[position_in_ron] = 5

        if letter == roman_numerals[2]:
            ron_list_worth[position_in_ron] = 10

        if letter == roman_numerals[3]:
            ron_list_worth[position_in_ron] = 50

        if letter == roman_numerals[4]:
            ron_list_worth[position_in_ron] = 100

        if letter == roman_numerals[5]:
            ron_list_worth[position_in_ron] = 500

        if letter == roman_numerals[6]:
            ron_list_worth[position_in_ron] = 1000

        position_in_ron += 1

    position_in_ron = 0

    for letter in roman_numeral:
        ron_equals += ron_list_worth[position_in_ron]

        if ron_list_worth[position_in_ron - 1] < ron_list_worth[position_in_ron] and position_in_ron > 0:
            #for debugging: print(ron_equals, "-", (2 * ron_list_worth[position_in_ron - 1]))
            ron_equals = ron_equals - (2 * ron_list_worth[position_in_ron - 1])

        #for debugging: print("Ron = ", ron_equals, "| p = ", position_in_ron)
        position_in_ron += 1

    return ron_equals

while True:

    roman_numeral = input("\nWrite your roman numeral here: \n")

    roman_numeral = roman_numeral.upper()

    roman_numerals = ["I", "V", "X", "L", "C", "D", "M"]

    valid_ron = False
    go_on = True

    for letter in roman_numeral:

        if go_on == True:

            if letter in roman_numerals:
                go_on = True
                valid_ron = True

            elif letter not in roman_numerals:
                go_on = False
                valid_ron = False

    if valid_ron == True:

        print("That is: ", calculatenumeral(roman_numeral))

    if valid_ron == False:
        print("Sorry, '", roman_numeral, "' includes characters which are not yet supported.")

 

W H E N   T H E   W O R L D   I S   A G A I N S T   Y O U ,   B U I L D   C O M P U T E R S !

Link to comment
Share on other sites

Link to post
Share on other sites

I wrote a basic video player for sphere, the fallback atm is that it relies on raw frames in the form of jpg or png images and a ripped audio file in order to work.

 

let video_object = function(name, audioFormat = "mp3", raw = true, preload = false)
{
	this.srate = 23.976024;
	this.multipler = 1;
	this.refRate = 1000 / GetFrameRate();
	this.rate = 1000 / this.srate;
	this.raw = raw;
	this.name = name;
	this.preload = preload;
	
	this.audioFormat = audioFormat;
	if (raw)
	{
		this.videoFormat = "RAW";
	} else {
		this.videoFormat = "wtfvf"; // stands for WHAT THE %!#$ video format.
	}
	
	this.volume = 100;
	
	this.frameList = GetFileList("images/" + name);
	
	this.frameData = {};
	if (preload)
	{
		Print("Loading video \"" + name + "\"");
		for (frame = 0; frae < this.frameList.length; frame++)
		{
			print("		Loading " + this.frameList[frame]);
			let cache = LoadImage(name + this.frameList[frame]);
			this.frameData[frame.toString()] = cache;
		}
	}
	
	this.frameData["audio"] = LoadSound(name + "." + audioFormat);
}

video_object.prototype.SetFrameRate = function(newframerate)
{
	this.srate = newframerate;
	this.rate = 1000 / this.srate;
}

video_object.prototype.play = function(x, y)
{
	
	let updateFrame = false;
	let updateTime = GetTime() + this.rate;
	let frame = 0;
	let frameCount = this.frameList.length;
	let lastFrame = LoadImage(this.name + "/" + this.frameList[0]);
	
	this.frameData["audio"].play();
	
	let currentTime = GetTime();
	
	while(frame < frameCount)
	{
		currentTime = GetTime();
		
		if (updateFrame)
		{
			lastFrame = LoadImage(this.name + "/" + this.frameList[frame]);
			updateFrame = false;
		}
		
		lastFrame.blit(x, y);
		FlipScreen();
		
		if (currentTime >= updateTime)
		{
			let correction = currentTime - updateTime;
			
			Print(frame + " - " + correction);
			Print(currentTime + " - " + updateTime);
			
			updateTime = currentTime + this.rate - correction;
			updateFrame = true;
			frame++;
		}
	}
}

 

My procrastination is the bane of my existence.

I make games and stuff in my spare time.

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

I mean, I code write a 30,000 line program then just inline everything so it fits down to 100? would that disqualify?

Link to comment
Share on other sites

Link to post
Share on other sites

A simple c++ sudoku solver using recursive backtracking I wrote a few weeks ago. This version only solves 9x9 sudokus, but adjusting to other sizes is only a matter of initializing the Sudoku template with another value (eg. Sudoku<4> for 16x16 sudokus).

It's plenty fast for any 9x9 sudoku and some 16x16 sudokus, usually only taking a few microseconds, but on harder sudokus it will take several minutes or hours (or more).

It's 107 lines of code actually, but I'm counting it anyway since the actual program only starts at line 10.

To compile using gcc, save as sudoku_solver.cpp and then type g++ --std c++17 -O3 sudoku_solver.cpp -o sudoku_solver.

Usage: ./sudoku_solver sudoku.txt

#include <iostream>
#include <fstream>
#include <iomanip>
#include <array>
#include <algorithm>
#include <optional>

using namespace std;

template<int n>
struct Sudoku {
	static const int width = n * n;
	static const int n_cells = width * width;
	typedef array<int, width> Row;
	typedef array<Row, width> Field;
	Field m_field;

	inline Sudoku<n>()
	    : m_field{}
	{}

	inline bool validate_row(int num, int i_row) const
	{
		return none_of(m_field[i_row].begin(), m_field[i_row].end(), [&](const int cell) { return cell == num; });
	}

	inline bool validate_col(int num, int i_col) const
	{
		return none_of(m_field.begin(), m_field.end(), [&](const Row &row) { return row[i_col] == num; });
	}

	inline bool validate_block(int num, int i_row, int i_col) const
	{
		const int block_row = i_row / n * n;
		const int block_col = i_col / n * n;
		for (int i = 0; i < width; ++i)
			if (num == m_field[block_row + i / n][block_col + i % n])
				return false;
		return true;
	}

	inline bool validate_cell(int num, int i_row, int i_col) const
	{
		return validate_row(num, i_row)  && validate_block(num, i_row, i_col) && validate_col(num, i_col);
	}

	inline optional<Sudoku<n>> get_solution()
	{
		Sudoku<n> solution(*this);
		return solution.solve_recursive(*this, 0) ? solution : optional<Sudoku<n>>{};
	}

	inline bool solve_recursive(const Sudoku<n> &sudoku, int index)
	{
		if (index == n_cells)
			return true;
		const int i_row = index / width;
		const int i_col = index % width;
		if (sudoku.m_field[i_row][i_col] != 0)
			return solve_recursive(sudoku, index + 1);
		for (int num = 1; num <= width; ++num) {
			if (validate_cell(num, i_row, i_col)) {
				m_field[i_row][i_col] = num;
				if (solve_recursive(sudoku, index + 1))
					return true;
			}
		}
		m_field[i_row][i_col] = 0;
		return false;
	}
};

template<int n>
ostream & operator<<(ostream &os, const Sudoku<n> &sudoku)
{
	for (const auto &row: sudoku.m_field) {
		for (const auto &cell: row)
			os << setw(2) << cell << " ";
		os << "\n";
	}
	return os;
}

template<int n>
istream & operator>>(istream &is, Sudoku<n> &sudoku)
{
	for (auto &row: sudoku.m_field)
		for (auto &cell: row)
			is >> cell;
	return is;
}

int main(int argc, char **argv)
{
	Sudoku<3> sudoku;
	ifstream(argv[1]) >> sudoku;
	auto solution = sudoku.get_solution();
	cout << "Input:\n" << sudoku << "\n";
	if (solution) {
		cout << "Found a solution:\n" << *solution;
		return 0;
	}
	cout << "No solution found.\n";
	return 1;
}

Example input file:

Spoiler

0 0 1 3 0 0 7 0 2
0 0 6 2 0 0 0 1 0
0 2 0 0 0 0 0 0 4
2 0 0 6 0 1 3 0 9
0 0 0 0 0 0 0 0 0
4 0 3 8 0 9 0 0 7
1 0 0 0 0 0 0 8 0
0 5 0 0 0 6 4 0 0
9 0 4 0 0 8 5 0 0

 

Example output:

Spoiler

$ time ./sudoku_solver sudoku.txt
Input:
 0  0  1  3  0  0  7  0  2
 0  0  6  2  0  0  0  1  0
 0  2  0  0  0  0  0  0  4
 2  0  0  6  0  1  3  0  9
 0  0  0  0  0  0  0  0  0
 4  0  3  8  0  9  0  0  7
 1  0  0  0  0  0  0  8  0
 0  5  0  0  0  6  4  0  0
 9  0  4  0  0  8  5  0  0

Found a solution:
 8  4  1  3  6  5  7  9  2
 7  3  6  2  9  4  8  1  5
 5  2  9  1  8  7  6  3  4
 2  8  5  6  7  1  3  4  9
 6  9  7  4  3  2  1  5  8
 4  1  3  8  5  9  2  6  7
 1  7  2  5  4  3  9  8  6
 3  5  8  9  2  6  4  7  1
 9  6  4  7  1  8  5  2  3

real    0m0,006s
user    0m0,001s
sys     0m0,006s

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

This is a chatbot written in Python, it is fairly simple, but is good enough, it might lag...

import random
say='Hi! I\'m an chatbot, called Medice, written in 50 lines! Enjoy!\n'
saylist=[]
try:
    savefile=open('savebot.txt','r')
except:
    savefile=open('savebot.txt','w')
    savefile.write('hello'+'\n')
    savefile.write('\n')
savefile.close()
savefile=open('savebot.txt','r')
while True:
    readl=savefile.readline()
    if readl=='\n':
        break
    saylist.append(readl)
savefile.close()
def s(word):
    saylist.append(word+'\n')
    savefile=open('savebot.txt','w')
    for i in range(0,len(saylist),1):
        savefile.write(saylist[i])
    savefile.write('\n')
    lastspace=0
    words=[]
    availible=[]
    word=word+' '
    for num,i in enumerate(word):
        if i == ' ':
            words.append(word[lastspace:num])
            lastspace=num
    for i in saylist:
        i=i.replace('\n','')+' \n'
        lastspace=0
        words2=[]
        for num,j in enumerate(i):
            if j == ' ':
                words2.append(i[lastspace:num])
                lastspace=num
        for j in words2:
            if j.replace('\n','') in words:
                if not j.replace('\n','') == word:
                    availible.append(i)
    print(availible)
    if availible == []:
        return random.choice(saylist)
    else:
        return random.choice(availible)
while True:
    say=s(input(say))
#should add matching for ?,. also find most matched phrasae, also dont let the bot repeat whatever was said in the first time it was said

Also, I realized that using less than 100 lines is easy with min.js ;).

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Here is a digital square root calculator in 26 lines.

 

#include <iostream>
#include <string>

unsigned digitalRoot(std::ostream &ostr, unsigned input)
{
    unsigned root = 0;
    while (input > 0)
    {
        unsigned digit = input % 10;
        root += digit;
        input /= 10;
        ostr << digit << " + ";
    }
    ostr << "\b\b\b = " << root << std::endl;
    return root < 10 ? root : digitalRoot(ostr, root);
}

int main()
{
    std::string input;
    std::cout << "Please enter a number: ";
    std::getline(std::cin, input);
    std::cout << "\nDigital root is " << digitalRoot(std::cout, (unsigned long long)std::stoi(input)) << ".\n\n";
    main();
    return 0;
}
Link to comment
Share on other sites

Link to post
Share on other sites

On 7/19/2018 at 6:35 PM, Wildstingray said:

I mean, I code write a 30,000 line program then just inline everything so it fits down to 100? would that disqualify?

you can code everything in just one single line in fact. Do this to annoy the hell out of your project manager

Sudo make me a sandwich 

Link to comment
Share on other sites

Link to post
Share on other sites

On 7/10/2018 at 8:09 PM, matias_a_etersen said:

 


        if letter == roman_numerals[0]:
            ron_list_worth[position_in_ron] = 1

        if letter == roman_numerals[1]:
            ron_list_worth[position_in_ron] = 5

        if letter == roman_numerals[2]:
            ron_list_worth[position_in_ron] = 10

        if letter == roman_numerals[3]:
            ron_list_worth[position_in_ron] = 50

        if letter == roman_numerals[4]:
            ron_list_worth[position_in_ron] = 100

        if letter == roman_numerals[5]:
            ron_list_worth[position_in_ron] = 500

        if letter == roman_numerals[6]:
            ron_list_worth[position_in_ron] = 1000

 

The above can be made a bit shorter in terms of lines if you want, though as always it's a little less readable, (haven't ran this but should work). I'm sure we could go even further but this becomes more of a code golf exercise at some point:

 

value = 1
for i in range(roman_numerals.index(letter)):
	value = (value * 5, value * 2)[i % 2 == 0]

ron_list_worth[position_in_ron] = value

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...

Once upon a time, I sat in a college lecture bored to death.  I texted one of my friends, who I could see from across the room was in a similar state.  A competition to write the shortest Python program to calculate e (the base of natural logarithms) ensued.  This is the code with which I won.

 


print(sum([1/(lambda p,q:q(p,q))(n,(lambda p,q:p!=0 and p*q(p-1,q) or 1)) for n in range(0,abs(int(input("Terms: "))))])**float(input("x: ")))

 

The program will ask for the number of terms to use in its power-series approximation for e, and for the exponent to use (because really this program calculates e raised to the x power).

 

Perhaps a bit of explaining is in order.  I don't know.  If you want an explanation of how this works, let me know.  18 terms seems to be enough for it to converge over the length of floating-point decimal data stored by Python.

Link to comment
Share on other sites

Link to post
Share on other sites

I will take this on when Im back from class

Really this just promotes the sloppier coding xD I checked some of my other projects and one is at like 108 lines with GOOD formatting and full if statements... if I butcher that down as much as I can I bet I can get a lot more lol

 

There was another trick I found for parsing strings on to the end of ArrayList individual strings in VB.net
Basically you use the function String.Join to combine the strings with a unique separator after the wanted suffix on the string (plus one more for the last string) then use String.Split on this new string to return it to an array.  There are a few other casts inbetween, but it can all be done in ONE line, something that no other built in function lets you do.  It cuts down on time MASSIVELY compared to iterating each string.  Example below:

OutputArrayList.AddRange((string.Join("SuffixString;", sourceStrings.ToArray()) + "SuffixString").Split(";".ToCharArray()).ToList());

You could do the same thing on the resulting output to add a suffix as well, just changing the location of the 2nd SuffixString to before the String.Join statement.

 

Again once I get back from class ill hopefully clean up and share a couple programs under 100 that I made for personal functionality.  Proxy scraper is the main one, but I also have a couple text tools that I made for unique uses I have daily.

Link to comment
Share on other sites

Link to post
Share on other sites

On 6/26/2018 at 12:02 PM, Fluxcabury said:

print("Remember to do under 100 line code chalinge!")

Seems legit to me....lol

 

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


×