Performance fixed: Rewrote to not use generators

This commit is contained in:
Rolf Martin Glomsrud 2022-12-06 16:40:58 +01:00
parent 7a48d0debb
commit c7255f5dcb
6 changed files with 174 additions and 203 deletions

1
.gitignore vendored
View file

@ -1 +1,2 @@
/target /target
.idea

29
index.html Normal file
View file

@ -0,0 +1,29 @@
<html lang="en">
<head>
<meta charset="utf-8">
<title>TITLE</title>
<style>
html,
body,
canvas {
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
overflow: hidden;
position: absolute;
background: black;
z-index: 0;
}
</style>
</head>
<body>
<canvas id="glcanvas" tabindex='1'></canvas>
<!-- Minified and statically hosted version of https://github.com/not-fl3/macroquad/blob/master/js/mq_js_bundle.js -->
<script src="https://not-fl3.github.io/miniquad-samples/mq_js_bundle.js"></script>
<script>load("./target/wasm32-unknown-unknown/release/BeepSortMacroQuad.wasm");</script> <!-- Your compiled wasm file -->
</body>
</html>

View file

@ -15,133 +15,123 @@ pub struct Algorithm{
} }
pub enum AlgoEnum{
InsertSort(Box<dyn Generator<Yield=GuiVec, Return=()>>),
}
impl Algorithm{ impl Algorithm{
pub fn insertSort(length:i32) -> impl Generator<Yield=GuiVec, Return=()>{ pub async fn insertSort(length:i32, delay:f32){
let mut list = GuiVec::new(screen_width(), screen_height(), length, delay);
list.randomize();
for index in 0..list.len(){
let mut j = index;
while j>0 && list.lessThan(j, j-1){
list.swap(j, j - 1).await;
j -= 1;
}
}
}
/*
pub fn stalinSort(length:i32){
let mut list = GuiVec::new(screen_width(), screen_height(), length); let mut list = GuiVec::new(screen_width(), screen_height(), length);
list.randomize(); list.randomize();
move ||{
let mut cur = 1;
loop{
if cur == list.len() {
break;
}
if list.lessThan(cur, cur-1){
list.delete(cur);
}else{
cur += 1;
}
yield list.clone(); yield list.clone();
for index in 0..list.len(){
let mut j = index;
while j>0 && list.lessThan(j, j-1){
yield list.swap(j, j - 1);
j -= 1;
}
}
} }
} }
pub fn stalinSort(length:i32) -> impl Generator<Yield=GuiVec, Return=()>{
pub async fn bubbleSort(length:i32){
let mut list = GuiVec::new(screen_width(), screen_height(), length); let mut list = GuiVec::new(screen_width(), screen_height(), length);
list.randomize(); list.randomize();
move ||{ let n = list.len();
yield list.clone(); for i in 0..n {
let mut cur = 1; for j in 0..(n - i - 1) {
loop{ if list.lessThan(j + 1, j) {
if cur == list.len() { list.swap(j, j + 1).await;
break;
} }
yield list.clone();
if list.lessThan(cur, cur-1){
list.delete(cur)
}else{
cur += 1;
}
yield list.clone();
} }
} }
} }
pub fn bubbleSort(length:i32) -> impl Generator<Yield=GuiVec, Return=()>{ pub async fn bogoSort(length:i32){
let mut list = GuiVec::new(screen_width(), screen_height(), length); let mut list = GuiVec::new(screen_width(), screen_height(), length);
list.randomize(); list.randomize();
move || { loop{
let n = list.len(); list.draw().await;
for i in 0..n { if list.isSorted() {
for j in 0..(n - i - 1) { break;
if list.lessThan(j + 1, j) {
yield list.swap(j, j + 1);
}
}
} }
list.randomize();
} }
} }
pub fn bogoSort(length:i32) -> impl Generator<Yield=GuiVec, Return=()>{ pub async fn cocktailShaker(length:i32){
let mut list = GuiVec::new(screen_width(), screen_height(), length); let mut list = GuiVec::new(screen_width(), screen_height(), length);
list.randomize(); list.randomize();
move || { let mut lowerBound = 0;
loop{ let mut upperBound = list.len()-1;
yield list.clone(); let mut swapped = true;
if list.isSorted() { while swapped{
break; swapped = false;
for i in lowerBound..upperBound {
if list.lessThan(i+1, i) {
list.swap(i+1, i).await;
swapped = true;
}
}
if !swapped{
break;
}
swapped = false;
upperBound = upperBound-1;
for i in ((lowerBound)..(upperBound-1)).rev() {
if list.lessThan(i+1, i) {
list.swap(i+1, i).await;
swapped = true;
} }
list.randomize();
} }
lowerBound = lowerBound+1;
} }
}
pub fn cocktailShaker(length:i32) -> impl Generator<Yield=GuiVec, Return=()>{
let mut list = GuiVec::new(screen_width(), screen_height(), length);
list.randomize();
move || {
let mut lowerBound = 0;
let mut upperBound = list.len()-1;
let mut swapped = true;
while swapped{
swapped = false;
for i in lowerBound..upperBound {
if list.lessThan(i+1, i) {
yield list.swap(i+1, i);
swapped = true;
}
}
if !swapped{
break;
}
swapped = false;
upperBound = upperBound-1;
for i in ((lowerBound)..(upperBound-1)).rev() {
if list.lessThan(i+1, i) {
yield list.swap(i+1, i);
swapped = true;
}
}
lowerBound = lowerBound+1;
}
}
} }
pub fn binaryHeap(length:i32) -> impl Generator<Yield=GuiVec, Return=()>{ pub async fn binaryHeap(length:i32){
let mut list = GuiVec::new(screen_width(), screen_height(), length); let mut list = GuiVec::new(screen_width(), screen_height(), length);
let mut indexMap:HashMap<i32, usize> = HashMap::new(); let mut indexMap:HashMap<i32, usize> = HashMap::new();
let mut binHeap:BinaryHeap<i32> = BinaryHeap::new(); let mut binHeap:BinaryHeap<i32> = BinaryHeap::new();
list.randomize(); list.randomize();
move || { let mut ind = 0;
let mut ind = 0; for bar in list.elements(){
for bar in list.elements(){ binHeap.push(bar.position);
binHeap.push(bar.position); indexMap.insert(bar.position, ind);
indexMap.insert(bar.position, ind); ind += 1;
ind += 1;
}
for i in (0..list.len()).rev(){
let bar = binHeap.pop().unwrap();
let barIndex = *indexMap.get(&bar).unwrap();
let clone = list.swap(i, barIndex);
let temp = list.get(barIndex).position;
indexMap.insert(temp, barIndex);
yield clone;
}
} }
for i in (0..list.len()).rev(){
let bar = binHeap.pop().unwrap();
let barIndex = *indexMap.get(&bar).unwrap();
list.swap(i, barIndex).await;
let temp = list.get(barIndex).position;
indexMap.insert(temp, barIndex);
}
} }
*/
} }

View file

@ -2,10 +2,14 @@
use std::borrow::{Borrow, BorrowMut}; use std::borrow::{Borrow, BorrowMut};
use std::ops::Add; use std::ops::Add;
use std::path::Iter; use std::path::Iter;
use macroquad::color::BROWN; use macroquad::color::{BROWN, WHITE};
use macroquad::hash;
use macroquad::prelude::{clear_background, Vec2};
use macroquad::rand::ChooseRandom; use macroquad::rand::ChooseRandom;
use macroquad::shapes::draw_rectangle; use macroquad::shapes::draw_rectangle;
use macroquad::window::{screen_height, screen_width}; use macroquad::time::get_frame_time;
use macroquad::ui::root_ui;
use macroquad::window::{next_frame, screen_height, screen_width};
use crate::BarPlugin::Bar; use crate::BarPlugin::Bar;
use crate::Algorithm::Algorithm; use crate::Algorithm::Algorithm;
@ -16,36 +20,75 @@ pub struct GuiVec{
list: Vec<Bar>, list: Vec<Bar>,
initialSize:usize, initialSize:usize,
pub lastTime:f64, pub lastTime:f64,
pub reads:i32, pub reads:i32,
pub writes:i32, pub writes:i32,
pub comps:i32, pub comps:i32,
screen_height:f32, screen_height:f32,
screen_width:f32 screen_width:f32,
isPaused:bool,
delay:f32
} }
impl GuiVec{ impl GuiVec{
pub fn new(screen_width:f32, screen_height:f32,length:i32) -> Self { pub fn new(screen_width:f32, screen_height:f32,length:i32, delay:f32) -> Self {
let barWidth = (screen_width/((length) as f32)) - 1_f32;
let barHeightStep = (screen_height/((length) as f32));
let colorStep = 360./length as f32; let colorStep = 360./length as f32;
let mut list:Vec<Bar> = vec!(); let mut list:Vec<Bar> = vec!();
for i in 1..length+1 { for i in 1..length+1 {
list.push(Bar::new(i, (colorStep*i as f32)/360.)); list.push(Bar::new(i, (colorStep*i as f32)/360.));
} }
GuiVec{list, initialSize:length as usize, lastTime: 0.0 , reads:0, writes:0, comps:0, screen_height, screen_width} GuiVec{list, initialSize:length as usize, lastTime: 0.0 , reads:0, writes:0, comps:0, screen_height, screen_width, isPaused:false, delay}
} }
pub fn draw(&self){ pub async fn draw(&mut self){
let mut count = 0; let mut frames = 0.0;
for bar in &self.list{ let mut delayText = self.delay.to_string();
draw_rectangle(screen_width() * ((count as f32)/(self.initialSize as f32)),screen_height() - (screen_height()/((self.len()) as f32))*bar.position as f32 , screen_width()/((self.len()) as f32), (screen_height()/((self.len()) as f32))*bar.position as f32, bar.color);
count += 1; loop {
/*
self.checkPaused();
if self.isPaused{
break;
}
*/
clear_background(WHITE);
let mut count = 0;
for bar in &self.list{
draw_rectangle(screen_width() * ((count as f32)/(self.initialSize as f32)),screen_height() - (screen_height()/((self.len()) as f32))*bar.position as f32 , screen_width()/((self.len()) as f32), (screen_height()/((self.len()) as f32))*bar.position as f32, bar.color);
count += 1;
}
root_ui().window(hash!(), Vec2::new(screen_width()*0.2, 5.), Vec2::new(200., 25.), |ui|{
ui.input_text(hash!(), "Delay (ms)", &mut delayText);
});
self.delay = match delayText.parse::<f32>(){
Ok(a) => a,
Err(error)=> {1.0}
};
next_frame().await;
if frames >= self.delay{
break;
}
frames += get_frame_time()*1000.0;
}
}
fn checkPaused(&mut self){
if root_ui().button(Vec2::new(screen_width()*0.01, 90.), "Pause"){
if self.isPaused {
self.isPaused = false;
}else{
self.isPaused = true;
}
} }
} }
pub fn resize(&mut self, length:i32){ pub fn resize(&mut self, length:i32){
self.list = GuiVec::new(self.screen_width, self.screen_height,length).list; self.list = GuiVec::new(self.screen_width, self.screen_height,length, self.delay).list;
} }
pub fn len(&self) -> usize{ pub fn len(&self) -> usize{
self.list.len() self.list.len()
@ -65,11 +108,11 @@ impl GuiVec{
self.initialSize -= 1; self.initialSize -= 1;
} }
pub fn swap(&mut self, index1:usize, index2:usize) -> GuiVec{ pub async fn swap(&mut self, index1:usize, index2:usize){
self.writes += 2; self.writes += 2;
self.reads += 2; self.reads += 2;
self.list.swap(index1, index2); self.list.swap(index1, index2);
self.clone() self.draw().await;
} }
pub fn randomize(&mut self){ pub fn randomize(&mut self){
self.list.shuffle(); self.list.shuffle();

View file

@ -1,71 +0,0 @@
use std::ops::{Generator, GeneratorState};
use std::pin::Pin;
use std::time::Instant;
use macroquad::color::{BLACK, WHITE};
use macroquad::math::Vec2;
use macroquad::prelude::{clear_background, draw_text, get_fps, get_time, next_frame, screen_width};
use macroquad::time::get_frame_time;
use macroquad::ui::{root_ui, hash};
use macroquad::window::screen_height;
use crate::Algorithm::Algorithm;
use crate::GuiHookVec::GuiVec;
pub struct State{
}
impl State{
pub async fn runInsertSort(timeout: f64, length:i32, mut generator:impl Generator<Yield=GuiVec, Return=()>+ std::marker::Unpin){
let mut finished = false;
let mut paused = false;
let mut ret = false;
let mut lasttime:f64 = 0.;
let mut holder = GuiVec::new(screen_width(), screen_height(), length);
let mut speed = 1;
let mut speedText = "1".to_owned();
loop{
clear_background(WHITE);
speed = match speedText.parse::<i32>(){
Ok(a) => a,
Err(error)=> {1}
};
for _ in 0..speed{
if get_time()-lasttime > timeout && !finished && !paused{
match Pin::new(& mut generator).resume(()){
GeneratorState::Yielded(x) => {
holder = x;
},
GeneratorState::Complete(x) => {
finished = true;
paused = true;
}
};
lasttime = get_time();
}
}
holder.draw();
draw_text(format!("Read: {}", holder.reads).as_str(), screen_width()*0.01, 20.0, 20.0, BLACK);
draw_text(format!("Write: {}", holder.writes).as_str(), screen_width()*0.01, 40.0, 20.0, BLACK);
draw_text(format!("Comparisons: {}", holder.comps).as_str(), screen_width()*0.01, 60.0, 20.0, BLACK);
draw_text(format!("FPS: {}", get_fps()).as_str(), screen_width()*0.01, 80., 20.0, BLACK);
root_ui().window(hash!(), Vec2::new(screen_width()*0.2, 5.), Vec2::new(200., 25.), |ui|{
ui.input_text(hash!(), "Speed", &mut speedText);
});
if root_ui().button(Vec2::new(screen_width()*0.01, 90.), "Pause"){
if paused {
paused = false;
}else{
paused = true;
}
}
if root_ui().button(Vec2::new(screen_width()*0.01, 120.), "Return"){
ret = true;
}
if ret{
break;
}
next_frame().await
}
}
}

View file

@ -2,20 +2,14 @@
mod BarPlugin; mod BarPlugin;
mod GuiHookVec; mod GuiHookVec;
mod Algorithm; mod Algorithm;
mod State;
use std::pin::Pin;
use macroquad::prelude::*; use macroquad::prelude::*;
use macroquad::prelude::scene::clear; use macroquad::prelude::scene::clear;
use crate::BarPlugin::Bar; use crate::BarPlugin::Bar;
use crate::GuiHookVec::GuiVec; use crate::GuiHookVec::GuiVec;
use std::ops::{Deref, Generator, GeneratorState};
use std::process::id;
use macroquad::hash; use macroquad::hash;
use macroquad::ui::root_ui; use macroquad::ui::root_ui;
use crate::Algorithm::AlgoEnum;
#[macroquad::main("BeepSort")] #[macroquad::main("BeepSort")]
@ -38,31 +32,16 @@ async fn main() {
draw_text("Sorting!", screen_width()*0.3, screen_height()*0.5, 100.0, GREEN); draw_text("Sorting!", screen_width()*0.3, screen_height()*0.5, 100.0, GREEN);
draw_text(format!("Length: {}", length.to_string()).as_str(), screen_width()*0.83, 30., 20.0, BLACK); draw_text(format!("Length: {}", length.to_string()).as_str(), screen_width()*0.83, 30., 20.0, BLACK);
draw_text(&get_fps().to_string(), screen_width()*0.7, 30.0, 20.0, BLACK);
root_ui().window(hash!(), Vec2::new(screen_width()*0.01, 45.), Vec2::new(250., 50.), |ui|{ root_ui().window(hash!(), Vec2::new(screen_width()*0.01, 45.), Vec2::new(250., 50.), |ui|{
ui.input_text(hash!(), "Delay (ms)", &mut delayText); ui.input_text(hash!(), "Delay (ms)", &mut delayText);
ui.input_text(hash!(), "Length Of Array!", &mut lengthString); ui.input_text(hash!(), "Length Of Array!", &mut lengthString);
}); });
if root_ui().button(Vec2::new(screen_width()*0.01, 100.), "InsertSort"){ if root_ui().button(Vec2::new(screen_width()*0.01, 100.), "RUN!"){
State::State::runInsertSort(delay,length, Algorithm::Algorithm::insertSort(length)).await; //State::State::runInsertSort(delay,length).await;
Algorithm::Algorithm::insertSort(length, 1.0).await;
} }
if root_ui().button(Vec2::new(screen_width()*0.01, 130.), "BogoSort"){
State::State::runInsertSort(delay,length, Algorithm::Algorithm::bogoSort(length)).await;
}
if root_ui().button(Vec2::new(screen_width()*0.01, 160.), "BubbleSort"){
State::State::runInsertSort(delay, length, Algorithm::Algorithm::bubbleSort(length)).await;
}
if root_ui().button(Vec2::new(screen_width()*0.01, 190.), "StalinSort"){
State::State::runInsertSort(delay, length, Algorithm::Algorithm::stalinSort(length)).await;
}
if root_ui().button(Vec2::new(screen_width()*0.01, 220.), "CoctailShaker"){
State::State::runInsertSort(delay, length, Algorithm::Algorithm::cocktailShaker(length)).await;
}
if root_ui().button(Vec2::new(screen_width()*0.01, 250.), "HeapSort!"){
State::State::runInsertSort(delay, length, Algorithm::Algorithm::binaryHeap(length)).await;
}
next_frame().await next_frame().await
} }