Search Results

Search found 647 results on 26 pages for 'rand mate'.

Page 4/26 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • JSF - Random Number using Beans (JAVA)

    - by Alex Encore Tr
    I am trying to create a jsf application which, upon page refresh increments the hit counter and generates two random numbers. What should be displayed on the window may look something like this: On your On your roll x you have thrown x and x For this program I decided to create two Beans, one to hold the page refresh counter and one to generate a random number. Those look like this for the moment: CounterBean.java package diceroll; public class CounterBean { int count=0; public CounterBean() { } public void setCount(int count) { this.count=count; } public int getCount() { count++; return count; } } RandomNumberBean.java package diceroll; import java.util.Random; public class RandomNumberBean { int rand=0; Random r = new Random(); public RandomNumberBean() { rand = r.nextInt(6); } public void setNextInt(int rand) { this.rand=rand; } public int getNextInt() { return rand; } } I have then created an index.jsp to display the above message. <html> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> <f:view> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Roll the Dice</title> </head> <body> <h:form> <p> On your roll # <h:outputText value="#{CounterBean.count} " /> you have thrown <h:outputText value="#{RandomNumberBean.rand}" />and <h:outputText value="#{RandomNumberBean.rand} " /> </p> </h:form> </body> </f:view> </html> However, when I run the application, I get the following message: org.apache.jasper.el.JspPropertyNotFoundException: /index.jsp(14,20) '#{RandomNumberBean.rand}' Property 'rand' not found on type diceroll.RandomNumberBean Caused by: org.apache.jasper.el.JspPropertyNotFoundException - /index.jsp(14,20) '#{RandomNumberBean.rand}' Property 'rand' not found on type diceroll.RandomNumberBean I suppose there's a mistake with my faces-config.xml file, so I will post this here as well, see if somebody can provide some help: faces-config.xml <?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> <managed-bean> <managed-bean-name>CounterBean</managed-bean-name> <managed-bean-class>diceroll.CounterBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>RandomNumberBean</managed-bean-name> <managed-bean-class>diceroll.RandomNumberBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> </faces-config>

    Read the article

  • Random generates same number in java

    - by user1613360
    This is my java code. import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; class search { private int numelem; private int[] input=new int[100]; public void setNumofelem() { System.out.println("Enter the total numebr of elements"); Scanner yz=new Scanner(System.in); numelem=yz.nextInt(); } public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { input[j]=rand.nextInt(max)+1; } } public void printinput() { int b=numelem,t=0; while(true) if(b!=0) { System.out.print(" "+input[t]); b--; t++; } else break; } } public class mycode { public static void main(String args[]) throws Exception { search a=new search(); a.setNumofelem(); a.randomnumber(); a.printinput(); } } Now the function randomnumber() just returns the same number.The function executes perfectly if I execute it as a separate java program but fails miserably if I call it using an object.I have also tried the following variations but nothing works everything return the same number. Variation 1: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { TimeUnit.SECONDS.sleep(1); input[j]=rand.nextInt(max)+1; } } Variation 2: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { rand.setSeed(System.nanoTime()); input[j]=rand.nextInt(max)+1; } } Variation 3: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { TimeUnit.SECONDS.sleep(1); rand.setSeed(System.nanoTime()); input[j]=rand.nextInt(max)+1; } } Sample input/Output: Enter the number of elements: 5 23 23 23 23 23 23

    Read the article

  • Haskell and random numbers

    - by John D.
    Hi, I've been messing with Haskell few days and stumbled into a problem. I need a method that returns a random list of integers ( Rand [[Int]] ). So, I defined a type: type Rand a = StdGen -> (a, StdGen). I was able to produce Rand IO Integer and Rand [IO Integer] ( (returnR lst) :: StdGen -> ([IO Integer], StdGen) ) somehow. Any tips how to produce Rand [[Int]]?

    Read the article

  • Where is the rand php function located? localhost php running, path of default functions?

    - by Bona Chon
    I have a local server installed on my Mac (MAMP). My question is, where I can find the php functions in my computer? What is the path to the functions folder? For instance, rand() time() isset() explode(). I would like to se the code to learn of it. I have a while looking for it, but I can't find it. Or is it that is already compiled? Can someone help me here? I'm kind of lost. Thanks people. EDIT: can you be a little bit more positive? I;m trying to learn here, forgive me if I'm not to smart for you. Thanks again. Explanations would help better than giving links I guess?

    Read the article

  • Rails: Accessing previous loop in Populator (rake db:populate)

    - by sscirrus
    I am populating my Rails database using populator, and I have a case where I would like to build a series of records where fields start_date and end_date follow seamlessly from each other (from today back into the past). Here is a sample of what I'm doing: Chain.populate 1 do |ch| ch.date_end = DateTime.now ch.date_start = DateTime.civil(DateTime.now.year-rand(40)-1, rand(12)+1, rand(31)+1) end Chain.populate 0..10 do |chs| chs.date_end = Chain.find(:last).date_start chs.date_start = DateTime.civil(chs.date_end.year-rand(10)-1, rand(12)+1, rand(31)+1) end Problem? undefined method 'date_start' for nil:NilClass. I assume the problem is the first Chain record hasn't been saved, so I added: Chain.save # in between the two loops This didn't work either. How can I make this work? Thank you!

    Read the article

  • Problem with alleg42.dll / program crashes / Allegro & Codeblocks

    - by user24152
    I'm having a serious problem with allegro. The program should display random pixels on the screen and when I build and run it I get the following error message: Below is the full code of my program: #include <stdio.h> #include <stdlib.h> #include <time.h> #include "allegro.h" #define Text_Color_Red makecol(255,0,0) int main() { int ret; int color_depth = 32; int x; int y; int red; int green; int blue; int color; //init allegro allegro_init(); //install keyboard install_keyboard(); //set color depth to 32 bits set_color_depth(color_depth); //init random seed srand(time(NULL)); //init video mode to 640 x 480 ret = set_gfx_mode(GFX_AUTODETECT_WINDOWED,640,480,0,0); if(ret !=0) { allegro_message(allegro_error); return 1; } //Display string textprintf(screen,font,0,0,10,0,Text_Color_Red,"Screen Resolution is: %dx%d -- Press ESC to quit !",SCREEN_W,SCREEN_H); //display pixels until ESC key is pressed //wait for keypress while(!key[KEY_ESC]) { //set a random location x = 10 + rand() % (SCREEN_W-20); y = 10 + rand() % (SCREEN_H-20); //set a random color red = rand() % 255; green = rand() % 255; blue = rand() % 255; color = makecol(red,green,blue); //draw the pixel putpixel(screen, x, y, color); } //quit allegro allegro_exit(); } END_OF_MAIN() Error message: AllegroPixels1.exe has encountered a problem and needs to close. We are sorry for the inconvenience. Error signature: AppName: allegropixels1.exe AppVer: 0.0.0.0 ModName: alleg42.dll ModVer: 4.2.3.0 Offset: 0006c05c I am using Windows XP inside a virtual machine under Parallels 7.0

    Read the article

  • Data Structures for Junior Java Developer

    - by user1639637
    Ok,still learning Arrays. I wrote this code which fills the array named "rand" with random numbers between 0 and 1( exclusive). I want to start learning Complexity. the For loop executes n times (100 times) ,every time it takes O(1) time,so the worse case scenario is O(n),am I right? Also,I used ArrayList to store the 100 elements and I imported "Collections" and used Collections.sort() method to sort the elements. import java.util.Arrays; public class random { public static void main(String args[]) { double[] rand=new double[10]; for(int i=0;i<rand.length;i++) { rand[i]=(double) Math.random(); System.out.println(rand[i]); } Arrays.sort(rand); System.out.println(Arrays.toString(rand)); } } ArrayList: import java.util.ArrayList; import java.util.Collections; public class random { public static void main(String args[]) { ArrayList<Double> MyArrayList=new ArrayList<Double>(); for(int i=0;i<100;i++) { MyArrayList.add(Math.random()); } Collections.sort(MyArrayList); for(int j=0;j<MyArrayList.size();j++) { System.out.println(MyArrayList.get(j)); } } }

    Read the article

  • if isset PHP not working?

    - by Ellie
    Okay, Im trying to set a captcha up, However with this code in, it breaks. if(isset($_POST["captcha"])) if($_SESSION["captcha"]==$_POST["captcha"]) When i do it with out it, the page works, but the captcha is letting incorrect submits through. Parse error: syntax error, unexpected '"', expecting T_STRING or T_VARIABLE or T_NUM_STRING in /hermes/waloraweb085/b2027/moo.lutarinet/jointest.php on line 71 <?php $pagetitle = "Home"; $checkrank = 0; include ($_SERVER['DOCUMENT_ROOT'].'/header.inc.php'); ECHO <<<END <br><br> <b><center><i><u>DO NOT</u> USE YOUR NEOPETS PASSWORD OR PIN NUMBER!!!</b></i></center> <p> ?> <?php session_start() ?> <center><P><FORM ACTION="join.pro.php" enctype="multipart/form-data" METHOD=POST> <table width="393" height="188" border="0" cellpadding="0" cellspacing="0"> <td width="150">Username</td> <td width="243"><input type=text name="name" value="" size=32 maxlength=15></td> </tr> <tr> <td>Password</td> <td><input type=password name="pass1" VALUE="" maxlength=15></td> </tr> <tr> <td>Confirm Password</td> <td><input type=password name="pass2" VALUE="" size=32 maxlength=15></td> </tr> <tr> <td>Security Code (4 Diget Number)</td> <td><input type=password name="security" VALUE="" size=32 maxlength=4></td> </tr> <tr> <td>Email Address</td> <td><INPUT TYPE=text NAME="email" VALUE="" SIZE=32 maxlength=100></td> </tr> <tr> <td height="41" colspan="2" valign="middle"><p><p><center> By registering an account here you agree to all of our <A HREF="$baseurl/tos.php">Terms and Conditions</A>. You can also view our <A HREF="$baseurl/privacy.php">Privacy Policy</A>. </center></p></td> </tr> <tr><td align="center">CAPTCHA:<br> (antispam code, 3 black symbols)<br> <table><tr><td><img src="captcha.php" alt="captcha image"></td><td><input type="text" name="captcha" size="3" maxlength="3"></td></tr></table> </td></tr> <td height="27" colspan="2" valign="middle"> <center><input type=submit name=Submit value="Register"></center> </td> </table> </form> <?php if(isset($_POST["captcha"])) if($_SESSION["captcha"]==$_POST["captcha"]) { //CAPTHCA is valid; proceed the message: save to database, send by e-mail ... echo 'CAPTHCA is valid; proceed the message'; } else { echo 'CAPTHCA is not valid; ignore submission'; } ?> <?php END; include ($_SERVER['DOCUMENT_ROOT'].'/footer.inc.php'); ?> captcha.php <?php session_start(); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); function _generateRandom($length=6) { $_rand_src = array( array(48,57) //digits , array(97,122) //lowercase chars // , array(65,90) //uppercase chars ); srand ((double) microtime() * 1000000); $random_string = ""; for($i=0;$i<$length;$i++){ $i1=rand(0,sizeof($_rand_src)-1); $random_string .= chr(rand($_rand_src[$i1][0],$_rand_src[$i1][1])); } return $random_string; } $im = @imagecreatefromjpeg("http://sketchedneo.com/images/sitedesigns/captcha.jpg"); $rand = _generateRandom(3); $_SESSION['captcha'] = $rand; ImageString($im, 5, 2, 2, $rand[0]." ".$rand[1]." ".$rand[2]." ", ImageColorAllocate ($im, 0, 0, 0)); $rand = _generateRandom(3); ImageString($im, 5, 2, 2, " ".$rand[0]." ".$rand[1]." ".$rand[2], ImageColorAllocate ($im, 255, 0, 0)); Header ('Content-type: image/jpeg'); imagejpeg($im,NULL,100); ImageDestroy($im); ?> Help please anyone? Line 71: if(isset($_POST["captcha"])) Line 72: if($_SESSION["captcha"]==$_POST["captcha"])

    Read the article

  • after BIOS splash, will not boot -- asks me to select an OS, but it just reboots

    - by user92040
    I'm running Linux Mint 13 MATE 64-bit. Everything has been working for several weeks. Yesterday, when I tried to boot up my computer, after the BIOS screen flashes I reach a screen with a black background that reads at the top: GNU GRUB version1.99-21ubuntu3.4 Then there is a box in which I can select from the following lines: Linux Mint 13 MATE 64-bit, 3.2.0-31-generic (/dev/sdb2) Linux Mint 13 MATE 64-bit, 3.2.0-31-generic (/dev/sdb2) -- recovery mode Previous Linux versions Memory test (memtest86+) Memory test (memtest86+, serial console 115200) At the bottom it reads: Use the ? and ? keys to select which entry is highlighed. Press enter to boot the selected OS, 'e' to edit the commands before booting or 'c' for a command-line. I have no idea why it started doing this and, worse, I have no idea how to get out of here. No matter which option I select, I can't get it to boot the OS. If I select either of the first two, it reboots to splash the BIOS and then I'm right back where I started. If I choose "Previous Linux versions" I get essentially the same screen with only two choices (which are the same as the first two choices listed above, Linux 13 MATE and the recovery mode). Again, choosing either one of those results in a reboot. If I try to run either of the memtest options, it reads: error: unknown command 'linux16', Press any key to continue... Then it brings me back to the same screen Can anyone help me please? Intel Core i5-2500 ASUS P8Z68-V LX Intel Motherboard G. Skill Ripjaws series F3-12800CL9D-8GBRL (4GB x2) Plextor 128GB M5S Series SSD

    Read the article

  • no more hitcollision at 1 life

    - by user1449547
    So I finally got my implementation of lives fixed, and it works. Now however when I collide with a ghost when I am at 1 life, nothing happens. I can fall to my death enough times for a game over. from what i can tell the problem is that hit collision is not longer working, because it does not detect a hit, I do not fall. the question is why? update if i kill myself fast enough it works, but if i play for like 30 seconds, it stops the hit collision detection on my ghosts. platforms and springs still work. public class World { public interface WorldListener { public void jump(); public void highJump(); public void hit(); public void coin(); public void dying(); } public static final float WORLD_WIDTH = 10; public static final float WORLD_HEIGHT = 15 * 20; public static final int WORLD_STATE_RUNNING = 0; public static final int WORLD_STATE_NEXT_LEVEL = 1; public static final int WORLD_STATE_GAME_OVER = 2; public static final Vector2 gravity = new Vector2(0, -12); public Hero hero; public final List<Platform> platforms; public final List<Spring> springs; public final List<Ghost> ghosts; public final List<Coin> coins; public Castle castle; public final WorldListener listener; public final Random rand; public float heightSoFar; public int score; public int state; public int lives=3; public World(WorldListener listener) { this.hero = new Hero(5, 1); this.platforms = new ArrayList<Platform>(); this.springs = new ArrayList<Spring>(); this.ghosts = new ArrayList<Ghost>(); this.coins = new ArrayList<Coin>(); this.listener = listener; rand = new Random(); generateLevel(); this.heightSoFar = 0; this.score = 0; this.state = WORLD_STATE_RUNNING; } private void generateLevel() { float y = Platform.PLATFORM_HEIGHT / 2; float maxJumpHeight = Hero.hero_JUMP_VELOCITY * Hero.hero_JUMP_VELOCITY / (2 * -gravity.y); while (y < WORLD_HEIGHT - WORLD_WIDTH / 2) { int type = rand.nextFloat() > 0.8f ? Platform.PLATFORM_TYPE_MOVING : Platform.PLATFORM_TYPE_STATIC; float x = rand.nextFloat() * (WORLD_WIDTH - Platform.PLATFORM_WIDTH) + Platform.PLATFORM_WIDTH / 2; Platform platform = new Platform(type, x, y); platforms.add(platform); if (rand.nextFloat() > 0.9f && type != Platform.PLATFORM_TYPE_MOVING) { Spring spring = new Spring(platform.position.x, platform.position.y + Platform.PLATFORM_HEIGHT / 2 + Spring.SPRING_HEIGHT / 2); springs.add(spring); } if (rand.nextFloat() > 0.7f) { Ghost ghost = new Ghost(platform.position.x + rand.nextFloat(), platform.position.y + Ghost.GHOST_HEIGHT + rand.nextFloat() * 3); ghosts.add(ghost); } if (rand.nextFloat() > 0.6f) { Coin coin = new Coin(platform.position.x + rand.nextFloat(), platform.position.y + Coin.COIN_HEIGHT + rand.nextFloat() * 3); coins.add(coin); } y += (maxJumpHeight - 0.5f); y -= rand.nextFloat() * (maxJumpHeight / 3); } castle = new Castle(WORLD_WIDTH / 2, y); } public void update(float deltaTime, float accelX) { updatehero(deltaTime, accelX); updatePlatforms(deltaTime); updateGhosts(deltaTime); updateCoins(deltaTime); if (hero.state != Hero.hero_STATE_HIT) checkCollisions(); checkGameOver(); checkFall(); } private void updatehero(float deltaTime, float accelX) { if (hero.state != Hero.hero_STATE_HIT && hero.position.y <= 0.5f) hero.hitPlatform(); if (hero.state != Hero.hero_STATE_HIT) hero.velocity.x = -accelX / 10 * Hero.hero_MOVE_VELOCITY; hero.update(deltaTime); heightSoFar = Math.max(hero.position.y, heightSoFar); } private void updatePlatforms(float deltaTime) { int len = platforms.size(); for (int i = 0; i < len; i++) { Platform platform = platforms.get(i); platform.update(deltaTime); if (platform.state == Platform.PLATFORM_STATE_PULVERIZING && platform.stateTime > Platform.PLATFORM_PULVERIZE_TIME) { platforms.remove(platform); len = platforms.size(); } } } private void updateGhosts(float deltaTime) { int len = ghosts.size(); for (int i = 0; i < len; i++) { Ghost ghost = ghosts.get(i); ghost.update(deltaTime); if (ghost.state == Ghost.GHOST_STATE_DYING && ghost.stateTime > Ghost.GHOST_DYING_TIME) { ghosts.remove(ghost); len = ghosts.size(); } } } private void updateCoins(float deltaTime) { int len = coins.size(); for (int i = 0; i < len; i++) { Coin coin = coins.get(i); coin.update(deltaTime); } } private void checkCollisions() { checkPlatformCollisions(); checkGhostCollisions(); checkItemCollisions(); checkCastleCollisions(); } private void checkPlatformCollisions() { if (hero.velocity.y > 0) return; int len = platforms.size(); for (int i = 0; i < len; i++) { Platform platform = platforms.get(i); if (hero.position.y > platform.position.y) { if (OverlapTester .overlapRectangles(hero.bounds, platform.bounds)) { hero.hitPlatform(); listener.jump(); if (rand.nextFloat() > 0.5f) { platform.pulverize(); } break; } } } } private void checkGhostCollisions() { int len = ghosts.size(); for (int i = 0; i < len; i++) { Ghost ghost = ghosts.get(i); if (hero.position.y < ghost.position.y) { if (OverlapTester.overlapRectangles(ghost.bounds, hero.bounds)){ hero.hitGhost(); listener.hit(); } break; } else { if(hero.position.y > ghost.position.y) { if (OverlapTester.overlapRectangles(hero.bounds, ghost.bounds)){ hero.hitGhostJump(); listener.jump(); ghost.dying(); score += Ghost.GHOST_SCORE; } break; } } } } private void checkItemCollisions() { int len = coins.size(); for (int i = 0; i < len; i++) { Coin coin = coins.get(i); if (OverlapTester.overlapRectangles(hero.bounds, coin.bounds)) { coins.remove(coin); len = coins.size(); listener.coin(); score += Coin.COIN_SCORE; } } if (hero.velocity.y > 0) return; len = springs.size(); for (int i = 0; i < len; i++) { Spring spring = springs.get(i); if (hero.position.y > spring.position.y) { if (OverlapTester.overlapRectangles(hero.bounds, spring.bounds)) { hero.hitSpring(); listener.highJump(); } } } } private void checkCastleCollisions() { if (OverlapTester.overlapRectangles(castle.bounds, hero.bounds)) { state = WORLD_STATE_NEXT_LEVEL; } } private void checkFall() { if (heightSoFar - 7.5f > hero.position.y) { --lives; hero.hitSpring(); listener.highJump(); } } private void checkGameOver() { if (lives<=0) { state = WORLD_STATE_GAME_OVER; } } }

    Read the article

  • Adding objects to the environment at timed intervals

    - by david
    I am using an ArrayList to handle objects and at each interval of 120 frames, I am adding a new object of the same type at a random location along the z-axis of 60. The problem is, it doesn't add just 1. It depends on how many are in the list. If I kill the Fox before the time interval when one is supposed to spawn comes, then no Fox will be spawned. If I don't kill any foxes, it grows exponentially. I only want one Fox to be added every 120 frames. This problem never happened before when I created new ones and added them to the environment. Any insights? Here is my code: /**** FOX CLASS ****/ import env3d.EnvObject; import java.util.ArrayList; public class Fox extends Creature { private int frame = 0; public Fox(double x, double y, double z) { super(x, y, z); // Must use the mutator as the fields have private access // in the parent class setTexture("models/fox/fox.png"); setModel("models/fox/fox.obj"); setScale(1.4); } public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures, ArrayList<Creature> new_creatures) { frame++; setX(getX()-0.2); setRotateY(270); if (frame > 120) { Fox f = new Fox(60, 1, (int)(Math.random()*28)+1); new_creatures.add(f); frame = 0; } for (Creature c : creatures) { if (this.distance(c) < this.getScale()+c.getScale() && c instanceof Tux) { dead_creatures.add(c); } } for (Creature c : creatures) { if (c.getX() < 1 && c instanceof Fox) { dead_creatures.add(c); } } } } import env3d.Env; import java.util.ArrayList; import org.lwjgl.input.Keyboard; /** * A predator and prey simulation. Fox is the predator and Tux is the prey. */ public class Game { private Env env; private boolean finished; private ArrayList<Creature> creatures; private KingTux king; private Snowball ball; private int tuxcounter; private int kills; /** * Constructor for the Game class. It sets up the foxes and tuxes. */ public Game() { // we use a separate ArrayList to keep track of each animal. // our room is 50 x 50. creatures = new ArrayList<Creature>(); for (int i = 0; i < 10; i++) { creatures.add(new Tux((int)(Math.random()*10)+1, 1, (int)(Math.random()*28)+1)); } for (int i = 0; i < 1; i++) { creatures.add(new Fox(60, 1, (int)(Math.random()*28)+1)); } king = new KingTux(25, 1, 35); ball = new Snowball(-400, -400, -400); } /** * Play the game */ public void play() { finished = false; // Create the new environment. Must be done in the same // method as the game loop env = new Env(); // Make the room 50 x 50. env.setRoom(new Room()); // Add all the animals into to the environment for display for (Creature c : creatures) { env.addObject(c); } for (Creature c : creatures) { if (c instanceof Tux) { tuxcounter++; } } env.addObject(king); env.addObject(ball); // Sets up the camera env.setCameraXYZ(30, 50, 55); env.setCameraPitch(-63); // Turn off the default controls env.setDefaultControl(false); // A list to keep track of dead tuxes. ArrayList<Creature> dead_creatures = new ArrayList<Creature>(); ArrayList<Creature> new_creatures = new ArrayList<Creature>(); // The main game loop while (!finished) { if (env.getKey() == 1 || tuxcounter == 0) { finished = true; } env.setDisplayStr("Tuxes: " + tuxcounter, 15, 0); env.setDisplayStr("Kills: " + kills, 140, 0); processInput(); ball.move(); king.check(); // Move each fox and tux. for (Creature c : creatures) { c.move(creatures, dead_creatures, new_creatures); } for (Creature c : creatures) { if (c.distance(ball) < c.getScale()+ball.getScale() && c instanceof Fox) { dead_creatures.add(c); ball.setX(-400); ball.setY(-400); ball.setZ(-400); kills++; } } // Clean up of the dead tuxes. for (Creature c : dead_creatures) { if (c instanceof Tux) { tuxcounter--; } env.removeObject(c); creatures.remove(c); } for (Creature c : new_creatures) { creatures.add(c); env.addObject(c); } // we clear the ArrayList for the next loop. We could create a new one // every loop but that would be very inefficient. dead_creatures.clear(); new_creatures.clear(); // Update display env.advanceOneFrame(); } // Just a little clean up env.exit(); } private void processInput() { int keyDown = env.getKeyDown(); int key = env.getKey(); if (keyDown == 203) { king.setX(king.getX()-1); } else if (keyDown == 205) { king.setX(king.getX()+1); } if (ball.getX() <= -400 && key == Keyboard.KEY_S) { ball.setX(king.getX()); ball.setY(king.getY()); ball.setZ(king.getZ()); } } /** * Main method to launch the program. */ public static void main(String args[]) { (new Game()).play(); } } /**** CREATURE CLASS ****/ /* (Parent class to Tux, Fox, and KingTux) */ import env3d.EnvObject; import java.util.ArrayList; abstract public class Creature extends EnvObject { private int frame; private double rand; /** * Constructor for objects of class Creature */ public Creature(double x, double y, double z) { setX(x); setY(y); setZ(z); setScale(1); rand = Math.random(); } private void randomGenerator() { rand = Math.random(); } public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures, ArrayList<Creature> new_creatures) { frame++; if (frame > 12) { randomGenerator(); frame = 0; } // if (rand < 0.25) { // setX(getX()+0.3); // setRotateY(90); // } else if (rand < 0.5) { // setX(getX()-0.3); // setRotateY(270); // } else if (rand < 0.75) { // setZ(getZ()+0.3); // setRotateY(0); // } else if (rand < 1) { // setZ(getZ()-0.3); // setRotateY(180); // } if (rand < 0.5) { setRotateY(getRotateY()-7); } else if (rand < 1) { setRotateY(getRotateY()+7); } setX(getX()+Math.sin(Math.toRadians(getRotateY()))*0.5); setZ(getZ()+Math.cos(Math.toRadians(getRotateY()))*0.5); if (getX() < getScale()) setX(getScale()); if (getX() > 50-getScale()) setX(50 - getScale()); if (getZ() < getScale()) setZ(getScale()); if (getZ() > 50-getScale()) setZ(50 - getScale()); // The move method now handles collision detection if (this instanceof Fox) { for (Creature c : creatures) { if (c.distance(this) < c.getScale()+this.getScale() && c instanceof Tux) { dead_creatures.add(c); } } } } } The rest of the classes are a bit trivial to this specific problem.

    Read the article

  • Algorithm for Shortest Job First with Preemption

    - by Shray
    I want to implement a shortest job first routine using C# or C++. Priority of Jobs are based on their processing time. Jobs are processed using a binary (min) heap. There are three types of jobs. Type 1 is when jobs come in between every 4-6 seconds, with processing times between 4-6. Type 2 job comes in between 8-12 seconds, with processing times between 8-12. Type 3 job comes in between 24-26 seconds, with processing times between 14-16. So far, I have written the binary heap functionality, but Im kinda confused on how to start processing spawn and also the processor. #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int timecounting = 20; struct process{ int atime; int ptime; int type; }; class pque{ private: int count; public: process pheap[100]; process type1[100]; process type2[100]; process type3[100]; process type4[100]; pque(){ count = 0; } void swap(int a, int b){ process tempa = pheap[a]; process tempb = pheap[b]; pheap[b] = tempa; pheap[a] = tempb; } void add(process c){ int current; count++; pheap[count] = c; if(count > 0){ current = count; while(pheap[count/2].ptime > pheap[current].ptime){ swap(current/2, current); current = current/2; } } } void remove(){ process temp = pheap[1]; // saves process to temporary pheap[1] = pheap[count]; //takes last process in heap, and puts it at the root int n = 1; int leftchild = 2*n; int rightchild = 2*n + 1; while(leftchild < count && rightchild < count) { if(pheap[leftchild].ptime > pheap[rightchild].ptime) { if(pheap[leftchild].ptime > pheap[n].ptime) { swap(leftchild, n); n = leftchild; int leftchild = 2*n; int rightchild = 2*n + 1; } } else { if(pheap[rightchild].ptime > pheap[n].ptime) { swap(rightchild, n); n = rightchild; int leftchild = 2*n; int rightchild = 2*n + 1; } } } } void spawn1(){ process p; process p1; p1.atime = 0; int i = 0; srand(time(NULL)); while(i < timecounting) { p.atime = rand()%3 + 4 + p1.atime; p.ptime = rand()%5 + 1; p1.atime = p.atime; p.type = 1; type1[i+1] = p; i++; } } void spawn2(){ process p; process p1; p1.atime = 0; srand(time(NULL)); int i = 0; while(i < timecounting) { p.atime = rand()%3 + 9 + p1.atime; p.ptime = rand()%5 + 6; p1.atime = p.atime; p.type = 2; type2[i+1] = p; i++; } } void spawn3(){ process p; process p1; p1.atime = 0; srand(time(NULL)); int i = 0; while(i < timecounting) { p.atime = rand()%3 + 25 + p1.atime; p.ptime = rand()%5 + 11; p1.atime = p.atime; p.type = 3; type3[i+1] = p; i++; } } void spawn4(){ process p; process p1; p1.atime = 0; srand(time(NULL)); int i = 0; while(i < timecounting) { p.atime = rand()%6 + 30 + p1.atime; p.ptime = rand()%5 + 8; p1.atime = p.atime; p.type = 4; type4[i+1] = p; i++; } } void processor() { process p; process p1; p1.atime = 0; int n = 1; int n1 = 1; int n2 = 1; for(int i = 0; i<timecounting;i++) { if(type1[n].atime == i) { add(type1[n]); n++; } if(type2[n1].atime == i) { add(type1[n1]); n1++; } if(type3[n2].atime == i) { add(type1[n2]); n2++; } /* if(pheap[1].atime <= i) { while(pheap[1].atime != 0){ pheap[1].atime--; i++; } remove(); }*/ } } };

    Read the article

  • How to return the output of a recursive function in Clojure

    - by Silanglaya Valerio
    Hi everyone! I'm new to functional languages and clojure, so please bear with me... I'm trying to construct a list of functions, with either random parameters or constants. The function that constructs the list of functions is already working, though it doesn't return the function itself. I verified this using println. Here is the snippet: (def operations (list #(- %1 %2) #(+ %1 %2) #(* %1 %2) #(/ %1 %2))) (def parameters (list \u \v \w \x \y \z)) (def parameterlistcount 6) (def paramcount 2) (def opcount 4) (defn generateFunction "Generates a random function list" ([] (generateFunction 2 4 0.5 0.6 '())) ([pc maxdepth fp pp function] (if (and (> maxdepth 0) (< (rand) fp)) (dotimes [i 2] (println(conj (generateFunction pc (dec maxdepth) fp pp function) {:op (nth operations (rand-int opcount))}))) (if (and (< (rand) pp) (> pc 0)) (do (dec pc) (conj function {:param (nth parameters (rand-int parameterlistcount))})) (conj function {:const (rand-int 100)}))))) Any help will be appreciated, thanks!

    Read the article

  • What does this PHP (function/construct?) do, and where can I find more documentation on it?

    - by Rob
    Simple question. Here is this code. $r = rand(0,1); $c = ($r==0)? rand(65,90) : rand(97,122); $inputpass .= chr($c); I understand what it does in the end result, but I'd like a better explanation on how it works, so I can use it myself. Sorry if this is a bad question. If you're unsure of what I'm asking about, its the (function?) used here: $c = ($r==0)? rand(65,90) : rand(97,122);

    Read the article

  • illigal start of type error (java).

    - by David
    here is the relevent code snippet: public static Rand searchCount (int[] x) { int a ; int b ; int c ; int d ; int f ; int g ; int h ; int i ; int j ; Rand countA = new Rand () ; for (int l= 0; l<x.length; l++) { if (x[l] = 0) a++ ; else if (x[l] = 1) b++ ; } } return countA ; } (Rand is the name of the class that this method is in) when compiling it get this error message: Rand.java:77: illegal start of type return countA ; ^ what's going wrong here? what does this error message mean?

    Read the article

  • Calendar issue in simple java form using swing package?

    - by Rand Mate
    I have created a form using java swing package, For the purpose of adding Date of Birth in the form I have used the following code particularly to add in java Frame via Swing Package. Is there any alternative way to simplify the code. JLabel l2 = new JLabel("Date of Birth"); l2.setBounds(200,160,100,20); String day[] ={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30"}; String month[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; String year[] = {"2012","2011","2010","2009","2008","2007","2006","2005","2004","2003","2002","2001","2000","1999","1998","1997","1996","1995","1994","1993","1992","1991","1990","1989","1988","1987","1986","1985","1984","1983","1982","1981","1980","1979","1976","1975"}; JComboBox cb1 = new JComboBox(day); cb1.setBounds(450,160,50,20); JComboBox cb2 = new JComboBox(month); cb2.setBounds(500,160,50,20); JComboBox cb3 = new JComboBox(year); cb3.setBounds(550,160,60,20);

    Read the article

  • What are the essential qualities to be a Java programmer? [closed]

    - by Rand Mate
    I just learnt a crash course from an institute for Core and Advanced Core Concepts in Java. I asked them what are all the algorithms, I need to know? They said: In Java there are more methods, you don't need to code more as in C/C++. After finishing core concepts in Java, I just passed on with more method usages from pre-defined classes in packages. So what's the next part I have to do, if the above mentioned is perfectly true (or) false based on the current expectations of IT Java programmers market? FYI: I'm fundamentally from the Electronics background, so please do excuse my ignorance.

    Read the article

  • Hibernate Criteria API equivalent to HQL select clause?

    - by Visus Zhao
    I'd like to have a combined query for two persistent classes. In HQL this could be achieved by the select clause, select new Family(mother, mate, offspr) from DomesticCat as mother join mother.mate as mate left join mother.kittens as offspr In the above example, Family is a conbined class with DemesticCat as its construtor params What is the Criteria equivalent of the HQL select clause ?

    Read the article

  • Textmate cucumber bundle issues - 'Run Feature' producing errors.

    - by Evolve
    From a cucumber feature file when I go to 'Run features' Im getting the error below in the popup box that appears. How do I fix this? /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in gem_original_require': no such file to load -- /Users/evolve/Projects/i9/Tornelo/.bundle/environment (LoadError) from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:inrequire' from /Users/evolve/Library/Application Support/TextMate/Bundles/Cucumber.tmbundle/Support/lib/cucumber/mate/../mate.rb:10 from /Users/evolve/Library/Application Support/TextMate/Bundles/Cucumber.tmbundle/Support/lib/cucumber/mate/feature_helper.rb:1:in require' from /Users/evolve/Library/Application Support/TextMate/Bundles/Cucumber.tmbundle/Support/lib/cucumber/mate/feature_helper.rb:1 from /tmp/cucumber-906.rb:2:inrequire' from /tmp/cucumber-906.rb:2

    Read the article

  • Crash when using Cocos2d

    - by ipodfreak0313
    Sorry about the poor question title, it's just that this seems to big for a title. So here's the dirt: I am making a game (obviously) and I want the enemies to shoot (not necessarily at the player). I want the shoot method to be in the Enemies file, so as not to clutter up my HelloWorldLayer.m file even more. Here's what I'm using right now: HelloWorldLayer.m -(void)addEnemy:(BigAndStrongEnemy *)enemy { enemy = nil; if((arc4random() % 4) == 3) { enemy = [BigAndStrongEnemy enemy]; } else { enemy = [SmallAndFastEnemy enemy]; } if(buffDude.position.y > character.position.y || buffDude.position.y < (character.position.y + 10)) { } int rand = arc4random() % 320; if((arc4random() % 2 == 1)) { [enemy setPosition:ccp(0,rand)]; }else{ [enemy setPosition:ccp(480,rand)]; } [self animateEnemy:enemy]; [self addChild:enemy]; } -(void)animateEnemy:(BigAndStrongEnemy *)enemy2 { float randX = arc4random() % 480; float randY = arc4random() % 320; int rand = arc4random() % 320; CGPoint moveToPoint = CGPointMake(randX, (randY - rand)); [enemies addObject:enemy2]; action = [CCSequence actions: [CCMoveBy actionWithDuration:1 position:ccpMult(ccpNormalize(ccpSub(moveToPoint, enemy2.position)), 75)], [CCMoveBy actionWithDuration:3 position:ccp(buffDude.position.x,buffDude.position.y)], nil]; CCCallFuncO *a = [CCCallFuncO actionWithTarget:self selector:(@selector(shoot:)) object:enemy2]; CCSequence *s = [CCSequence actions:action,a, nil]; CCRepeatForever *repeat = [CCRepeatForever actionWithAction:s]; [enemy2 runAction:repeat]; } And here's the Shoot info from the Enemies class: Enemies.m: -(void)shoot:(id)sender { self = (BigAndStrongEnemy *)sender; [self shoot]; } -(void)spriteMoveFinished:(id)sender { CCSprite *b = (CCSprite *)sender; [self removeChild:b cleanup:YES]; } -(void)shoot { self = [CCSprite spriteWithFile:@"bigAndStrongEnemy.gif"]; CCSprite *b = [CCSprite spriteWithFile:@"bullet.gif"]; b.position = ccp(self.position.x,self.position.y); b.tag = 2; [self addChild:b]; [bullets addObject:b]; CGSize winSize = [[CCDirector sharedDirector] winSize]; CGPoint point = CGPointMake((winSize.width - (winSize.width - self.position.x)),0); [b runAction:[CCSequence actions: [CCMoveBy actionWithDuration:0.5 position:point], [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]]; } Every time the 3 seconds goes by, the app crashes, and goes to the breakpoint in the CCCallFuncO file. I haven't touched it, is the thing. I am completely confused. Any help is greatly appreciated.

    Read the article

  • Neural Networks in C# using NeuronDotNet

    - by kingrichard2005
    Hello, I'm testing the NeuronDotNet library for a class assignment using C#. I have a very simple console application that I'm using to test some of the code snippets provided in the manual fro the library, the goal of the assignment is to teach the program how to distinguish between random points in a square which may or may not be within a circle that is also inside the square. So basically, which points inside the square are also inside the circle. Here is what I have so far: namespace _469_A7 { class Program { static void Main(string[] args) { //Initlaize the backpropogation network LinearLayer inputLayer = new LinearLayer(2); SigmoidLayer hiddenLayer = new SigmoidLayer(8); SigmoidLayer outputLayer = new SigmoidLayer(2); new BackpropagationConnector(inputLayer, hiddenLayer); new BackpropagationConnector(hiddenLayer, outputLayer); BackpropagationNetwork network = new BackpropagationNetwork(inputLayer, outputLayer); //Generate a training set for the ANN TrainingSet trainingSet = new TrainingSet(2, 2); //TEST: Generate random set of points and add to training set, //for testing purposes start with 10 samples; Point p; Program program = new Program(); //Used to access randdouble function Random rand = new Random(); for(int i = 0; i < 10; i++) { //These points will be within the circle radius Type A if(rand.NextDouble() > 0.5) { p = new Point(rand.NextDouble(), rand.NextDouble()); trainingSet.Add(new TrainingSample(new double[2] { p.getX(), p.getY() }, new double[2] { 1, 0 })); continue; } //These points will either be on the border or outside the circle Type B p = new Point(program.randdouble(1.0, 4.0), program.randdouble(1.0, 4.0)); trainingSet.Add(new TrainingSample(new double[2] { p.getX(), p.getY() }, new double[2] { 0, 1 })); } //Start network learning network.Learn(trainingSet, 100); //Stop network learning //network.StopLearning(); } //generates a psuedo-random double between min and max public double randdouble(double min, double max) { Random rand = new Random(); if (min > max) { return rand.NextDouble() * (min - max) + max; } else { return rand.NextDouble() * (max - min) + min; } } } //Class defines a point in X/Y coordinates public class Point { private double X; private double Y; public Point(double xVal, double yVal) { this.X = xVal; this.Y = yVal; } public double getX() { return X; } public double getY() { return Y; } } } This is basically all that I need, the only question I have is how to handle output?? More specifically, I need to output the value of the "step size" and the momentum, although it would be nice to output other information as well. Anyone with experience using NeuronDotNet, your input is appreciated.

    Read the article

  • Generating moderately interesting images

    - by Williham Totland
    Abstract: Can you propose a mathematical-ish algorithm over a plane of pixels that will generate a moderately interesting image, preferably one that on the whole resembles something? The story thus far: Once upon a time I decided in an effort to reduce cycle waste on my (admittedly too) numerous computers, and set out to generate images in a moderately interesting fashion; using a PRNG and some clever math to create images that would, on the whole, resemble something. Or at least, that was the plan. As it turns out, clever math requires being a clever mathematician; this I am not. At some length I arrived at a method that preferred straight lines (as these are generally the components of which our world is made), perhaps too strongly. The result is mildly interesting; resembling, perhaps, city grids as such: Now for the question proper: Given the source code of this little program; can you improve upon it and propose a method that gives somewhat more interesting results? (e.g. not city grids, but perhaps faces, animals, geography, what have you) This is also meant as a sort of challenge; I suppose and as such I've set down some completely arbitrary and equally optional rules: The comments in the code says it all really. Suggestions and "solutions" should edit the algorithm itself, not the surrounding framework, except as for to fix errors that prevents the sample from compiling. The code should compile cleanly with a standard issue C compiler. (If the example provided doesn't, oops! Tell me, and I'll fix. :) The method should, though again, this is optional, not need to elicit help from your friendly neighborhood math library. Solutions should probably be deliverable by simply yanking out whatever is between the snip lines (the ones that say you should not edit above and below, respectively), with a statement to the effect of what you need to add to the preamble in particular. The code requires a C compiler and libpng to build; I'm not entirely confident that the MinGW compiler provides the necessities, but I would be surprised if it didn't. For Debian you'll want the libpng-dev package, and for Mac OS X you'll want the XCode tools.. The source code can be downloaded here. Warning: Massive code splurge incoming! // compile with gcc -o imggen -lpng imggen.c // optionally with -DITERATIONS=x, where x is an appropriate integer // If you're on a Mac or using MinGW, you may have to fiddle with the linker flags to find the library and includes. #include <stdio.h> #include <stdlib.h> #include <png.h> #ifdef ITERATIONS #define REPEAT #endif // ITERATIONS // YOU MAY CHANGE THE FOLLOWING DEFINES #define WIDTH 320 #define HEIGHT 240 // YOU MAY REPLACE THE FOLLOWING DEFINES AS APPROPRIATE #define INK 16384 void writePNG (png_bytepp imageBuffer, png_uint_32 width, png_uint_32 height, int iteration) { char *fname; asprintf(&fname, "out.%d.png", iteration); FILE *fp = fopen(fname, "wb"); if (!fp) return; png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr = png_create_info_struct(png_ptr); png_init_io(png_ptr, fp); png_set_filter(png_ptr, PNG_FILTER_TYPE_DEFAULT, PNG_FILTER_NONE); png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_set_rows(png_ptr, info_ptr, imageBuffer); png_set_invert_mono(png_ptr); /// YOU MAY COMMENT OUT THIS LINE png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); free(fname); } int main (int argc, const char * argv[]) { png_uint_32 height = HEIGHT, width = WIDTH; int iteration = 1; #ifdef REPEAT for (iteration = 1; iteration <= ITERATIONS; iteration++) { #endif // REPEAT png_bytepp imageBuffer = malloc(sizeof(png_bytep) * height); for (png_uint_32 i = 0; i < height; i++) { imageBuffer[i] = malloc(sizeof(png_byte) * width); for (png_uint_32 j = 0; j < width; j++) { imageBuffer[i][j] = 0; } } /// CUT ACROSS THE DASHED LINES /// ------------------------------------------- /// NO EDITING ABOVE THIS LINE; EXCEPT AS NOTED int ink = INK; int x = rand() % width, y = rand() % height; int xdir = (rand() % 2)?1:-1; int ydir = (rand() % 2)?1:-1; while (ink) { imageBuffer[y][x] = 255; --ink; xdir += (rand() % 2)?(1):(-1); ydir += (rand() % 2)?(1):(-1); if (ydir > 0) { ++y; } else if (ydir < 0) { --y; } if (xdir > 0) { ++x; } else if (xdir < 0) { --x; } if (x == -1 || y == -1 || x == width || y == height || x == y && x == 0) { x = rand() % width; y = rand() % height; xdir = (rand() % 2)?1:-1; ydir = (rand() % 2)?1:-1; } } /// NO EDITING BELOW THIS LINE /// ------------------------------------------- writePNG(imageBuffer, width, height, iteration); for (png_uint_32 i = 0; i < height; i++) { free(imageBuffer[i]); } free(imageBuffer); #ifdef REPEAT } #endif // REPEAT return 0; } Note: While this question doesn't strictly speaking seem "answerable" as such; I still believe that it can give rise to some manner of "right" answer. Maybe. Happy hunting.

    Read the article

  • Catalyst forgets monitor settings after reboot or log out in 12.10

    - by Mate Weisz
    I have a Samsung monitor connected to my ATI Radeon graphic card via HDMI. By default the screen has a black border around, but I can disable it in the Catalyst menu to get full screen. (There is a scalebar that I have to set to the highest value.) My problem is that every time I turn off and on my computer it changes back and I have to set it up again. It is really annoying. Is there any way to make this setting permanent? Notes: 1. I open Catalyst with admin rights. 2. When I open the Catalyst settings menu, it looks like that it keeps my settings, because the scalebar stays at the highest point, but still it doesn't scale up my screen until I move back and forth the scale bar to the same point

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >