c - 生成从 1 到 limit 的所有可能的不重复整数

标签 c recursion integer user-input

我很难改变这个程序。该算法对于生成非重复列表来说已经是正确的。但是,我希望从用户的整数范围生成列表。 (1 到 n)

例如:用户输入 5 -> 打印 (1 2 3 4 5),然后要求 5 个整数来生成组合。

如何更改此设置,以便从 (1-n) 找到组合,而不是单独输入整数 n 次?任何帮助将不胜感激。 (抱歉,如果有点乱,我是学生:P)

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

int a1[50], a2[50]; // arrays
int count=-1, range;
int w; // user defined variable

void main()
{ 

    printf("Please enter a number. (1-10): ");
    scanf("%d", &w);

    int x,y; // comparing
    printf("You have entered %d\n\n",w);
    for(range=1; range<=w; range++){
        printf("%d", range);
        printf(" ");
    } // end for "range"

    printf("\n");

    for(x=0; x<w; x++){

        a1[x]=0;
        y=x+1;
        scanf("%d\n\n" ,&a2[y]); 

    }// end for 

    combo(w);

} // end main


combo(int z) // function with algorithm to find combonations 
{
    while (w<1 || w>10){

        printf("\nThat number is not in range. Please try again. \n\n");
        printf("Please enter a number. (1-10): ");
        scanf("%d", &w);

    } // end while

    int x;
    a1[z]=++count;

    if(count==w){

        for(x=0; x<w; x++)
        printf("%2d",a2[a1[x]]);
        printf("  ");

    } // end if 

    for(x=0; x<w; x++)
    if(a1[x]==0)
    combo(x);
    count--;
    a1[z]=0;

} // end "combo"

最佳答案

#include <stdio.h>
#include <string.h>

void swap (int *X, int *Y)
{
  int temp;
  temp = *X;
  *X = *Y;
  *Y = temp;
}

void print_array(int *a, int n) {
   int i; 
   printf("\t=>  ");
   for(i = 0; i < n; i++){
     printf("%d, ", a[i]);
   }
   printf("\n");
}

void mixmatch (int *Arr, int i, int n)
{
  int j;
  int *A = Arr;
  if (i == n)
     print_array(A,n+1);
  else
  {
     for (j = i; j <= n; j++)
     {
        swap((A+i), (A+j));
        mixmatch(A, i+1, n);
        swap((A+i), (A+j));
     }
  }
}

int main()
{
   int A[10];
   int k;
   int i;
   printf("Enter a number between (1-10):");
   scanf("%d", &k);
   for(i = 0; i < k && i < 10; i++) {
       printf("%d, ",i);
       A[i] = i; 
   }
   printf("\n");
   mixmatch(A, 0, k-1);
   return 0;
}

这是您可以修改它以合并整数及其数组的方法。

关于c - 生成从 1 到 limit 的所有可能的不重复整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15126324/

相关文章:

java - Java 中的黎曼 Zeta 函数 - 具有函数形式的无限递归

ruby - 对一串 ID 值进行数字排序

java - 在文件中搜索与给定条件匹配的行

c - 对整数的奇数位求和的递归函数

javascript - 动态遍历未知深度键的对象

java - Java中如何保证用户输入始终为Integer

C - 读取文件并打印到文件后获取无效字符,可能是缓冲区溢出

c - Libcurl:为什么 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, obj) 传递我的 writefunction 指针,它不等于 obj?

c - 如何使用指针移动字符

c - 如何使用结构修复函数内的段错误(核心转储)