Problem of the Day
A new programming or logic puzzle every Mon-Fri

Open Random Image

Welcome back from a thrilling weekend! I hope everyone is pumped for Monday. If not maybe today's problem will bring you a quick laugh.

Today is my first day working at Imgur. In honor of my first day, today's Problem of the Day will be to create a program that opens up a random Imgur image every time it is run. To get a random image simply generate a random 5 or 7 character alphanumeric string. Then append that string to "http://imgur.com/gallery/" Here are two examples:

  • vvdBmro -> http://imgur.com/gallery/vvdBmro
  • Gy6PK -> http://imgur.com/gallery/Gy6PK

Note: Your program should actually open the image in a browser and not just print out the string.

Permalink: http://problemotd.com/problem/open-random-image/

Comments:

  • jedrek - 10 years, 7 months ago

    Actionscript 3:

    package {
    
        import flash.net.URLRequest;
        import flash.net.navigateToURL;
    
        public class Test {
    
            public function Test() {
    
                var urlLength:int = (Math.random() > 0.5) ? 7 : 5;
                var urlString:String = '';
    
                for (var i:int = 0; i < urlLength; i++) {
    
                    var code:int = Math.round(Math.random() * (26 + 26 + 10));
    
                    code = (code >= 10) ? code + 54 : code + 48;
                    code = (code > 90) ? code + 7 : code;
    
                    urlString += String.fromCharCode(code);
    
                }
    
                trace(urlString)
    
                navigateToURL(new URLRequest('http://imgur.com/gallery/' + urlString));
            }
    
    
    
        }
    
    }
    

    reply permalink

  • D - 10 years, 7 months ago

    Python 3. Needs the "open" command (works on Mac OS X).

    #!/usr/bin/env python3
    import random
    import subprocess
    
    URL = 'http://imgur.com/gallery/'
    CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    
    nchars = random.choice([5, 7])
    url = URL + ''.join(random.choice(CHARS) for _ in range(nchars))
    subprocess.call(['open', url])
    

    reply permalink

  • Dustin - 10 years, 7 months ago

    Built with Python 2.7 and Flask. For 5 characters goto 127.0.0.1/5 For 7 characters goto 127.0.0.1/7

    import random, string 
    from flask import Flask, redirect
    
    app = Flask(__name__)
    
    @app.route('/<int:characters>')
    def imgur(characters):
      if characters not in [5,7]:
        return "You can only enter 5,7"
      random_string = ''.join(random.choice(string.letters + string.digits) for _ in range(characters))
      return redirect("http://imgur.com/gallery/" + random_string, code=302)
    
    if __name__ == '__main__':
      app.run()
    

    reply permalink

  • duddles - 10 years, 7 months ago

    Congrats on the new job!

    def open_random_image():
        counter = 0
        while True:
            alphanumeric = '0123456789' + string.lowercase
            string_length = random.choice([5,7])
            l = list('http://imgur.com/gallery/')
            for i in xrange(string_length):
                char = random.choice(alphanumeric)
                if not char.isdigit() and random.random() < 0.5:
                    char = char.upper()
                l.append(char)
    
            url = ''.join([str(i) for i in l])
    
            r = requests.get(url)
            soup = bs(r.text)
            title = str(soup.title)
            if title != '<title>    imgur: the simple 404 page</title>':
                break
            counter += 1
            if counter > 10000:
                break
        print 'Found a valid url after {} tries'.format(counter)
        webbrowser.open_new(url)
    

    reply permalink

  • duddles - 10 years, 7 months ago

    forgot the imports:

    from bs4 import BeautifulSoup as bs
    import requests
    import webbrowser
    

    reply permalink

  • Anonymous - 10 years, 7 months ago

    Cool, didn't know about "webbrowser".

    reply permalink

  • duddles - 10 years, 7 months ago

    I actually learned about it from this site when someone used it for the digital typewriter PotD!

    reply permalink

  • Max Burstein - 10 years, 7 months ago

    Thanks!

    reply permalink

  • D - 10 years, 7 months ago

    And now in J!

    urlprefix=: 'http://imgur.com/gallery/'
    chars=: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    
    browse_j_ urlprefix , chars {~ ? (({~ ?@#) 5 7) $ # chars
    

    reply permalink

  • keemz - 10 years, 7 months ago

    
    import random
    import webbrowser
    import urllib2
    from urllib2 import URLError
    
    pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    imgStr = ""
    url = ""
    while True:
        rangeLen = random.choice([5,7])
        for i in range(0,rangeLen):
            randI = random.choice(pool)
            imgStr = imgStr + randI
    
        url = "http://www.imgur.com/gallery/" + imgStr
    
        try:
            response = urllib2.urlopen(url)
        except URLError as e:
            imgStr = ""
        else:
            break
    
    browser = webbrowser.get('safari')
    browser.open(url,new=2)
    
    

    reply permalink

  • Jake - 10 years, 7 months ago

    In js

    <script>
    function randomImage(){
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for( var i=0; i < 5; i++ )
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        window.open("http://imgur.com/gallery/"+text);
    }
    </script>
    

    reply permalink

  • Emre Ozdemir - 10 years, 7 months ago

    #include <iostream>
    #include <ctime>
    #include <string>
    #include <Windows.h>
    using namespace std;
    
    int myRand(){
        return rand()%58+65;
    };
    
    
    int main() {
        srand(time(NULL));
        int forLoop;
        char letter1, xRand;
        for(int k=1;k<=10;k++)
        {
        int sValue=rand()%3 +5;     //  Determines array size 5-6-7
    
            char a[8];
            for(forLoop=0;forLoop<=sValue-1;forLoop++)  //Fills up the array with Upper/Lower case letters
            {   
                xRand=myRand();
                while(xRand<=96 && xRand>=91)
                    xRand=myRand();
    
                a[forLoop]=xRand;
            }
            a[sValue] = '\0';
            string path("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe http://imgur.com/gallery/");
            string arg(a);
            string fin = path + arg;
            cout<<fin<<endl;
            cout<<arg;
            WinExec(fin.c_str() ,SW_SHOW);
        }
    }
    

    reply permalink

  • Anonymous - 10 years, 7 months ago

    One of the random images I got was NSFW!

    reply permalink

  • Anonymous - 10 years, 7 months ago

    Python

    from webbrowser import open
    
    from random import choice
    
    open("https://i.imgur.com/"+"".join([chr(choice(range(48,58)+range(65,91)+range(97,123))) for x in range(5)])+".jpg") 
    

    IPython version:

    from IPython.core.display import Image
    
    from random import choice
    
    Image(url="https://i.imgur.com/"+"".join([chr(choice(range(48,58)+range(65,91)+range(97,123))) for x in range(5)])+".jpg") 
    

    reply permalink

  • Anonymous - 10 years, 6 months ago

    #python 2.7
    import webbrowser
    import random
    import string
    
    x = 0
    mystring = ""
    p = random.choice([5, 7])
    while x < p:
        mystring = mystring + random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
        x = x + 1
    myadd = "http://imgur.com/gallery/" + mystring
    webbrowser.open(myadd)
    

    Some of those images are NSFW!

    reply permalink

Content curated by @MaxBurstein