Hi i am working on a random number generator which i faced a road block. I have done my program but i'm quite lost on how to do a loop for the C++ program to keep on looping. following below is the conditions for program:
The program prompts the user to enter a number.
This number determines the number of times the loop will repeat. The number ranges from 0 to 100. Validate this range.
The program uses a random number to generate a number from 0 to 9999 and then
checks if the generated number contains the digit 1, digit 2 or digit 3.
Please advise on how do i require to do a switch or while loop for point 3.
your inputs is greatly appreciated.
Easiest way to check would be to use the mod operation and division to extract every digit.
A loop would be something like
int randInt = randomFunction();
while(randInt > 0){
//Get Last Digit
int lastDigit = randInt % 10;
switch(lastDigit){
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
}
/*
Divide the number by 10 to remove the last digit.
Integers will automatically truncate remainders.
i.e int a = 21/10, a will = 2
*/
randInt /= 10;
}
Related
First time I am learning algorithms and trying to figure out with stratch. I am following tutorials on Stratch wiki. How can I convert this to algorithm?( with flow chart or normal steps). Especially the loop.( I uploaded as picture) Please click here to see picture
I Started:
Step:1 Start
Step2: İnt: delete all of numbers, iterator, amount,sum
Step3: How many numbers you want?
Step4:initialize sum=0,amount=0,iterator=1
Step5: Enter the elements values
Step6: found the sum by using loop in array and update sum value in which loop must be continue till (no of elements-1 ) times
Step7:avg=sum/no of elements
Step8: Print the values average
I don't think It's true. I mean I feel there are errors? Thank you for time.
Scratch
Here is the algorithm in variant 2 (see Java algorithm below) in Scratch. The output should be identical.
Java
Here is the algorithm in Java where I did comment the steps which should give you a step-by-step guide on how to do it in Scratch as well.
I have also implemented two variants of the algorithm to show you some considerations that a programmer often has to think of when implementing an algorithm which mainly is time (= time required for the algorithm to complete) and space (= memory used on your computer).
Please note: the following algorithms do not handle errors. E.g. if a user would enter a instead of a number the program would crash. It is easy to adjust the program to handle this but for simplicity I did not do that.
Variant 1: Storing all elements in array numbers
This variant stores all numbers in an array numbers and calculates the sum at the end using those numbers which is slower than variant 2 as the algorithm goes over all the numbers twice. The upside is that you will preserve all the numbers the user entered and you could use that later on if you need to but you will need storage to store those values.
public static void yourAlgorithm() {
// needed in Java to get input from user
var sc = new Scanner(System.in);
// print to screen (equivalent to "say"/ "ask")
System.out.print("How many numbers do you want? ");
// get amount of numbers as answer from user
var amount = sc.nextInt();
// create array to store all elements
var numbers = new int[amount];
// set iterator to 1
int iterator = 1;
// as long as the iterator is smaller or equal to the number of required numbers, keep asking for new numbers
// equivalent to "repeat amount" except that retries are possible if no number was entered
while (iterator <= amount) {
// ask for a number
System.out.printf("%d. number: ", iterator);
// insert the number at position iterator - 1 in the array
numbers[iterator - 1] = sc.nextInt();
// increase iterator by one
iterator++;
}
// calulate the sum after all the numbers have been entered by the user
int sum = 0;
// go over all numbers again! (this is why it is slower) and calculate the sum
for (int i = 0; i < amount; i++) {
sum += numbers[i];
}
// print average to screen
System.out.printf("Average: %s / %s = %s", sum, amount, (double)sum / (double)amount);
}
Variant 2: Calculating sum when entering new number
This algorithm does not store the numbers the user enters but immediately uses the input to calculate the sum, hence it is faster as only one loop is required and it needs less memory as the numbers do not need to be stored.
This would be the best solution (fastest, least space/ memory needed) in case you do not need all the numbers the user entered later on.
// needed in Java to get input from user
var sc = new Scanner(System.in);
// print to screen (equivalent to "say"/ "ask")
System.out.print("How many numbers do you want? ");
// get amount of numbers as answer from user
var amount = sc.nextInt();
// set iterator to 1
int iterator = 1;
int sum = 0;
// as long as the iterator is smaller or equal to the number of required numbers, keep asking for new numbers
// equivalent to "repeat amount" except that retries are possible if no number was entered (e.g. character was entered instead)
while (iterator <= amount) {
// ask for a number
System.out.printf("%d. number: ", iterator);
// get number from user
var newNumber = sc.nextInt();
// add the new number to the sum
sum += newNumber;
// increase iterator by one
iterator++;
}
// print average to screen
System.out.printf("Average: %s / %s = %s", sum, amount, (double)sum / (double)amount);
Variant 3: Combining both approaches
You could also combine both approaches, i. e. calculating the sum within the first loop and additionally storing the values in a numbers array so you could use that later on if you need to.
Expected output
Info
Hi everyone
I was searching an efficient way to check if a number is multiple of 5. So I searched on google and found this solution on geeksforgeeks.org.
There were 3 solutions of my problem.
First solution was to subtract 5 until reaching zero,
Second solution was to convert the number to string and check last character to be 5 or 0,
Third solution was by doing some interesting operations on bitwise level.
I'm interested in third solution as I can fully understand the first and the second.
Here's the code from geeksforgeeks.
bool isMultipleof5(int n)
{
// If n is a multiple of 5 then we
// make sure that last digit of n is 0
if ( (n & 1) == 1 )
n <<= 1;
float x = n;
x = ( (int)(x * 0.1) ) * 10;
// If last digit of n is 0 then n
// will be equal to (int)x
if ( (int)x == n )
return true;
return false;
}
I understand only some parts of the logic. I haven't even tested this code. So I need to understand it to use freely.
As said in mentioned article this function is multiplying number by 2 if last bit is set and then checking last bit to be 0 and returns true in that case. But after checking binary representations of numbers I got confused as last bit is 1 in case of any odd number and last bit is 0 in case of any even number. So...
Actual question is
What's the logic of this function?
Any answer is appreciated!
Thanks for all!
The most straightforward way to check if a number is a multiple of 5 is to simply
if (n % 5 == 0) {
// logic...
}
What the bit manipulation code does is:
If the number is odd, multiply it by two. Notice that for multiples of 5, the ones digit will end in either 0 or 5, and doubling the number will make it end in 0.
We create a number x that is set to n, but with a ones digit set to 0. (We do this by multiplying n by 0.1, which removes the ones digit, and then multiply by 10 in order to add a 0, which has a total effect of just changing the ones digit to 0).
We know that originally, if n was a multiple of 5, it would have a ones digit of 0 after step 1. So we check if x is equal to it, and if so, then we can say n was a multiple of 5.
We have a number N and the problem is to find the smallest even number E such that E > N and digits in N and E are same. Digits in N could be huge.
For example
1 -> 34722641 answer would be 34724126
111 -> no even number is possible just greater then it.
1123 -> output would be 1132
I have done it with brute force by making all the permutations of the digits of the number. I was thinking if a better approach is there for it? A code would be better.
Thanks.
You can use the following strategy in finding the next permutation:
Lets say your number = 12344875
To find the next permutations which is bigger, you start from the right and find the first number is smaller than the previous one.
In this case: number = 12344875, this is 4.
Now you start from the 4 moving right and find the smallest number there.
Which is the 5 -> 875. Now swap those 2 numbers resulting in 12345874.
After the swap sort the numbers after the 5 in ascending order. 12345874 --> 12345784.
This strategy will always lead to next permutations wich is bigger, only this gives both even and uneven numbers.
So for finding the next even permutations, you need to change this slightly.
If in last step you have an even number, permutate that part till its an even number.
Otherwise start again from the right. And find the first even number, which has a larger number to its right side. For example with the number = 123475531.
Now swap with smallest number to its right which is greater than 4.
Resulting in the following 123575431.
From this put the even number 4 at the end and put the numbers between
the swapped numbers in ascending order, 123575314 --> 123513574.
For the case were you have the following number 136531. There is no even number with a greater number to the right. So you look at the next number,
and see if to the right there is a number wich is greater (but not the first even number). Here it is for 136531 --> 136531 so swap those and put the even number at the back and finally put in ascending order. 136531 --> 156331 --> 153316 --> 151336.
There is no solution when the number is in descending order(for example 97654).
While making this explaination I realised that for an even number this gets more convoluted. Ill try to improve the answer later on.
I hope this was useful.
Cheers
Find the rightmost digit, i, that has a higher digit, j, to its right, where j is not the highest even digit to its right, e. Pick the smallest such j, switch i and j, place e as the rightmost digit, and sort (ascending) the digits to the right of where i was (excluding e).
Find the next greater number for a given number. For eg - for 1234, the next greater number is 1243 and for 534976 the next greater is 536479.
The algorithm can be found here. If the last digit is even then you've found the next greater even number.
Otherwise, repeat the above step until we find the even number.ie-find the next greater even
number than this with the now the new input number as the one that
we output in the previous step (even if we didn't find the desired
output(greater even number))
For eg - Input number - 21856521, running the first steps yields - 21861255(odd) so we again run step 1 on 21861255 which yields 21861525(again odd), running again yields 21861552
PS: C++ code:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main(){
string s;cin>>s;
int n = s.length();
while(true){
int idx = -1;
for(int i=n-2;i>=0;--i){
if(s[i]<s[i+1]){
idx = i;
break;
}
}
if(idx==-1){
cout<<-1<<endl;
break;
}
int swapidx = -1;
for(int i=n-1;i>=idx+1;--i){
if(s[i]>s[idx]){
swapidx = i;
break;
}
}
swap(s[idx],s[swapidx]);
//swapidx will never remain -1 bcz. we will surely find an element greater than s[idx](the right next element to idx is greater than s[idx])
sort(s.begin()+idx+1,s.end());
if((s[n-1]-'0')%2==0){
cout<<s<<endl;
break;
}
}
return 0;
}
def getNextEven(self,x):
s,p,flag,r = [],0,0,int(x)
for i in x:
p +=int(i)
if int(i)%2==0:
flag=1
s.append(i)
if flag==0:
return -1
n,x = len(s),int(x)
while r%2!=0 or r<=x:
l,k = -1,-1
for i in range(n-2,-1,-1):
if s[i]<s[i+1]:
k = i
break
if k==-1:
return -1
for i in range(k+1,n):
if s[k]<s[i]:
l = i
s[k],s[l] = s[l],s[k]
s = s[:k+1]+s[k+1:][::-1]
r = int(''.join(s))
return r
Almost all my input parameters work except for some larger number inputs for my hexadecimal addition program. My program asks user to input two numbers and it would give out the sum of the two numbers. However, the number should be only 10 digits long, and if it exceeds 10 digits it should output an Addition Overflow.
If I input "1" for first number and "ffffffffff" (10 digits) for my second number I would get an output of "Addition Overflow.". (Correct)
However, if my first number were to be a "0" and second number to still be "ffffffffff" I would get an "Addition Overflow." which is incorrect. The output should still be "ffffffffff"
When you take the final carry, and shift everything over in this loop:
if (c != 0){
for(i = digits; i >= 0; i--)
answer[i] = answer[i-1];
answer[0] = hex[c];
}
You need to increment digits by one, as you have now added another digit at the end.
Then you need to change this statement:
if(digits > length - 1)
to this statement:
if(digits > length)
That will fix your problem.
Can i have an efficient solution for the above problem.... I tried to figure out the problem from this website http://www.ihas1337code.com/2010/11/rejection-sampling.html
but couldn't get the reason
idx = col + (row-1)*7; why are they multiplying with 7....
we could have done this also (rand7() * rand7()) % 10... or multiplying with any other number, because at the end we have to do mod 10 which will give the results within 10 only....
why they have made the solution so difficult.. Please explain and your thoughts on it...
And what does uniformly means in the question?
Thanks..
(rand7() * rand7()) % 10
won't do, since some values will be more probable than others.
Lets compare the probability of for instance getting a 1 and getting a 2:
To get a 1:
rand7() * rand7() would need to equal 1, 11, 21, 31 or 41.
This can be achieved in the following ways: 1*1, 3*7 or 7*3.
That is, 3 times out of 49 you'll get a 1
To get a 2:,
rand7() * rand7() would need to equal 2, 12, 22, 32 or 42.
This can be achieved in the following ways: 1*2, 2*1, 3*4, 4*3, 2*6, 6*2, 6*7, 7*6.
That is, 8 times out of 49 you'll get a 2!
Their solution solves this by letting each number (from 1 through 10) be equally probable: Each number occurs 4 times in the 49 possible outcomes, (9 outcomes are discarded and result in a re-sampling).
As a matter of fact, the implementation of Random.nextInt(int n) does something similar:
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0); // re-sample until in range.
return val;
This actually uses a rand2 to implement a randN.
It's the base conversion of a two-digit base-7 number into a base-10 number. And it's exactly the way you would extend this to the solution to the
Generalized problem
Implementing a randA() function using randB(), for B,A > 1.
Solution
Generate sufficiently many (ceil(ln(A)/ln(B))) base-B digits
Ensure uniform distribution: If number > A*floor(pow(B,ceil(ln(A)/ln(B)))/A) reject it and continue with 1, else continue with 3
Base convert the resulting number into base-A, choose least significant digit to be result of randA()
JavaScript-Example
// This function returns a randN function. Usage
// example rand7=randn(7); rand7(); rand7()
function randn(i) {
return function () {return Math.floor(Math.random() * i);};
}
// Given a random generator for numbers 0..b-1 this
// function returns a random generator for numbers 0..a-1
function randA(b, randB, a) {
var digits=Math.ceil(Math.log(a)/Math.log(b));
var maxNum=a*Math.floor(Math.pow(b, digits)/a)-1;
return function() {
var s;
var number;
do {
s="";
// Step 1
for ( var i=0; i<digits; i++ )
s += randB();
number=parseInt(s, b);
} while (number>maxNum); // Step 2
return number%a; // Step 3
};
}
// generates a rand8() number generator
rand8=randA(2,randn(2),8);
// generates array containing random numbers 0..7
[rand8(), rand8(), rand8()]
Uniformly means that each outcome occurs equally frequently. If you call rand7() seven million times, you will get each outcome roughly one million times.
But try counting the outcomes of (rand7() * rand7()) % 10. You'll be surprised how much more frequent one of the outcomes is compared to the others.