Efficient Code Thread

  1. last year
    Edited last year by SharpSerac

    i don't know how many coders we got on the forums but i wrote a pretty efficient sorting algorithm that i think is the best out there due to the sheer versatility and usability it has.

    in the code block you'll see it's algorithm then an example, you could copy and paste it into an online python 3 interpreter and it'll work for ya and it'll tell you the run time

    show me your efficient code guys, doesn't have to be sorting but just anything you're really really proud of that you wrote well

    import random
    import time
    
    #only brainlets write inefficient sorting algorithms
    # this sorting algorithm has an efficiency of O(log(n)) prove me wrong
    # >>>protip: you can't
    #            ,+@;                  
    #      .@@@@@@@#                   
    #     .@@@@@@@#                    
    #    `@@@@@@@@@;                   
    #   .@@@@@@@@@@'#                  
    #  ;@@@@@@;:@#`,;;                 
    #  ``+  @@@@: ''+',                
    #    +  @'+#`; :,:@                
    #    ,   +,`` .' ';                
    #    ..  .#  ` ,  `                
    #    :@   :,:      ,               
    #    ,@     `      . +             
    #    .@     :; `  ,  @@@@+`        
    #     #     ` ,#    ,@@@@@@@@'     
    #             @@ .` #@@@@@@@++@    
    #            @@@'  ,@@@@@@+@;#'@   
    #          `@@@@@  :@@@@@@:@@@@':  
    #          @#'@@@' @@@@@@@@@@;@@@  
    #          @#,@@@@@@@@@@@@@@@#@@@: 
    #          @,.@@@@@@@@@@@@@@@@@@@@ 
    #         ,@@:@@@@@@@@@@@@@@@@@@@@ 
    #         @@@+@@@@@@@@@@@@@@@@@@@@.
    #         @@@#@@@@@@@@@@@@@@@@@@@@@
    #   `#    @@@#@@@@@@@@@@@@@@@@@@@@@
    #  ;: ,   @@@@@@@@@@@@@@@@@@@@@@@@@
    #   :   + @@@@@@@@@@@@@@@@@@@@@@@@@
    #     '  `;@@@@@@@@@@@@@@@@@@@@@@@@
    #      ..  '  @@@@@@@@@@@@#'+@@@@@@
    #        +  ,  #@@@@@@@@@@@@@@@@@@@
    #         `.#,  :@';:'@@@@;@'@@@@@@
    #          ,     `@@@:@@@@@#@:@@@@@
    
    start_time = time.time()
    def efficientSort(sort):
        temp = sort
        sortedbool = False
        while not sortedbool:
            print(temp)
            var1 = random.randint(0, len(temp)-1)
            while True:
                var2 = random.randint(0, len(temp)-1)
                if var1 != var2:
                    break
            temp1 = temp[var1]
            temp[var1] = temp[var2]
            temp[var2] = temp1
            sortedbool = True
            for i in range(0, len(temp)-1):
                if temp[i] > temp[i+1]:
                    sortedbool = False
            
    
    sort = [7,6,5,4,3,2,1,0]
    efficientSort(sort)
    print("Runtime: ", time.time() - start_time)
  2. Edited last year by bSan420

    An 'PHP array' in Javascript. Quite like PHP arrays but there are only id's instead of indexes.

    Can be used like

    var list = new List();
    
    list.add('someid', {anObject: 'with stuff'});
    list.add('someotherid', {anObject: 'with stuff'});
    
    list.remove(id);
    
    list.get('someid'); // returns object by id
    list.all(); //returns all objects
    
    and you can also do
    
    list.add('listInsideList', new List());
    
    list.get('listInsideList').add('value_inside_the_list_of_the_list', 'asdasdads');
  3. Edited last year by bSan420

    I also made a 2d array compressor to compress maps to a file format of the games i'm developing
    an 1.9mb stringfied JSON has been reduced to only 78k, one of the best results I got.

    Of course there must be other solutions out there, but sometimes I like to isolate myself and force me to reinvent the wheel.

    Will convert stuff like:

    var map = [
        [0, 0, 0, 0, 0, 0],
        [0, 1, 1, 1, 1, 0],
        [0, 0, 1, 1, 1, 0],
        [2, 2, 2, 0, 0, 0],
        [1, 1, 1, 2, 0, 0],
        [3, 0, 0, 3, 3, 3]
    ];

    into:

    var map_packed = '6|6x0;0,4x1,0;2x0,3x1,0;3x2,3x0;3x1,2,2x0;3,2x0,3x3';

    [/code]

    Source code:

    function unpack(string) {
        let result = [];
    
        /* picks length of each row */
        let info = string.split('|');
        let length = parseInt(info[0]);
    
        /* splits items into lines */
        let lines = info[1].split(';');
    
        for (let l = 0; l < lines.length; l++) {
            /* an index to represent the last added element to the current line */
            let itemIndex = 0;
    
            /* splits lines into items */
            let items = lines[l].split(',');
    
            /* creates and pushes an array for the current row/line */
            let buffer = new ArrayBuffer(length);
            result.push(new Uint8Array(buffer));
    
            for (let i = 0; i < items.length; i++) {
                /* multi numbs */
                if (items[i].indexOf('x') > 0) {
                    let itemInfo = items[i].split('x');
                    let mult = parseInt(itemInfo[0]);
                    let number = parseInt(itemInfo[1]);
                    result[l].fill(number, itemIndex, itemIndex + mult);
                    itemIndex += mult;
                }
    
                if (isNaN(items[i]) === false) {
                    let number = parseInt(items[i]);
                    result[l][itemIndex] = number;
                    itemIndex++;
                }
            }
        }
    
        return result;
    }
    
    
    function pack(array) {
        let result = [];
        let length = array[0].length;
        let current = {};
        for (let l = 0; l < array.length; l++) {
            result.push('');
            current = {
                item: -1,
                length: 0
            };
    
            for (let i = 0; i < array[l].length; i++) {
                /* first item of current line, storing it */
                if (i === 0) {
                    current.item = array[l][i];
                    current.length++;
                } else {
                    /* if it aint the first item, then lets compare it */
                    if (current.item === array[l][i]) {
                        current.length++;
                    } else {
                        if (current.length > 1) {
                            result[l] += (current.length + 'x' + current.item) + ',';
                        } else {
                            result[l] += (current.item) + ',';
                        }
                        current.item = array[l][i];
                        current.length = 1;
                    }
                }
            }
    
            if (current.length > 1) {
                result[l] += (current.length + 'x' + current.item);
            } else {
                result[l] += (current.item);
            }
        }
    
        return length + '|' + result.join(';');
    }

    More on my github

  4. Edited last year by Stone__Warrior

    @SharpSerac
    Wow, your algorithm is so fast!

    lol, all it does is switch random elements around until it happens upon the sorted array.

    var1 = random.randint(0, len(temp)-1)
            while True:
                var2 = random.randint(0, len(temp)-1)
                if var1 != var2:
                    break

    This part finds two different locations in the array.

    temp1 = temp[var1]
            temp[var1] = temp[var2]
            temp[var2] = temp1

    This code swaps the two elements.

    for i in range(0, len(temp)-1):
                if temp[i] > temp[i+1]:
                    sortedbool = False

    This last bit checks if the array has been sorted, and if so, it stops rearranging elements. If not, it continues finding two random elements and swapping them until the array has been sorted.

    Efficiency at its finest! Nice job.

  5. Here is a new, efficiently efficient recursive algorithm for sorting an array in ascending order.

    #include <cstdlib>
    #include <ctime>
    #include <iostream>
    #include <algorithm>
    #include <chrono>
    
    // A simple algorithm that efficiently efficient sorts an array with recursion.
    void _efficientEfficientlySort (int *arr, size_t start, size_t count) {
    	bool is_valid;
    	if (count > 1) {
    		is_valid = true;
    	} else if (count <= 1) {
    		is_valid = false;
    	}
    
    	if (is_valid == true) {
    		int subdivision = count / 2;
    		_efficientEfficientlySort (arr, start, subdivision);
    		_efficientEfficientlySort (arr, start + subdivision, count - subdivision);
    
    		// Randomly shuffle the current subdivision while it is unsorted, this will give us a new sorted array
    		bool is_sorted;
    		do {
    			is_sorted = true;
    			for (int i = 0; is_sorted != false && i < count - 1; ++ i) {
    				if (arr [start + i] > arr [start + i + 1]) {
    					is_sorted = false;
    				}
    			}
    
    			if (is_sorted == false) {
    				std::random_shuffle (&arr [start], &arr [start + count]);
    			} else if (is_sorted == true) {
    				break;
    			}
    		} while (is_sorted == false);
    	}
    }
    
    void efficientEfficientSort (int *arr, size_t size) {
    	_efficientEfficientlySort (arr, 0, size);
    }
    
    const int SIZE = 100;
    
    int main (int argc, char ** argv) {
    	std::srand (std::time (NULL));
    	int arr [SIZE];
    
    	for (int i = 0; i < SIZE; ++ i) {
    		arr [i] = std::rand () % 1000;
    	}
    
    	std::cout << "Your array is ";
    	for (int i = 0; i < SIZE; ++ i) {
    		std::cout << arr [i] << ", ";
    	}
    
    	auto before = std::chrono::high_resolution_clock::now ();
    	efficientEfficientSort (arr, SIZE);
    	auto after = std::chrono::high_resolution_clock::now ();
    
    	std::cout << "Your new sorted array is ";
    	for (int i = 0; i < SIZE; ++ i) {
    		std::cout << arr [i] << ", ";
    	}
    	std::cout << "!\n" << std::endl;
    	std::cout << "And it took only "
    	          << std::chrono::duration_cast <std::chrono::seconds> (after - before).count ()
    	          << "seconds!\n" << std::endl;
    
    	return -1;
    }
    
    /*
                ,+@;                  
          .@@@@@@@#                   
         .@@@@@@@#                    
        `@@@@@@@@@;                   
       .@@@@@@@@@@'#                  
      ;@@@@@@;:@#`,;;                 
      ``+  @@@@: ''+',                
        +  @'+#`; :,:@                
        ,   +,`` .' ';                
        ..  .#  ` ,  `                
        :@   :,:      ,               
        ,@     `      . +             
        .@     :; `  ,  @@@@+`        
         #     ` ,#    ,@@@@@@@@'     
                 @@ .` #@@@@@@@++@    
                @@@'  ,@@@@@@+@;#'@   
              `@@@@@  :@@@@@@:@@@@':  
              @#'@@@' @@@@@@@@@@;@@@  
              @#,@@@@@@@@@@@@@@@#@@@: 
              @,.@@@@@@@@@@@@@@@@@@@@ 
             ,@@:@@@@@@@@@@@@@@@@@@@@ 
             @@@+@@@@@@@@@@@@@@@@@@@@.
             @@@#@@@@@@@@@@@@@@@@@@@@@
       `#    @@@#@@@@@@@@@@@@@@@@@@@@@
      ;: ,   @@@@@@@@@@@@@@@@@@@@@@@@@
       :   + @@@@@@@@@@@@@@@@@@@@@@@@@
         '  `;@@@@@@@@@@@@@@@@@@@@@@@@
          ..  '  @@@@@@@@@@@@#'+@@@@@@
            +  ,  #@@@@@@@@@@@@@@@@@@@
             `.#,  :@';:'@@@@;@'@@@@@@
              ,     `@@@:@@@@@#@:@@@@@
    */
  6. Edited last year by Stone__Warrior

    @deyahruhd If you add

    #include <thread>

    at the top, there's this pretty sweet trick by which you can make to significantly impact the speed your process takes. In all of your functions, just copy-paste

    std::this_thread::sleep_for(std::chrono::milliseconds(std::numeric_limits<unsigned long int>::max()));

    wherever you see fit.
    :D

  7. Edited last year by deyahruhd

    @Stone__Warrior @deyahruhd If you add

    #include <thread>

    at the top, there's this pretty sweet optimization you can make to significantly impact the speed your process takes. In all of your functions, just copy-paste

    std::this_thread::sleep_for(std::chrono::milliseconds(std::numeric_limits<unsigned long int>::max()));

    wherever you see fit.
    :D

    Wow, that made my algorithm even more efficient by a factor of (9,223,372,036,854,775,807 + 1) * 2 - 1! Thanks!

  8. Edited last year by WBlaine

    The codes I write for work are for mathematical computation and analyzing specific data formats, so those aren't widely applicable and aren't interesting for this thread. So, I'll hop onto the sorter bandwagon and post a small python sorter to throw into the mix:

     
    def efficientSort(sort):
        temp = sort
        l = len(sort)-1
        issorted = False
    
        while not issorted:
            swapped = False
            for i in range(l,0,-1):
                if temp[i] < temp[i-1]:
                    swapped = True
                    hold = temp[i-1]
                    temp[i-1] = temp[i]
                    temp[i] = hold
    
            issorted = not swapped
    
        print sort
  9. @WBlaine The codes I write for work are for mathematical computation ... so those aren't interesting for this thread.

    Sounds very interesting to me if it involves math. :^)

  10. you r all Cool i can only bold text hhhaha

  11. Edited last year by MamaNeon

    @Fingerbib you r all Cool i can only bold text hhhaha

    Y'all mind if I

    Bottom Text

  12. Tables Anyone?
    how about
    that Eh?

  13. @CraftyMyner

    Tables Anyone?
    how about
    that Eh?

    crafty is a coding god

  14. I program calculators

  15. I pretend to help @CactusOwnage coding shit computer games while he does all the work

  16. Not like we achieve anything

  17. Trust the process ma boi

or Sign Up to reply!