Created
October 27, 2009 18:16
-
-
Save tbuehlmann/219797 to your computer and use it in GitHub Desktop.
AJAXy Sieve of Eratosthenes with Sinatra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'index' | |
run Sinatra::Application |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!!! | |
%html{:xmlns => "http://www.w3.org/1999/xhtml"} | |
%head | |
%script{:type => "text/javascript", :src => "js/prototype.js"} | |
%body | |
%h1 Wieviele Primzahlen gibt es zwischen 0 und der Eingabe? | |
%input{:type => 'text', :id => 'myval', :size => '10'} | |
%input{:type => 'button', :value => 'Prime it!', :onClick => "ajaxRequest('/ajax', 'val='+$F('myval')); $('result').innerHTML = 'loading'"} | |
#result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'sinatra' | |
require 'haml' | |
require 'timeout' | |
@@liste = {} | |
get '/' do | |
haml :index | |
end | |
get '/ajax' do | |
if request.xhr? | |
n = params[:val].to_i | |
if @@liste.has_key?(n) | |
return @@liste[n] | |
else | |
begin | |
Timeout.timeout 15 do | |
neu = sieb(n) | |
@@liste[n] = neu | |
@output = neu.to_s | |
end | |
rescue Timeout::Error | |
@output = "Timeout" | |
end | |
return @output | |
end | |
end | |
end | |
helpers do | |
def sieb(x) | |
liste = [] | |
prim = [] | |
for i in (2..x) do | |
liste << i | |
end | |
until liste.length == 0 | |
prim << liste[0] | |
del = liste[0] | |
for i in liste do | |
if i % del == 0 | |
liste.delete(i) | |
end | |
end | |
end | |
return prim.length.to_s | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Prototype in here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment