Zhao Dachao's Study Zhou Zhi (1)

Zhao Dachao's Study Zhou Zhi (1)

This week is the first week of basic Java learning. The learning content includes keywords and identifiers, data types, operators, standard input, random numbers, branch statements, loop statements, etc., and a simple start to the array. Most of the content has been learned and basically mastered in the trial stage, so learning is relatively easy. There are two difficult questions in the related exercises of the array on the last day. The record research is as follows:

1. Joseph ring problem

Topic: There are 500 people besieging the city in a circle, and count them in turn. Every person who counts to a multiple of 3 leaves the circle. After counting a circle, continue counting from 1 until the last person is left in the circle. Ask the rest Position in the circle (Joseph ring problem)

Implementation logic: The
key to implementation lies in how to indicate whether the participant is eliminated , and how to achieve the circle report , and the final winner needs to be recorded . The stored value of the element can be used to record the state of the game player . If the value is 0, it means that it has not been eliminated. If it is eliminated, the element value is changed to 1, which means that it has been eliminated. The player state is judged before the game count. If it has been eliminated, it will not enter the game. If it has not been eliminated, the number will be reported. If the number is judged to be a multiple of 3, the number will be eliminated. The number is reported +1, the array index is +1, and the next cycle is entered. Every time regardless of whether the current subscript element is eliminated, the subscript needs to be automatically incremented to ensure that it is the turn of the subscript element to make judgments , and to ensure that the game proceeds normally. Whenever the subscript reaches the array length -1, the next time It is the turn of the element whose subscript is 0 to make a judgment to ensure the effect of circle reporting. Finally, when the remaining one is not eliminated, the loop ends, and the subscript of the corresponding array of the player is recorded. The winner is the subscript + 1 person.
① If 500 people encircle and report the number, define an array of length 500. If no value is assigned, the initial value defaults to 0. If the element value is set to 0, it means the state has not been eliminated, and the value 1 is the eliminated state.
②The initial value of the variable count is defined as the length of the array, which means the number of people who have not been eliminated; the initial value of the variable num is 1, which represents the number currently reported; the initial value of the variable index is defined as 0, which is used to record the subscript of the current element.
③Use the loop to play the game. When the number of uneliminated numbers is equal to 1, the loop ends; the loop determines whether the current subscript element is eliminated, if it is eliminated, it determines whether the current element is the last player, and if so, reset the index to 0 to start from Continue to report the number in the next lap, if otherwise, index+1 will be judged on the next element; if it is not eliminated, enter the game to determine whether the reported number of the current element is a multiple of 3, and if it is a multiple of 3, the status will be changed from 0 Set to 1 means being eliminated, and count-1 to reduce the number of people who have not been eliminated; after that, judge whether the current element is the last player, the operation is as above, and finally num+1 is used as the number of the next personal report, and index+1 enters the next The judgment of the element.
④ Loop through the array element values. When the element value is 0, it exits the loop and records the current subscript index. The winner is the first subscript +1.

Code:

	//定义数组
	int[] arr = new int[500];
	//未被淘汰人数
	int count = arr.length;
	//当前已报数
	int num = 1;
	//当前数组索引
	int index = 0;
	
	//未淘汰人数仅剩1人时退出循环
	while(count != 1) {
    
    
		//未被淘汰则参与游戏
		if(arr[index] == 0) {
    
    
			//报数被3整除
			if(num % 3 == 0) {
    
    
				//状态置1,淘汰
				arr[index] = 1;
				//未淘汰人数-1
				count --;
			}
			//若当前报数人为最后一人
			if(index == arr.length - 1) {
    
    
				//下标置0,实现围圈报数
				index = 0;
				//下一任所报数
				num ++;
				//跳出本次进入下次循环
				continue;
			}
			//下一任所报数
			num ++;
			}else{
    
      //若为已被淘汰者
				if(index == arr.length - 1) {
    
    
					index = 0;
					continue;
				}
			}
		//下标+1,保证游戏向下进行
		index ++;
	}
	
	int i;
	for (i = 0; i < arr.length; i++) {
    
    
		//找出未淘汰者则记录下标,退出循环
		if(arr[i] == 0) {
    
    
			break;
		}
	}
	//胜利者为第该下标+1人
	System.out.println("第" + (i + 1) + "个玩家获得胜利");

Then I compared the Joseph ring code written by the previous teacher, as follows:

// 约瑟夫环
		Scanner scanner = new Scanner(System.in);
		// 确定游戏参数
		System.out.print("请输入参与人数:");
		int n = scanner.nextInt();
		System.out.print("请输入淘汰数值:");
		int outN = scanner.nextInt();

		// 定义一个数组保存玩家的状态: 0-未淘汰 1-淘汰
		int[] states = new int[n];

		// 定义一个变量记录当前玩家所报的数
		int number = 0;
		// 定义一个变量纪录玩家的下标
		int index = 0;

		while (true) {
    
    
			// 如果玩家没有被淘汰,则进入游戏报数
			if (states[index % states.length] == 0) {
    
    
				// 如果玩家报的数等于淘汰值,则淘汰玩家
				if (++number == outN) {
    
    
					// 修改玩家状态,让玩家淘汰出局
					states[index % states.length] = 1;
					// 玩家淘汰,游戏人数-1,判定游戏是否结束
					if (--n == 1) {
    
    
						break;
					}
					// 游戏继续,重置报数值
					number = 0;
				}
			}
			// 游戏继续,让后一个玩家继续游戏
			index++;
		}

		for (int i = 0; i < states.length; i++) {
    
    
			if (states[i] == 0) {
    
    
				System.out.println("第" + (i + 1) + "个玩家取得胜利!");
				break;
			}
		}

Comparative find themselves in the code can be modified as follows:
to achieve an index I is reset to 0 will be achieved when the number of turns around packets, while the teacher is the index modulo the array length , the resulting number of packets is the next lap element Indexing also avoids the judgment of whether the index exceeds the length of the array every time, which is more concise and clever.

2. How to output the character string entered by the keyboard

Topic: Define an array, assign values ​​by keyboard input, and output the values ​​of the array

Implementation logic: When
designing the topic, the teacher should just want to define an array of known length, and then assign the input elements to the array, but I added a little difficulty to myself when implementing it. One is to input the array in the form of a string. Check how to determine the length of the array or how to output only the value you input when outputting the array in string form, without outputting the default initialized null value "0"; the other is how to make the user end the input element. The solution to the length of the array is to first create an array large enough to store the array initially, or define a dynamic array , that is, define a smaller array first, and then create a current length when the number of values ​​exceeds the length of the array For arrays that are 1.5 times the length, the disadvantage of the first method is that the length may be insufficient and the length defined during initialization will be too long to waste memory. Therefore, it is better to use the second method for dynamic arrays. This time, for the convenience of introduction Use the first method to define the length as 1000, and post the implementation code of the dynamic array next time. How to end the keyboard input array is to prompt the user to enter "over" when prompting the user to enter an integer, and then use the Scanner.nextLine() method to receive the element, if it is an integer, store it in the array, if it is " "over" jumps out of the loop and no longer enters it, and records the number of times of storage. The obtained array is an array with a null value "0". If you want the length of the array to be the length of the number of input elements, create a new array. The length of the array is the number of times of input recorded when the value was just entered. There are two ways to output. If you just output the non-empty value "0" in the original array, you can use string splicing, or you can use the Arrays.toString() method to output.

code show as below:

Scanner sc = new Scanner(System.in);
		/*	
		 * 	尽量将数组长度定义的大些保证够用,确定是浪费空间内存
		 * 	也可以先定义一个长度较小数组,
		 * 	再编写一个长度不足时增加一半数组长度的方法进行调用
		 */
		int[] tempArr = new int[1000];
		int count = 0;
		String str = null;
		System.out.println("输入存入数组的值(输入\"over\"结束输入):");
		
		for (int i = 0; i < tempArr.length; i++) {
    
    
			str = sc.nextLine();
			//当比较引用数据类型的值时使用equals方法,直接使用"=="比较的话比较的是引用地址
			if(str.equals("over")) {
    
    
				break;
			}
			tempArr[i] = (Integer.parseInt(str));
			count ++;
		}
		System.out.print("生成的数组为:[");
		
		/*	
		 * 	若要使新数组没有初始化的值,即数组长度等于用户输入数的次数,
		 * 	则定义新数组,通过循环将老数组中非0值(指初始化的0,手动输入的0不影响)传入其中,
		 * 	使用循环方式输出数组中非0(指初始化的0,手动输入的0可以输出)的数
		 * 	也采用Arrays.toString()方法以字符串形式输出新数组
		 */
		int i = 0;
		while(i < count) {
    
    
			System.out.print(tempArr[i ++]);
			if(i != count) 
			System.out.print(",");
		}
		System.out.print("]");
		
		int[] arr = new int[count];
		

The problem encountered in the code implementation is: the judgment condition when judging whether the string "over" is entered is if (str == "over"), and an error is reported after entering "over" at runtime, and it is found after debugging. , When the judgment of str == "over" is not met, it does not break out of the loop but continues to convert "over" to int type failure, so an error is reported. It is found that the reference type cannot be compared with "==" when comparing values. In this way, two reference address values ​​are compared, so the conditions will not be met to break out of the loop. After querying, it is found that the equals() method of String should be used to compare the values. After the conditions are met, the program executes normally.

Guess you like

Origin blog.csdn.net/Mr_SuperZhao/article/details/109430758