English 中文(简体)
从使用C的一系列数字中随机返回的人数
原标题:Returning a random number from a range of numbers using C
  • 时间:2011-08-09 16:56:35
  •  标签:
  • c
  • random

a 体积。 我需要随机抽调阵列,因为功能大体(n)把1到1英(两者兼而有相同概率)的重新分类。 我知道 j的随机功能,但我希望利用C加以执行。

问题回答

您可以创建如下机构:

int rand_n( int N )
{
  return ( rand() % N ) + 1;
}

<代码>rand(>在stdlib.h上公布。

#include <stdio.h>
#include <stdlib.h>

int randint(int min, int max) 
{ 
    if (min>max) 
    { 
        return max+(int)((min-max+1)*rand()/(RAND_MAX+1.0)); 
    } 
    else 
    { 
        return min+(int)((max-min+1)*rand()/(RAND_MAX+1.0)); 
    } 
}

如果我正确理解,问题不是要写一个PRNG,而是要利用一个预先界定的Land_n功能撰写算法,以填补阵列。 撰写全国促进平等运动并非三重,我怀疑他们会问你,在一次面谈中。 但是, algorithm脚算是一个不同的故事。 这里,在纸浆中,我头顶部外的顶部:

1. 选择1:

  • Fill an array with the numbers from 1 to N, let s call it positions
  • i = rand_n(N);
  • shuffled[0] = toShuffle[ positions[i] ];
  • Delete i from positions and resize it (now it has N-1 elements)

循环:

  • i = rand_n(N-1)
  • shuffled[1] = toShuffle[ positions[i] ];
  • Delete i from positions and resize it (now it has N-2 elements)

...... 我的漂流?

查阅Fisher-Yatesshuffle。 通过随机抽取元素(使用简单的<代码>rand_n)随机抽取阵列。 选择要素的类型功能。





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签