UNIT 11 Random Numbers.

Slides:



Advertisements
Similar presentations
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Advertisements

Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 8P. 1Winter Quarter Control Statements Lecture.
Building Java Programs
UNIT 12 UNIX I/O Redirection.
Exercise 4 1. Write a program that simulates coin tossing. For each toss of the coin the program should print Heads or Tails. Let the program toss the.
Building Java Programs Chapter 5
Basic Programming II. Outline Standard Deviation Function (SD) Complex Guessing Game.
Programming Assignment #3 CS-2301, B-Term Programming Assignment #3 User-defined Functions Due, November 18, 11:59 PM (Assignment adapted from C:
1 Session-23 CSIT 121 Spring 2006 Revision Ch 7: Reference Parameters Revision Ch 7: Reference Parameters Chapter 8: Value Returning Functions Chapter.
Random (1) Random class contains a method to generate random numbers of integer and double type Note: before using Random class, you should add following.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 12 – Craps Game Application: Introducing Random.
1 Lab Session-9 CSIT-121 Fall 2003 w Random Number Generation w Designing a Game.
1 Random numbers Random  completely unpredictable. No way to determine in advance what value will be chosen from a set of equally probable elements. Impossible.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
WEEK 9 Class Activities Lecturer’s slides.
Lecture 15 Practice & exploration Subfunctions: Functions within functions “Guessing Game”: A hands-on exercise in evolutionary design © 2007 Daniel Valentine.
Craps!. Example: A Game of Chance Craps simulator Rules – Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4,
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 10 Program Organization (continued)
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 7: One More Loop Problem, Generating “random” values, Midterm Review.
Computer Programming for Engineers. Outline Tic-Tac-Toe (O-X Game) Drawing 3x3 grid Receiving the inputs Checking for a winner Taking turns between.
WEEK 4 Class Activities Lecturer’s slides.
UNIT 14 Functions with Pointer Parameters.
CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015.
CS1010E Programming Methodology Tutorial 4 Modular Programming with Functions C14,A15,D11,C08,C11,A02.
Week 7 - Wednesday.  What did we talk about last time?  scanf()  Memory allocation  malloc()  free()
CMSC 1041 Functions II Functions that return a value.
 2008 Pearson Education, Inc. All rights reserved Case Study: Random Number Generation C++ Standard Library function rand – Introduces the element.
Random numbers. 2 The Random class A Random object generates pseudo-random numbers. –Class Random is found in the java.util package. import java.util.*;
C++ Programming Lecture 10 Functions – Part II
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions (continued)
CS221 Random Numbers. Random numbers are often very important in programming Suppose you are writing a program to play the game of roulette The numbers.
Dr. Soha S. Zaghloul2 Let arr be an array of 20 integers. Write a complete program that first fills the array with up to 20 input values. Then, the program.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
WEEK 6 Class Activities Lecturer’s slides.
Problems Reads a letter grade from user and displays the corresponding range for that letter grade (A  , B  80-89, C  70-79, D  60-69, otherwise.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Random UNPREDICTABLE NUMBERS. A FEW APPLICATIONS THAT USE RANDOM…. Predictions for life expectance used in insurance Business simulations Games (Give.
Random numbers in C++ Nobody knows what’s next....
UNIT 10 Multidimensional Arrays.
+ Arrays & Random number generator. + Introduction In addition to arrays and structures, C supports creation and manipulation of the following data structures:
WEEK 8 Class Activities Lecturer’s slides.
Computer Programming for Engineers
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Review (before the 1 st test): while (conditions) { statements; } while loop: if/else if/else statements: if (conditions) { statements; } else if (different.
Chapter 8: Arrays Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Move the first element to the.
Function Call Stack and Activation Frame Stack Just like a pile of dishes Support Two operations push() pop() LIFO (Last-In, First-Out) data structure.
8. ARRAYS. Aggregate variables Scalar variables –Single value Aggregate variables –Collection of values –Arrays: elements have the same type.
CSE202: Lecture 13The Ohio State University1 Function Scope.
UNIT 17 Recursion: Towers of Hanoi.
Engineering Problem#1 Engr201 Computer Programming for Engineers Faculty of Engineering Chiang Mai University 1.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
1 Generating Random Numbers Textbook ch.6, pg
MR. CRONE Generating Random Numbers. Random Numbers Many programs require the computer to generate random numbers Random numbers are used in many applications.
Revision. Generating a pseudo-random number Necessary libraries: and Seeding: srand(time(NULL))  We set the seed based on the current time  NB! Time-dependent.
Week 12 Class Activities.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
Chapter 9: Value-Returning Functions
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CS1010 Programming Methodology
Number guessing game Pick a random number between 1 and 10
CS1010 Programming Methodology
CS1010 Programming Methodology
CS1010 Programming Methodology
Lab Session-9 CSIT-121 Spring 2005
CprE 185: Intro to Problem Solving (using C)
We’re moving on to more recap from other programming languages
CS150 Introduction to Computer Science 1
Presentation transcript:

UNIT 11 Random Numbers

Unit 11: Random Numbers CS1010 (AY2014/5 Semester 1)Unit11 - 2© NUS Objective:  Learn the use of random numbers

Unit 11: Random Numbers CS1010 (AY2014/5 Semester 1)Unit11 - 3© NUS 1.Introduction 2.rand() 3.srand() 4.“Randomising” the Seed 5.The HiLo Game

1. Introduction CS1010 (AY2014/5 Semester 1)Unit11 - 4© NUS  In simulation and games, we need random number generation.  Computer cannot generate true random numbers. At most, they could generate pseudo-random numbers, close enough to being random and good enough for most practical purposes.  We will learn two functions here:  rand()  srand()

#include int main(void) { int i; for (i = 1; i <= 10); i++) printf("%d\n", rand()); return 0; } Unit11_Random1.c 2. rand() (1/2) CS1010 (AY2014/5 Semester 1)Unit11 - 5© NUS  Run the following program Unit11_Random1.c needed to use rand() function The same set of numbers are generated every time the program is run!

2. rand() (2/2) CS1010 (AY2014/5 Semester 1)Unit11 - 6© NUS  In sunfire, rand() generates an integer in the range [0, 32676]. (Note: [a, b] indicates a closed range, i.e. the range is inclusive of both a and b.)  The same set of numbers are printed every time the program is run because the numbers are picked from a pre-determined sequence based on some seed.  Question: How to generate an integer in the range [101, 500]? for (i = 1; i <= 10); i++) printf("%d\n", rand()% ); Unit11_Random2.c In general, to generate an integer in the range [a, b], we write: rand()%(b-a+1) + a (This is not the best way, but a simple technique for our purpose.)

3. srand() (1/2) CS1010 (AY2014/5 Semester 1)Unit11 - 7© NUS  As mentioned, these “random numbers” generated are the same from run to run, due to the same default seed being used.  To get a different set of random numbers each time the program is run, the trick is to change the seed, by calling the srand() function.  A particular seed (which is an integer) indicates which pre-determined sequence of pseudo-numbers to use, and a subsequent call to rand() will pick up the next number from this sequence.  Hence, you need only call srand() function once, before you call the rand() function.

3. srand() (2/2) CS1010 (AY2014/5 Semester 1)Unit11 - 8© NUS  Test out the program Unit11_Random3.c #include int main(void) { int seed, i; printf("Enter seed: "); scanf("%d", &seed); srand(seed); // feed srand() with a new seed for (i = 1; i <= 10); i++) printf("%d\n", rand()% ); return 0; } Unit11_Random3.c Enter seed: Enter seed:

4. “Randomising” the Seed (1/2) CS1010 (AY2014/5 Semester 1)Unit11 - 9© NUS  In the preceding example, the user is asked to enter a value for the seed.  However, in many applications such as games or simulations, we want to “automate” this step since we do not want user’s invention.  How do we ensure that everytime the program is run, a different seed is used?  One simple solution is to use the time(NULL) function, which returns an integer that is the number of seconds since 1 st of January This value can then be used as the seed for the srand() function.

4. “Randomising” the Seed (2/2) CS1010 (AY2014/5 Semester 1)Unit © NUS #include int main(void) { int i; srand(time(NULL)); for (i = 1; i <= 10); i++) printf("%d\n", rand()% ); return 0; } Unit11_Random4.c needed to use time() function

5. The HiLo Game (1/3) CS1010 (AY2014/5 Semester 1)Unit © NUS  We will illustrate with the HiLo game, where user is asked to guess a secret number between 1 and 100 inclusive, given up to 5 attempts. *** Welcome to the HiLo game! *** Guess a number between 1 and 100 inclusive. Enter your guess [1]: 50 Your guess is too low! Enter your guess [2]: 70 Your guess is too low! Enter your guess [3]: 90 Your guess is too high! Enter your guess [4]: 83 Your guess is too high! Enter your guess [5]: 76 Too bad. The number is 72. Better luck next time! Do you want to play again (y/n)?

5. The HiLo Game (2/3) CS1010 (AY2014/5 Semester 1)Unit © NUS #include void play_a_game(int); int main(void) { int secret; char response; srand(time(NULL)); printf("*** Welcome to the HiLo game! ***\n"); do { secret = rand()% ; play_a_game(secret); printf("Do you want to play again (y/n)? "); scanf(" %c", &response); } while (response == 'y'); printf("\n*** Thanks for playing. Bye! ***\n"); return 0; } Unit11_HiLo.c

5. The HiLo Game (3/3) CS1010 (AY2014/5 Semester 1)Unit © NUS // Play one HiLo game void play_a_game(int secret) { int guess, tries = 0; printf("\nGuess a number between 1 and 100 inclusive.\n"); do { tries++; printf("Enter your guess [%d]: ", tries); scanf("%d", &guess); if (guess < secret) printf("Your guess is too low!\n"); else if (guess > secret) printf("Your guess is too high!\n"); } while ( (tries < 5) && (guess != secret) ); if (guess == secret) { printf("Congratulations! You did it in %d step", tries); if (tries == 1) printf(".\n"); else printf("s.\n"); } else printf("Too bad. The number is %d. Better luck next time!\n", secret); } Unit11_HiLo.c

Summary CS1010 (AY2014/5 Semester 1)Unit © NUS In this unit, you have learned about Generating pseudo-random numbers using rand() Seeding a pseudo-random sequence using srand() Providing a “random” seed by using time(NULL) in the srand() function

End of File CS1010 (AY2014/5 Semester 1)Unit © NUS