C++ Are pseudo random number generators thread safe? - c++

Q1: Are pseudo random number generators thread safe? Can I use a shared generator in multiple threads?
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <random>
#include <math.h>
using namespace std;
random_device seed;//Should I use thread_local here?
default_random_engine engine(seed());//Should I use thread_local here?
int random_int(int x, int y)
{
binomial_distribution<int> distribution(y - x);
return distribution(engine) + x;
}
int a[10],b[10],c[10];
void thread_task() {
for (int i = 0; i < 10; i++)
{
a[i] = random_int(1, 8);
}
}
void thread_task1() {
for (int i = 0; i < 10; i++)
{
b[i] = random_int(1, 8);
}
}
void thread_task2() {
for (int i = 0; i < 10; i++)
{
c[i] = random_int(1, 8);
}
}
int main()
{
thread t(thread_task);
thread t1(thread_task1);
thread t2(thread_task2);
t.join();
t1.join();
t2.join();
for (int i = 0; i < 10; i++)
cout << a[i] << " ";
cout << endl;
for (int i = 0; i < 10; i++)
cout << b[i] << " ";
cout << endl;
for (int i = 0; i < 10; i++)
cout << c[i] << " ";
cout << endl;
getchar();
return 0;
}
result 1:
7 4 4 3 7 5 4 4 4 4
5 4 4 7 2 3 6 5 4 7
4 4 4 6 1 6 3 5 3 4 //seems fine.
result 2:
5 3 5 6 3 4 5 5 3 5
5 6 5 6 8 3 5 7 3 2
4 6 4 5 4 4 4 3 6 7 //still works fine.
Q2: Does thread safe means lock-free?
If a class is thread safe, then does that mean I can use a shared instance of it in multiple threads without locking it?
Q3: I didn't use either a lock or a thread_local keyword, it still generates different integer sequences for different threads, then what's a lock good for?

If you don't need deterministic sequences per thread could use use locks with one PRNG. If the pseudo-random sequences can't differ over different threads over different runs then use a PRNG per thread.

Related

How do I save all the numbers from a string into a multi-dimensional array in c++?

I have to write a program that takes a completed sudoku board, saves only the numbers (meaning all the symbols used between the numbers to separate them such as '-', '|' etc cant be saved) into a two-dimensional array.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int input[11] = { 0 };
int sudoku[9][9] = { 0 };
for (int line = 0; line <= 10; line++)
{
cin >> input[line];
}
system("PAUSE");
return 0;
}
This is the only working code I've got so far. I've tried different kinds of for loops to get this done but I can't figure why it doesn't work.
So I wanted to ask, is it even possible save all the numbers of a string into a multi-dimensional array? And if it's not, where is my approach wrong or how could I solve this task?
One example of the input would be:
.5.1.4.|.8.6.9.|.7.2.3
.8.7.2.|.3.4.5.|.6.1.9
.9.6.3.|.2.1.7.|.5.4.8
-------|-------|-------
.6.2.8.|.1.3.4.|.9.5.7
.1.9.7.|.6.5.2.|.8.3.4
.4.3.5.|.7.9.8.|.1.6.2
-------|-------|-------
.2.4.6.|.9.7.1.|.3.8.5
.7.5.1.|.4.8.3.|.2.9.6
.3.8.9.|.5.2.6.|.4.7.1
One approach is to use regular expressions. This way the formatting of the sudoku board can change but your will still be able to parse out the numbers.
The reason I broke it into two for loops was to easily ignore the row that has no numbers in it.
#include <iostream>
#include <regex>
#include <string>
#include <vector>
int main()
{
std::string line;
// this regular expression matches a single digit
std::regex exp("(\\d)");
std::smatch res;
int sudoku[9][9] = {{0}};
int row = 0;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
// get a line of the board
std::getline(std::cin, line);
// search for the next digit in the line
for (int k = 0; std::regex_search(line, res, exp); ++k)
{
// convert the digit into an integer and store it in the board
sudoku[row][k] = std::stoi(res[0]);
// the rest of the line after the first match becomes the new
// line so that we can search for the next digit
line = res.suffix();
}
row += 1;
}
// ignore every third row that is used to separate the board sections
std::getline(std::cin, line);
}
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
std::cout << sudoku[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
For your example board, it produces this output:
5 1 4 8 6 9 7 2 3
8 7 2 3 4 5 6 1 9
9 6 3 2 1 7 5 4 8
6 2 8 1 3 4 9 5 7
1 9 7 6 5 2 8 3 4
4 3 5 7 9 8 1 6 2
2 4 6 9 7 1 3 8 5
7 5 1 4 8 3 2 9 6
3 8 9 5 2 6 4 7 1

Weird Input output in cpp

I was solving subarray with given sum,Where we have to print the starting and ending index of array if subarray with sum is found , when I tried with two test cases simultaneously i got wrong result
But when I was tried one at a time I got right answer in both.
You please also check in your IDE this is happening in every IDE.
Testcase (Simultaneously)
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Output
2 4 (expected 2 4)
2 5 (But expected 1 5)
But when I tried like this for second test cases
1
10 15
1 2 3 4 5 6 7 8 9 10
Output : 1 5(As expected)
I got correct answer ,why my program this kind of weird behaviour ?
#include<iostream>
#include<vector>
#include<queue>
#include<unordered_map>
using namespace std;
vector<int>a;
unordered_map<int, int>seen;
int main()
{
int t;
cin >> t;
while (t--) {
int n, s;
cin >> n >> s;
a.resize(n);
int sum = 0;
seen[0] = -1;
for (int i = 0; i < n; i++) {
cin >> a[i];
sum += a[i];
if (seen.find(sum - s) != seen.end()) {
int x;
x = seen[sum - s] + 2;
cout << x << " " << i + 1 << endl;
break;
}
else {
seen[sum] = i;
}
}
seen.clear();
a.clear();
//cout<<endl;
}
return 0;
}

Create all possible combinations using a deque and recursion C++

I have a deque that contains a series of numbers {0, 1, 2, 3, 4, 5, 6} and I am trying to create all possible combinations of these numbers using recursion.
Here is my current code
void combination(vector<node> &comb, deque<node> &numbers) {
if (numbers.empty()) {
for (unsigned int i = 0; i < comb.size(); i++) {
cout << comb[i].id << " ";
}
cout << "\n";
return;
}
comb.push_back(numbers.front());
numbers.pop_front();
combination(comb, numbers);
comb.pop_back();
combination(comb, numbers);
}
I've ran this through on paper and it makes sense but when I run it this is the output:
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
Why isn't the function printing out all possible combinations?
Also, this is what I want to use - A deque that contains the numbers and a vector that contains each combination.
You are using Pass by reference, i have made some minor changes and it works
code :
#include <bits/stdc++.h>
using namespace std;
void combination(vector<int> comb, deque<int> numbers) {
if (numbers.empty()) {
for (unsigned int i = 0; i < comb.size(); i++) {
cout << comb[i] << " ";
}
cout << "\n";
return;
}
comb.push_back(numbers.front());
numbers.pop_front();
combination(comb, numbers);
comb.pop_back();
combination(comb, numbers);
}
int main() {
// your code goes here
vector<int> comb;
deque<int> numbers;
for(int i = 0;i < 7;i++) numbers.push_back(i);
combination(comb, numbers);
return 0;
}
Link to solution on ideone : http://ideone.com/vgukF3

print a table of decremented numbers

I want to write a code that print a table like this:
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
I wrote a code to print a table as said above, but it just print 5's.
I know that I have to use a condition to print such a table. What's the condition to print it ?
int main () {
int number = 5;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (condition)
...
else
cout << number << " ";
}
cout << endl;
}
return 0;
}
As I mentioned in comments, what you want to print is the Chebyshev distance to the center +1. I dont know what condition can make your code work, but instead I would use a simple formula to calculate each value:
#include <iostream>
using namespace std;
int main() {
for (int i=0;i<9;i++){
for (int j=0;j<9;j++){
cout << std::max(abs(i-4),abs(j-4)) +1 << " " ;
}
cout << endl;
}
}
/*To make boxes and inside box and so on
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
void main()
{
int a[100][100],n,i,j,k=0,l;
clrscr();
cout<<"Enter the outside No. n \n";
//like for your answer it is 5;
//i and j are loop element for 2D array
//k is used for making n boxes
cin>>n;
l=n;
n=2*n-1;
while(k<n)
{
if(k%2==0)
{
for(i=k;i<n-k;i++)
{
a[0+k][i]=l;
a[i][0+k]=l;
a[n-1-k][i]=l;
a[i][n-1-k]=l;
}
k++;l--;
}
else
{
for(i=k;i<n-k;i++)
{
a[0+k][i]=l;
a[i][0+k]=l;
a[n-1-k][i]=l;
a[i][n-1-k]=l;
}
k++;l--;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout << a[i][j];
if(a[i][j]>9)
cout<<" ";
else
cout<<" ";
}
cout<<endl;
}
getch();
}

Weird vector<long> addition with '0' as '-1'

I'm writing a basic chess program to calculate how many sets you can make with the given chess figures. The data file:
4
22 3 5 6 2 0
1 1 1 1 1 1
8 4 4 4 1 2
5 3 3 3 0 2
The code:
#include <iostream>
#include <fstream>
#include <vector>
int main
(int argc, char *argv[])
{
std::fstream data_file;
size_t i, k;
std::vector<long> chess;
long t, n;
data_file.open("U1.txt", std::ios::in);
data_file >> n;
for (i = 0; i < n; i++)
chess.push_back(0);
for (i = 0; i < n; i++) {
for (k = 0; k < 6; k++) {
data_file >> t;
std::cout << t << " ";
chess[k] += t;
}
std::cout << std::endl;
}
data_file.close();
for (int i = 0; i < 6; i++)
std::cout << chess[i] << " ";
std::cout << std::endl;
data_file.open("U1rez.txt", std::ios::out);
data_file << n;
std::cout << n << std::endl;
data_file.close();
return EXIT_SUCCESS;
}
The output:
22 3 5 6 2 0
1 1 1 1 1 1
8 4 4 4 1 2
5 3 3 3 0 2
36 11 13 14 3 4
4
Why am I getting 3 and 4 at the end result just after 36, 11, 13 and 14 at line 5? When I print the test values I seem to get the right numbers but something goes terribly wrong in the addition of them in the vector container.
for (i = 0; i < n; i++)
chess.push_back(0);
.
.
.
for (i = 0; i < n; i++) {
for (k = 0; k < 6; k++) {
data_file >> t;
std::cout << t << " ";
chess[k] += t;
}
std::cout << std::endl;
}
here, you initialized n(=4) places in the vector, but here you are accessing the index 4 and 5 of the vector chess which is causing the addition problem.
On an unrelated note, you will have a much easier time with C++ if you let go of some of the rules imposed by C.
The C++ API uses scope-bounded resource management; i.e. there's no need to explicitly close the file handle here, since the class does this for you when its destructor is called at the end of the declared scope.
Prefer std::cout << "\n" to std::cout << std::endl, unless you actually intend to insert a newline and flush the buffer. Many C++ programmers still use printf, and I personally think that it's a lot more elegant than C++'s ugly standard solution to IO -- feel free to use printf.
Do you find your code easier to manage and read when you declare your variable where they are used (e.g. for (size_type i = 0; ... ; ...)), rather than at the beginning of your method? This also allows the compiler to potentially make better choices about register usage, since it has more information about the scopes of your temporary variables.
Here are a few features of C++11 that can also save you some time:
Automatic type inference: when the compiler can infer the type of a variable, it's not necessary for you to explicitly specify it; you can use auto instead (e.g. auto x = parse_data();).
Range-for: if you are operating on a container that provides global definitions begin() and end() (such as any standard container), then instead of this:
typedef typename container_type::const_iterator iter;
for (iter i = begin(container), iter l = end(container); i != l; ++i) { ... }
You can do this:
for (const auto& x : container) { ... }
I just wanted to give you a few quick pointers that can save you some time.