Generating 3 unique random numbers in Objective-C? - ios

I'm trying to generate 3 random numbers between 0 to 25. I used arc4random_uniform(25) for this and it generate 3 random numbers.but problem is that some time I get two or even all three numbers are same, but I require 3 unique numbers.

As #Thilo said you have to check they are random and repeat if they are not:
// This assumes you don't want 0 picked
u_int32_t numbers[3] = { 0, 0, 0 };
for (unsigned i = 0; i < 3; i++)
{
BOOL found = NO;
u_int32_t number;
do
{
number = arc4random_uniform(25);
if (i > 0)
for (unsigned j = 0; j < i - 1 && !found; j++)
found = numbers[j] == number;
}
while (!found);
numbers[i] = number;
}

int checker[3];
for(int i = 0 ; i < 3 ; i++){
checker[i] = 0;
}
for(int i = 0 ; i < 3 ; i++){
random = arc4random() % 3;
while(checker[random] == 1){
random = arc4random() % 20;
}
checker[random] = 1;
NSLog(#"random number %d", random);
}

I am generating an Array of unique Random Number in the following way:
-(void)generateRandomUniqueNumberThree{
NSMutableArray *unqArray=[[NSMutableArray alloc] init];
int randNum = arc4random() % (25);
int counter=0;
while (counter<3) {
if (![unqArray containsObject:[NSNumber numberWithInt:randNum]]) {
[unqArray addObject:[NSNumber numberWithInt:randNum]];
counter++;
}else{
randNum = arc4random() % (25);
}
}
NSLog(#"UNIQUE ARRAY %#",unqArray);
}

Related

Why am I getting wrong answer for this SPOJ Question

I still dont know weather I am allowed discuss Competetive Programming Doubts here, please let me know..
Can someone help me on this SPOJ question, I am getting wrong Answer:
https://www.spoj.com/problems/SPIKES/
I have tried all the test cases I could think of and the code always gives correct output.
Before posting it here, I also asked it in spoj forum but Its been two days, no one replies...
#include<bits/stdc++.h>
using namespace std;
// # = 35
// # = 64
// . = 46
// s = 115
// Using Dijkstra to find the path with minimum no. of Spikes
int n,m,j;
const int N = 100;
const int INF = 9;
vector<int> g[N];
int vis[N][N];
pair<int,int> dist[N][N];
vector<pair<int,int>> movements = {
{0,1},{0,-1},{1,0},{-1,0}
};
bool isvalid(int i, int j){
return i>=0 && j>=0 && i<n && j<m;
}
void bfs(int sourcei, int sourcej){
set<pair<int,pair<int,int>>> q;
q.insert({0,{sourcei,sourcej}});
dist[sourcei][sourcej] = {0,INF};
while(q.size()>0){
auto curr_v = *q.begin();
int curr_i = (curr_v.second).first;
int curr_j = (curr_v.second).second;
int spikes = curr_v.first;
q.erase(q.begin());
if(vis[curr_i][curr_j]) continue;
vis[curr_i][curr_j] = 1;
for(auto m : movements){
int child_i = curr_i + m.first;
int child_j = curr_j + m.second;
int spikec = spikes;
if(!isvalid(child_i,child_j)) continue;
if(g[child_i][child_j] == 115) spikec = spikes+1;
if(vis[child_i][child_j]) continue;
if(g[child_i][child_j]==35) continue;
if(dist[child_i][child_j].second > spikec){
dist[child_i][child_j] = {(dist[curr_i][curr_j].first +1),spikec};
q.insert({spikec , {child_i,child_j}});
}
}
}
}
int main(){
cin>>n>>m>>j;
int start_j,start_i;
int end_j,end_i;
for (int i = 0; i < N; ++i){
for (int j = 0; j < N; ++j){
dist[i][j].second = INF;
dist[i][j].first = 0;
}
}
for (int i = 0; i < n; ++i){
for (int j = 0; j < m; ++j){
char x; cin>>x;
g[i].push_back((int)x);
if(x=='#') {
start_i = i;
start_j = j;
}
if(x=='x'){
end_i = i;
end_j = j;
}
}
}
bfs(start_i,start_j);
// for (int i = 0; i < n; ++i){
// for (int j = 0; j < m; ++j){
// cout<<dist[i][j].first<<","<<dist[i][j].second<<" ";
// }cout<<endl;
// }
if(dist[end_i][end_j].second <= (int)j/2) cout<<"SUCCESS"<<endl;
else cout<<"IMPOSSIBLE"<<endl;
return 0;
}

How do I loop through NSString N number of times?

how do I loop the string 9 times ? (z x c v b n z x c)
NSString *fl = #"zxcvbn";
Here's a fast and dirty snippet:
NSString *string = #"abcdef";
NSString *letter = nil;
int n = 9;
for (int index = 0; index < n; index++) {
// start over if it's more than the length
int currentIndex = index % string.length;
letter = [string substringWithRange:NSMakeRange(currentIndex, 1)];
NSLog(#"letter: %#", letter);
}
If you want a low-level example with detailed explanation check this out.
In addition to using substringWithRange (which returns a NSString), you can also use characterAtIndex to get the character value:
NSInteger n = 9;
for (NSInteger index = 0; index < n; index++) {
unichar character = [fl characterAtIndex:index % fl.length];
// do something with `character`, e.g.
//
// if (character == 'z') { ... }
}

Boxing Detected Objects in OpenCV

I am currently implementing a connected components algorithm and the last step of the algorithm requires me to enclose the objects I found in a box. I have attempted to enclose an object in a box and this is the result:
As you can see some of them seem to be enclosed in a box. Some of the lines of the box are not seen unless I stretch the windows of the imshow function's output and also some of them have color when I expected a line with a shade of gray.
My question is: Is the object really getting enclosed since I remember when I ran a similar code of mine into a different OS the lines with color are not see at all but are seen in my computer. Additionally, why are some of the lines in a different color given that I was expecting a shade of gray.
Mat src, src_gray;
Mat dst, detected_edges;
const char* window_name = "THRESHOLDED IMAGE";
/**
* #function connectedComponent
*/
static void connectedComponent(int, void*)
{
Mat test; //dummy
Mat sub;
int newObject = 0;
int zeroTest = 0, nonZero = 0;
int arr[5] = {0,0,0,0,0};
/// Reduce noise with a kernel 3x3
blur( src_gray,detected_edges, Size(3,3) ); //filtering out of noise
namedWindow("INITIAL", WINDOW_NORMAL);
imshow("INITIAL",detected_edges);
resizeWindow("INITIAL", 300, 300);
threshold(detected_edges, detected_edges, 0,255, THRESH_BINARY | THRESH_OTSU);
int** newSub = new int*[detected_edges.rows];
for(int i = 0; i < detected_edges.rows; i++)
newSub[i] = new int[detected_edges.cols];
for(int i = 0; i < detected_edges.rows; i++){
for(int j = 0; j < detected_edges.cols; j++){
newSub[i][j] = 0;
}
}
/*INITIAL MARKING LOOP*/
for(int i = 0; i < detected_edges.rows; i++){
for(int j = 0; j < detected_edges.cols; j++){
if(detected_edges.at<uchar>(i,j) == 0){
if(i-1 < 0 && j-1 < 0){
newObject = newObject + 1; //no values
newSub[i][j] = newObject;
}else if(i-1 >= 0 && j-1 < 0){
if(newSub[i-1][j] != 0){
newSub[i][j] = newSub[i-1][j]; //only up has value
}else{
newObject = newObject + 1; //no values
newSub[i][j] = newObject;
}
}else if(i-1 < 0 && j-1 >= 0){
if(newSub[i-1][j] != 0){
newSub[i][j] = newSub[i-1][j]; //only left has value
}else{
newObject = newObject + 1; //no values
newSub[i][j] = newObject;
}
}else{
if(newSub[i-1][j] == 0 && newSub[i][j-1] == 0){
newObject = newObject + 1; //no values
newSub[i][j] = newObject;
}else if(newSub[i-1][j] == newSub[i][j-1]){ //same value
newSub[i][j] = newSub[i-1][j];
}else if((newSub[i-1][j] != 0 && newSub[i][j-1] == 0)){
newSub[i][j] = newSub[i-1][j]; //only up has value
}else if(newSub[i-1][j] == 0 && newSub[i][j-1] != 0 ){
newSub[i][j] = newSub[i][j-1]; //only left has value
}else if(newSub[i-1][j] != newSub[i][j-1]){
newSub[i][j] = newSub[i-1][j]; //different values follow upper's value
}
}
}
}
}
int a = 1;
int maxRows = detected_edges.rows;
int maxCols = detected_edges.cols;
/*CONNECTING PIXELS RIGHT-BOTTOM*/
while(a < newObject){
int update = 0;
for(int i = 0; i < maxRows; i++){
for(int j = 0; j < maxCols; j++){
if(newSub[i][j] == a){
if(i+1 < maxRows && j+1 < maxCols){
if(newSub[i][j+1] > a){ //both points allowed
int value = newSub[i][j+1]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){ //replace all instances of that value
newSub[h][k] = a;
}
}
}
update = 1;
}
if(newSub[i+1][j] > a){ //both points allowed
int value = newSub[i+1][j]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){
newSub[h][k] = a; //replace all instances of that value
}
}
}
update = 1;
}
}else if(i+1 > maxRows && j+1 < maxCols){
if(newSub[i][j+1] > a){ //bottom is not allowed
int value = newSub[i][j+1]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){
newSub[h][k] = a; //replace all instances of that value
}
}
}
update = 1;
}
}else if(i+1 < maxRows && j+1 > maxCols){
if(newSub[i+1][j] > a){ //right is not allowed
int value = newSub[i+1][j]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){ //replace all instances of that value
newSub[h][k] = a;
}
}
}
update = 1;
}
}
}
}
}
a++;
}
/*CONNECTING PIXELS LEFT-TOP*/
a = newObject;
while(a > 0){
int update = 0;
for(int i = maxRows-1; i > 0; i--){
for(int j = maxCols-1; j > 0 ; j--){
if(newSub[i][j] == a){
if(i-1 >= 0 && j-1 >= 0){
if(newSub[i][j-1] > a){ //both points allowed
int value = newSub[i][j-1]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){
newSub[h][k] = a;
}
}
}
update = 1;
}
if(newSub[i-1][j] > a){
int value = newSub[i-1][j]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){ //replace all instances of that value
newSub[h][k] = a;
}
}
}
update = 1;
}
}else if(i-1 >= 0 && j-1 < 0){
if(newSub[i][j-1] > a){ //left is not allowed
int value = newSub[i][j-1]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){ //replace all instances of that value
if(newSub[h][k] == value){
newSub[h][k] = a;
}
}
}
update = 1;
}
}else if(i-1 < 0 && j-1 >= 0){
if(newSub[i-1][j] > a){ //top is not allowed
int value = newSub[i-1][j]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){ //replace all instances of that value
if(newSub[h][k] == value){
newSub[h][k] = a;
}
}
}
update = 1;
}
}
}
}
}
a--;
}
for(int i = 0; i < maxRows; i++){
for(int j = 0; j < maxCols; j++){
int check = 0;
if(newSub[i][j] != 0){
for(int k = 0; k < 5; k++){
if(newSub[i][j] == arr[k]){ //check if there is an instance of the value in the given array of values
check = 1;
break;
}
}
if(check == 0){
for(int r = 0; r < 5; r++){
if(arr[r] == 0){
arr[r] = newSub[i][j]; //if new value is found add to array
break;
}
}
}
}
}
}
/*
I HAVE AN ARRAY CONTAINING ALL VALUES
**/
src.copyTo( sub, detected_edges);
sub = Scalar::all(0);
/*SET AN INTENSITY FOR CORRESPONDING VALUES*/
int intensity = 50;
a = 0;
while(a < 5){
int update = 0;
for(int i = 0; i < maxRows; i++){
for(int j = 0; j < maxCols; j++){
if(newSub[i][j] == arr[a]){
sub.at<uchar>(i,j) = intensity;
}
}
}
a++;
intensity = intensity + 50;
}
a = 250;
/*GETTING MIN-MAX COORDINATES*/
while(a >= 50){
int setter = 0;
int minRow = 0;
int minCol = 0;
int maxRow = 0;
int maxCol = 0;
for(int i = 0; i < maxRows; i++){
for(int j = 0; j < maxCols; j++){
if(sub.at<uchar>(i,j) == a){
if(setter == 0){
minRow = i;
minCol = j;
maxRow = i;
maxCol = j;
setter = 1;
}else{
if(i <= minRow){
minRow = i;
}
else{
if(i > maxRow){
maxRow = i;
}
}
if(j <= minCol){
minCol = j;
}
else{
if(j > maxCol){
maxCol = j;
}
}
}
}
}
}
/*THIS IS WHERE I MAKE MY BOUNDING BOX*/
for(int i = minRow; i < maxRow; i++){
sub.at<uchar>(i,minCol) = 255; //set up the horizontal lines
sub.at<uchar>(i,maxCol) = 255;
}
for(int i = minCol; i < maxCol; i++){
sub.at<uchar>(minRow,i) = 255; //set up the vertical lines
sub.at<uchar>(maxRow,i) = 255;
}
a = a - 50;
}
dst = Scalar::all(0);
src.copyTo( dst, detected_edges);
imshow( window_name, dst );
namedWindow("FINAL", WINDOW_NORMAL);
imshow("FINAL",sub); //final output
resizeWindow("FINAL", 300, 300);
for(int i = 0; i < detected_edges.rows; i++)
delete[] newSub[i];
delete[] newSub;
}
/**
* #function main
*/
int main( int, char** argv )
{
/// Load an image
src = imread( argv[1] );
if( src.empty() )
{ return -1; }
/// Create a matrix of the same type and size as src (for dst)
dst.create( src.size(), src.type() );
/// Convert the image to grayscale
cvtColor( src, src_gray, COLOR_BGR2GRAY ); //grayscale for one channel for easy computation
/// Create a window
namedWindow( window_name, WINDOW_NORMAL );
resizeWindow(window_name, 300,300);
/// Show the image
connectedComponent(0, 0);
/// Wait until user exit program by pressing a key
waitKey(0);
return 0;
}

Invalid Conversion from int* to int c++

I've been following a tutorial to try and wrap my head around Dijkstra's shortest path algorithm. Originally it was in Java, but I tried my best to switch it over to C++, but unfortunately I've run into a problem that I can't seem to fix.
here's my code
The error happens in the line
---Distancearray[0] = Testarray[0];
#include <iostream>
using namespace std;
int main(){
int Testarray[5][5] = {{}};
//stores first row of test array
//updates when visiting nodes
int Distancearray[5] = {};
//stores visited nodes
int visitedN[5] = {};
//stores previous node
int PreviousN[5] = {};
//holds the minimum value
int Min = 999999;
//holds the next node value
int NextNode = 0;
cout << "Enter Numbers:\n" << endl;
for(int i=0; i < 5; i++){
//initialize visited array to 0
visitedN[i] = 0;
//same
PreviousN[i] = 0;
for(int j=0; j < 5; j++){
cin >> Testarray[i][j];
if(Testarray[i][j] == 0){
//sets the largest possible number
Testarray[i][j] = 999999;
}
}
}
Distancearray[0] = Testarray[0];
//Sets source node as checked
visitedN[0] = 1;
//Sets distance from sources to 0, starting point
Distancearray[0] = 0;
for(int i=0; i<5; i++){
Min = 9999999;
for(int j = 0; j<5 ; j++){
if(Min > Distancearray[j] && visitedN[j] != 1){
//sets next node to J
Min = Distancearray[j];
NextNode = j;
}
}
visitedN[NextNode] = 1;
for(int i=0; i<5; i++){
if(visitedN[i] != 1){
if(Min+Testarray[NextNode][i] <= Distancearray[i]){
Distancearray[i] = Min+Testarray[NextNode][i];
PreviousN[i] = NextNode;
}
}
}
}
for(int i=0; i<5; i++){
cout << "Lenght" + Distancearray[i] << endl;
}
for(int i=0; i<5; i++){
int j;
cout <<"Path:" + i << endl;
j=i;
do{
j = PreviousN[j];
cout<<"<---" + j<<endl;
}
while(j!=0);
}
return 0;
}
any thoughts?

How do I randomize the questions pulled from my dictionary-plist

Hey Guys any ideas for randomising the questions that I pull from my -plist file?
-(NSUInteger)nextQuestionID:(NSUInteger)question_number{
return (question_number>=[self.questions count]-1) ? 0 : (question_number+1);
return 0;
}
-(NSDictionary*) getQuestion:(NSUInteger)question_number{
if (question_number>=[self.questions count]) question_number = 0;
return [self.questions objectAtIndex:question_number];
return NULL;
}
To get a random integer, I would suggest using arc4random function, here is some code to do this:
int randomInt = arc4random() % questionNumber;
return [self.questions objectAtIndex: randomInt];
You can use the arc4random_uniform(upper_bound) function. The parameter is the upper bound of your random number.
An example:
int index = arc4random_uniform([self.question count]);
question_number = arc4random() % self.questions.count;
set question number as random number
replace the function
-(NSDictionary*) getQuestion:(NSUInteger)question_number{
if (question_number>=[self.questions count]) question_number = 0;
question_number = arc4random()%[self.questions count];// changes made here
return [self.questions objectAtIndex:question_number];
return NULL;
}
the random integers:
srand(time(nil));
for (int i = 0; i < 100; i++) {
NSLog(#"random number between 72 and 96 : %d", rand() % (96 - 72) + 72);
}
UPDATE
and for your specific case:
- (NSUInteger)nextQuestionID {
srand(time(nil));
return rand() % [self.questions count];
}
- (NSDictionary*)getQuestion {
return [self.questions objectAtIndex:[self nextQuestionID]];
}
UPDATE#2
test the following loop two, three or more times and compare the outputs:
srand(time(nil));
for (int i = 0; i < 10; i++) {
NSLog(#"random number : %d", rand() % 89 + 10);
}
you should get 10 random numbers between 10 and 99, I've tested it on a real device, not on the simulator but it should work on the simulator as well.
if you get the same result always, let me know.

Resources