lab13: impl

This commit is contained in:
2026-04-09 15:57:41 -07:00
parent 4fd0fec404
commit 7b54fa5303
4 changed files with 76 additions and 18 deletions

View File

@@ -1,9 +1,11 @@
name = "Monty"; /*global console*/
/*jslint this*/
var name = "Monty";
var r = new Rabbit("Python");
function Rabbit(name) { function Rabbit(name) {
this.name = name; this.name = name;
} }
var r = Rabbit("Python");
console.log(r.name); // ERROR!!! console.log(r.name); // ERROR!!!
console.log(name); // Prints "Python" console.log(name); // Prints "Python"

15
lab13/rabbit.ts Normal file
View File

@@ -0,0 +1,15 @@
// rabbit.ts
class Rabbit {
name: string;
constructor(name: string) {
this.name = name;
}
}
let myName: string = "Monty";
let r: Rabbit = new Rabbit("Python");
console.log(r.name); // ERROR!!!
console.log(myName); // Prints "Python"

View File

@@ -1,15 +1,28 @@
function swap(arr,i,j) { /*global console*/
tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; /*jslint for */
}
function sortAndGetLargest (arr) {
tmp = arr[0]; // largest elem
for (i=0; i<arr.length; i++) {
if (arr[i] > tmp) tmp = arr[i];
for (j=i+1; j<arr.length; j++)
if (arr[i] < arr[j]) swap(arr,i,j);
}
return tmp;
}
var largest = sortAndGetLargest([99,2,43,8,0,21,12]);
console.log(largest); // should be 99, but prints 0
var largest = sortAndGetLargest([99, 2, 43, 8, 0, 21, 12]);
function swap(arr, i, j) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
function sortAndGetLargest(arr) {
var tmp = arr[0]; // largest elem
var i;
var j;
for (i = 0; i < arr.length; i += 1) {
if (arr[i] > tmp) {
tmp = arr[i];
}
for (j = i + 1; j < arr.length; j += 1) {
if (arr[i] < arr[j]) {
swap(arr, i, j);
}
}
}
return tmp;
}
console.log(largest); // should be 99, but prints 0

View File

@@ -0,0 +1,28 @@
// sortAndGetLargest.ts
function swap(arr: number[], i: number, j: number): void {
const tmp: number = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
function sortAndGetLargest(arr: number[]): number {
if (arr.length === 0) {
throw new Error("Array must not be empty");
}
// Sort the array in descending order
for (let i = 0; i < arr.length; i += 1) {
for (let j = i + 1; j < arr.length; j += 1) {
if (arr[i] < arr[j]) {
swap(arr, i, j);
}
}
}
// The largest element is now at index 0
return arr[0];
}
const largest: number = sortAndGetLargest([99, 2, 43, 8, 0, 21, 12]);
console.log(largest); // should be 99, but prints 0