1/* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16export class AccessFannkuch { 17 public n: int; 18 constructor() { 19 this.n = 8; 20 } 21 22 static expected: int = 22; 23 24 public fannkuch(n: int): int { 25 // Not parsed new int[n] 26 let perm: int[] = new int[this.n]; 27 // Not parsed new int[n] 28 let perm1: int[] = new int[this.n]; 29 // Not parsed new int[n] 30 let count: int[] = new int[this.n]; 31 // Not parsed new int[n] 32 let maxPerm: int[] = new int[this.n]; 33 let maxFlipsCount: int = 0; 34 let m: int = this.n - 1; 35 36 for (let i: int = 0; i < this.n; i++) perm1[i] = i; 37 let r: int = this.n; 38 39 while (true) { 40 while (r != 1) { 41 count[r - 1] = r; 42 r--; 43 } 44 if (!(perm1[0] == 0 || perm1[m] == m)) { 45 for (let i: int = 0; i < this.n; i++) perm[i] = perm1[i]; 46 47 let flipsCount: int = 0; 48 let k: int; 49 50 while (!((k = perm[0]) == 0)) { 51 let k2: int = (k + 1) >> 1; 52 for (let i = 0; i < k2; i++) { 53 let temp: int = perm[i]; 54 perm[i] = perm[k - i]; 55 perm[k - i] = temp; 56 } 57 flipsCount++; 58 } 59 60 if (flipsCount > maxFlipsCount) { 61 maxFlipsCount = flipsCount; 62 for (let i = 0; i < this.n; i++) maxPerm[i] = perm1[i]; 63 } 64 } 65 66 while (true) { 67 if (r == n) return maxFlipsCount; 68 let perm0: int = perm1[0]; 69 let i: int = 0; 70 while (i < r) { 71 let j: int = i + 1; 72 perm1[i] = perm1[j]; 73 i = j; 74 } 75 perm1[r] = perm0; 76 77 count[r] = count[r] - 1; 78 if (count[r] > 0) break; 79 r++; 80 } 81 } 82 } 83 84 public run(): void { 85 let ret = this.fannkuch(this.n); 86 assert ret == AccessFannkuch.expected: "Invalid result"; 87 } 88} 89 90function main(): void { 91 let a = new AccessFannkuch; 92 a.run(); 93} 94