欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Shuffling Machine

程序员文章站 2024-02-17 13:51:16
...

解题思路:分两步分析:
第一解决替换的问题,从序号为1开始索引,找到所在的位置得到对应序号,此时的序号即为对应字符串的序号,将该字符串与a数组
(就是原数组)的第一位进行替换,此时,必须也对数值数组进行类似替换,然后从序号为2开始索引,再到3,以此类推。

第二个,解决第二个问题,就是捆绑字母与数字,采用二维数组的方式可以做到,一行即为一个字符串 。
Shuffling Machine
Shuffling Machine
Shuffling Machine

#include <iostream>
#include <stdio.h>
using namespace std;

void swap(char a[][4], int b[], int e[]);
void output(char a[][4]);

int main()
{//对a数值 一共是54个元素 占有54行, 这里涉及到二维数组的初始化的知识, 假如赋值没有填满空间的话,系统会自动分配为 '\0' 
	char a [54][4] = {"S1", "S2", "S3","S4", "S5","S6","S7","S8","S9","S10","S11","S12","S13",
	"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","H11","H12","H13",
	"C1", "C2", "C3","C4","C5","C6","C7","C8","C9","C10","C11","C12","C13",
	"D1", "D2", "D3","D4","D5","D6","D7","D8","D9","D10","D11","D12","D13","J1","J2"};
	
	//定义b数组, 赋值需要掉换的顺序(即数字) 定义e数组的目的是保证下一次调用swap函数时 b数组的值不变,详见下 
	int b[55], e[55]; 
	int n;
	cin >> n;
	
	//吸收回车符,保证数组b能够赋值 
	getchar();
	
	for (int g=0; g<54; g++)
		cin >> b[g];
		
	//复制 b数组	
	for (int i=0; i<54; i++)
		e[i] = b[i];
	
	//调用已经定义的swap函数	
	for (int c=0; c<n; c++)
		swap(a, b, e);
	
	output(a);
	
	return 0;
} 

void swap(char a[][4], int b[], int e[])
{
	// 保证每一次调用b数组的值都不变的关键步骤 
	for (int v=0; v<54; v++)
		b[v] = e[v];
		
		
	int i, j=1, p, q=0;
	
	//交换的中介 
	char t;
	int d;
	//元素替换 
	for (p=0; p<54; p++)
	{
		//得到数字为j的下标 
		for (i=p; i<54; i++)
			if (b[i] == j)	 q=i;

		//对字符数组进行替换 ,f的意思是使得每次交换 3 次,保证最长的行都能够交换 
		int k=0, f=3; 
		
		for ( ;k<f; k++)
		{
			t = a[p][k];
			a[p][k] = a[q][k];
			a[q][k] = t;
		}
		
		// 对数值数组进行替换,如果不进行该操作的话会导致上一步的索引出现问题 
		d = b[p];
		b[p] = b[q];
		b[q] = d;
	
		j++;
	}
}


void output(char a[][4])
{//保证最后一个字符后面没有空格 
	int i;
	for (i=0; i<53; i++)
		cout << a[i] << " ";
			
	cout << a[i];
}
相关标签: c++ 字符串