repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/dimchor/big-data-project
https://raw.githubusercontent.com/dimchor/big-data-project/main/report/conf.typ
typst
#let cont() = { set page(numbering: "i") counter(page).update(1) outline(title: [Περιεχόμενα]) } #let conf(title, details, start_date, end_date) = { set align(center) text(17pt, "ΠΑΝΕΠΙΣΤΗΜΙΟ ΔΥΤΙΚΗΣ ΑΤΤΙΚΗΣ") linebreak() text(15pt, "ΤΜΗΜΑ ΜΗΧΑΝΙΚΩΝ ΠΛΗΡΟΦΟΡΙΚΗΣ ΚΑΙ ΥΠΟΛΟΓΙΣΤΩΝ") v(1fr) image("uniwa.png", width: 50%) v(2fr) text(17pt, title) linebreak() text(15pt, details) linebreak() text(15pt, "ΔΗΜΗΤΡΙΟΣ ΧΟΡΕΒΑΣ (ΑΜ: 20390261), ΑΝΔΡΕΑΣ ΜΙΧΑΪΛΙΔΗΣ (ΑΜ: 20390149)") v(1fr) text(15pt, "Ημερομηνία διεξαγωγής: ") text(15pt, start_date) linebreak() text(15pt, "Ημερομηνία παράδοσης: ") text(15pt, end_date) v(1fr) text(15pt, "ΑΘΗΝΑ ") text(15pt, datetime.today().display("[year]")) } #let bib(str) = { bibliography(str, title: [Βιβλιογραφία]) }
https://github.com/piepert/typst-seminar
https://raw.githubusercontent.com/piepert/typst-seminar/main/Beispiele/Essay/template.typ
typst
#import "fullcite.typ": footnotes-gen-footer #let project(title: "", authors: (), date: none, body) = { // Set the document's basic properties. set document(author: authors.map(a => a.name), title: title) set page( margin: (left: 25mm, right: 40mm, top: 30mm, bottom: 30mm), number-align: center, footer: footnotes-gen-footer() ) let fontsize = 12pt let linespreadfactor = 1.25 set text(size: fontsize, font: "Linux Libertine", lang: "de") // Author information. pad( bottom: 0.25em, x: 0em, y: -2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(left)[ #text(size: 10pt, table( columns: (auto, auto), inset: 2pt, stroke: none, strong[Universität:], author.affiliation, strong[Institut:], author.institute, strong[Dozent:], author.docent, strong[Veranstaltung:], author.course, strong[Semester:], author.semester, strong[Autor:], author.name, strong[Datum:], date )) ]), ), ) set par(justify: true) // Title row line(length: 100%, stroke: 0.25mm) block(text(weight: 700, 1.45em, title)) v(1.5em, weak: true) set par(leading: fontsize*linespreadfactor, first-line-indent: 1.5em, justify: true, linebreaks: "optimized") show par: set block(spacing: fontsize*linespreadfactor) // Main body body }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/inlay_hints/base.typ
typst
Apache License 2.0
#let f(x, y) = x + y #f(1, 2)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/036%20-%20Guilds%20of%20Ravnica/003_Clans%20%26%20Legions.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Clans & Legions", set_name: "Guilds of Ravnica", story_date: datetime(day: 24, month: 10, year: 2018), author: "<NAME>", doc ) "Salutations and congratulations, Wojek Weslyn," my boss says to me, positively burning with pride. I've served under Sergeant Skormak, the associate director of war development, for the past thirteen years I've worked at Sunhome Annex Four, but we've hardly ever spoken face to face. He extends his hand, and I fight the urge to flee. They say there are two types of people within Boros Legion: those who flock to flame-kin, and those who run from them. I definitely fall into that latter category, but I shake my boss's hand anyway. Even through the protection of his enchanted gloves, I can feel the fire burning beneath. "Your adulations are noted," I say. "There is no doubt your glowing recommendation was a big factor in my promotion." Sergeant Skormak smiles and shakes his head, red-golden flames rising off his scalp. "My words were nothing but the truth. You did the work. You passed the tests. It is you who have earned this honor." He places a small box and an envelope on my desk. "I will miss your efficiencies when you move to the Wojek Annex," he says to me. His breathless voice wavers in and out like a flickering flame. "But I know you will make us all proud." And now it's me who's burning up, figuratively, at least. I'm the first of my coworkers to be promoted to Wojek in eight years. Sure, we all pretend everything is fair and equitable, and that if you work with integrity and decency you will eventually gain recognition, but in reality, Annex Four is where Boros Legion sends its chaff—swiftblades who'd bombed the wrong encampments, skyknights who'd developed a fear of heights, flame-kin who'd been too hot-headed to dissipate upon battle's completion, and minotaurs like me, who'd simply had the misfortune of being born into the wrong family line. It's kind of fitting that this building used to be a warehouse. It's a great place to store all the people the Legion would rather forget about. My fingers tremble as I open the box. I can hardly bear to look at what I think, I #emph[hope] , lies inside. As the lid loosens, I make out a hint of red. My heart seizes up, and all the fur on my hide stands on end, and suddenly I'm just staring at it, biting my lip so I don't start bawling over Sergeant Skormak with big, fat tears that extinguish his flames. I rein in my emotions, puff my chest with pride, then take the red cord out of the box and drape it around my neck and under one arm. My first accolade. A copper token dangles from it with "<NAME>" printed around the rim. They've entrusted me to keep the peace in our lands, to combat injustice, and to seek out what is honorable and righteous. #figure(image("003_Clans & Legions/01.jpg", width: 100%), caption: [Boros Locket | Art by: <NAME>], supplement: none, numbering: none) "It suits you," Sergeant Skormak says. "Perhaps the sun does indeed shine upon your line." "Perhaps," I say, going to open the letter next. Sergeant Skormak clears his throat. "It's to be read in private. Good luck to you, <NAME>." The title gives me chills. Or perhaps it's the sudden dip in temperature now that my boss has walked away. I look closely at the letter. My name is printed across the envelope in gold foil. I slip a fingernail under the lip and carefully open it. There's a card inside—an invitation.  #linebreak This note is to inform you that#linebreak your presence is requested this evening at dusk#linebreak at the Sunhome Solarium#linebreak for a reception held in honor of the new Wojek inductees.#linebreak  #linebreak Light refreshments will be served.#linebreak Dress attire to consist of formal robes and belts.#linebreak  #linebreak #emph["A war fought with an unjust mind dies in the trenches. A war fought with a valiant heart lives forever in the rubble of your enemies' bones."] #linebreak #emph[—Klattic, Boros legionnaire] I look at it. I mean #emph[really] look at it. The first thing to strike me is the Boros Legion symbol imprinted into the paper~a fist silhouetted by a sunburst, but something's off. Then I realize it's a right-handed fist, not a left-handed one like it should be. And the sunburst has ten rays instead of nine. My mind snaps to the counterintelligence exam I'd taken a couple months back. There'd been a task like this one, finding concealed messages among the mundane. We'd gone out searching for hidden Dimir codes—a pattern of drawn shades in an apartment tower's windows, sewer grates twisted to indicate a series of directions, that sort of thing. I'd detected eight of them, more than anyone else in the cohort. And from now on, I would always need to remain on high alert, searching for signs and signals, like the one I'm holding in my hands. This isn't an invitation. It's the briefing for my first assignment as a Wojek counterintelligence agent. Now, I must decode it. I scrutinize every word, every letter. I turn the paper sideways, squint my eyes and assess the blank space between words. The story starts to take shape—a meeting point with an informant~It's like a game. I play with the words: Light refreshments will be served. Food. Soldiers call food gruel. Gruul. And if that's a real Klattic quote, I've never heard it. Trenches. Rubble. The location has to be a bunker near the Gruul Rubblebelt. It's all starting to click into— "Ooh, party at the Solarium. Can I be your plus-one?" Aresaan says, looking over my shoulder. I crumple up the invitation, hide it in my fist, and then right before I turn around to face my workplace nemesis, I empty my lungs. I don't care how many times you've seen a Razia copy, they always take your breath away when you look at them. I won't give her that satisfaction. "I'm not sure what you're talking about," I say, fumbling over my words, pretending that her radiant red hair isn't dazzling the hell out of me. That message was meant for my eyes only. First day as Wojek counterintelligence, and I've already jeopardized an assignment. "There's no party." She raises a brow. "Sure, Ossett. Anyway, just wanted to congratulate you on your promotion. It's a fine accomplishment for someone with such weak convictions." My nostrils flare. She's the worst of the washouts, a former Warleader whose bad decision on the battlefield had led to fifteen thousand dead Boros soldiers some thirty years ago. As penance, she'd had her wings bound and was stripped of nearly all her magic, except a few rallying spells to help with recruitment efforts. Even after decades in exile, she still flaunts the unapologetic arrogance and intrusiveness typical of angels, but she's no better than the rest of us misfits. "My convictions are just fine," I say, head tilted forward, my horns aimed right at her. "I've earned this. If you've got issues about my promotion, you'd better make peace with them." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) I never knew peace growing up. My father had been in and out of battle, and our family spent its time worrying over his safety out there on the front line, and then worrying over our own safety when he'd return. He'd watched as his Ordruun counterparts got promoted past him, year after year. Maybe those minotaurs deserved it more than him, I don't know. What I do remember is that his temper had gotten shorter and shorter each time he returned, and I can't even count the number of times he and my mother had butted heads, horns scraping, angry hooves putting gashes in the wooden floors, sometimes the walls. As soon as they started yelling, I'd hole up in my room, my sister's red hair ribbons slung across my chest, and pretend I was a Wojek officer, charged with keeping the peace. Wojek counterintelligence needed to be alert and astute. I'd concentrate on finding hidden messages in the water stains on the ceiling, in the patterns of dust gathered on the floorboards, in the silent moments when my parents finally stopped arguing. I became good at noticing things that didn't want to be noticed. And now, here I am on my first mission at the outskirts of Tenth District chasing down information that will help us keep the peace. A Gruul encampment has steadily encroached into this quaint neighborhood and tensions are high. I've heard rumors that this area was the site of a dragon extermination ten or so millennia ago and that the dust here is largely comprised of disintegrated dragon bone. They also say the bone is not totally, completely one hundred percent dead. Working in a place like this, my Boros armor is a must for protection, but stealth is important as well. I've got a red-gray cloak draped over me, the color of the dirt here. Dragon bone or not, it gets into everything, making me feel gritty all over, but the dirt isn't the only thing that makes me uncomfortable. It's impossible not to notice the Gruul presence, eager to tear down everything we've worked so hard to build. The children are feral, bone and leather strung together in a loose attempt at clothing. A drunken ogre stumbles past, then falls, his momentum obliterating an incense cart. I try to find some redeeming qualities among them but fall short. My hand keeps itching to give out violation notices, but I maintain focus on finding my informant. In the market, I witness a Gruul child steal a melon from a cart. The merchant yells out, a brittle old Viashino who couldn't give chase if he'd wanted to. The child runs right in front of me, and it's all I can do to grab her arm. I clench it tight, and she looks up at me with the eyes of a trapped boar. "You shouldn't steal," I scold her. "You dishonor your city. Your family. Yourself." I try to be mad at her, but her arm, it's so thin I feel like it's going to snap in my grip. I loosen up some. She grunts at me, teeth bared. And, whew, the smell coming off her. But something churns in my mind, and I can't bring myself to separate her from the fruit. I sigh, then let the child go. She snorts at me, then runs off, her bounty clutched tight, eyes darting this way and that. I pull a couple zigs from my coin purse and pay the merchant. He grins at me, and then flicks his tongue out to moisten an eyeball. "You know what they say," he croaks, "fight the Gruul, and you've got a problem for a day. Feed the Gruul, and you've got a problem for life." I nod. Fortunately, I'm just in town for the evening, and she won't be my problem any longer than that. I press on. It doesn't take long to locate the bunker, hidden beneath overgrown weeds and wild cindervine enchantments slowly turning the facade to rubble. The place looks nearly forgotten, except for the infestation of baby hydras, each no bigger than the span of my hand. A few of the heads spit at me. I step out of the way, but some of the frothy saliva hits my boot. The acid isn't strong enough to eat through it, but light tan splotches develop on the dark brown leather. Protocol dictates that I report the hydras immediately, but they're not going anywhere, and my informant might. #figure(image("003_Clans & Legions/02.jpg", width: 100%), caption: [Gruul Turf | Art by: <NAME>], supplement: none, numbering: none) I enter the bunker. The heavy metal door screeches as it closes behind me, and I get my first breath of cold, stale air. It's dark in here, and it takes a long while for my eyes to adjust from the light outside. Finally, I see a set of stairs in front of me, and I cling to a loose railing as I make my way down. The stairwell opens up into a large room with a packed dirt floor. Several industrial tables and chairs sit about, cots are stacked high in the corners, and cabinets that must have once been well stocked sit open and empty. A haggard man who looks worn beyond his years sits at one of the tables with a six-sided Clans & Legions playing board set up in front of him. My throat instantly clenches up. My father had taught me to play the first time he came back from battle. The fighting had hardened him, but he was still nurturing then. It was a good way for us to be together, to sit and be near without much talking. "You've got information for me?" I say those words like I've practiced them my whole life. I can't believe this guy is sitting here. That means I'd decoded the hidden message and found him, and this wasn't some conspiracy I'd knitted together in my head. "I do," he says, the weariness obvious in his raspy voice. "But first, let's play." "I'm afraid I'm a bit rusty." I draw closer, keeping my calm. I can't afford to spook him now. I take a seat at the table across from him and read his face. It's dark down here, but I can make out the pattern of discoloration on his neck and up toward his temples, like faint scars. Interesting. Wojek apothecaries were known to make money on the side by removing tattoos from Gruul defectors, and the spells to disenchant the ink were harsher than the ones that put it there in the first place. Now I have a better idea of who I'm dealing with. Black pieces sit before me, so I make the first move. He twirls a finger, and one of his soldier pieces slides across the board. Is he a mage, then? Beyond the typical observations, you can also learn a lot about someone by watching how they play Clans & Legions. The first time I'd beaten my father—really beaten him, not just him throwing me a mercy win—he'd been so proud. Next time I'd beaten him, he flipped the board. My hand shakes as I pick up the cleric piece. A solid but predictable move. "Do you have a name I can call you?" I ask. "Brazer, if you must, <NAME>." "You can call me Ossett." I narrow the distance between us to build up trust. I watch as he pushes his angel piece forth with the flick of a finger, leaving her completely exposed. Bait? I want so badly to inquire about the information, but it is too soon. I ignore the boldness of his move and counter with a skyknight. Completely bland, completely boring. "Do you play Clans & Legions often?" I ask instead. "I used to do league competitions when I was younger." "We didn't have those where I grew up." "Pity. All kids can benefit from the discipline learned from the game." I realize I've said the wrong thing as a snarl curls his top lip. I backpedal. "But you know, there's a bit of beauty in the chaos of it all, too. My father once told me that there are more combinations of forty-move games than there are hairs on every single living thing in Ravnica." "Really?" Brazer says, eyebrow arched. "I never thought of it that way." I move my angel out, a sacrifice. I could still play the game without her, but it would be only a matter of time before he nullified my whole army. Brazer knocks my angel over with one of his soldiers, but he doesn't claim my piece for his boneyard. Instead, he looks up at me, the pain behind his weary eyes making me ache all over. He's ready to talk. "What is it that you want to tell me, Brazer?" I ask. "I'm listening, and I will hold whatever you say in the strictest confidence." "There's a spy in the Boros Legion." "Okay. Can you tell me who?" He nods. "But first I want a prisoner freed from Wargate. Release her, and I will have the information delivered to you in the market at sundown tomorrow." He passes me a note with a name on it. <NAME>. I've never heard of her, certainly not one of our renowned political prisoners. "I want to help you, Brazer, but things like this take time. There's a formal process. Applications need to be submitted and reviewed." "Do you know how many three-move games of Clans & Legions there are?" Brazer asks me. I nod. Everyone knows it. "One. Razia's Folly. But your opponent has to practically be in collusion with you to pull it off." "Mmmm-hmmm. Bribery. Extortion. Favors. You're the player, Ossett, but this definitely isn't a game." I hold my head perfectly still, because all I want to do is shake it right now. There's nothing honorable in corrupting justice. But a traitor among Boros Legion would be worse, especially now when tensions are brewing. In Boros Legion, we see things in black and white. There isn't the option for shades of gray: we'll take a person's freedom for crimes not yet committed, we'll forfeit a soldier's life to uphold the idea of peace throughout Ravnica, we'll punish a starving child for stealing food. It is our sworn strength, but it is also one of our biggest weaknesses. "I will see what I can do." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) I work late into the evening, preparing prisoner release forms. <NAME>, arrested in a Gruul riot. No other previous charges. Likely, she was in the wrong place at the wrong time. Simple case, really. All it took was a small bribe to <NAME>'s assistant, and she'd snuck the prisoner release form into his signature pile. I'm sure my old boss won't mind. He'd said how much he wanted to see me succeed, for me to make him proud. He's been stuck at Annex Four for nearly as long as I have, and he knows how much of an accomplishment it is to make it out. First thing in the morning, I'll walk the case down to the Wargate Prison Camp myself, saving two more days of bureaucratic mishandlings, and by lunchtime tomorrow, <NAME> will be a free— My eyes stick to the release form. Something jumps out at me, something bad. I try to ignore it. Try to miss it like whoever'd processed her intake had. But seems like those things I try not to notice scream to be noticed, too. <NAME> isn't her full name. <NAME>. Most likely related to <NAME>, the Rubblebelt raider who set off a mass chaos spell at Tin Street Market. Shoppers had been consumed with sudden rage and confusion, and they turned upon each other, food and wares becoming weapons. Twenty-four killed. A hundred seventy-six injured. I tuck the paper behind the others, but I can't unsee it. My heart pounds. Which is more of a threat to peace? Someone who we know is trying to attack us from out there in the streets, or some unknown who's here to dismantle us from the inside? "Late night, Wojek?" Aresaan says, her hand on my shoulder. "You can always count on a minotaur to work twice as long and half as hard, am I right?" #figure(image("003_Clans & Legions/03.jpg", width: 100%), caption: [Light of the Legion | Art by: <NAME>], supplement: none, numbering: none) "For Tajic's sake," I glower, shaking her off. "Don't you have some potential recruits to foist your 'powers' on?" I clear my lungs again, nearly like instinct, now, then look at her. It's like staring into the sun and not giving a care that your eyes are burning. Her stance is aggressive, arms crossed. Mouth pinched tight. Too bad it won't stay that way. "Just so you know, I signed up twenty-seven fools today, so eager to spread their blood across the battlefield." "Impressive. So when you're out there recruiting, do you use some kind of script, or do you #emph[wing] it?" I smirk as the arrogance drops off Aresaan's face, and suddenly, she's shifting her wings, bound up tight with razor wire. Couldn't be comfortable. I sigh. She didn't deserve that. Or, probably she did, but I should be the one taking the path of righteousness. "Please go away. I'm in the middle of something." "Something important?" "Something that's none of your business. I'm beginning to understand why they banished you from the Parhelion." "Woah, now," she says, hands up. "Not banishment~just a reassignment. And fifty years is a blink for angels. I'm just twiddling my thumbs, waiting for someone else to mess up worse than me, and that's only a matter of time with the way Aurelia is running this place. You, you'll piddle around with the Wojeks, trying to make a name for yourself, then eventually, everyone will see the imposter you are and start wondering why they promoted you in the first place. You'll be right back here within five years, I guarantee it." "You don't know crap about my capabilities." "Language, Wojek!" she scolds me, thin smile on her lips. "Where is the honor in a foul mouth?" "Suck hoof, Aresaan." I turn my attention away from her, and eventually, she gives up and goes away. I look at the case file. It feels so heavy now. What would it mean to my career if I can't carry out my first mission? This isn't hard. I don't even have to lie. I just need to go on ignoring the truth. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) <NAME> is free. I'd watched her walk out of the prison gates myself, a pit in my first stomach. Now I calmly wait at the market. The sun is still hours from setting, but I got here early, just in case. Brazer will show up. I can't let doubt into my heart. Not yet. Just like it takes the eyes a few minutes to adjust from stepping out of the sun and into the dark, it takes the mind time to adjust to seeing shades of gray. I notice the child from yesterday, eyeing a loaf of bread sitting too close to the edge of a display table. I rush over before she makes the decision to steal, open my coin purse, and press five zigs into her palm. I get down onto her level. "This is no kind of life, you know that right? There are people out there who want to be proud of you. But you have to make the right decisions, even when it's hard, okay? Ask for help when you need to. There is so much good inside you." The girl lights up and something sparks behind her eyes. "Kahti, good," she says, pressing her hand to her chest. Her voice is gravelly, almost a growl. "Yes. Yes, you are. Kahti is good." She extends her arms, and I fall into her hug. "Kahti good," she says into my ear. "So very good." She smiles again, then backs up and runs off. I'm filled with a warm feeling, too. Then I notice my coin purse is gone. Embarrassed and angry, I wait for my informant to show, and every moment my self-doubt grows. Had I let a violent raider go~for nothing? Two hours after the sun sets, I face reality. I head back to the bunker, half expecting not to find it, hoping that this had been some sort of weird dream, but no, it's there, hydras and all. My eyes adjust quicker this time, and I rush down the stairs, the concrete tacky underneath my feet, hoping to find a clue or hidden message. Only what I find is Brazer's dead body, sitting where I'd left him, slit across his neck. The playing board is red and bloated from soaking in his blood. A set of red-black footprints leads back out of the bunker. The game pieces are exactly as they were, so he must have been killed right after I'd left. I look for more clues, but I'm shaking too hard to concentrate. I must report this to the Legion, I don't care what kind of trouble I'm in for. I turn to leave, but wait~ I turn back and examine the board closely. There's one piece missing. My angel. She should have been where I'd left her. I summon the courage to wedge up Brazer's slumped body. No piece hiding under him, none on the floor. I look everywhere. Whoever killed him had taken the piece with them. I'm running back to Sunhome, fast as I can, but right before I make it to the gates, I'm intercepted. "Woah, woah, woah, Wojek," Aresaan says like she's trying to bring a churlish mount to a halt. She grabs me by my shoulders, looks me up and down, sees the panicked state I'm in. "What happened to you?" "I don't have time for your antics, Aresaan. There's been a murder." "Seriously?" "Do I look like I'm joking?" I hold up my hands, blood already matting my fur. "Crap, Ossett. I didn't realize~" she presses me forward toward the gates, and I nearly stumble over my own hooves. "You need to report this. I know we haven't been the most cordial of co-workers, but I'll come with you if you want~" I grumble. I don't want her with me, but I don't want to go in there alone either. "Fine," I say. "But don't be all~" I gesture at the whole of her, "~you." I've always felt tiny standing before Sunhome, with its blocky stone towers like massive fists punching into the sky, but now I feel even smaller. Flames of justice burn high in their pyres, shedding light upon deceit and threats to order and unity. They may brighten the streets, but no way they're strong enough to reach through the shadows dwelling in my heart. We're greeted by the Sunhome Guard, a battalion of them standing in front of the silver-rimmed gates. Many of the guards are giants—brawny and bare-chested, save for a few well-placed buckles. Any money saved on clothing the brutes had clearly gone toward paying for the enormous maces they brandished. I work hard to ignore my urgent need to flee. Then two of the guards approach me, and I'm too petrified to run, even if I wanted to. #figure(image("003_Clans & Legions/04.jpg", width: 100%), caption: [Sunhome, Fortress of the Legion | Art by: <NAME>ova], supplement: none, numbering: none) "<NAME>? You are wanted for questioning," one guard says to me, a giant, his thumb and forefinger large enough to encircle the girth of my bicep. "Wait, what? This is about the Baas Solvar case file? See, I thought it might be problematic, but I wasn't sure, and I didn't have enough time to really, and, and~" "You're suspected in the acute poisonings of Sergeant <NAME>, Second Lieutenant Dev<NAME>, and Guildmage R<NAME>." My boss, my boss's boss, and her boss. I shake my head. "No, that wasn't me. I would never! Tell them, Aresaan, that I couldn't—" I turn around, looking for Aresaan, but she's nowhere to be found. Figures. "Aresaan!" I scream out. She's an angel, so I know she can hear me call her name. Unless they'd stripped that power from her as well. Another guard, a minotaur wearing her weight in gold-trimmed armor, pats me down and empties my pockets. There's my coin purse. She opens it, pulls out my invitation to the dinner and the missing angel piece. She sniffs the game piece, twists it, and the top starts to screw apart from the bottom. There's liquid inside. "Some kind of Golgari poison, all right. A few drops would bring down a giant, easy." She holds it further away from her, screws it back up. "That's not mine, I swear!" "You're saying I won't find your prints all over it?" she asks me. "No! Well, yeah. I touched it. I was playing Clans & Legions. But I had no idea there was poison inside it!" "Says the heifer with blood all over her hands," the giant bellows, pushing me forth. The minotaur shoots him a displeased glance, but he misses it. "Two good leaders died because of you. I suppose you have an alibi of where you were during the ceremony yesterday? Someone who could vouch for you? Maybe your opponent?" "No, he's~" I bite my lip. "See, I was invited to the ceremony, but the invitation wasn't an invitation, you see? It was really a coded message to meet with an informant. See how the watermark is inverted, and the sunburst has one extra ray?" The minotaur holds the invitation up. "Looks like the normal symbol to me. Left-handed fist. Nine rays." #figure(image("003_Clans & Legions/05.jpg", width: 100%), caption: [Integrity \/\/ Intervention | Art by: <NAME>], supplement: none, numbering: none) I shake my head. "That can't be right. I saw it!" I squint, but as hard as I try, that thing in my brain that brought order to chaos is gone. It's nothing but a standard invitation on Boros letterhead. "I didn't do it. There is a traitor among us!" My mind feels so twisted up now, but I do know there are three high-ranking vacancies, and Boros always promotes from within. Which means the true killer will rise higher within the guild. Then it hits me, all at once—Aresaan. She'd been standing there when I read the invitation that wasn't an invitation. She could have enlisted the help of a Dimir mind-mage to bend my brain to see something that wasn't there. She'd bought a Golgari elixir on the black market and had conspired with that Gruul child to steal my coin purse, then~then~just now she could have put it back when she'd run into me. Who knows how deep her allies stretched, spanning guilds, spanning decades. Who knows how long she'd been hatching this plan, waiting for the right time. Boros Legion has been so obsessed with order lately, more so than usual. You can't walk a block without seeing a soldier in full furs and armor, can't go a weekend without a parade honoring the accomplishments of a garrison that had dominated on the battlefield. They try harder and harder to project solidarity and strength, and I can't help but think of how vulnerable to chaos we really are—how one spurned angel hellbent on working her way back up to Parhelion had set me up, and then, then~ And, and~and wait. The web of possibilities spreads out in my mind, like all the combinations of Clans & Legions games. Games could go on forever, but most games were fast, uncomplicated. Instead of focusing on the chaos, I need to focus on the order. I look at the three-move game. The easiest explanation. "Wait, you said that there were three poisonings, but two deaths?" I ask the giant. He scowls down at me. "<NAME> was lucky to survive. A dozen shamans worked him over well into the night." "You're saying the poison killed a minotaur and a giant, but not a flame-kin?" "Maybe death elixirs don't work so well on flame-kin, I don't know." Hmmm. Probably wouldn't work well on someone who wasn't truly alive in the first place, someone who should have flamed out years ago. That wouldn't stop the outpouring of compassion, though. They'd let him rest up, just to be sure he was okay, but he'd be back in the office~all that sympathy and no one would think twice about promoting him. He'd make his way into Sunhome, with a nice cushy job. But no way could he have done this himself. A flame-kin outside of the battlefield would draw too much attention. He needed someone who could walk around the city, unnoticed. Someone people were used to seeing on the streets. #figure(image("003_Clans & Legions/06.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) I look at the minotaur, those big furry hands that could wield huge bludgeons also seemed delicate enough to plant a coin purse in my pocket. I look down at her boots. Dark brown leather, tan splotches from hydra spit. She'd been to the bunker. She'd killed Brazer. "You!" I say. "Skormak is behind this and he poisoned himself to escape the blame. You're in collusion with him!" The giant balks at the accusation of his fellow guard and handles me rougher. "Maybe you should keep your mouth shut until you meet with your counsel." He pushes me forward. "You have to believe me. She's a killer," I plead with him. I'm not sure if they're working together, but it's worth a shot. "Skormak framed me so he could move up to Sunhome. And your partner here is in on it. Maybe you are, too." The minotaur stomps her hoof. "I would never do something so honorless!" "If you have proof, the truth will be discovered," the giant says. "You take me to Wargate and no one will ever hear from me again. Look! Look, there's spit from the hydra at the bunker where I met my informant." I point to my boots. "The pattern is the same on her boots. And there's dust on her uniform." "There's dust on your uniform," the minotaur says. "There's dust on my uniform. There's dust on his uniform~" she says, pointing to her partner. "Yes, but your dust~it's from the Rubblebelt—a very specific part where it butts up against Tenth District." "That'll be tough to prove, won't it," the minotaur gloats, "with you being locked up in Wargate?" "No one is going anywhere," says a voice. It's Aresaan. She's back, probably because she felt guilty about abandoning me. Or more likely, she couldn't stand to miss watching my career flame out in such an amazing spectacle. "You're sure what you're saying is true, Ossett?" "I'm sure. I didn't do what they're saying I did, Aresaan. You know me." "I can prove it, then," she says, waving her hands in the air, gathering white flames into her palms. She aims a ball of fire at the minotaur. It surrounds her, not quite touching. Maybe Aresaan's sob story about being a fallen angel hadn't been quite all true. Her magic is strong. It's imbued with a healing spell, and instead of turning the guard to ashes, the dust from her uniform coalesces into the shape of a dragon. The dusty figure writhes like an apparition. "Rubblebelt dust, high concentration of dragon bone," she says, confidently. "Care to explain?" I say to the guard. "I just~it's a—" the minotaur stammers. The iron head of the giant's mace is pointed at her, glowing fire-hot now, like it just spent twenty minutes in the forge. She throws the angel game piece down, and it breaks into two, death elixir spreading upon the ground. Aresaan blasts it with another fire spell, and the liquid vaporizes before it can affect us. When we regain our composure, the spy is gone. "We must not let her get away!" Aresaan says. "She isn't who we're after," I say. "It's Skormak. He's behind this." And the way Aresaan looks at me, there are no traces of doubt. I've earned the trust of an angel, and even though we will never be true equals, she sees me as close enough to one, now. She was beautifully radiant before, but she grows into something else right before my eyes, absolutely frightening to behold. Razor wire crumbles as she flexes her wings against it, and finally she stretches wing-tip to wing-tip, like a yawn decades overdue. The white feathers are long and delicate, but the power hidden beneath them cannot be denied. "I misjudged you, Wojek. Come with me, and we'll see this through. If there is a spy among us, it is our duty to restore justice." I grab her arm and am enveloped into her being. She flaps her wings, and the world speeds past us. When her feet finally hit the ground again, we're back in Annex Four, standing at Skormak's desk. He's there also, packing up his belongings. "Getting ready to move offices?" I ask. He jumps and the flames on his head flicker. "You're looking fit and well for someone who nearly died," Aresaan says, standing behind me. She's actually letting me take the lead on this. "Annex Four wasn't good enough for you, was it?" I say. "You wanted more, and you'd do anything to get it." "Do you know how many elementals serve in Sunhome? I can count them on one hand." He holds up three fingers, all aflame. "Three out of #emph[thousands] . Just because we were cast instead of born doesn't mean we aren't capable of performing in high ranks. They deny our sentience, they balk at giving us names, but the truth is we're not uncontrollable zealots and we deserve life past battle." "You killed two people," I remind him. "That's not what I'd call controllable." "Aresaan killed fifteen thousand, and all she got was a slap on the wrist. Double standards. Look around, Ossett. Lies, treachery, injustice. This is what your Legion is founded upon." "<NAME>," I say. "What?" "That's my title. Use it." Skormak laughs. "You wouldn't even have that title if it weren't for me, you arrogant heifer." The game has reached its rightful conclusion, and I say the line that has given me pleasure since I'd cleared my first Clans & Legions board. "You're nullified, Skormak." He raises a smoldering brow. "Huh—" I tilt my head, aim my horns, and ram him with all my might. He flies back into the wall, and the papers on his desk ignite. I didn't think that one all the way through. Maybe it's the shock of the hit, maybe it was me putting him in his place, but his flames burn less brightly now. "I got you, Wojek," Aresaan says. She frees an emergency water elemental from the wall nearby, then aims it at Skormak. The elementals clash, steam fills the office, but soon both the fire on the desk and the fire upon Skormak's skin extinguish. He smolders like a pinched wick, then dissipates into a pile of wet ashes and charred armor. #figure(image("003_Clans & Legions/07.jpg", width: 100%), caption: [Invert \/\/ Invent | Art by: <NAME>], supplement: none, numbering: none) "Thanks, Aresaan," I say. "Maybe I underestimated you, too." "Nah, what you see is what you get." She shrugs a shoulder, wings clenched tightly behind her, radiance faded back to normal. I don't know what she's planning, or what she's hiding, but there is definitely more to Aresaan than what she seems. "I guess I won't be seeing much of you now that you'll be off to the Wojek Annex," she says. "Congratulations. For real. You deserve it, Wojek Weslyn." I smile, adjust my cord, pinch my medallion. Wojek Weslyn. I'm pretty sure that will never get old.
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/enum-align.typ
typst
Apache License 2.0
// Test the alignment of enum numbers. --- // Alignment shouldn't affect number #set align(horizon) + ABCDEF\ GHIJKL\ MNOPQR + INNER\ INNER\ INNER + BACK\ HERE --- // Enum number alignment should be 'end' by default 1. a 10. b 100. c #set enum(number-align: start) 1. a 8. b 16. c --- // Number align option should not be affected by the context #set align(center) #set enum(number-align: start) 4. c 8. d 16. e\ f 2. f\ g 32. g 64. h --- // Test valid number align values (horizontal) // Ref: false #set enum(number-align: start) #set enum(number-align: end) #set enum(number-align: left) #set enum(number-align: right) --- // Error: 25-28 expected `start`, `left`, `center`, `right`, or `end`, found top #set enum(number-align: top)
https://github.com/xiaoxuan-yu/CUDA-CCL
https://raw.githubusercontent.com/xiaoxuan-yu/CUDA-CCL/main/report/main.typ
typst
BSD 3-Clause "New" or "Revised" License
#import "@preview/arkheion:0.1.0": arkheion, arkheion-appendices #import "@preview/tablex:0.0.8": cellx, hlinex, tablex, rowspanx, colspanx #show: arkheion.with( title: "CUDA 驱动的并行连通域标记", authors: ( (name: "余笑轩", email: "<EMAIL>", affiliation: "化学与分子工程学院"), ), abstract: [ #set text(font: ("Times New Roman", "SimSun", "Noto Serif CJK SC"),) #align(left)[#h(2em)连通域标记是计算机视觉中的基本操作, 广泛应用于图像分割、目标检测和图像分析等领域。本次作业实现了对于二维二值图像的8-连通域标记算法。我们使用 CUDA 实现了 KE 算法,并对其进行了性能测试。通过正确性验证和性能测试,我们验证了实现的正确性和性能,取得了相对于 CPU 串行实现的显著加速。我们使用 `nsys` 和 `nsight-compute` 工具对程序进行了性能分析,发现了程序的性能瓶颈,并提出了进一步的优化方向。] ], keywords: ("连通域标记","并行计算","CUDA"), date: datetime.today().display("[month repr:short] [day], [year]"), ) #set cite(style: "chicago-author-date") #show link: underline // set chinese fonts #set text(lang: "zh", region: "cn") #set text( font: ("Times New Roman", "SimSun", "Noto Serif CJK SC"), ) #show figure.where( kind: table ): set figure.caption(position: top) #set figure.caption(separator: [. ]) #let indent = 2em #set par(first-line-indent: indent) #let indent-par(body) = par(h(indent) + body) = 连通域标记问题 #indent-par[连通域标记(Connected Component Labeling, CCL)是计算机视觉中的一种基本操作,广泛应用于图像分割、目标检测和图像分析等领域。它的主要任务是识别和标记图像中相连的像素块,即连通域。连通域标记在图像处理、模式识别和计算机视觉的许多应用中起着关键作用。] 在图像中,连通域是指所有像素值相同且通过某种连通性准则(如4-连通或8-连通,如 @CCL 所示)相连的区域。连通域标记算法的目标是为每个连通域分配一个唯一的标签,以便后续的图像处理和分析工作。具体而言,本次作业将实现对于二维二值图像的8-连通域标记算法。 #figure( grid( columns: (auto, auto), rows: (auto, auto), gutter: 0em, [ #image("./figure/Square_4_connectivity.png", width: 60%) ], [ #image("./figure/Square_8_connectivity.png", width: 60%) ], ), caption:[4-连通性和8-连通性的示意图 @enwiki:1192036140], ) <CCL> = 算法 == CCL的串行算法: 并查集 #indent-par[基于并查集的串行算法是一种经典的连通域标记算法。并查集 (Union-Find) 是一种常用的数据结构,能够高效地处理连通域标记问题。并查集主要包含两个操作:查找 (Find) 和合并(Union),如 @UnionFind 所示。 - 查找: 确定某个元素属于哪个连通域。 - 合并: 将两个连通域合并为一个。] #figure( image("./figure/UnionFind.png", width:60%), caption:[并查集示意图 @8798895], ) <UnionFind> #indent-par[基于并查集的算法通过逐像素扫描图像,使用并查集记录和合并相邻像素的连通信息,从而实现连通域标记。具体步骤如下: 1. 初始化并查集,每个像素作为一个独立的集合。 2. 逐像素扫描图像,对每个像素检查其上方和左方像素的连通情况,进行合并操作。 3. 第二次扫描图像,对每个像素进行查找操作,确定其最终的连通域标签。] == GPU 并行的 CCL: Komura Equivalence 算法 <alg> #indent-par[对于并查集的并行化并不是显而易见的。传统的并查集算法是基于串行处理的, 直接并行化会面临许多挑战, 尤其是在处理等价类合并时, 需要解决多个线程之间的同步和冲突问题。为了有效地在GPU上实现并行的连通域标记, 研究者们提出了多种改进方案, KE(Komura-Equivalence) 算法就是其中之一。KE算法@KOMURA201554 通过一系列步骤来实现高效的GPU并行连通域标记, 其过程如 @KE 所示:] - 初始化: 为每个像素分配一个唯一的初始标签,通常使用其线性索引值。 - 等价类更新: 在此步骤中, 多个GPU线程并行处理像素, 检查每个像素与其相邻像素的连通性,并更新等价类信息。这一步骤通常需要多次迭代, 直到所有像素的标签稳定下来。 - 标签压缩: 使用路径压缩技术对等价类进行压缩,确保所有等价像素的标签一致。这一步骤通过在并查集的“查找”操作中进行路径压缩来实现。 - 标签传播: 将最终标签传播到所有连通像素,确保每个连通域的所有像素共享相同的标签。 #figure( image("./figure/KE.jpg", width:80%), caption:"KE算法示意图", ) <KE> #indent-par[ KE算法通过分阶段处理和并行化技术, 有效地克服了传统并查集在GPU上的并行化困难, 提高了连通域标记的效率。2018 年,Allegretti 等人给出了 8 连通的 KE 算法 @8708900,该算法主要对@KE 中的 reduction 部分进行了改进,如@KE8 所示。 ] #figure( image("./figure/KE8.png", width:80%), caption:"8-连通的 KE 算法示意图", ) <KE8> = 实现 == 概述 #indent-par[我们使用 `CUDA` 实现了 KE 算法,并对其进行了性能测试,参见 `algorithm/` 文件夹下的相关代码。] ```bash . ├── CMakeLists.txt └── src ├── alg │ ├── KE.cu │ └── UFTree.cuh ├── CMakeLists.txt ├── include │ ├── alg_runner.cuh │ ├── Matrix.cuh │ └── timer.cxx ├── main.cu └── serial.cxx ``` #indent-par[`main.cu` 是并行版本的主程序入口,包含输入输出的处理,`Matrix` 对象的初始化以及 `KE` 算法的调用及性能评估。`include` 文件夹下包含了必要的功能函数和类,主要是用于包装矩阵的结构体 `Matrix` 以及其输出函数,计时器 `Timer` 以及用于性能评估的并行算法的运行器 `alg_runner`。`alg` 文件夹下包含了 `KE` 算法的实现以及并查集相关操作的实现。`serial.cxx` 是给定的串行版本的主程序,只是进行了简单的修改用于多次运行算法以进行性能评估。] 在我们的实现中,每个 CUDA `thread` 负责处理一个像素。我们选择了 `dim3(16,16,1)` 作为 `block` 的大小,并计算出所需的 `grid` 的形状 `dim3(cols+BLOCK_COLS-1)/BLOCK_COLS, (rows+BLOCK_ROWS-1)/BLOCK_ROWS,1)`,以保证开启的总线程数至少多于图像的像素数。 == Komura-Equivalence 算法的实现 #indent-par[如 @alg 描述,KE 算法主要包含三个不同操作:初始化、路径压缩和归并。在此,分别给出相应的伪代码。在 InitKernel 中,我们为每个像素分配初始标签。] ```python def InitKernel(images, labels, index): row, col = index // images.cols, index % images.cols # row and col from threadID, blockDim, blockIdx, thus need to check if it is valid if (row < images.rows and col < images.cols): if (row>0 and images[row][col] == images[row-1][col]): labels[row][col] = index - images.cols + 1 # labels[row-1][col] elif (row>0 and col>0 and images[row][col]s == images[row-1][col-1]): labels[row][col] = index - images.cols # labels[row-1][col-1] elif (row>0 and col<images.cols-1 and images[row][col] == images[row-1][col+1]): labels[row][col] = index - images.cols + 2 # labels[row-1][col+1] elif (col>0 and images[row][col] == images[row][col-1]): labels[row][col] = index # labels[row][col-1] else: labels[row][col] = index + 1 ``` #indent-par[在 CompressionKernel 中,我们对并查集进行路径压缩。这个 Kernel 也在完成归并操作后调用,用于进行标签的传播] ```python def CompressionKernel(labels, index): row, col = index // images.cols, index % images.cols if (row < images.rows and col < images.cols): label = labels[row][col] if (label){ labels[row][col] = Find_label(labels, index, label) + 1 } ``` #indent-par[在 ReduceKernel 中,我们进行并查集的归并操作。由于实现的是 8-连通的 KE 算法,因此我们除了检查当前像素的左侧外,还需要检查右上方的像素。] ```python def ReduceKernel(images, labels, index): row, col = index // images.cols, index % images.cols if (row < images.rows and col < images.cols): if (col>0 and images[row][col] == images[row][col-1]): Union(labels, index, index-1) if (row>0 and col<images.cols-1 and images[row][col] == images[row-1][col+1]): Union(labels, index, index-images.cols+1) ``` #indent-par[顺次调用这三个 Kernel 函数并最后调用一次 `CompressionKernel` 用于标签传播,即可完成整个 KE 算法的实现。] ```python def KE(images, labels): InitKernel<<<grid, block>>>(images, labels) CompressionKernel<<<grid, block>>>(labels) ReduceKernel<<<grid, block>>>(images, labels) CompressionKernel<<<grid, block>>>(labels) ``` 具体的 Kernel 函数及 KE 算法流程的实现参见 `algorithm/src/alg/KE.cu`,在此不再赘述。 = 结果与讨论 == 正确性验证 #indent-par[以作业中给定的串行程序作为参考,我们对并行程序的结果进行了验证。在正确性验证中,一个难以处理的问题是即使结果正确,标签的顺序和值也都可能不同。因而,我们实现了一个映射算法,将并行程序的标签映射到串行程序的标签,从而验证两者的结果是否一致。映射算法的实现非常平凡,我们将每个标签对应的像素坐标全部记录并进行匹配,从而得到一个标签之间的映射表。根据这个映射表执行映射后,我们可以直接比较两个 `label` 数组是否一致从而验证正确性。正确性验证的相关代码参见 `validation/val.py` 和 `validation/validation.ipynb`。此处给出核心功能函数的实现。] ```python def get_match_dict(labels_a, labels_b): uni_labels_a = np.unique(labels_a) uni_labels_b = np.unique(labels_b) labels_a_dict = {label: [] for label in uni_labels_a} labels_b_dict = {label: [] for label in uni_labels_b} for i in range(labels_a.shape[0]): for j in range(labels_a.shape[1]): labels_a_dict[labels_a[i][j]].append(i * labels_a.shape[1] + j) for i in range(labels_b.shape[0]): for j in range(labels_b.shape[1]): labels_b_dict[labels_b[i][j]].append(i * labels_b.shape[1] + j) match_dict = {} for label in uni_labels_a: label_index_list = labels_a_dict[label] for b_label in uni_labels_b: b_label_index_list = labels_b_dict[b_label] if len(label_index_list) != len(b_label_index_list): continue if all( [ label_index_list[i] == b_label_index_list[i] for i in range(len(label_index_list)) ] ): match_dict[label] = b_label break return match_dict def map_with_dict(labels, match_dict): labels = labels.copy() for i in range(labels.shape[0]): for j in range(labels.shape[1]): labels[i][j] = match_dict[labels[i][j]] return labels ``` #indent-par[在验证过程中,我们发现并行程序的结果与串行程序的结果一致,验证通过。对于每一个标签,我们将其重新映射到一个随机的颜色,用于可视化连通域标记问题的结果。以下给出对于作业中要求的四个样例的可视化结果。] #figure( grid( columns: (auto, 17em, 17em), rows: (auto, auto, auto, auto, auto, auto), gutter: 0em, align: center+horizon, //[ #image("../validation/figure/serial_labels_debug.png", width:) ], //[ #image("../validation/figure/KE_labels_debug.png", ) ], [],[串行算法的可视化结果],[GPU并行的KE算法的可视化结果], [],[#v(1em)],[#v(1em)], [pixels_1.txt #h(2em)],[ #image("../validation/figure/serial_labels_1.png") ], [ #image("../validation/figure/KE_labels_1.png") ], [pixels_2.txt #h(2em)], [ #image("../validation/figure/serial_labels_2.png")], [ #image("../validation/figure/KE_labels_2.png") ], [pixels_3.txt #h(2em)], [ #image("../validation/figure/serial_labels_3.png")], [ #image("../validation/figure/KE_labels_3.png") ], [pixels_4.txt #h(2em)], [ #image("../validation/figure/serial_labels_4.png")], [ #image("../validation/figure/KE_labels_4.png") ], ), caption:[连通域标记结果的可视化], ) #indent-par[上述结果直观地证明,我们的并行程序实现了正确的连通域标记。] == 性能测试 #indent-par[使用数院集群,我们完成了串行和GPU并行算法的性能测试。CPU 程序在单颗 E5-2650 v4 处理器上运行,计算节点内存为 128 GB;GPU 程序在一块 NVIDIA Titan XP GPU 上运行,其具有 3840 个 CUDA core, 12 GB GDDR5X 现存和 1582 MHz 的主频,计算节点内存为 256 GB。所有程序使用 `GCC Compiler 9.3.0` 和 `nvcc 11.3` 进行编译。] 以下给出串行和并行算法的性能测试结果,如@perf 所示。受计算资源限制,串行算法运行20次取平均运行时间,而GPU并行算法运行100次取平均时间作为测试结果。性能测试结果的原始文件见 `perf/CPU_CCL.out` 和 `perf/GPU_CCL.out`。 #let toprule = hlinex(stroke: (thickness: 0.08em)) #let bottomrule = toprule #let midrule = hlinex(stroke: (thickness: 0.05em)) #let rows = ( toprule, rowspanx(2)[*算法*], colspanx(5)[*运行时间* ($mu$s)], (),(),(),(), (), [Debug],[Sample 1],[Sample 2],[Sample 3],[Sample 4], midrule, [Serial UF], [67.3341],2.93872e5,7.27506e5,4.65453e+06,8.28364e+06, [GPU KE], 64.2954, 2058.72, 4092.8, 22955.9, 40088.3, bottomrule, ) #figure( caption: [串行算法和并行算法的运行时间对比], tablex( columns: 6, align: center + horizon, auto-vlines: false, auto-hlines: false, header-rows: 2, ..rows), // TODO(@daskol): Fix gutter between rows in body. kind: table, ) <perf> 从而可以计算 $S = T_"serial" \/ T_"parallel"$,如 @acc-table 所示。 #let acc_rows = ( toprule, [Debug],[Sample 1],[Sample 2],[Sample 3],[Sample 4], midrule, 1.047, 142.75, 177.75, 202.76, 206.63, bottomrule, ) #figure( caption: [GPU 算法的加速倍数], tablex( columns: 5, align: center + horizon, auto-vlines: false, auto-hlines: false, header-rows: 2, ..acc_rows), // TODO(@daskol): Fix gutter between rows in body. kind: table, ) <acc-table> #indent-par[可以看到,除了非常小的测试案例Debug,GPU 算法在其他测试案例中都取得了显著的加速效果。在最大的测试案例中,GPU 算法的加速效果达到了 207 倍。] == 性能分析 === 总览 #indent-par[我们使用 `nsys` 工具对程序在 GPU 上的运行时间进行了详细的分析。我们注意到,在 `CUDA` 程序第一次启动时,需要执行初始化相关的 kernel 函数,同时完成 PTX 编译,因此第一次运行算法的时间会显著高于后续的运行时间。这也是我们在程序进行性能测试时从第二次运行算法开始计时的原因。对于一次典型的 KE 算法运行,给出 `nsys` 绘制的 timeline 图如 @timeline 所示。] #figure( align(center)[#image("./figure/nsys.png")], caption: [KE 算法的时间线图], ) <timeline> #indent-par[在 `nsys` 的分析结果中,我们可以看到,GPU 程序的主要时间消耗在 `cudaMemcpy`。尽管仅仅在输入图像和输出标签时分别进行了一次 host2device 和 device2host 的数据传输,但它们的合计用时接近算法运行总时长的 2/3,与整个连通域标记算法的执行用时相当。对于我们自行编写的算法部分,其主要时间消耗在 `ReduceKernel` 和 `CompressionKernel` 两个核函数上,尤其是 `ReduceKernel` 消耗了约一半的运行时长。这的确是符合逻辑的,因为在 KE 算法中,`ReduceKernel` 是用于进行并查集的归并操作,是整个算法的核心部分;但这同样提醒我们,进一步优化 `ReduceKernel` 的性能是提高整个算法效率的关键。另一个值得关注的点是对于 `Init_L` 这个 kernel,调用时存在 CPU 和 GPU 均处于空闲状态的情况,也是进一步优化的潜在方向。 ] === 性能热点的进一步分析 #indent-par[为了进一步的明确性能瓶颈,我们使用 `nsight-compute` 对核函数的性能进行了分析。主要关注 hotspot 也就是 `ReduceKernel` 和 `CompressionKernel` 两个核函数。首先,我们需要确定这两个核函数是计算密集型的还是内存密集型的。给出两个kernel分别的 `GPU Throughput` 结果如 所示。] #let throughput_rows = ( toprule, [Kernel], [Compute Throughput / %], [Memory Throughput / %], midrule, [ReduceKernel], [66.04 %], [79.80 %], [CompressionKernel], [77.79 %], [26.31 %], bottomrule, ) #figure( caption: [核函数的 GPU Throughput], tablex( columns: 3, align: center + horizon, auto-vlines: false, auto-hlines: false, header-rows: 2, ..throughput_rows), // TODO(@daskol): Fix gutter between rows in body. kind: table, ) <throughput> #indent-par[ 结合 `nsight-compute` 进行 roofline 分析 @roofline 的结果,我们可以看到 `CompressionKernel` 是计算密集型的,而 `ReduceKernel` 是内存密集型的。从而,可以进一步分析相应的工作负载。 ] 对于内存密集型的 `ReduceKernel`, 给出其显存吞吐量如@Memory 所示。 #figure( align(center)[#image("./figure/Memory.png")], caption: [ReduceKernel 的显存工作负载], ) <Memory> #indent-par[可以看到,大部分的数据传输发生在 L1 cache 和 L2 Cache 之间,这是相对较快的。但是,也有一部分数据传输发生在 L2 Cache 和 Device Memory 之间,相对较慢。查看 `nsight-compute` 的统计数据,发现这一部分访问中执行了比较多的越界访问,这些访问基本都出现在 `if` 语句的判断条件中,作为用于判断的索引值可能超出了数组的范围。尽管由于其他判断条件的作用,这并不会产生结果上的错误,但是会导致额外的访存,从而影响性能。`nsight-compute` 预计这个问题的修复可能带来约 15% 的性能提升。除此之外,L1 cache 的命中率约 72%,仍有提升空间。] 对于计算密集型的 `CompressionKernel`, 给出其计算的管线利用率如@Compute 所示。 #figure( align(center)[#image("./figure/Pipe Utilization.png")], caption: [CompressionKernel 的计算工作负载], ) <Compute> #indent-par[可以看到绝大多数操作是用于逻辑运算和位运算的 ALU 操作,同时涉及较高比例的条件判断、循环体等带来的 ADU 操作。这意味着在当前算法的框架下,此处的性能瓶颈优化潜力相对有限。在总调用次数难以减少的情况下,进一步的优化可能需要考虑对于逻辑运算和位运算的优化,例如使用高效的掩码位运算代替条件判断等。] 除此之外,由于在整个运算过程中,图形的原始数组 `img` 实际上是只读的,同时也是与 Device Memory 交互的重要来源,因而,通过使用 CUDA 的纹理内存以加速访问,也是一个潜在的优化方向。此外,由于纹理内存对二维数据的访问有着天然的优势,因此,可以考虑将 `img` 和 `labels` 从一维数组转换为二维数组,以进一步提高访存效率和缓存的命中率。 = 总结 #indent-par[本次作业中,我们实现了基于 CUDA 的并行连通域标记算法。我们首先介绍了连通域标记问题的背景和串行算法,并详细介绍了 KE 算法的并行实现。我们通过正确性验证和性能测试验证了实现的正确性和性能,取得了相对于 CPU 串行代码百倍以上的加速效果。我们使用 `nsys` 和 `nsight-compute` 工具对程序进行了性能分析,发现了程序的性能瓶颈,并提出了进一步的优化方向。] #set heading(numbering: none) = 代码可用性 本次作业的代码已经开源在 GitHub 上,地址为 https://github.com/xiaoxuan-yu/CUDA-CCL. #set text(lang: "en") // Add bibliography and create Bibiliography section = 参考文献 #bibliography("bibliography.bib", title: none)
https://github.com/mem-courses/linear-algebra
https://raw.githubusercontent.com/mem-courses/linear-algebra/main/note/6.线性空间的基与子空间.typ
typst
#import "../template.typ": * #show: project.with( title: "Linear Algebra #6", authors: ( (name: "<NAME>", email: "<EMAIL>", phone: "3230104585"), ), date: "December 3, 2023", ) #let alpha = math.bold(math.alpha) #let beta = math.bold(math.beta) #let gamma = math.bold(math.gamma) #let theta = math.bold(math.theta) #let eta = math.bold(math.eta) #let nu = math.bold(math.nu) #let xi = math.bold(math.xi) #let ds = math.dots.c #let TT = math.upright("T") = 线性空间的基 == 基和维数 设 $V$ 是数域 $PP$ 上的(非零)线性空间,当我们把 $V$ 中的全体向量看成一个向量组时,如果该向量组存在一个有限个向量所组成的极大线性无关组,则称 $V$ 是有限维的.当 $V$ 是有限维时,称其极大线性无关组的向量个数为它的 *维数*,记为 $dim V$. 若 $dim V = n$ 且 $xi_1,xi_2,dots.c,xi_n$ 为 $V$ 的一个极大线性无关组,则称 $xi_1,xi_2,dots.c,xi_n$ 的任意一个排列为 $V$ 的一组 *基*. === 常用基 线性空间 $V$ 中形式最简单的一组基,称为 $V$ 的 *常用基*. $PP^n$ 的常用基:$e_1=display(mat(1,0,dots.c,0))^TT$,$e_2=display(mat(0,1,dots.c,0))^TT$,$dots.c$,$e_n=display(mat(0,0,dots.c,1))^TT$. $PP^(m times n)$ 的常用基:$e_(i j) sp(i=1,2,dots.c,m,sp j=1,2,dots.c,n)$(其中 $e_(i j)$ 是第 $i$ 行第 $j$ 列元素为 $1$,其他元素为 $0$ 的矩阵)$=> dim PP^(m times n) = m times n$. $PP[x]_n$ 的常用基为 $1,x,x^2,dots.c,x^(n-1) => dim PP[x]_n = n$. == 坐标 设 $V$ 是数域 $PP$ 上的 $n$ 维线性空间,即 $dim V = n$,又设 $xi_1,xi_2,dots.c,xi_n$ 是 $V$ 的一组基,则 $forall alpha in V$,$alpha$ 可由基 $xi_1,xi_2,dots.c,xi_n$ 唯一的线性表示,设 $ alpha = x_1 xi_1 + x_2 xi_2 + dots.c + x_n xi_n = mat(xi_1,xi_2,dots.c,xi_n) mat(x_1,x_2,dots.c,x_n)^TT = mat(xi_1,xi_2,dots.c,xi_n) bold(X) $ 其中 $bold(X) in PP^n$ 称为 $alpha$ 在基 $xi_1,xi_2,dots.c,xi_n$ 下的坐标. #def[定理1]设 $V$ 是数域 $PP$ 上的 $n$ 维线性空间,$xi_1,xi_2,dots.c,xi_n$ 为 $V$ 的一组基,则对于 $V$ 中的任意一个向量组 $alpha_1,alpha_2,dots.c,alpha_s$,设其在基下的坐标分别为 $bold(X)_1,bold(X)_2,dots.c,bold(X)_s$.那么 $alpha_1,alpha_2,dots.c,alpha_s$ 线性无关 $<=>$ $bold(X)_1,bold(X)_2,dots.c,bold(X)_s$ 线性无关 $<=>$ $r(bold(A)_(n times s)) = s$.其中 $bold(A)_(n times s) = display(mat(bold(X)_1,bold(X)_2,dots.c,bold(X)_s))$. #note[ 由于 $bold(X)_ i in PP^n$,通过这一定理,我们可以把矩阵的秩与任意线性空间的线性无关性的判定联系起来. ] #def[推论1.1]设 $dim V = n$,$V$ 中的任意 $n+1$ 个向量必线性相关. #def[推论1.2]设 $dim V=n$,$seqn(alpha,n)$ 线性无关 $<=> |bold(A)_(n times n)| != 0$.(其中 $bold(A)_n = vecn(bold(X),n)$. #def[推论1.3]设 $dim V = n$,则 $V$ 中任意 $n$ 个线性无关的向量都是 $V$ 的一组基. #def[定理2]设 $dim V=n$,$seqn(xi,n)$ 为 $V$ 的一组基,向量 $seqn(alpha,s) in V$ 在所给基下的坐标分别为 $seqn(bold(X),n)$,向量 $beta in V$ 在所给基下的坐标为 $bold(Y)$,则: #deft[定理2]1. $beta = vecn(alpha,s) bold(X)_0 <=> bold(A) bold(X)_0 = bold(Y)$. #deft[定理2]2. $beta$ 可被向量组 $seqn(alpha,s)$ 线性表示 $<=> bold(A)bold(X) = bold(Y)$ 有解 $<=>$ $bold(Y)$ 可由 $seqn(bold(X),s)$ 线性表示. #note[ 回顾:如何证明 $PP^n$ 下的向量组 $seqn(alpha,m) sp (m<=n)$ 的线性关系? 1. 从定义出发:$k_1 alpha_1 + k_2 alpha_2 + dots.c + k_n alpha_n = theta$. 2. 令 $bold(A) = vecn(alpha,n)$,比较 $r(bold(A))$ 与 $m$. 3. 利用某组基下的坐标所构成的矩阵 $bold(A)_(n times m)$ 进行判定. ] == 过渡矩阵 设 $dim V = n$,$V$ 的两组基 (I) $seqn(xi,n)$ 和 (II) $seqn(eta,n)$, $ vecn(eta,n) = vecn(xi,n) mat( m_11,m_12,dots.c,m_(1 n); m_21,m_22,dots.c,m_(2 n); dots.v,dots.v,,dots.v; m_(n 1),m_(n 2),dots.c,m_(n n); ) = vecn(xi,n) bold(M) $ 则称矩阵 $bold(M)$ 为从基 (I) 到基 (II) 的过渡矩阵. #note[ 1. 过渡矩阵是有方向的:$upright("(II)") = upright("(I)") bold(M)$,则 $bold(M)$ 是向量组 (I) 过渡到向量组 (II) 的过渡矩阵. 2. $bold(M)$ 可逆.$bold(M)^(-1)$ 是从基 (II) 到基 (I) 的过渡矩阵 3. $PP^n$ 下 *求过渡矩阵的方法*:记 $bold(A) = vecn(xi,n)$,$bold(B) = vecn(eta,n)$,则有 $bold(B) = bold(A M)$ $=>$ $bold(M) = bold(A)^(-1) bold(B)$.那么写成分块矩阵 $display(mat(bold(A),:,bold(B)))$ 的形式,通过初等行变换将左边消成单位矩阵,那么右边就是 $bold(M)$. ] === 坐标变换公式 设 $alpha in V$,设 $alpha$ 在基 (I) 下坐标为 $bold(X)$,在基 (II) 下坐标为 $bold(Y)$,$bold(M)$ 是从基 (I) 到基 (II) 的过渡矩阵,即: $ alpha = vecn(xi,n) bold(X) = vecn(eta,n) bold(Y) = vecn(xi,n) bold(M Y) $ 则 $bold(X) = bold(M Y)$ 或称 $bold(Y) = bold(M)^(-1) bold(X)$. = 线性空间的子空间 数域 $PP$ 上一个线性空间 $V$ 的一个非空集合 $W$,如果关于 $V$ 的加法和数乘也构成 $PP$ 上的线性空间,那么称 $W$ 是 $V$ 的一个 *子空间*.显然 ${theta}$ 和 $V$ 是 $V$ 的两个字空间,称为 $V$ 的平凡子空间. #def[定理]线性空间 $V$ 的任意一个非空子集 $W$,如果满足 *加法封闭*、*乘法封闭*,则称 $W$ 是 $V$ 的一个子空间. == 张成 设 $V$ 是数域 $PP$ 上的线性空间,$seqn(alpha,t) in V$,记 $ L(seqn(alpha,t)) = {k_1 alpha_1 + k_2 alpha_2 + dots.c + k_t alpha_t | t_i in PP} $ 可以证明 $L(seqn(alpha,t))$ 是 $V$ 的一个子空间,记 $L(seqn(alpha,t))$ 为由向量组 $seqn(alpha,t)$ *张成* 的子空间. == 线性方程组解的结构 对线性方程组 $bold(A)_(m times n) bold(X) = beta (!= theta)$ 和 $bold(A)_(m times n) bold(X) = theta$,当 $r(bold(A)) = r display(mat(bold(A),:,beta)) = r$ 时,第一个线性方程组有解.特别地当 $r<n$ 时这两个线性方程组有无穷多解. 记 $W={bold(A) bold(X) = beta | bold(X) in PP^n}$,$W_0={bold(A) bold(X) =theta | bold(X) in PP^n}$,则 $W,W_0$ 都是 $PP^n$ 的子集.但 $W_0$ 是 $PP^n$ 的子空间,$W$ 不是 $PP^n$ 的子空间. - $W_0$ 的结构:由基础解系(极大线性无关组)张成 - $W$ 的结构:由对应齐次线性方程组的解空间平移而成 === 齐次线性方程组解的结构 $bold(A X) = theta$ 的解空间 $W_0$ 的任意一个极大线性无关组 $seqn(xi,n-r)$ 称为 $W_0$ 的一个 *基础解系*.有 $W_0 = L(seqn(xi,n-r))$. TBD #prof[ #def[证明]:$seqn(xi,n-r)$ 为 $W_0$ 的一个基础解系. 1. $seqn(xi,n-r) in W_0$(即 $bold(A) xi_i = theta, sp i=1,2,dots.c,n-r$); 2. $seqn(xi,n-r)$ 线性无关; 3. $forall bold(X) in W$,$bold(X)$ 可被 $seqn(xi,n-r)$ 表示. 其中:记:$bold(B) = vecn(xi,n-r) = display(mat(bold(C)_(r times (n-r)); bold(E)_((n-r)times(n-r))))$. 由 $r(bold(B))<=n-r$ 且 $r(bold(B)) >= r(bold(E)_((n-r)times(n-r))) =n-r$ 得 $r(bold(B))=n-r$,即 $seqn(xi,n-r)$ 线性无关. ] === 解的结构定理 $bold(A X) = beta$ 的任意解,$bold(X) = xi_0 + (t_1 xi_1 + t_2 xi_2 + dots.c + t_(n-r) xi_(n-r))$.其中 $xi_0$ 是 $bold(A X) = beta$ 的某个特解,$seqn(xi,n-r)$ 是 $bold(A X) = theta$ 的基础解系. // === 例题 // 01:29:42
https://github.com/bamiesking/bicop-2023
https://raw.githubusercontent.com/bamiesking/bicop-2023/main/theme.typ
typst
// Adapted from Dr. <NAME>'s modified form of https://github.com/anishathalye/gemini #let primary = rgb(0, 30, 130) #let secondary = rgb(230, 235, 240) #let author(name, affiliation, bold: false) = { if (bold) { strong[#name] } else { name } " " if type(affiliation) == int { super[#affiliation] } else if type(affiliation) == array { for (i, a) in affiliation.enumerate() { super[#a] if i + 1 < affiliation.len() { super[,] } } } } #let conf() = { set text(font: "Raleway", size: 18pt) }
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/headings.typ
typst
#let rosy(it) = locate((loc) => { if it.level == 1 { if loc.page > 1 { pagebreak() it } else { it v(12pt) } } else if it.level == 2 { it v(12pt) } else if it.level == 3 { it v(10pt) } else if it.level == 4 { it v(10pt) } }) // this is used somewhere else #let example = locate(loc => { let elems = query( selector(heading).before(loc), loc, ) let academy = smallcaps[ Typst Academy ] if elems == () { align(right, academy) } else { let body = elems.last().body academy + h(1fr) + emph(body) } })
https://github.com/hesampakdaman/baby-rudin
https://raw.githubusercontent.com/hesampakdaman/baby-rudin/master/exercises.typ
typst
#let first-indent-spacing = 1.8em #let indent = h(first-indent-spacing) #set page(margin: 1.75in) #set par(leading: 0.55em, first-line-indent: first-indent-spacing, justify: true) #set text(size: 11pt, font: "New Computer Modern") #show raw: set text(font: "New Computer Modern Mono") #show par: set block(spacing: 0.55em) #show heading: set block(above: 1.4em, below: 1em) #show ref: it => { let eq = math.equation let el = it.element if el != none and el.func() == eq { numbering( el.numbering, ..counter(eq).at(el.location()) ) } else { it } } #let algebraicset = $cal(A)$ #let integers = $bb(Z)$ #let irrationals = $bb(I)$ #let naturals = $bb(N)$ #let qed = [#h(1fr) $qed$] #let rationals = $bb(Q)$ #let reals = $bb(R)$ #let closure(X) = $overline(#X)$ #let bvec(v) = $bold(upright(#v))$ == Chapter 2 === Exercise 2.1 #quote(block: true)[Prove that the empty set is a subset of every set.] Let $A$ be any set, $emptyset$ be the empty set and assume the opposite. Then there exists at least one element $x in emptyset$ such that $x in.not A$. But the empty set does not contain any elements and no such $x$ can therefore be found. This is a contradiction and hence $emptyset subset A$ must be true. #qed === Exercise 2.2 #quote(block: true)[Prove that the set of all algebraic numbers is countable.] Let $alpha = (a_0, dots, a_n) in B_(n+1)$ be an n+1-tuple of integers. Example 2.5 shows that the set of all integers $integers$ is countable. Using Theorem 2.13 with $A = integers$ shows that the set of n+1-tuples $B_(n+1)$ is countable. For particular choice of integers $a_0, dots, a_n$ we may construct an equation of the form $ a_n z^n + dots.c + a_1 z + a_0 = 0. $ This polynomial has at most $n$ solutions. Let $E_alpha$ be the set of all complex numbers $z$ that is a solution to that polynomial. Hence $E_alpha$ is a finite subset of $algebraicset$ with at most $n$ elements. If $S_n$ is a set such that $ S_n = union.big_(alpha in B_(n+1)) E_alpha $ then it is the union of a countable collection of finite sets. It follows from Theorem 2.12 that $S_n$ is at most countable. Since the union of a countable collection of at most countable sets is at most countable (follows from Theorem 2.12 again); the union $ S = union.big_(n=1)^(infinity) S_n, $ is at most countable. We shall show that $algebraicset subset S$. For any $z in algebraicset$ there exist integers $a_0, dots, a_k$ such that $a_k z^k + dots.h.c + a_1 z + a_0 = 0$. For these integers there is a k+1-tuple $alpha = (a_0, dots, a_k)$ which is associated with exactly one set $E_alpha$. Hence there exists at least one $alpha$ for which $z in E_alpha$ and therefore it follows that $algebraicset subset S$. This means that $algebraicset$ is at most countable since it is a subset of $S$. Lastly we need to show that $algebraicset$ is infinite. The set of rational numbers $rationals$ is countable by the corollary to Theorem 2.13. For any $q in rationals$ there are integers $m, n$ such that $q = n/m$. Now choose $a_1 = m$ and $a_0 = -n$, then $ a_1 q + a_0 = m n/m - n = 0, $ which means that $q$ is algebraic. Since $q$ is arbitrary it follows that $rationals subset algebraicset$. This shows that $algebraicset$ has an infinite subset and must therefore itself be infinite. $algebraicset$ is an infinite set that is at most countable, and therefore it is countable as desired. #qed === Exercise 2.3 #quote(block: true)[Prove that there are real numbers which are not algebraic.] Suppose not. Let $algebraicset$ be the set of all algebraic numbers. Since we assume the opposite any real number is algebraic and it follows that $reals subset algebraicset$. From Exercise 2.2 we know that $algebraicset$ is countable. By Theorem 2.8 this would entail that $reals$ is countable, since it is an infinite subset of a countable set. But this is a contradiction since Theorem 2.43 shows that $reals$ is uncountable. Hence our assumption is false and there exists real numbers $x in reals$ such that $x in.not algebraicset$. #qed === Exercise 2.4 #quote(block: true)[Is the set of all irrational real numbers countable?] Denote the set of irrational numbers by $irrationals$. According to Theorem 2.13 $rationals$ is countable. Now suppose $irrationals$ is countable. We already know that $ reals = rationals union irrationals, $ which means that $reals$ is countable by Theorem 2.12. But this is a contradiction since by Theorem 2.43 the set of real numbers $reals$ is uncountable. If $irrationals$ is assumed to be finite, then that still would make $reals$ countable. Hence, $irrationals$ must be uncountable. #qed === Exercise 2.5 #quote(block: true)[Construct a bounded set of real numbers with exactly three limit points.] Let $k$ be a natural number and consider the set $E_k$ of numbers $k + 1/n$ where $n = 1, 2, 3, dots$ . Clearly $E_k subset (k, k+1]$ and is therefore bounded. We need to show that $E_k$ does not contain any limit points. For any natural numbers $n, m$ we have that $ d( k + 1/n, k+ 1/m) = abs(k + 1/n - (k + 1/m)) = abs(1/n - 1/m) = d(1/n, 1/m). $ For a fixed $n$ we want to show that $ d(1/n, 1/m) gt.eq d(1/n, 1/(n+1)), $ holds with any natural number $m eq.not n$. If $m gt.eq n+1$, then $ d(1/n, 1/m) = abs(1/n - 1/m) gt.eq abs(1/n - 1/(n+1)) = d(1/n, 1/(n+1)). $ \ If $m lt.eq n - 1$, then $ d(1/n, 1/m) &= abs(1/n - 1/m) = 1/m - 1/n gt.eq 1/(n-1) - 1/n \ &= 1/(n(n-1)) > 1/(n(n+1)) =1/n - 1/(n+1) \ &= abs(1/n - 1/(n+1)) = d(1/n, 1/(n+1)), $ which gives us the result. Hence any neighborhood $N_r (k + 1/n)$ with radius $0 < r < abs(1/n - 1/(n+1)) = 1/(n(n+1))$ will contain no other points of $E_k$ except $k + 1/n$. This means that $k + 1/n$ cannot be a limit point of $E_k$. We now show that $k in.not E_k$ is a limit point of $E_k$. For any radius $r > 0$ we can find a natural number $N$ such that $1/N < r$ by using the Archemdian property of $reals$ (Thm. 1.20) $ d (k, k + 1/N) = abs(k - ( k + 1/N )) = 1/N < r, $ which means that $k+1/N in N_r (k)$. The desire is to construct a set that is bounded with exactly three limit points. We accomplish this by choosing the set $E$ such that $ E = E_1 union E_2 union E_3. $ Specifically, the limit points to $E$ are $1, 2, 3$ and $E_1, E_2, E_3$ are all bounded which makes $E$ bounded as well. #qed === Exercise 2.6 #quote(block: true)[Prove that $E'$ is closed. Prove that $E$ and $overline(E)$ have the same limit points. Do $E$ and $E'$ always have the same limit points? ] We first prove that $E'$ is closed. If $x$ is a limit point of $E'$ then for any neighborhood $N_r (x)$ with radius $r > 0$ there exists a $y in E'$ such that $y in N_r (x)$. It follows then that the distance is $d(x, y) = h$ for some real number $ 0 < h < r$. Since $y in E'$ we know that $y$ is a limit point of $E$. Hence, we can find a $z in E$ such that $z in N_(r-h) (y)$. We have that $ d(x, z) lt.eq d(x, y) + d(y, z) < h + r - h = r, $ which means that $z in N_r (x)$ so that $x in E'$. Next we show that $overline(E)$ and $E$ have the same limit points. If $x$ is a limit point of $overline(E)$, then since $overline(E) = E' union E$, it must be the case that $x$ is a limit point of $E'$ or $E$. Assuming $x$ is a limit point of $E$ leaves us with nothing to prove. So we suppose that $x$ is a limit point of $E'$ alone. We already have established that $E'$ is closed, and therefore $x in E'$. This directly implies that $x$ is a limit point of $E$ because the members of $E'$ are all limit points of $E$. Conversely, let $y$ be a limit point of $E$. Since $E subset overline(E)$, it follows that $y$ is a limit point of $overline(E)$. Lastly, we show that $E$ and $E'$ do not always have the same limit points. Let $E = { 1, 1/2, 1/3, 1/4, dots }$ and note that $0$ is the only limit point of $E$. This means that $E' = { 0 }$. We know by Corollary to Theorem 2.20 that $E'$ has no limit points. This shows the result by example. #qed === Exercise 2.7 #quote(block: true)[ Let $A_1, A_2, A_3,dots$ be subsets of a metric space. #enum( numbering: "(a)", enum.item[If $B_n = union_(i=1)^n A_i$, prove that $overline(B)_n = union_(i=1)^n overline(A)_i$.], enum.item[If $B = union_(i=1)^infinity A_i$, prove that $overline(B) supset union_(i=1)^infinity overline(A)_i$. Show, by an example, that this inclusion can be proper. ] ) ] (a) We first need to show that for any sets $A$ and $B$ it is true that $(A union B)' = A' union B'$. If $x in (A union B)'$, then for every neighborhood $N_r (x)$ with a radius $r > 0$ there exists at least one point $p in N_r (x)$ such that $p in A union B$. Thus, $p in A$ or $p in B$ which implies that $x in A'$ or $x in B'$ so that $x in A' union B'$. Suppose now that $x in A' union B'$, then for any neighborhood $N_r (x)$ with a radius $r > 0$ there is a point $p in N_r (x)$ such that $p in A$ or $p in B$. This means that $p in A union B$ and it follows that $x in (A union B)'$. We now turn to the question at hand. This will be a proof by induction. The base case for $n=1$ is clearly true. Assume the statement holds for $n$, then $ overline(B)_(n+1) =& overline( union.big_(i=1)^(n+1) A_i ) = overline( union.big_(i = 1)^(n) A_i union A_(n+1) ) = overline( B_n union A_(n+1) ) \ =& B_n union A_(n+1) union ( B_n union A_(n+1) )' \ =& B_n union B'_n union A_(n+1) union A'_(n+1) \ =& overline(B)_n union overline(A)_(n+1) = union.big_(i=1)^(n) overline(A)_i union overline(A)_(n+1) \ =& union.big_(i=1)^(n+1) overline(A)_i, $ where we have used the induction hypothesis in the penultimate equality. \ \ (b) If $x in union.big_(i=1)^infinity overline(A)_i$, then there is an $n in naturals$ such that $x in overline(A)_n$. We have that $ overline(B) = overline(union.big_(i=1)^infinity A_i) supset overline(union.big_(i=1)^n A_i) = union.big_(i=1)^n overline(A)_i supset overline(A)_n, $ where we used the result in (a) to get the second equality. This implies that $x in overline(B)$. Since $x$ is arbitrary it follows that $ overline(B) supset union.big_(i=1)^infinity overline(A)_i$ as desired. We shall conclude by showing that this subset can indeed be proper. Let $A_i = {1, 1/2, 1/3, dots, 1/i}$ and note that there exists no $k in naturals$ such that $0 in A_k$. Thus $0 in.not union.big_(i=1)^infinity A_i$. Furthermore, each set $A_i$ has no limit points which is why $overline(A)_i = A_i$, and therefore $union.big_(i=1)^infinity overline(A)_i = union.big_(i=1)^infinity A_i$. It follows then that $0 in.not union.big_(i=1)^infinity overline(A_i)$. Now let's consider $overline(B)$ $ overline(B) &= overline(union.big_(i=1)^infinity A_i) = overline( { 1, 1/2, 1/3, dots } ) = { 0, 1, 1/2, 1/3, dots }, $ which implies that $0 in overline(B)$. Since $0 in.not union.big_(i=1)^infinity overline(A_i)$ we've shown that the inclusion can be proper. #qed === Exercise 2.8 #quote(block: true)[Is every point of every open set $E subset reals^2$ a limit point of $E$? Answer the same question for closed sets in $reals^2$.] We first show that every point in every open set $E subset reals^2$ is a limit point of $E$. Suppose not. Then there exists an open set $E subset reals^2$ with a point $x in E$ that is not a limit point of $E$. It follows that there exists an $r > 0$ such that the neighborhood $N_r (x)$ contains no point of $E$ except $x$. Since $E$ is an open set, $x$ must be an interior point. Hence, there is a neighborhood with radius $s > 0$ such that $N_s (x) subset E$. Neighborhoods in $reals^2$ are non-empty interiors of circles, which means that $N_r$ is circle centered at $x$. Consider the cases for $r$ and $s$: + If $r > s$ then $N_s$ is a circle inscribed in a larger circle $N_r$. This implies $N_s subset N_r$. Consequently, there exists points $y in N_s subset N_r subset E$ where $y eq.not x$. However, this contradicts our assumption that $N_r (x)$ contains no points of $E$ other than $x$. + If $r lt.eq s$, then $N_r$ is inscribed in $N_s$. Given that $N_s$​ is non-empty circle such that $N_s subset E$, it follows that $N_s$ contains points of $E$ arbitrarily close to its center point $x$. In particular, for any distance $0 < d < r$, there are points $y in E$ where $y eq.not x$ such that $y in N_s$. Since $N_r subset N_s$, these $y$ must be a point of $N_r$ because $d < r$. This contradicts our assumption that $x$ is not a limit point of $E$. Since none of the relations $r < s$, $r = s$ and $r > s$ can be true, such an $r$ cannot exists. We've reached a contradiction and the assumption is wrong. Hence, each point of $E$ is a limit point of $E$. Now we show that the case does not hold true in general for closed sets. Consider the set of all natural numbers $naturals subset reals^2$. This set is closed, yet every point in this set is not a limit point of it. #qed === Exercise 2.9 #let interior(E) = $#E^circle.small$ #quote(block: true)[ Let $interior(E)$ be the set of all interior points of $E$. #enum( numbering: "(a)", enum.item[Prove that $interior(E)$ is always open.], enum.item[Prove that $E$ is open if and only if $interior(E) = E$.], enum.item[If $G subset E$ and $G$ is open, prove that $G subset interior(E)$.], enum.item[Prove that the complement of $interior(E)$ is the closure of the complement of $E$.], enum.item[Do $E$ and $overline(E)$ always have the same interiors?], enum.item[Do $E$ and $interior(E)$ always have the same closures?], ) ] (a) If $p in interior(E)$ then $p$ is an interior point of $E$. This means that there exists some neighborhood $N(p)$ with $r > 0$ such that $N(p) subset E$. By Theorem 2.19 $N(p)$ is an open set, implying that every point in $N(p)$ is an interior point. Hence, $N(p) subset interior(E)$ and it follows $interior(E)$ is an open set. \ \ (b) If $E$ is open then for every point $x in E$ we can find a neighborhood $N(x)$ with $r > 0$ such that $N subset E$. This implies that every point $x in E$ is an interior point of $E$ and it is therefore true that $x in interior(E)$. This shows that $E subset interior(E)$. Since by construction $interior(E) subset E$ we have that $interior(E) = E$. Conversely, if $interior(E) = E$ then it follows from (a) that $E$ is open. \ \ (c) If $G$ is open, then for every point $p in G$ we can find a neighborhood $N(p)$ with $r > 0$ such that $N(p) subset G$. Since $G subset E$, we have that $N(p) subset E$, which shows that $p$ is an interior point of $E$. Hence, $p in interior(E)$. Therefore, $G subset interior(E)$ since $p$ was arbitrary chosen from $G$. \ \ (d) Let $x$ be any point in $(interior(E))^c$. First we show that $(interior(E))^c subset overline(E^c)$. Suppose that $x in.not E$. Then $ x in E^c subset E^c union E^c' = overline(E^c). $ Now let $x in E$. Since $x$ is in the complement of $interior(E)$, we know that $x$ is not an interior point of $E$. Therefore, for every neighborhood $N(x)$ with radius $r > 0$, we have that $N(x) subset.not E$. This means that $N(x)$ always has points in $E^c$, which makes $x$ a limit point of $E^c$. Thus, $x in E^c' subset overline(E^c)$. This shows that $(interior(E))^c subset overline(E^c)$. Conversely, let $p in overline(E^c) = E^c union E^c'$ . Then it is clear that either $p in E^c$ or $p in E^c'$. Assume $p in E^c$. Then we know that $p$ is not an interior point to $E$, so $p in.not interior(E)$, which implies that $p in (interior(E))^c$. If $p in E^c'$, then it is a limit point of $E^c$, and therefore every neighborhood $N(p)$ with radius $r > 0$ have points (other than $p$) from $E^c$. Hence, there is no neighborhood such that $N(p) subset E$ which means that $p$ cannot be an interior point of $E$. Therefore, $p in (interior(E))^c$, and we have now shown that $overline(E^c) subset (interior(E))^c$. \ \ (e) Let $E = (0, 1) union (1, 2)$ be a set consisting of line segments in $reals$. Since $E$ is open we have that $interior(E) = E$ by (b). The set of limit points $E'$ is the closed interval $[0, 2]$, so the closure is $overline(E) = E union E' = [0, 2]$. From here we can see that $interior((overline(E))) = (0, 2)$, which shows that $ interior(E) eq.not interior((overline(E)))$. Therefore, $E$ and $overline(E)$ do not always have the same interiors. \ \ (f) Consider the set $E = {1/n | n = 1, 2, 3, dots}$ as subset of $reals$. Since $0$ is the only limit point of $E$, we have that its closure is $overline(E) = E union {0}$. However, none of the points in $E$ are interior points, and therefore $interior(E) = emptyset$. This means that $overline(interior(E)) = emptyset$ so that $overline(E) eq.not overline(interior(E))$. We have shown that $E$ and $interior(E)$ do not always have the same closures. #qed === Exercise 2.10 #quote(block: true)[Let $X$ be an infinite set. For $p in X$ and $q in X$, define $ d(p,q) = cases( 1 quad quad "(if" p eq.not q")", 0 quad quad "(if" p eq q")". ) $ Prove that this is a metric. Which subsets of the resulting metric space are open? Which are closed? Which are compact? ] We begin by showing that $d$ is a metric. Conditions 2.15 (a) and (b) are clearly satisfied. We show (c) also is true. Suppose $p eq.not q$ so that $d(p,q) = 1$. For any $r in X$ we have two cases, either $r$ equals one of $p$, $q$ or neither. Suppose WLOG that $r = p$. Then we have that $d(p,r) = 0$ and $d(r,q) = 1$. It follows that $ underbrace(d(p,q), = 1) lt.eq underbrace(d(p, r), =0) + underbrace(d(r, q), = 1) = 1. $ Now let $r eq.not p eq.not q$ be true. Then $d(p,r) = d(r,q) = 1$, and we can show that $ underbrace(d(p, q), =1) < underbrace(d(p, r), =1) + underbrace(d(r, q), =1) = 2. $ Lastly, if $p = q$ then $d(p, q) = 0$ and any point $r in X$ will satisfy (c) since the distance function is non-negative. This shows that $X$ is a metric with distance function $d$. We shall now show that any subset $E subset X$ is open. Let $p$ be any point in $E$ and consider the neighborhood $N_r (p)$ with radius $r = 1$. Given the metric, this neighborhood contains only $p$ itself so that $N_r (p) subset E$. Hence, every point in $E$ is an interior point and $E$ is open. We now show that every subset in $X$ is closed. Let $E$ be any subset of $X$. Since every subset of $X$ is open, the complement $E^c$ is also open. By Thm. 2.33 $E$ is closed. Lastly, we show that only finite sets of $X$ are compact (by Definition 2.32). Suppose not, then we have a compact set $K subset X$ that is infinite. For every $p in K$ let $G_p$ be the open neighborhood around $p$ with radius $r = 1$. Since every $p in K$ is associated with an open set $G_p$, the collection ${G_p}$ is an open cover of $K$. Because $K$ is compact, there exists a finite number of indices such that $ K subset G_(p_1) union dots.c union G_(p_m). $ Every subset $G_(p_n)$ is an open neighborhood around $p_n$ with radius $1$. From before we know that these sets only contain a single point, namely $p_n$. But that is absurd, since it would make $K$ finite. #qed === Exercise 2.11 #quote(block: true)[ For $x in reals$ and $y in reals$, define $ d_1(x, y)& = (x - y)^2, \ d_2(x, y)& = sqrt(abs(x-y)), \ d_3(x, y)& = abs(x^2 - y^2), \ d_4(x, y)& = (x - 2y), \ d_5(x, y)& = abs(x - y) / (1 + abs(x - y)). $ Determine, for each of these, whether it is a metric or not. ] $d_1$ Condition 2.15 (c) is not satisfied, which therefore is not a metric. We give an example, $ d_1(10, 0) > d_1(10, 4) + d_1(4, 0). $ \ $d_2$ Both 2.15 (a) and (b) are clearly true. We show that (c) is also satisfied. Assume not, then there exists points $x$, $y$ and $r$ such that $ d_2(x, y) > d_2(x, r) + d_2(r, y), $ which in this particular case is $ sqrt(abs(x-y)) > sqrt(abs(x-r)) + sqrt(abs(r-y)). $ If $0 < q < p$ then $q^2 < p^2$ for any $p, q in reals$ so that $ abs(x - y) &= sqrt(abs(x - y))^2 > (sqrt(abs(x-r)) + sqrt(abs(r-y)))^2 \ &= abs(x - r) + 2 sqrt(abs(x-r) abs(r-y)) + abs(r - y) \ &gt.eq abs(x - r) + abs(r - y), $ where the last inequality comes from the fact that $sqrt(abs(x-r) abs(r-y)) gt.eq 0$. The above shows that $d(p,q) = abs(p - q)$ cannot be a metric. But that is a contradiction, since Theorem 1.37 shows that $abs(p-q)$ satisfies 2.15 (c). Hence, $d_2$​ is a metric. \ \ $d_3$ Condition 2.15 (a) is not satisfied. We show an example $ d_3(2, -2) &= abs(2^2 - (-2)^2) = 4 - 4 = 0. $ We have found $x eq.not y$ such that $d_3(x, y) = 0$. This shows that $d_3(x, y)$ is not a metric. \ \ $d_4$ We show that $d_4$ is not a metric since condition (a) of Definition 2.15 is not satisfied. If $x eq.not 0$ then $ d_4(x, x) = |x - 2x| = |x| > 0. $ \ #let distfive(x, y) = $abs(#x)/(1 + abs(#y))$ #let distfivenoabs(x, y) = $#x/(1 + #y)$ $d_5$ Conditions in (a), (b) are clearly satisfied so we focus on (c). Throughout this exercise WLOG assume $x lt.eq y$. Suppose $x lt.eq r lt.eq y$, we have that $ d_5(x, y) &= distfive(x-y, x-y) = distfive(x-r + r-y, x-y) \ &lt.eq distfive(x-r, x-y) + distfive(r-y, x-y) \ &lt.eq distfive(x-r, x-r) + distfive(r-y, r-y) \ &lt.eq d_5(x, r) + d_5(r, y), $ where we used Theorem 1.37 in the first inequality. Since $x lt.eq r lt.eq y$ we know that $abs(x-r) lt.eq abs(x-y)$ and $abs(r-y) lt.eq abs(x-y)$, both of which we used to get the second inequality. Now assume $x lt.eq y < r$. First we show that for any $epsilon > 0$ #math.equation(block: true, numbering: "(1)")[ $ distfive(w, w) < distfivenoabs(abs(w)+epsilon, abs(w)+epsilon), $ ] <intermediate> holds. The statement is clearly true for $w=0$. If $|w| > 0$, then $ distfive(w, w) = distfivenoabs(1, 1/abs(w)) < distfivenoabs(1, 1/(abs(w) + epsilon)) = distfivenoabs(abs(w)+epsilon, abs(w)+epsilon), $ which shows that @intermediate is true. Since $x lt.eq y < r$, we have that $abs(x-y) < abs(x-r)$. This means we can use @intermediate to get the first inequality below, $ d_5(x, y) &= distfive(x-y, x-y) < distfive(x-r, x-r) \ &lt.eq distfive(x-r, x-r) + distfive(r-y, r-y) \ &= d_5(x, r) + d_5(r, y). $ The last inequality is due to the last term being non-negative. Similar argument can be made for $r < x lt.eq y$ because $abs(x-y) < abs(r-y)$ which allows us to use @intermediate again. This shows that $d_5(x,y)$ is a metric. #qed === Exercise 2.12 #quote(block: true)[ Let $K subset reals$ consist of 0 and the numbers $1 slash n$, for $n = 1, 2, 3, dots$ . Prove that $K$ is compact directly from the definition (without using the Heine-Borel theorem). ] Let ${G_alpha}$ be any open cover of $K$. Then we know that there is an index $alpha_0$ such that $0 in G_(alpha_0)$. Since $G_(alpha_0)$ is an open set, we know that there exists a neighborhood $N_r (0)$ with radius $r > 0$ where $N_r subset G_(alpha_0)$. If $r gt.eq 1$, then $G_(alpha_0)$ covers $K$ and there is nothing to prove. Assume therefore that $r < 1$. By Archimedean property of $reals$ we can find positive integers $p$ such that $r gt.eq 1 slash p$. Let $m$ be the smallest integer such that $r gt 1 slash m$. It follows that if $q$ is an integer where $q > m$, then $r > 1 slash q$ so that $1 slash q in N_r (0)$. This shows that there are at most $m-1$ points in $E$ that are not in $N_r$, $ 1/(m-1), 1/(m-2), dots, 1/2, 1. $ \ Let $G_(alpha_k)$ denote an open set in the collection ${G_alpha}$ such that $1 slash k in G_(alpha_k)$ $(k = 1, 2, 3, dots)$. Because ${G_alpha}$ is an open cover of $K$, each of the above $m-1$ points can be associated this way to at least one index (not necessarily distinct) in the collection. Therefore $ K subset G_(alpha_0) union G_(alpha_1) union dots.c union G_(alpha_(m-1)). $ We have shown that any open cover of $K$ has a finite sub-cover which implies that $K$ is compact as desired. #qed === Exercise 2.13 #quote(block: true)[Construct a compact set of real numbers whose limit points form a countable set.] Let $n$ be a natural number and construct a sequence ${x_k}$ as follows. Define $x_1$ as the midpoint between $1/(n+1)$ and $1/n$ $ x_1 = (1/(n+1) + 1/n) / 2. $ Having chosen $x_1, dots, x_(k-1)$ (for $k= 2, 3, 4, dots$), define $x_k$ as the midpoint between $x_(k-1)$ and $1/n$ $ x_k = (x_(k-1) + 1/n) / 2. $ Let $E_n$ be the set of all numbers generated by the sequence ${x_k}$, along with the point $1/n$. For example, if $n=1$ we have $ E_1 = { 1, 3/4, 7/8, 15/16, 31/32, dots}. $ Since the sequence ${x_k}$ is constructed by repeatedly taking midpoints between the previous term and $1/n$​, the sequence will approach the value $1/n$​, making it a limit point of $E_n$. We can show that any other point $y in reals$ such that $y eq.not 1 / n$ cannot be a limit point of $E_n$. Since $E_n$ is a countable set of values that approach $1/n$, there is a number $x_k eq.not y$ in $E_n$ that minimises $d(y, x_k)$. Then the neighborhood with $0 < r < d(y, x_k)$ will have no point of $E_n$ (other than possibly $y$). Hence, $1/n$ is the only limit point so that $ E'_n = {1 / n}$. The collection of sets ${E_n}$ is disjoint since $E_n subset (1/(n+1), 1/n]$. Let $S$ be the union of this collection along with the point $0$, $ S = {0} union union.big_(n=1)^infinity E_n subset [0, 1]. $ Since $S$ is a union of disjoint sets, the limit points of $S$ is given by $ S' = {0} union union.big_(n=1)^infinity E' = {0, 1, 1/2, 1/3, dots}, $ which is countable. Furthermore, because $E' subset E$ and $0 in S$ we see that $S' subset S$ so that $S$ is closed. Since $S$ is a subset of the compact interval $[0, 1]$, by Theorem 2.35 $S$ is compact. As desired, we have constructed a compact set $S$ of real numbers whose limit points $S'$ form a countable set. #qed === Exercise 2.14 #quote(block: true)[Give an example of an open cover of the segment $(0, 1)$ which has no finite sub-cover.] Let $G_n$ be the open set on the form $(1 slash n, 1)$ for any natural number $n$. The collection ${G_n}$ is an open cover of $(0, 1)$ $ union.big_(n=1)^infinity G_n = union.big_(n=1)^infinity (1 slash n, 1) = (0, 1). $ Choose finitely many indices $n_1, n_2, dots, n_m$ and let $p$ be the largest index among them. If $x$ is the midpoint between $0$ and $1/p$, then $x in.not G_p$. Since $G_(n_k) subset G_p$ ($k=1, 2, dots, m$) we see that $ x in.not G_(n_1) union G_(n_2) union dots.c union G_(n_m), $ yet clearly $x in (0, 1)$. This shows that the union constructed with indices $n_k$ ($k=1, 2, dots, m)$ cannot be a sub-cover of $(0, 1)$. The choice of indices were arbitrary, therefore there does not exist a finite sub-cover of $(0, 1)$ using the open cover ${G_n}$. #qed === Exercise 2.15 #quote(block:true)[Show that Theorem 2.36 and its Corollary become false (in $reals$, for example) if the word "compact" is replaced by "closed" or by "bounded."] We first show that "compact" cannot be replaced by closed. Consider the set of natural numbers starting from the positive integer $n$ and beyond $ E_n = {n, n+1, n+2, dots}. $ Each set in the collection ${E_n}$ is closed relative to $reals$ and is unbounded. Since we have that $E_n supset E_(n+1)$ ($n = 1, 2, 3, dots$) any intersection of a finite sub-collection of ${E_n}$ is non-empty. However, the countable intersection $ E = sect.big_(n=1)^infinity E_n, $ is empty. To see this, note that for any natural number $m$ we have that $m in.not E_n$ whenever $m < n$. Hence, there exists no natural number $m$ which belongs to all sets in the collection ${E_n}$ and it follows that the intersection is empty. Now we show that the word "compact" cannot be replaced by "bounded." Let $A_n$ be the set that consists of numbers $ A_n = { 1/n , 1/(n+1), 1/(n+2), dots }. $ This set is bounded by $1$ and is not closed since it does not contain its limit point $0$. We also have that $A_n supset A_(n+1)$ for $n=1, 2, 3, dots$ and hence any intersection of a finite sub-collection will be non-empty. The countable intersection $ A = sect.big_(n=1)^infinity A_n, $ is, however, empty. This can be proven with similar argument as for why the intersection $E$ is empty. We have shown that the word "compact" cannot be replaced by "bounded." #qed === Exercise 2.16 #quote(block: true)[Regard $rationals$, the set of all rational numbers, as a metric space, with $d(p,q) = |p - q|$. Let $E$ be the set of all $p in rationals$ such that $2 < p^2 < 3$. Show that $E$ is closed and bounded in $rationals$, but that $E$ is not compact. Is $E$ open in $rationals$?] We begin with showing that $E$ is bounded. If $2 < p^2 < 3$ then $1 < abs(p) < 2$, and indeed we see that $E$ is bounded. To show that $E$ is closed, consider any rational number $q in.not E$. If $q^2 < 2$ then for any $p in E$ $ abs(q^2-2) &< abs(p^2 - q^2) = abs((p+q)(p-q)) \ &lt.eq abs(p+q) abs(p-q) lt.eq (abs(p) + abs(q)) abs(p-q) \ &lt 4 abs(p-q), $ which shows that $ 0 < abs(q^2 - 2) / 4 lt abs(p-q)$. Hence, any neighborhood with radius $abs(q^2 - 2) / 4$ would contain no point of $E$. If $q^2 > 3$ then $ abs(q^2 - 3) &< abs(q^2 - p^2) = abs((q+p)(q-p)) \ &lt.eq (abs(p) + abs(q)) abs(p-q) \ &lt 2abs(q) abs(p-q). $ Similarly, it follows that any neighborhood around $q$ with radius $abs(q^2 - 3) / (2 abs(q))$ contains no point of $E$. This shows that any $q in.not E$ cannot be a limit point of $E$ and hence $E$ must be closed. To prove that $E$ is not compact in $rationals$, it suffices by Theorem 2.33 to show that $E$ is not compact in $reals$. First, note that $E$ is not closed in $reals$ because it does not contain all of its limit points. In particular, $sqrt(2)$ is an irrational number that is a limit point of $E$ but not a member of the set. Therefore, by Heine-Borel's theorem (Theorem 2.41) $E$ cannot be compact in $reals$. Lastly, we answer the question if $E$ is open in $rationals$. Consider the open intervals $A = (-sqrt(3), -sqrt(2))$ and $B = (sqrt(2), sqrt(3))$ in $reals$. Put $G = A union B$ and note that by Theorem 2.24 $G$ is open in $reals$. Since $E = rationals sect G$, it follows by Theorem 2.30 that $E$ is open in $rationals$. #qed === Exercise 2.17 #quote(block: true)[Let $E$ be the set of all $x in [0, 1]$ whose decimal expansion contains only the digits $4$ and $7$. Is $E$ countable? Is $E$ dense in $[0, 1]$? Is $E$ compact? Is $E$ perfect?] That $E$ is not countable can be shown using Cantor's diagonal process. Simply exchange $0$, $1$ with $4$, $7$ respectively in Theorem 2.14 and its proof. Alternatively, if we can show that $E$ is perfect then by Theorem 2.43 $E$ is uncountable. $E$ is not dense in $[0, 1]$ since $0$ is neither a limit point of $E$, nor a point of $E$. Since $E subset [0, 1]$ we know it is a subset of a compact set by Theorem 2.40. According to Theorem 2.35, it suffices to show that $E$ is closed to prove that $E$ is compact. Suppose $x in.not E$ and write the decimal expansion of $x$ using the notation from Section 1.22, $ x_0 dot x_1 x_2 x_3 dots $ Recall that $x_0$ is the largest integer such that $x_0 lt.eq x$. We will show that for any $p in E$ the distance $d = abs(x - p)$ cannot be less than $2 dot.c 1 / 10^(n+1)$. Since $x in.not E$ there exists a first integer $n$ such that $x_n$ is neither $4$, nor $7$. Let $p$ be a point of $E$ that has the same decimal expansion as $x$ up to $n$ $ p = 0 dot p_1 p_2 p_3 dots, $ so that $p_k = x_k$ for $k = 1, 2, dots, n - 1$ and $abs(x_n - p_n) gt.eq 1$. It is clear that any other choice of decimals up to $n$ for $p$ would make the distance to $x$ larger. Note that $x_0 = 0$ for otherwise $d gt.eq 0.222 dots$ which is larger than $2 dot.c 1 / 10^(n+1)$. No matter how we choose the rest of the decimals $p_i$, where $i > n$, the distance $d = abs(x - p)$ cannot be less than $2 dot.c 1 / 10^(n+1)$. For if $abs(x_n - p_n) = 1$ and we borrow from it when calculating $d$, then we see that $ abs(min(x_(n+1), p_(n+1)) + 10 - max(x_(n+1), p_(n+1))) gt.eq 3. $ If we would need to borrow from decimal n+1:th place at some later point during our calculations of $d$, then the n+1:th decimal place of $d$ would be $2$. Since we can borrow at most once from any decimal place when calculating $d$, we have that $ d = abs(x - q) gt.eq 2 dot.c 1 / 10^(n+1) $ for any $q in E$. Therefore, any neighborhood $N(x)$ with radius $r = 1 / 10^(n+1) < d$ would contain no point of $E$. Hence, $E$ must be closed and it follows by Theorem 2.35 that $E$ is compact. Now we prove that $E$ is perfect. Since we already have shown that $E$ is closed, we need only to show that no point of $E$ is isolated. For any $q in E$ let $N(q)$ be some neighborhood around $q$ with radius $r >0$. Choose any integer $k > 0$ such that $3 dot.c 10^(-k) < r$. Suppose $p$ is a number with the exact same decimal expansion as $q$ except at decimal place $k$, for which we choose either $4$, or $7$ such that $p_k eq.not q_k$. Clearly, $p in E$ and we have that $ abs(p - q) & = abs(p_k - q_k) dot.c 10^(-k) = 3 dot.c 10^(-k) < r. $ Thus, $q$ is a limit point of $E$ and we have shown that $E$ is perfect. #qed === Exercise 2.18 #quote(block: true)[Is there a nonempty perfect set in $reals$ which contains no rational number?] Let $E$ be the set from Exercise 2.17. This set is a nonempty perfect set in $reals$ that contains rational numbers. We want to find a number $y$ such that for every $x in E$ the sum $x + y$ is irrational. Then the set of irrational numbers given by $ P = { x + y | x in E} $ is perfect. This is due to the fact that the relationships between any points in $E$ are preserved after having moved them all by the same amount $y$. We construct a number $y= 0 dot y_1 y_2y_3 dots $ using only the digits $0$ and $1$. Here we use the notation defined in Section 1.22. The decimals are chosen to be $1$s that are spaced by $0$s. Specifically, starting with one space of $0$ between the first and second $1$, then two $0$s between the second and third $1$, and so on. Below we write the first few digits of the infinite decimal expansion for this number $ y = 0.101001000100001000001000000100000001000000001000 dots $ Intuitively, this number is irrational since it is a non-terminating decimal number that does not contain any repetitions. We can prove this more formally. Suppose that $y$ is rational. Since $y$ has infinite decimals it must be a repeating decimal. Let $i$ be the first index of the decimal where repetition starts and let $rho$ be the length of the period. Hence, for any natural number $k gt.eq i$ it must be true that $x_k = x_(k+m rho)$ for any positive multiple integer $m$ of $rho$, otherwise the decimals would not be repeating. Since $1$ is in the decimal expansion of $y$, we know that there exists some natural number $j gt.eq n$ such that $x_j = 1$. We have that $ x_j = x_(j+rho) = x_(j + 2rho) = 1. $ This means that the spacing between $1$ is constant $rho$, which contradicts the assumption about $y$ and hence $y$ is irrational. Now that we have shown that our $y$ is irrational, we need only to prove that for any $x in E$ the number $z = x + y$ is also irrational. Since both $x$ and $y$ are irrational, and cannot be added in such a way to get a terminating decimal expansion, we see that the decimals of $z$ are infinite. There are two cases we need to verify, whether $x$ is rational or not. If we assume that $x$ is rational, then by Exercise $1.1$ the sum $x + y$ is irrational. Assume therefore that $x$ is irrational. Suppose, to get a contradiction, that the sum $z = x + y$ is rational. Since $z$ is rational with an infinite decimal expansion, it follows that $z$ has a repeating decimal. Let $sigma$ be the length of the repetition and $z_i$ the first decimal where the repetition starts. Take any natural number $k gt.eq i$ such that $y_k = 1$. Since the number of zeros between the $1$s in $y$ are increasing, we know that we can find a natural number $b$ such that $y_(k + b sigma) = 0$. Now we use the fact that $z$ repeats after the $i$-th place $ z_k = x_k + y_k = x_(k + b sigma) + y_(k + b sigma). $ Plugging in the values for $y_k$ and $y_(k + b sigma)$ we get the following expression that must be satisfied #math.equation(block: true, numbering: "(1)")[ $ x_k + 1 = x_(k + b sigma). $ ] <2.17-rel> Since $x in E$ we know that each decimal of $x$ is either $4$ or $7$. However, the relation @2.17-rel cannot be satisfied using any combination of these two digits, and therefore $z$ cannot be a repeating decimal. This contradicts our assumption about $z$ and the sum $z = x + y$ is thus irrational for every $x in E$. We have shown that $P$ is a nonempty set of irrational numbers that is perfect as desired. #qed === Exercise 2.19 #quote(block: true)[ #enum( numbering: "(a)", enum.item[If $A$ and $B$ are disjoint closed sets in some metric space $X$, prove that they are separated.], enum.item[Prove the same for disjoint open sets.], enum.item[Fix $p in X$, $delta > 0$, define $A$ to be the set of all $q in X$ for which $d(p, q) < delta$, define $B$ similarly, with $>$ in place of $<$. Prove that $A$ and $B$ are separated.], enum.item[Prove that every connected metric space with at least two points is uncountable. _Hint_: Use (c).], ) ] (a) If $A$ and $B$ both are closed, then by Theorem 2.27 we have that $overline(A) = A$ and $overline(B) = B$. Therefore $ A sect overline(B) = overline(A) sect B = A sect B = emptyset, $ since $A$ and $B$ are disjoint. \ \ (b) We prove that the set $A sect overline(B)$ is empty. If $p in B'$, then for every radius $r > 0$ the neighborhood $N_r (p)$ contains points from $B$. Hence, $N(p) subset.not A$ and $p$ is not an interior point of $A$. Because $A$ is open, by definition 2.18 (f) every point of $A$ is an interior point. It follows that $p in.not A$ and therefore $A sect B' = emptyset$. Since $A$ and $B$ are disjoint we have that $A sect overline(B) = emptyset$. With the same argument we can establish that $overline(A) sect B = emptyset$. This show that $A$ and $B$ are separated. \ \ (c) By definition 2.18 (a) and Theorem 2.19 $A$ is open. Now consider the complement of $B$. This set $B^c$ contains all numbers $q$ such that $d(p, q) lt.eq delta$. But this is exactly the closure of $A$, that is $B^c = overline(A)$. The complement to $B$ is therefore closed and by Theorem 2.23 $B$ is open. The sets $A$ and $B$ are disjoint. For otherwise there exists some point $q in A sect B$ such that $d(p, q) < delta$ and $d(p, q) > delta$, which is absurd. We have shown that $A$ and $B$ are disjoint open sets, hence they are separated using the result in (b). \ \ (d) We prove the contrapositive. Let $X$ be at most countable and arrange the elements in a sequence ${q_n}$. If $X$ has less than two points, then $X$ is connected since at least one of the sets $A$ or $B$ will be empty. Hence, assume $X$ has two or more points. Fix any $p in X$ and enumerate all distances from this point. #figure( table( stroke: none, columns: 1, $d(p, q_1) = d_1$, $d(p, q_2) = d_2$, $dots.v$, ) ) Using Cantor's diagonal process we can construct a real number $delta > 0$ such that $d(p, q_n) eq.not delta$ for all $n in naturals$. We do so in the following manner. Let the $n$-th decimal of $delta$ be the $n$-th decimal of $d_n$ that we increment by $1$ if $d_n$'s $n$-th decimal is less than $9$, otherwise we decrement by $1$. Lastly, we set the integer part of $delta$ to $1$. This procedure will create a non-negative real number $delta > 0$ that is different to distance $d_k$ in the $k$-th decimal. Hence, there are no points $q in X$ such that $d(p, q) = delta$. Due to this we can write $X$ in terms of the sets $A = {q in X | d(p, q) < delta}$ and $B = {q in X | d(p, q) > delta}$, $ X = A union B. $ By the result in (c) we have that $A$ and $B$ are separated. It follows therefore that $X$ is not connected. #qed === Exercise 2.20 #quote(block: true)[Are closures and interiors of connected sets always connected? (Look at subsets of $reals^2$.)] We prove that closures of connected sets are always connected. Let $E$ be a connected subset of a metric space $X$. If $E$ is closed, then by Theorem 2.27 we have that $closure(E) = E$ and it follows that $closure(E)$ is connected. Assume therefore that $E$ is not closed. Suppose, for the sake of getting a contradiction, the opposite. Then there exists non-empty separated sets $A$ and $B$ such that $closure(E) = A union B$. Since $E$ is connected, one of the intersections $E sect A$ or $E sect B$ must be empty. For otherwise either $A sect closure(B)$ or $closure(A) sect B$ would be non-empty, because each of these sets would contain parts of the connected set $E$. And this would contradict the fact that $closure(E)$ is not connected. Without loss of generalization assume that $E subset A$. Now consider the non-empty set $B$. Since $E subset A$ and is disjoint with $B$, there exists at least one point $p$ such that $p in E' sect B$. Because $E' subset closure(A)$ this would mean that $p in closure(A) sect B$ so that this intersection is non-empty. But this is a contradiction since we assume that $closure(E)$ is not connected. Hence, closures of connected sets are always connected. We now turn our attention to interiors of connected sets and show by example that they are not always connected. Let $A = {(x, y) in R^2 | x > 0}$ and $B = {(x, y) in R^2 | x < 0}$. These are disjoint open sets and are separated by Exercise 19 (b). If $E = A union B union {bold(0)}$, then $E$ is connected. To see this, note that any partition of $E$ into two subsets $F$ and $G$ would contain points from $A$. The only way to make sure the intersections $F sect closure(G)$ and $closure(F) sect G$ are non-empty would be to ensure that $A sect F$ or $A sect G$ is empty. This is because $A$ is connected (the same applies for $B$). Therefore, assume without loss of generalization that $A subset F$ and $B subset G$. Finally, because $bold(0)$ is a limit point to both $A$ and $B$, no matter where we put this point in $F$ or $G$, we see that exactly one of the intersections $F sect closure(G)$ or $closure(F) sect G$ would be non-empty. And so, $E$ is connected. Now consider the interior of $E$. The point $bold(0)$ is not an interior point of $E$ and so $interior(E) = A union B$. As we know from before $A$ and $B$ are separated. Therefore, interiors of connected sets are not always connected. #qed === Exercise 2.21 #quote(block: true)[ Let $A$ and $B$ be separated subsets of some $reals^k$, suppose $bvec(a) in A$ and $bvec(b) in B$, and define $ bvec(p)(t) = (1-t) bvec(a) + t bvec(b) $ for $t in reals$. Put $A_0 = bvec(p)^(-1)(A)$, $B_0 = bvec(p)^(-1)(B)$. [Thus $t in A_0$ if and only if $bvec(p)(t) in A$.] #quote(block: true)[ #enum( numbering: "(a)", enum.item[Prove that $A_0$ and $B_0$ are separated subsets of $reals$.], enum.item[Prove that there exists $t_0 in (0,1)$ such that $bvec(p)(t_0) in.not A union B$.], enum.item[Prove that every convex subset of $reals^k$ is connected.] ) ] ] #enum( numbering: "(a)", enum.item[Assume the opposite, then at least one of the intersections $A_0 sect closure(B_0)$ or $closure(A_0) sect B_0$ is nonempty. Assume that exists a point $t in A_0 sect closure(B_0)$. Since $t in A_0$ it follows that $bvec(p)(t) in A$. Hence, $bvec(p)(t) in.not B$ because $A$ and $B$ are separated, and we can conclude that $t in.not B_0$. It must be therefore true that $t$ is a limit point of $B_0$, that is $t in A_0 sect B'_0$. Let $N$ be a neighborhood around $bvec(p)(t)$ with radius $r > 0$. Since $t$ is a limit point of $B_0$, we can find a point $t' in B_0$ such that the distance $d(t, t') < r / abs(bvec(a) - bvec(b))$. As for the points $bvec(p)(t')$ and $bvec(p)(t)$, the distance between them is $ abs(bvec(p)(t') - bvec(p)(t)) &= abs((1-t') bvec(a) + t' bvec(b) - (1-t) bvec(a) - t bvec(b)) \ &= abs((t-t') bvec(a) - (t-t') bvec(b)) \ &lt.eq abs(t' - t) dot.c abs(bvec(a) - bvec(b)) \ &< r / abs(bvec(a) - bvec(b)) dot.c abs(bvec(a) - bvec(b)) \ &< r, $ which implies that $bvec(p)(t)$ is a limit point of $B$. This means that $bvec(p)(t) in A sect closure(B)$. And similarly, it can be shown that $bvec(p)(t) in closure(A) sect B$ if $ t in closure(A_0) sect B_0$ is nonempty. But this is a contradiction since $A$ and $B$ are separated. \ \ ], enum.item[ Suppose not, then $bvec(p)(t) in A union B$ whenever $t in (0, 1)$. Since $A_0$ and $B_0$ are separated, the interval $(0, 1)$ belongs to either $A_0$ or $B_0$ exclusively. For otherwise, $(0, 1)$ would be a connected set that is also a union of two nonempty separated sets $(0,1) sect A_0$ and $(0,1) sect B_0$, which is absurd. If we assume that the intersection $(0, 1) sect A_0$ is empty, then $(0, 1) subset B_0$. Since $0 in A_0$ and is a limit point of $(0, 1)$, we would get that $closure(A_0) sect B_0 eq.not emptyset$. But this is a contradiction since $A_0$ and $B_0$ are separated. If we assume that the intersection $(0, 1) sect B_0$ is empty, then similarly $A_0 sect closure(B_0) eq.not emptyset$ since $1 in B_0$ would be a limit point of $A_0$. We have exhausted all possibilities and have seen that they lead to contradiction. Hence, our initial assumption must be wrong and therefore there must exist a $t_0 in (0, 1)$ such that $bvec(p)(t_0) in.not A union B$. \ \ ], enum.item[Assume the opposite, and let $E$ be a convex subset of $reals^k$. Then there exists two nonempty separated sets $A$ and $B$ such that $E = A union B$. Take any two points $bvec(a) in A$ and $bvec(b) in B$, then put $ bvec(p)(t) = (1-t) bvec(a) + t bvec(b). $ By the result in (b) we know that there is a number $t_0 in (0, 1)$ such that $bvec(p)(t_0) in.not A union B$, which means that $bvec(p)(t_0) in.not E$. But this is a contradiction since $E$ is supposed to be convex and no such $t_0$ should exist (see Definition 2.17). #qed ], ) === Exercise 2.22 #quote(block: true)[A metric space is called _separable_ if it contains a countable dense subset. Show that $reals^k$ is separable. _Hint:_ Consider the set of points which have only rational coordinates.] From Theorem 1.20 (b), we know that $rationals$ is dense in $reals$ and that every point of $reals$ is a limit point of $rationals$. We shall show that the set of points which have only rational coordinates $rationals^k$ is a countable dense subset of $reals^k$. That $rationals^k$ is countable follows from Theorem 2.13, simply put $A = rationals$ and $B_k$ will be the set of all points with rational coordinates with $k$-dimensions. It remains to show that any point of $reals^k$ is a limit point of $rationals^k$. Fix $bvec(x) in reals^k$ and let $N$ be a neighborhood around $bvec(x)$ with some chosen radius $r > 0$. Since $rationals$ is dense in $reals$, for every coordinate $x_i in reals$ we can choose rational number $p_i in rationals$ such that the $abs(p_i - x_i) < r / sqrt(k)$. Having done so for $1 lt.eq i lt.eq k$, we can construct the rational number $ bvec(p) = (p_1, p_2, dots, p_k) in rationals^k. $ Consider now its distance to $bvec(x)$ $ abs(bvec(p) - bvec(x)) &= sqrt(sum_(i=0)^k (p_i - x_i)^2) &lt.eq sqrt(sum_(i=0)^k abs(p_i - x_i)^2) & lt sqrt(k dot.c r^2/ k) &= r, $ which means that $bvec(p) in N$, and therefore $bvec(x)$ is a limit point of $rationals^k$. Since the choice of $bvec(x)$ was arbitrary, it follows that every point of $reals^k$ is a limit point of $rationals^k$. This proves that $rationals^k$ is a countable dense subset of $reals^k$, and it follows by definition that $reals^k$ is separable. #qed === Exercise 2.23 #quote(block: true)[A collection ${V_alpha}$ of open subsets of $X$ is said to be a _base_ for $X$ if the following is true: For every $x in X$ and every open set $G subset X$ such that $x in G$, we have $x in V_alpha subset G$ for some $alpha$. In other words, every open set in $X$ is the union of a sub-collection of ${V_alpha}$. Prove that every separable metric space has a _countable_ base. _Hint:_ Take all neighborhoods with rational radius and center in some countable dense subset of $X$.] Since $X$ is separable, it contains a countable dense subset $E$. For every $p in E$ let $W_p$ consists of all neighborhoods with non-negative rational radius $h > 0$ $ W_p = {N_h (p) | h in rationals, h > 0 }. $ Each member of $W_p$ is associated with exactly one non-negative rational radius. This means that $W_p$ is countable. By the Corollary to Theorem 2.12 the union $ V = union.big_(p in E) W_p $ is also countable. Hence, the members of $V$ can be arranged in a sequence ${V_alpha}$ where each $alpha$ is a member of some countable set. It remains to be shown that the collection of open sets ${V_alpha}$ is a base. Let $x$ be any point of $X$ and $G$ be any open subset of $X$ such that $x in G$. Since $x$ is an interior point of $G$, we know that there exists a radius $r > 0$ such that the neighborhood $N_r (x) subset G$. $E$ is dense in $X$ and therefore we can find a point $p in E$ such that the distance $d(p, x) = delta < r / 2$. Since $rationals$ is dense in $reals$, there exists a $h in rationals$ such that $delta < h < r / 2$ by Theorem 1.20. For this $p$ and rational radius $h$ there exists a neighborhood $V_alpha$ in the collection. Because the distance $d(x, p) = delta < h$ we have that $x in V_alpha$. In fact, for any point $y in V_alpha$ we have that $ d(y, x) & lt.eq d(y, p) + d(p, x) lt h + delta < 2 dot.c r / 2 = r, $ which implies $y in N_r (x)$ and therefore $V_alpha subset N_r (x)$. Since the choice of $x$ and $G$ were arbitrary it follows that the collection ${V_alpha}$ is a countable base of $X$. #qed === Exercise 2.24 #quote(block: true)[ Let $X$ be a metric space in which every infinite subset has a limit point. Prove that $X$ is separable. _Hint:_ Fix $delta > 0$, and pick $x_1 in X$. Having chosen $x_1, dots, x_j in X$, choose $x_(j+1) in X$, if possible, so that $d(x_i, x_(j+1)) gt.eq delta$ for $i = 1, dots, j$. Show that this process must stop after a finite number of steps, and that $X$ can therefore be covered by finitely many neighborhoods of radius $delta$. Take $delta = 1/n$ ($n=1, 2, 3, dots$), and consider the centers of the corresponding neighborhoods. ] We begin by showing that the process in the hint must stop after a finite number of steps. Assume the opposite to get a contradiction. Then the process never stops and the set of the chosen points $ A = {x_1, x_2, x_3, dots} $ is infinite. By construction of $A$ it is true that for any two points $x_n, x_m in A$ such that $m eq.not n$, the distance is $d(x_m, x_n) gt.eq delta$. This implies that no point of $A$ is a limit point of $A$. Let $y$ be a point in the complement of $A$. If $y$ is such that $d(y, x_i) = r < delta / 2$ for some $x_i in A$, then for any natural number $j eq.not i$ we have that $ d(x_j, x_i) lt.eq d(x_j, y) + d(y, x_i) lt d(x_j, y) + delta slash 2 $ which after rearranging $ d(x_j, y) gt d(x_j, x_i) - delta slash 2 gt.eq delta - delta slash 2 = delta slash 2. $ Hence, the neighborhood with center in $y$ and radius $h < r$ would contain no point of $A$. But this is absurd, since that would make $A$ an infinite subset of $X$ that has no limit point.
https://github.com/Nianyi-GSND-Projects/GSND-5130-GP1
https://raw.githubusercontent.com/Nianyi-GSND-Projects/GSND-5130-GP1/master/Thesis/Thesis.typ
typst
#let figureplaceholder(height) = box( width: 100%, height: height, stroke: black, )[ #set align(center + horizon) placeholder ] #set page(paper: "us-letter", margin: 0.8in) #set par(justify: true) #show quote: set text(style: "italic") #show quote: set pad(top: -1em, bottom: -0.5em) #set quote(block: true, quotes: true) #set text(font: "Times New Roman") #set heading(numbering: "1.1.1") #show heading.where(level: 2): set heading(numbering: none) #show heading.where(level: 3): set heading(numbering: none) #let heading1size = 15pt; #let resetheadingsize() = { show heading.where(level: 1): set text(size: heading1size); } #resetheadingsize(); #set cite(style: "alphanumeric") #show link: set text(size: 0.9em, font: "Consolas") #let title = [Examining "2-week Minecraft Phase": The Cyclical Engagement Patterns in Sandbox Gaming] #{ set align(left); set text(size: 19pt, weight: "bold"); v(1em); title; } #{ set align(center); let author(name: "", mail: "") = { h(0.5em); box()[ #text(style: "italic")[#name] #parbreak() #link("mailto:" + mail)[#mail] ]; h(0.5em); } author( name: [<NAME>], mail: "<EMAIL>", ); author( name: [<NAME>], mail: "<EMAIL>", ); author( name: [<NAME>], mail: "<EMAIL>", ); } #heading(numbering: none)[Abstract] The 2011 video game, _Minecraft_, has sparked a craze across the globe. Due to its nature as a sandbox game, _Minecraft_ offers players extensive creative liberties to build their dream world. However, a peculiar yet common phenomenon is observed among many _Minecraft_ players: A cyclical pattern of fatigue with the worlds they are currently playing, usually within a range of 2 weeks. This phenomenon, colloquially referred to as the "2-week Minecraft phase", remains largely unstudied in academic literature. To investigate this occurrence, we conducted a pilot survey among Minecraft players to assess its prevalence. Subsequent in-depth interviews were conducted with representative samples to gather more nuanced insights. The final analysis reveals the distribution and underlying causes of this phenomenon. Our study examines the "2-week Minecraft phase" from psychological and social aspects, providing valuable insights for game developers seeking to enhance long-term player engagement and satisfaction. *Keywords:* Minecraft, Game psychology, Cyclical engagement pattern #v(1em) // #outline() // #pagebreak() #columns(2)[ = Introduction _Minecraft_, the video game released by the Swedish game company _Mojang Studios_ in 2011, has achieved a great success in the global game market. Being a sandbox game, its internal freedom grants the players unlimited possibilities to build their dream world virtually. Starting from the most basic element of the game, blocks, countless styles of game play have been adopted by players of all kind. Because the game mechanic itself doesn't limit players' actions, players could have full control of what they would do in a game world. Although a highly free mechanic would theoretically allow unlimited playing with in a single game world, many _Minecraft_ players would usually experience a boredom towards the world they're currently playing, then either stop playing the game or turn to a new world, leading to a cyclical engagement pattern. This experience is shared by players from worldwide, but hasn't been discussed widely in the public. In March 2024, user "Legitimate-Bath-9651" made a post on _Reddit_ @Leg24, stating the experience publicly and giving five possible reasons behind this cyclical fatigue: - Novelty: Players like the freshness of participating in new worlds, so the motivation is lost when a world gets old. - Direction: The unsatisfied requirements (like mining, building a shelter) push players to play; when the game comes to the ending stage, all requirements are either fulfilled or automated, so players become aimless. - Attrition (multiplayer): When a player stops playing, more players would tend to follow. - Activity difference (multiplayer): Players at different engagement level would have different developing pace. Slower players may feel detached with the rest of the world. - Differences in goals/directions (multiplayer): Players having different ideas for progression may drift away from each other, eventually losing motivation to play as a part of the world. The post has lit up a mild but not strong discussion among other _Reddit_ users, sharing their views and solutions on/to the experience. In the title of the post, the phrase _"2-week Minecraft Phase"_ is used. It is necessary to mention that this is not the first time the phrase _"Minecraft Phase"_ has appeared on the Internet. Earlier in February 2023, user "gawkgawkcumsock" has created the entry _"minecraft phase"_ on _Urban Dictionary_ @gaw23, but its meaning was defined as _"the annual 2 week phase of the minecraft grind that most people find themselves stuck in"_, a bit off from the definition in the later _Reddit_ post. Back to an even earlier stage of years ago, the exact same phenomenon has been brought up occationally on the _Minecraft_ _subreddit_, but without the now-coined term. Later in July 2024, _YouTube_ content creator "niko" made video with title _"The 2 Week Minecraft Phase Explained"_ @nik24. The title is somehow ambiguous, as the video only explained _what_ is the _2-week Minecraft Phase_, but not _why it occurs_. The video became a hit, furtherly pushing the concept to a wider range of the _Minecraft_ community. By the end of September 2024, the video has gained over 1.3M clicks. Data from _Google Trends_ (@fig:google-trend-data) shows that starting from September 2024, the phenomenon has gone into the public's eyesight. #figure( placement: top, outlined: true, image("images/google-trends.jpg"), caption: [Search count of _"Minecraft Phase"_ over a month in the United States according to _Google Trends_.] ) <fig:google-trend-data> = Related Work === General Psychology The fatigue of players' towards a certain video game is nothing new to the academical community. _Bikas et al._'s work @BPDM22 has stated clearly that for most recreational activities, the physical fatigue caused by prolonged execution and the lacking of proper rest are usually not the cause of people quitting. They furtherly stated that it is more of psychological factors. One of the earliest research studying video game fatigue from a psychological approach was in 2007, where _Lee et al._ conducted a series of interviews on the reasons of players in Taiwan quitting MMORPGs @LYL07. They concluded that the psychological factors that cause a player to quit a video game are never one-dimensional. However, their research addresses the topic more as a problem of video game addiction that needs to be solved, instead of treating it as an objective phenomenon. Str<NAME> Verhagen's work @SV18 has traced a group of players playing an AAA video game for 20 hours, and has done longitudinal case studies to invesigate the change on their experience towards the game. They then concluded several retention inhibiting factors that could be used in game designs to prevent early drop-off. Their study provided valuable insights for designing more attractive games, but the playing manner they chose to study appears to be short-ranged for normal game players. Although there are indeed many heavy players who could bear with a video game for more than 20 continuous hours, but that is not what the majority of the player group would do. Especially among child players, the median of the play time could be at the level of one or two hours per day @MCG18. === Story-telling It is well known that storytelling is a powerful element of video games, as addressed in Schell's book _The Art of Game Design: A Book of Lenses_ @Story. _<NAME>_ has proposed this very intuitive point in the book _The Digital Gaming Handbook_: #quote(block: false)[Once players 'get the good ending', they are unlikely to have much, if any, motivation to replay. Story-focused games, as opposed to more abstract games, tend to be seen as having limited replay value.] @Ale20 _Minecraft_, although being a sandbox game, does feature a "main story line". That is, to enter the _End_ and slay the _Enderdragon_. Even more, _Minecraft_'s native _hardcore_ mode features a "perma-death" (permanent-death) style of gameplay. In Keogh's work in 2013, they stated that by adding this "perma-death" feature, the game's narrative weight is increased, leading to a more influential story-telling @Keo13. With all these being said, due to its freedom on the mechanisms as a sandbox game, there could be so many different play styles that player could freely choose. As a result, players don't really have to follow the official story line @o2016building. Therefore, we need to explore topics beyond just story-telling. === Our Work In this research, we want to focus on the engagement pattern towards _Minecraft_ that lasts at least _week-long_ and is cyclical. Also, we want to explore a wider possibilities of the factors that may affect players' experience throughout the engagement cycle. Following Creswell's guidance on selecting the research approach @creswell2017research, we decided to conduct a qualitative research to collect data directly from _Minecraft_ players. = Method The method used for this research is intended to be qualitative, but before diving directly into finding the causes, the research team wanted to validate the existence of the phenomenon and the size of the popularity affected by it. To do that, it is the best to a quantitative method. == Pilot Survey The validation is realised via an online survey towards a collection of _Minecraft_ players. The survey questions consist of non-private information related to players' experience with _Minecraft_, including how long they have been playing the game, how frequently they create new worlds, what modes they play the most, what negative feelings have the game caused on them, etc. There are two purposes for this pilot survey: - To find the distribution of players' engagement duration towards worlds to validate if the 2-week phase really exists. - To collect a sample base that could be filtered and used for the later interview stage. A table of survey questions could be found in the appendix section (@table:survey-questions). == Interview After the survey data is collected, it is possible to analyze it and filter out a subset of players who have strong resonance with the phenomenon. The research team then conduct one-to-one interviews with these selected players. The interviews could either be online or in-person. The main purpose of the interview stage is to find out the causes of the phenomenon by gathering subjective experiences from individual samples. The gathered data is then be transcribed, coded, grouped into categories for later analysis. A table of interview questions could be found in the appendix section (@table:interview-questions). == Analysis The main form of analysis involved applying thematic analysis to data relating to our focus question: "What happened during the 2-week _Minecraft_ phase?" This involved an inductive, systematic identification of emergent patterns from the interview and survey data relating to players' reasons for world abandonment and the factors that influenced their funnel through the "2-week _Minecraft_ phase". Thematic analysis was employed on the data in two stages. The first stage involved coding the text into categories, according to the general types of player experience---For example, progression milestones; multiple-player relationships; affective bonds with worlds; and update/mod impacts. The experiences in turn revealed a set of overarching themes, which were subject to a finer-grained thematic analysis. By assessing the content of the responses, we looked more closely into the reasons why players engage in cyclical patterns of play. The data was then rearranged into a set of key themes (e.g. attachment, updates-as-motivators, mods/customisation, and multiplayer versus singleplayer), which in turn generated sub-themes (e.g. the challenge of exploring remade worlds, and the social dynamics involved in keeping multiplayer engagement alive), which were then further analyzed and ordered into a matrix according to their frequency and intensity across the players. The analysis commenced in the close reading of all the interview transcripts and survey results, where every transcript was read and re-read independently several times to gain a deep understanding of the participant's story. Thereafter, codes were developed for all responses that pertained to meaningful player behaviors regarding the creation, abandonment and continuation of their _Minecraft_ worlds. These codes were then used to group narratives into themes that allowed us to map both observed expected player behaviors (e.g. boredom as a trigger for discontinuation), as well as more surprising results (the enduring effect of multiplayer social bonds on extending the lifespan of a world). After the codes were established, we looked for recurring themes by examining those codes from a larger, more abstract perspective, such as identifying patterns across player quotes regarding how updates both invoke excitement and disappointment, and charting how they linked across cases. Themes were identified, and then we looked back at the raw data to check for reliability: Do the themes truly define the experience of players? We pared down the hierarchy of themes where necessary. This was managed by, among other things, involving a large sample in the research (all frequent _Minecraft_ players), having multiple independent coders scrutinize the data, and the iterative nature of thematic analysis, which allowed the coding and identification of themes to be refined and improved through feedback. This yielded several important insights about the dynamics of _Minecraft_ engagement, including how updates, mods and multiplayer sessions all have different effects (and lengths) that cause the "2-week _Minecraft_ phase" to repeat itself. = Interview Results By analysing their responses in more than 25 in-depth interviews, recurring themes that cause players "break" their current worlds and create new ones could be identified. These patterns relate to emotionality, the effects of game updates, multiplayer dynamics, and game mods (user-created additions to the game). The interviews offer a nuanced understanding of the ways in which and why players cycle through these "2-week _Minecraft_ phases". #let theme(body) = { set text(size: 1em, weight: "bold"); body; } === Attachment to Worlds and the Influence of Updates Many players reported a strong sense of identification with the worlds they built in _Minecraft_, especially as their playtime had been considerable. Players spoke about how they had crafted aquariums or architectural replicas in their worlds, or had simply engaged in just walking around to explore rare and unusual biomes. One player said: #quote[I get attached to every small thing in life, and _Minecraft_ worlds are no different.] It prevented them from leaving such a world, particularly if they had built something particularly elaborate, or if they had accumulated in-game memories with other players. One player explained: #quote[If the map was fun to explore and I built a cool house or had a dog, I feel bad leaving it behind.] Nonetheless, the vast majority of players said they would start a new world following a major _Minecraft_ update. These updates usually implement new content (such as biomes, structure, or mechanics) which are difficult or impossible to find in the player's old world. There wasn't an easy way to play with new content, so players said that it would take too long to reach new features if they stuck with their old world. One player explained: #quote[It's hard to find the new stuff that's added in the update in an already existing world. You have to travel out really far.] The desire of experiencing the latest features of the game tended to override attachment to the old worlds (they quit). The interviews showed that, despite the feeling of attachment to old worlds, players had a high chance to quit them all the time for the sake of novelty. === Challenge and Hardcore Mode If the players chose to play in hardcore mode, their approach to their worlds would be quite different from players who selected regular mode. In hardcore mode, the world deletes upon death, making the experience more adventurous since your death is final. Players in this mode said that they accepted the notion that they would lose it all if they died, saying: #quote[If it's a hardcore world, I already know that if I die, I'm going to delete the world immediately.] It encourages play of the "let's pretend" kind, with little emotional involvement and an attitude that, or "what's the worst that could happen?" Again and again, such players talked of making fresh hardcore worlds on an almost daily basis, dying within a few minutes at best of logging on to the new world. One said: #quote[My pattern is creating hardcore worlds, dying, and recreating them. I want to complete everything without dying, and if I can't, I start a new world.] This cycle of world-building and -abandonment is fuelled by the competing impulses of needing to survive and needing to perfect, as players try to achieve 100 percent completion without losing their worlds. In contrast to competitions, players who place greater value on creative expression and exploration would tend to stay in their worlds longer before abandoning their creations for newer versions or updates. === Multiplayer vs. Singleplayer Dynamics The type of play (multiplayer or singleplayer) has a big influence on when and why players feel inclined to start new worlds. For two-thirds of our respondents, singleplayer was perceived as the type of play that made it more probable they would restart worlds. When playing alone, they had full editorial authority over their world, and they could walk away without affecting anyone else's experience. One player explained: #quote[I'm way more likely to start over in singleplayer because I don't have to worry about destroying the efforts of other players.] This allows players to experiment, blow things up and, if they want to, restart as often as necessary. In contrast to solo play, the multiplayer setting tends to prolong the life of a world. Several players said that they feel they have to take care of the other players who share a server with them. This made it harder for them to leave a world: #quote(block: false)[I feel somewhat responsible for the other guys on the server.] #quote[In multiplayer, it's easier to stick around because you're part of a group.] Multiplayer is also a committal factor: The socializing and the cooperation can keep players producing in the same world even when they'd like to start again; on the other hand, players can abandon feed-the-beast servers because some have lost interest and stopped playing, or are much further ahead in other ways. We won't edit that last quote. #quote[If people stop playing or progress too slowly, it kills the world.] === The Role of Mods and Customization For many, the availability of mods or other customisation options becomes a major factor in determining when it's time to start over. Mods add new mechanics, challenges and structures that players can relish and enjoy by starting anew. One interviewee explained: #quote[Mods play a very important part in starting a new world... There are so many great mods that change the game in a good way.] Some mods, such as _Create_, add mechanical objects to the game; others introduce a new biome, another a boss, another a dungeon, and so on, adding content for players to explore as they go. Despite the option of modding, not every player uses mods as a supplement to the game or way of playing they have chosen. Some players maintain that when it comes to _Minecraft_, less is more, and they're not interested in using mods. The example of one player: #quote[Mods don't influence my decision to make a new world---I'm not interested in non-vanilla stuff.] This reflects the different ways in which modded and vanilla players have learned to respond to the actions or capabilities granted to them in _Minecraft_, giving rise to different styles of play. These different playstyles also give rise to different responses to world-ending gameplay events---whether through resetting or carrying on. === Impact of Social Play and Community Engagement Social interaction and community are key to whether players stay in a world of leave it. Many said that making friends while they played was sometimes more important than the game itself. One player stated: #quote[It's not the world itself that's hard to leave---it's the people I played with on that server.] This investment in the social experience of the game can sustain a multiplayer world long after it would be abandoned in singleplayer: Playing isn't just about progressing a world but about playing with friends, building a social experience. But if, for example, friends leave, they will be more likely to leave the world in turn once the social group of the game starts to break up. One player said: #quote[Once the group stops playing, there's no point in sticking around. That's when I usually start a new world.] === Progression Milestones and the Desire for a Fresh Start Several players reported having a common last hurrah, clearing "staircases" that mark hitting milestones (defeating the Ender Dragon; completing armor made of Netherite)---often the point at which they get bored of a world. As another player put it: #quote[Once I've done everything, it feels like time to start fresh.] These players feel they have done what they need to do in this world once they reach these thresholds, and there is no sense in continuing the great toil in the same world because it is no longer "new"---novelty is still desired. As another player commented: #quote[After I've finished my main goal, like building a big project or getting all the advancements, I usually feel like it's time to move on.] This cyclical nature of _Minecraft_ engagement is apparent when we consider that users begin with a huge drive to explore, build and go forward---eventually, they run out of interesting things to do and end up quitting and starting up a new world. = Discussion The study's findings can also be helpful in thinking broadly about the long-term retention issues faced by sandbox and open-world games in general, such as the wildly popular, tremendously influential _Minecraft_. Players report that they engage with the game because it offers them freedom of action: freedom to build, explore and create. But they also report that this very freedom eventually results in periods of disengagement as a result of having accomplished their short-term goals. When long-term goals or structured progression are undefined, a lack of motivation can set in when players reach certain milestones, such as dispatching player-controlled boss NPCs, engineering large building projects in the world, or simply gaining important skills or emerging victorious from exciting quests. This points to another significant design challenge to overcome when it comes to open-world games: The need for constant progression systems. Players in games such as _Minecraft_---where players set their own goals---often find that, after an initial period of play, they run out of personal goals or bored of doing the same tasks. Adding greater long-term challenges, layers of progression systems, or shifting world mechanics, for example, could provide an open-world game with reasons for people to keep playing past the point of survival or creating new worlds or creatures. Offering in-game achievements, for example, that must be played as a collective goal more committing than building a castle, reaching certain benchmarks that unleash content with greater depth (i.e. a narrative) or ongoing narrative strands that provide folk-tales or strung-out goals over time could keep a player in a game for longer periods. One of the most interesting findings from the study is that game updates exacerbate world abandonment: Updates can be a blessing and a curse. On the one hand, they revitalize the game by adding new content, but on the other hand, they contribute to world abandonment with most people feeling the need to start a new world to get the full experience of a substantial update. This is especially true for sandbox games, where new content (e.g. new biomes, new mechanics, etc.) that is introduced in an update might appear only in areas of the game world that the player hasn't fully explored yet. Here, developers could explore ways to add updates without forcing players to reset further into the world or start completely anew. For example, more extensive use of dynamic world generation or selective world updates---perhaps bringing new content closer to where players currently are---might reduce the need to reset over and over again. The study also points to the usefulness of multiplayer dynamics in maintaining engagement. While multiplayer can cause players to stick with a game for longer periods of time, thanks to the social bonds and shared goals it fosters, it also brings its own problems. When players on a multiplayer server advance at different rates, or simply lose interest in playing, the entire group can suffer. What new designs might be needed to help games better accommodate these divergent play styles and progression speeds? This might include systems that allow for internalizing some of the progression achieved by a slower-moving player in an open world multiplayer game without unfairly disadvantaging them, or at least rewarding them with a sense of accomplishment rather than just being forgotten. Or could the game lean more heavily on balanced mechanics that enable all the players to maintain their agency for longer, preventing fast progression players from running away with some form of the meta-game? Then there are mods. In fact, the seemingly unlimited possibilities for new gameplay that come with mods is a major reason why many players reset worlds to experiment with new content. This ability to keep the game fresh, however, may also provoke the same feedback loop of peak engagement followed by disengagement described above with regard to updates. So, for example, game-makers might better support mod continuity by providing official recognition for mods that allow players to integrate new content into an existing world without needing to reset. Paradoxically, providing this support could improve long-term engagement with both modded content and long-term world-building, by encouraging its frequency. Overall, this study illustrates how engagement in sandbox games like _Minecraft_ fluctuates in cycles, and serves as a jumping-off point for future work on the role that game design can play in retention. Providing better progression, improving how updates are incorporated into the experience, and adjusting the balance of authentication for multiplayer can all create more compelling 'little brother loops'---those interactions within games that create a feedback loop that keeps players hooked. The "2-week _Minecraft_ phase" points to the importance of balancing player freedom with more externally determined incentives in order to mitigate the burnout that can come with the increased autonomy afforded by open-world games. = Conclusion Qualitative survey and interview research supports the "2-week _Minecraft_ phase", indicating that abandonment of worlds follows similar cyclical patterns and is usually provoked by a similar set of factors after a period of intensive play. Many of these have to do with the fact that, while _Minecraft_'s sandbox-style gameplay enables creativity and exploration, it requires skills and design that can dry up after key goals are achieved via methods that are too simple. One discovery was that worlds in singleplayer tended to be restarted more frequently, as there is no sustained social motivation when playing on your own. The multiplayer experience tends to extend the lifespan of the world, more often than not. But having players running into each other isn't all rosy: Things can go wrong, and the study found that multiplayer worlds can also become stale, if there isn't a synchronized experience in terms of player progression, or if that excitement isn't there. Furthermore, the study found that game updates and mods were often a factor in the decision to opt for new worlds. While many players still expressed a desire to revisit older worlds, their weekly updating meant that players wanted to play with the new content as soon as it appeared. However, if players had stored wealth in older worlds, these world resets made it harder to access that new content---often leading to starting over. In this way, _Minecraft_'s ever-evolving nature, through its weekly updates and its modding community, encouraged both player engagement and regular bouts of world resetting. Taken together, we've identifed burnout, self-imposed goals and the prospect of new content as the main drivers of the cycle of engagement and disengagement. We also conclude that despite _Minecraft_'s "behemoth of a sandbox" that offers freedom and replayability, facilitating long-term engagement with the game will be an ongoing challenge. We hope that greater recognition of the micro-dynamics presented by the survey will open up prospects for designing more enduring engagement in games that rely on activities created by players, such as open-world titles that offer freedom in exchange for players creating their own content. Possible enhancements include more targeted progression systems or other types of gameplay-based rewards. ] #{ set text(size: 10pt); resetheadingsize(); [#bibliography("bibliography.bib", full: true, style: "ieee" )] } #set heading(numbering: (..numbers) => { numbers = numbers.pos(); numbers.remove(0); return numbering("A.1.", ..numbers); }) #heading(numbering: none)[Appendix] #show table.cell.where(y: 0): set text(weight: "bold") #let tnocounter = counter("tno") #let tno() = { context tnocounter.display(); tnocounter.step(); } #let notable(..args) = { tnocounter.update(1); table(..args); } #show table: set text(size: 10pt); #show figure: set block(breakable: true) == Survey Questions #figure( notable( columns: 3, stroke: none, align: (center, left, center), table.hline(), table.header[No.][#set align(center); Question][Expected Answer], table.hline(stroke: 0.25pt), [#tno()], [How many years have you played Minecraft?], [0-11], [#tno()], [How often do you play Minecraft?], [Occasionally, once a month, multiple times a month, etc.], [#tno()], [Do you play singleplayer or multiplayer more often?], [Singleplayer, multiplayer], [#tno()], [What Minecraft mode do you play the most?], [Survival, creative, online servers], [#tno()], [On average, how many hours do you play in a single Minecraft world?], [0-5, 5-10, 10-15, 15+], [#tno()], [Have you defeated the Enderdragon in a survival world?], [yes, no], [#tno()], [What aspects of your previous world caused you to stop playing?], [Boredom, frustration, etc.], table.hline(), ), caption: [The survey questions used to pilot the research.] ) <table:survey-questions> == Interview Questions #figure( notable( columns: 2, stroke: none, align: (center, left), table.hline(), table.header[No.][#set align(center); Question], table.hline(stroke: 0.25pt), [#tno()], [ Can you describe the last time you decided to start a new world? - What was the main reason you wanted to start over? - How did the new world compare to the one you left behind? ], [#tno()], [ When you create a new world, do you have specific goals in mind, or do you play more spontaneously? - If you have goals, what are they? (e.g., building a specific structure, exploring, defeating bosses) ], [#tno()], [ Do you feel a sense of attachment to the worlds you leave behind, or is it easy to move on? - If you feel attached, what makes it hard to move on? ], [#tno()], [ How do new updates or changes in Minecraft influence your decision to start a new world? - Have there been updates that made you want to restart? ], [#tno()], [ What role do mods play in your decision to start a new world? - Do you start new worlds specifically to try out mods? ], [#tno()], [ Have you ever regretted abandoning a world? If so, why? ], [#tno()], [ How does playing in multiplayer or singleplayer affect your decision to start fresh? - Are you more likely to start over in one mode versus the other? ], [#tno()], [ What's your process when deciding where to settle in a new world? - Do you explore a lot before choosing, or do you settle down quickly? ], [#tno()], [ Are there any moments of progression during which you feel like you want to start a new world instead of continuing? - Do you fight the Ender Dragon, Wither, make Netherite equipment? - Why do these progression points make you feel this way? ], [#tno()], [ Have you noticed any patterns in your behavior when it comes to restarting worlds? - For example, do you tend to restart after reaching certain milestones or facing specific challenges? ], table.hline(), ), caption: [A brief outline of the questions to be asked in the interview.] ) <table:interview-questions>
https://github.com/spidersouris/touying-unistra-pristine
https://raw.githubusercontent.com/spidersouris/touying-unistra-pristine/main/src/settings.typ
typst
MIT License
#let SHOW-HEADER = true #let SHOW-FOOTER = true #let FOOTER-UPPER-SEP = " | " #let FOOTER-LOWER-SEP = " | " #let FOOTER-SHOW-SUBTITLE = true #let ADMONITION-NUMBERING = false #let FONT = ("Unistra A", "Segoe UI", "Roboto") #let LANGUAGE = "fr" #let QUOTES = ( left: "«", right: "»", ) #let DEBUG = false
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0A00.typ
typst
Apache License 2.0
#let data = ( (), ("GURMUKHI SIGN ADAK BINDI", "Mn", 0), ("GURMUKHI SIGN BINDI", "Mn", 0), ("GURMUKHI SIGN VISARGA", "Mc", 0), (), ("GURMUKHI LETTER A", "Lo", 0), ("GURMUKHI LETTER AA", "Lo", 0), ("GURMUKHI LETTER I", "Lo", 0), ("GURMUKHI LETTER II", "Lo", 0), ("GURMUKHI LETTER U", "Lo", 0), ("GURMUKHI LETTER UU", "Lo", 0), (), (), (), (), ("GURMUKHI LETTER EE", "Lo", 0), ("GURMUKHI LETTER AI", "Lo", 0), (), (), ("GURMUKHI LETTER OO", "Lo", 0), ("GURMUKHI LETTER AU", "Lo", 0), ("GURMUKHI LETTER KA", "Lo", 0), ("GURMUKHI LETTER KHA", "Lo", 0), ("GURMUKHI LETTER GA", "Lo", 0), ("GURMUKHI LETTER GHA", "Lo", 0), ("GURMUKHI LETTER NGA", "Lo", 0), ("GURMUKHI LETTER CA", "Lo", 0), ("GURMUKHI LETTER CHA", "Lo", 0), ("GURMUKHI LETTER JA", "Lo", 0), ("GURMUKHI LETTER JHA", "Lo", 0), ("GURMUKHI LETTER NYA", "Lo", 0), ("GURMUKHI LETTER TTA", "Lo", 0), ("GURMUKHI LETTER TTHA", "Lo", 0), ("GURMUKHI LETTER DDA", "Lo", 0), ("GURMUKHI LETTER DDHA", "Lo", 0), ("GURMUKHI LETTER NNA", "Lo", 0), ("GURMUKHI LETTER TA", "Lo", 0), ("GURMUKHI LETTER THA", "Lo", 0), ("GURMUKHI LETTER DA", "Lo", 0), ("GURMUKHI LETTER DHA", "Lo", 0), ("GURMUKHI LETTER NA", "Lo", 0), (), ("GURMUKHI LETTER PA", "Lo", 0), ("GURMUKHI LETTER PHA", "Lo", 0), ("GURMUKHI LETTER BA", "Lo", 0), ("GURMUKHI LETTER BHA", "Lo", 0), ("GURMUKHI LETTER MA", "Lo", 0), ("GURMUKHI LETTER YA", "Lo", 0), ("GURMUKHI LETTER RA", "Lo", 0), (), ("GURMUKHI LETTER LA", "Lo", 0), ("GURMUKHI LETTER LLA", "Lo", 0), (), ("GURMUKHI LETTER VA", "Lo", 0), ("GURMUKHI LETTER SHA", "Lo", 0), (), ("GURMUKHI LETTER SA", "Lo", 0), ("GURMUKHI LETTER HA", "Lo", 0), (), (), ("GURMUKHI SIGN NUKTA", "Mn", 7), (), ("GURMUKHI VOWEL SIGN AA", "Mc", 0), ("GURMUKHI VOWEL SIGN I", "Mc", 0), ("GURMUKHI VOWEL SIGN II", "Mc", 0), ("GURMUKHI VOWEL SIGN U", "Mn", 0), ("GURMUKHI VOWEL SIGN UU", "Mn", 0), (), (), (), (), ("GURMUKHI VOWEL SIGN EE", "Mn", 0), ("GURMUKHI VOWEL SIGN AI", "Mn", 0), (), (), ("GURMUKHI VOWEL SIGN OO", "Mn", 0), ("GURMUKHI VOWEL SIGN AU", "Mn", 0), ("GURMUKHI SIGN VIRAMA", "Mn", 9), (), (), (), ("GURMUKHI SIGN UDAAT", "Mn", 0), (), (), (), (), (), (), (), ("GURMUKHI LETTER KHHA", "Lo", 0), ("GURMUKHI LETTER GHHA", "Lo", 0), ("GURMUKHI LETTER ZA", "Lo", 0), ("GURMUKHI LETTER RRA", "Lo", 0), (), ("GURMUKHI LETTER FA", "Lo", 0), (), (), (), (), (), (), (), ("GURMUKHI DIGIT ZERO", "Nd", 0), ("GURMUKHI DIGIT ONE", "Nd", 0), ("GURMUKHI DIGIT TWO", "Nd", 0), ("GURMUKHI DIGIT THREE", "Nd", 0), ("GURMUKHI DIGIT FOUR", "Nd", 0), ("GURMUKHI DIGIT FIVE", "Nd", 0), ("GURMUKHI DIGIT SIX", "Nd", 0), ("GURMUKHI DIGIT SEVEN", "Nd", 0), ("GURMUKHI DIGIT EIGHT", "Nd", 0), ("GURMUKHI DIGIT NINE", "Nd", 0), ("GURMUKHI TIPPI", "Mn", 0), ("GURMUKHI ADDAK", "Mn", 0), ("GURMUKHI IRI", "Lo", 0), ("GURMUKHI URA", "Lo", 0), ("GURMUKHI EK ONKAR", "Lo", 0), ("GURMUKHI SIGN YAKASH", "Mn", 0), ("GURMUKHI ABBREVIATION SIGN", "Po", 0), )
https://github.com/Mc-Zen/zero
https://raw.githubusercontent.com/Mc-Zen/zero/main/docs/figures/grouping.typ
typst
MIT License
#import "/src/zero.typ": * #import "@preview/cetz:0.2.2" #set text(1.3em) #set page(width: auto, height: auto, margin: 1em) #let clr = if "dark" in sys.inputs { white } else { black } #set page(fill: white) if clr == black #set text(fill: clr) #let grouping = cetz.canvas({ import cetz.draw: * scale(130%) content((0, 0), num[10973731.5682], anchor: "south-west") set-style(stroke: .3pt + clr) line((0.46, -.045), (0.46, -.12), (1.04, -.12), (1.04, -.045)) content((.4, -.35), text(.8em)[`group.size`]) line((1.83, -.045), (1.83, -.12), (2.59, -.12), (2.59, -.045)) content((2.9, -.35), text(.8em)[`< group.threshold`]) line((1.2,.5), (1.1,.3), name: "line1") content((1.9, .7), text(.8em)[`group.separator`]) }) #grouping
https://github.com/frankadrian/typster-ngrx
https://raw.githubusercontent.com/frankadrian/typster-ngrx/master/README.md
markdown
# TypsterNgrx This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.3.2. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
https://github.com/Daillusorisch/HYSeminarAssignment
https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/template/components/appendix.typ
typst
#import "../utils/style.typ": * #let appendix( title: "附录", display_title: "附  录", outlined: true, body, ) = { show <_appendix_>: { align(center)[ #v(5pt) #text( font: 字体.黑体, size: 字号.小二, weight: "regular" )[#display_title] ] } pagebreak(weak: true) [ #heading(level: 1, numbering: none, outlined: outlined, title) <_appendix_> #body ] }
https://github.com/Zeta611/simplebnf.typ
https://raw.githubusercontent.com/Zeta611/simplebnf.typ/main/simplebnf.typ
typst
MIT License
#let bnf( ..body, ) = { let content = body.pos().flatten() table( columns: ( auto, auto, auto, auto, auto, ), align: ( right, center, center, left, left, ), inset: 0.28em, stroke: none, ..content, ) } #let Prod( lhs, annot: none, delim: $::=$, ..rhs, ) = { let pad = ( none, none, $|$, ) let rhses = rhs.pos().flatten().chunks(2).intersperse(pad) ( annot, lhs, delim, rhses, ) } #let Or( var, annot, ) = ( var, annot, )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1740.typ
typst
Apache License 2.0
#let data = ( ("BUHID LETTER A", "Lo", 0), ("BUHID LETTER I", "Lo", 0), ("BUHID LETTER U", "Lo", 0), ("BUHID LETTER KA", "Lo", 0), ("BUHID LETTER GA", "Lo", 0), ("BUHID LETTER NGA", "Lo", 0), ("BUHID LETTER TA", "Lo", 0), ("BUHID LETTER DA", "Lo", 0), ("BUHID LETTER NA", "Lo", 0), ("BUHID LETTER PA", "Lo", 0), ("BUHID LETTER BA", "Lo", 0), ("BUHID LETTER MA", "Lo", 0), ("BUHID LETTER YA", "Lo", 0), ("BUHID LETTER RA", "Lo", 0), ("BUHID LETTER LA", "Lo", 0), ("BUHID LETTER WA", "Lo", 0), ("BUHID LETTER SA", "Lo", 0), ("BUHID LETTER HA", "Lo", 0), ("BUHID VOWEL SIGN I", "Mn", 0), ("BUHID VOWEL SIGN U", "Mn", 0), )
https://github.com/TheLukeGuy/turnstile
https://raw.githubusercontent.com/TheLukeGuy/turnstile/main/src/lib.typ
typst
Apache License 2.0
// Copyright © 2023 <NAME> // This file is part of Turnstile. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at <http://www.apache.org/licenses/LICENSE-2.0>. // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. Hello, world!
https://github.com/Goldan32/brilliant-cv
https://raw.githubusercontent.com/Goldan32/brilliant-cv/main/modules/skills.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Skills") #cvSkill( type: [Languages], info: [English (C1) #hBar() Hungarian (native)] ) #cvSkill( type: [Programming], info: [C #hBar() C++ #hBar() Rust #hBar() Python #hBar() BASH #hBar() Robot Framework #hBar() Matlab #hBar() Verilog] ) #cvSkill( type: [Development], info: [GCC/G++ #hBar() Makefile #hBar() CMake #hBar() Visual Studio #hBar() VSCode #hBar() Linux kernel #hBar() OpenBMC #hBar() Petalinux] ) #cvSkill( type: [Other], info: [Git #hBar() Linux usage #hBar() Yocto Project #hBar() KiCAD #hBar() JIRA #hBar() Confluence] )
https://github.com/zyf722/typst-tabler-icons
https://raw.githubusercontent.com/zyf722/typst-tabler-icons/main/src/lib.typ
typst
MIT License
//! typst-tabler-icons //! //! https://github.com/zyf722/typst-tabler-icons // Implementation of `tabler-icon` #import "lib-impl.typ": tabler-icon // Generated icons #import "lib-gen.typ": * // Re-export the `tabler-icon` function // The following doc comment is needed for lsp to show the documentation /// Render a [Tabler icon](https://tabler.io/icons) by its name or unicode. /// /// Parameters: /// - `icon`: The name of the icon /// - This can be name in string or unicode of the icon /// - `tabler-icon-map`: The map of icon names to unicode /// - Default is a map generated from Tabler metadata /// - *Not recommended* You can provide your own map to override it /// - `..args`: Additional arguments to pass to the `text` function /// /// Returns: The rendered icon as a `text` element #let tabler-icon = tabler-icon.with(tabler-icon-map: tabler-icon-map)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/coordinate.typ
typst
Apache License 2.0
#import "vector.typ" #import "util.typ" #import "deps.typ" #import deps.oxifmt: strfmt #let resolve-xyz(c) = { // (x: <number> or <none>, y: <number> or <none>, z: <number> or <none>) // (x, y) // (x, y, z) return if type(c) == array { vector.as-vec(c) } else { ( c.at("x", default: 0), c.at("y", default: 0), c.at("z", default: 0), ) } } #let resolve-polar(c) = { // (angle: <angle>, radius: <number>) // (angle: <angle>, radius: (x, y)) // (angle, radius) // (angle, (x-radius, y-radius)) let (angle, xr, yr) = if type(c) == array { ( c.first(), ..if type(c.last()) == array { c.last() } else { (c.last(), c.last()) } ) } else { ( c.angle, ..if type(c.radius) == array { c.radius } else { (c.radius, c.radius) } ) } return ( xr * calc.cos(angle), yr * calc.sin(angle), 0 ) } #let resolve-anchor(ctx, c) = { // (name: <string>, anchor: <number, angle, string> or <none>) // "name.anchor" // "name" let (name, anchor) = if type(c) == str { let parts = c.split(".") if parts.len() == 1 { (parts.first(), "default") } else { (parts.slice(0, -1).join("."), parts.last()) } } else { (c.name, c.at("anchor", default: "default")) } // Check if node is known assert(name in ctx.nodes, message: "Unknown element '" + name + "' in elements " + repr(ctx.nodes.keys())) // Resolve length anchors if type(anchor) == length { anchor = util.resolve-number(ctx, anchor) } // Check if anchor is known let node = ctx.nodes.at(name) let pos = (node.anchors)(anchor) assert(pos != none, message: "Unknown anchor '" + repr(anchor) + "' for element '" + name + "'") let pos = util.revert-transform( ctx.transform, pos ) return pos } #let resolve-barycentric(ctx, c) = { // dictionary of numbers return vector.scale( c.bary.pairs().fold( vector.new(3), (vec, (k, v)) => { vector.add( vec, vector.scale( resolve-anchor(ctx, k), v ) ) } ), 1 / c.bary.values().sum() ) } #let resolve-relative(resolve, ctx, c) = { // (rel: <coordinate>, update: <bool> or <none>, to: <coordinate>) let update = c.at("update", default: true) let (ctx, rel) = resolve(ctx, c.rel, update: false) let (ctx, to) = if "to" in c { resolve(ctx, c.to, update: false) } else { (ctx, ctx.prev.pt) } c = vector.add( rel, to, ) c.insert(0, update) return c } #let resolve-tangent(resolve, ctx, c) = { // (element: <string>, point: <coordinate>, solution: <integer>) // https://stackoverflow.com/a/69641745/7142815 let C = resolve-anchor(ctx, c.element) let (ctx, P) = resolve(ctx, c.point, update: false) // Radius let r = vector.len(vector.sub(resolve-anchor(ctx, c.element + ".north"), C)) // Vector between C and P let D = vector.sub(P, C) // C - P // Distance between C and P let pc = vector.len(D) if pc < r { panic("No tangent solution for element " + c.element + " and point " + repr(c.point)) } // Distance between P and X0 let d = r*r / pc // Distance between X0 and X1(X2) let h = calc.sqrt(r*r - d*d) return if c.solution == 1 { ( C.at(0) + (D.at(0) * d - D.at(1) * h) / pc, C.at(1) + (D.at(1) * d + D.at(0) * h) / pc, 0 ) } else { ( C.at(0) + (D.at(0) * d + D.at(1) * h) / pc, C.at(1) + (D.at(1) * d - D.at(0) * h) / pc, 0 ) } } #let resolve-perpendicular(resolve, ctx, c) = { // (horizontal: <coordinate>, vertical: <coordinate>) // (horizontal, "-|", vertical) // (vertical, "|-", horizontal) let (ctx, horizontal, vertical) = resolve(ctx, ..if type(c) == array { if c.at(1) == "|-" { (c.first(), c.last()) } else { // c.at(1) == "-|" (c.last(), c.first()) } } else { (c.horizontal, c.vertical) }, update: false) return ( horizontal.at(0), vertical.at(1), 0 ) } #let resolve-lerp(resolve, ctx, c) = { // (a: <coordinate>, number: <number,ratio>, // angle?: <angle>, b: <coordinate>) // (a, <number, ratio>, b) // (a, <number, ratio>, angle, b) let (a, number, angle, b) = if type(c) == array { if c.len() == 3 { ( ..c.slice(0, 2), none, // angle c.last(), ) } else { c } } else { ( c.a, c.number, c.at("angle", default: 0deg), c.b ) } (ctx, a, b) = resolve(ctx, a, b) if angle != none { let (x, y, _) = vector.sub(b,a) b = vector.add( ( calc.cos(angle) * x - calc.sin(angle) * y, calc.sin(angle) * x + calc.cos(angle) * y, 0 ), a, ) } let ab = vector.sub(b, a) let is-absolute = type(number) != ratio let distance = if is-absolute { let dist = vector.len(ab) if dist != 0 { util.resolve-number(ctx, number) / dist } else { 0 } } else { number / 100% } return vector.add(a, vector.scale(ab, distance)) } #let resolve-function(resolve, ctx, c) = { let (func, ..c) = c (ctx, ..c) = resolve(ctx, ..c) func(..c) } #let resolve-pos(ctx, c) = { // (name: str, pos: float, auto?: left|right, swap?: bool) } // Returns the given coordinate's system name #let resolve-system(c) = { let t = if type(c) == dictionary { let keys = c.keys() let len = c.len() if len in (1, 2, 3) and keys.all(k => k in ("x", "y", "z")) { "xyz" } else if len == 2 and keys.all(k => k in ("angle", "radius")) and (type(c.radius) in (int, float, length) or (type(c.radius) == array and c.radius.len() == 2)) { "polar" } else if len == 1 and keys == ("bary",) { "barycentric" } else if len in (1, 2) and keys.all(k => k in ("name", "anchor")) { "anchor" } else if len == 3 and keys.all(k => k in ("element", "point", "solution")) { "tangent" } else if len == 2 and keys.all(k => k in ("horizontal", "vertical")) { "perpendicular" } else if len in (1, 2, 3) and keys.all(k => k in ("rel", "to", "update")) { "relative" } else if len in (3, 4) and keys.all(k => k in ("a", "number", "angle", "abs", "b")) { "lerp" } } else if type(c) == array { let len = c.len() let types = c.map(type) if len == 0 { "previous" } else if len in (2, 3) and types.all(t => t in ("integer", "float", "length")) { "xyz" } else if len == 2 and types.first() == "angle" { "polar" } else if len == 3 and c.at(1) in ("-|", "|-") { "perpendicular" } else if len in (3, 4) and types.at(1) in ("integer", "float", "length", "ratio") and (len == 3 or (len == 4 and types.at(2) == "angle")) { "lerp" } else if len >= 2 and types.first() == "function" { "function" } } else if type(c) == str { if c.contains(".") { "anchor" } else { "element" } } if t == none { panic("Failed to resolve coordinate: " + repr(c)) } return t } /// Resolve a list of coordinates to absolute vectors /// /// #example(``` /// line((0,0), (1,1), name: "l") /// get-ctx(ctx => { /// // Get the vector of coordinate "l.start" and "l.end" /// let (ctx, a, b) = cetz.coordinate.resolve(ctx, "l.start", "l.end") /// content("l.start", [#a], frame: "rect", stroke: none, fill: white) /// content("l.end", [#b], frame: "rect", stroke: none, fill: white) /// }) /// ```) /// /// - ctx (context): Canvas context object /// - ..coordinates (coordinate): List of coordinates /// - update (bool): Update the context's last position /// -> (ctx, vector..) Returns a list of the new context object plus the /// resolved coordinate vectors #let resolve(ctx, ..coordinates, update: true) = { let result = () for c in coordinates.pos() { let t = resolve-system(c) let out = if t == "xyz" { resolve-xyz(c) } else if t == "previous" { ctx.prev.pt } else if t == "polar" { resolve-polar(c) } else if t == "barycentric" { resolve-barycentric(ctx, c) } else if t in ("element", "anchor") { resolve-anchor(ctx, c) } else if t == "tangent" { resolve-tangent(resolve, ctx, c) } else if t == "perpendicular" { resolve-perpendicular(resolve, ctx, c) } else if t == "relative" { (update, ..c) = resolve-relative(resolve, ctx, c) c } else if t == "lerp" { resolve-lerp(resolve, ctx, c) } else if t == "function" { resolve-function(resolve, ctx, c) } else { panic("Failed to resolve coordinate of format: " + repr(c)) }.map(util.resolve-number.with(ctx)) if update { ctx.prev.pt = out } result.push(out) } return (ctx, ..result) }
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/line-numbers.typ
typst
--- line-numbers-enable --- #set page(margin: (left: 2.5em)) #set par.line(numbering: "1") First line \ Second line \ Third line --- line-numbers-clearance --- #set page(margin: (left: 1.5cm)) #set par.line(numbering: "1", number-clearance: 0cm) First line \ Second line \ Third line --- line-numbers-margin --- #set page(margin: (right: 3cm)) #set par.line(numbering: "1", number-clearance: 1.5cm, number-margin: end) First line \ Second line \ Third line --- line-numbers-default-alignment --- #set page(margin: (left: 3em)) #set par.line(numbering: "1") a #([\ a] * 15) --- line-numbers-start-alignment --- #set page(margin: (left: 3em)) #set par.line(numbering: "i", number-align: start) a \ a #pagebreak() a \ a \ a --- line-numbers-auto-alignment --- #set page(margin: (right: 3cm)) #set par.line(numbering: "i", number-clearance: 1.5cm, number-margin: end) First line \ Second line \ Third line --- line-numbers-rtl --- #set page(margin: (right: 3em)) #set text(dir: rtl) #set par.line(numbering: "1") a #([\ a] * 15) --- line-numbers-columns --- #set page(columns: 2, margin: (x: 1.5em)) #set par.line(numbering: "1", number-clearance: 0.5em) Hello \ Beautiful \ World #colbreak() Birds \ In the \ Sky --- line-numbers-columns-alignment --- #set page(columns: 2, margin: (x: 1.5em)) #set par.line(numbering: "i", number-clearance: 0.5em) Hello \ Beautiful \ World #colbreak() Birds \ In the \ Sky --- line-numbers-multi-columns --- #set page(columns: 3, margin: (x: 1.5em)) #set par.line(numbering: "1", number-clearance: 0.5em) A \ B \ C #colbreak() D \ E \ F #colbreak() G \ H \ I --- line-numbers-columns-rtl --- #set page(columns: 2, margin: (x: 1.5em)) #set par.line(numbering: "1", number-clearance: 0.5em) #set text(dir: rtl) Hello \ Beautiful \ World #colbreak() Birds \ In the \ Sky --- line-numbers-columns-override --- #set columns(gutter: 1.5em) #set page(columns: 2, margin: (x: 1.5em)) #set par.line(numbering: "1", number-margin: end, number-clearance: 0.5em) Hello \ Beautiful \ World #colbreak() Birds \ In the \ Sky --- line-numbers-page-scope --- #set page(margin: (left: 2.5em)) #set par.line(numbering: "1", numbering-scope: "page") First line \ Second line #pagebreak() Back to first line \ Second line again #page[ Once again, first \ And second ] Back to first --- line-numbers-page-scope-with-columns --- #set page(margin: (x: 1.1cm), columns: 2) #set par.line( numbering: "1", number-clearance: 0.5cm, numbering-scope: "page" ) A \ A \ A #colbreak() B \ B \ B #pagebreak() One \ Two \ Three #colbreak() Four \ Five \ Six #page[ Page \ Elem #colbreak() Number \ Reset ] We're back #colbreak() Bye! --- line-numbers-page-scope-quasi-empty-first-column --- // Ensure this case (handled separately internally) is properly handled. #set page(margin: (x: 1.1cm), height: 2cm, columns: 2) #set par.line( numbering: "1", number-clearance: 0.5cm, numbering-scope: "page" ) First line #colbreak() Second line #pagebreak() #place[] #box(height: 2cm)[First!] --- line-numbers-nested-content --- #set page(margin: (left: 1.5cm)) #set par.line(numbering: "1", number-clearance: 0.5cm) #grid( columns: (1fr, 1fr), column-gutter: 0.5cm, inset: 5pt, block[A\ #box(lorem(5))], [Roses\ are\ red], [AAA], [], [], block[BBB\ CCC], ) --- line-numbers-place-out-of-order --- #set page(margin: (left: 1.5cm)) #set par.line(numbering: "1", number-clearance: 0.5cm) #place(bottom)[Line 4] Line 1\ Line 2\ Line 3 #v(1cm) --- line-numbers-deduplication --- #set page(margin: (left: 1.5cm)) #set par.line(numbering: "1", number-clearance: 0.5cm) #grid( columns: (1fr, 1fr), column-gutter: 0.5cm, row-gutter: 5pt, lorem(5), [A\ B\ C], [DDD], [DDD], [This is], move(dy: 2pt)[tough] ) --- line-numbers-deduplication-tall-line --- #set page(margin: (left: 1.5cm)) #set par.line(numbering: "1", number-clearance: 0.5cm) #grid( columns: (1fr, 1fr), column-gutter: 0.5cm, stroke: 0.5pt, grid.cell(rowspan: 2)[very #box(fill: red, height: 4cm)[tall]], grid.cell(inset: (y: 0.5pt))[Line 1\ Line 2\ Line 3], grid.cell(inset: (y: 0.5pt))[Line 4\ Line 5\ Line 6\ Line 7\ Line 8\ Line 9\ End] ) --- line-numbers-deduplication-zero-height-number --- #set page(margin: (left: 1.5cm)) #set par.line(numbering: n => move(dy: -0.6em, box(height: 0pt)[#n]), number-clearance: 0.5cm) #grid( columns: (1fr, 1fr), column-gutter: 0.5cm, row-gutter: 5pt, lorem(5), [A\ B\ C], [DDD], [DDD], [This is], move(dy: 3pt)[tough] )
https://github.com/miliog/typst-penreport
https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/helper/cve.typ
typst
MIT No Attribution
#let CVE(id: "") = { assert(id.matches(regex("^\d{4}-\d{4,7}$")).len() == 1, message: "The CVE number must match the format \d{4}-\d{4,7}.") link("https://www.cve.org/CVERecord?id=CVE-" + id)[CVE-#id] }
https://github.com/jassielof/cv
https://raw.githubusercontent.com/jassielof/cv/main/test.typ
typst
#import "@preview/fontawesome:0.1.0": * = Section #fa-linkedin()
https://github.com/patricoferris/typst-template
https://raw.githubusercontent.com/patricoferris/typst-template/main/lib.typ
typst
#import "@preview/gentle-clues:0.8.0": clue, question, conclusion #import "@preview/codelst:2.0.1": sourcecode // Workaround for the lack of an `std` scope. #let std-bibliography = bibliography #let std-smallcaps = smallcaps #let std-upper = upper // Overwrite the default `smallcaps` and `upper` functions with increased spacing between // characters. Default tracking is 0pt. #let smallcaps(body) = std-smallcaps(text(tracking: 0.6pt, body)) #let upper(body) = std-upper(text(tracking: 0.6pt, body)) // Colors used across the template. #let stroke-color = luma(400) #let fill-color = luma(250) // This function gets your whole document as its `body` and formats it as a simple // non-fiction paper. #let ilm( // The title for your work. title: [Your Title], // Author's name. author: "Author", // The paper size to use. paper-size: "a4", // Date that will be displayed on cover page. // The value needs to be of the 'datetime' type. // More info: https://typst.app/docs/reference/foundations/datetime/ // Example: datetime(year: 2024, month: 03, day: 17) date: none, // Format in which the date will be displayed on cover page. // More info: https://typst.app/docs/reference/foundations/datetime/#format date-format: "[month repr:long] [day padding:zero], [year repr:full]", // An abstract for your work. Can be omitted if you don't have one. abstract: none, // The contents for the preface page. This will be displayed after the cover page. Can // be omitted if you don't have one. preface: none, // The result of a call to the `outline` function or `none`. // Set this to `none`, if you want to disable the table of contents. // More info: https://typst.app/docs/reference/model/outline/ table-of-contents: outline(), // The result of a call to the `bibliography` function or `none`. // Example: bibliography("refs.bib") // More info: https://typst.app/docs/reference/model/bibliography/ bibliography: none, // Whether to start a chapter on a new page. chapter-pagebreak: true, // Display an index of figures (images). figure-index: ( enabled: false, title: "", ), // Display an index of tables table-index: ( enabled: false, title: "", ), listing-index: ( enabled: false, title: "", ), body, ) = { set document(title: title, author: author) set text( font: ("IBM Plex Serif"), weight: "regular", style: "normal", size: 10pt, ) show raw: set text(font: ("IBM Plex Mono"), size: 8.5pt) show figure.caption: emph // Configure page size and margins. set page( paper: paper-size, margin: (bottom: 1.75cm, top: 2.25cm), ) // Cover page. page( align( left + horizon, block(width: 90%)[ #let v-space = v(2em, weak: true) #text(3em)[*#title*] #v-space #text(1.6em, author) #if abstract != none { v-space block(width: 80%)[ // Default leading is 0.65em. #par( leading: 0.78em, justify: true, linebreaks: "optimized", abstract, ) ] } #if date != none { v-space // Display date as MMMM DD, YYYY text(date.display(date-format)) } ], ), ) // Configure paragraph properties. // Default leading is 0.65em. set par(leading: 0.7em, justify: true, linebreaks: "optimized") // Default spacing is 1.2em. show par: set block(spacing: 1.35em) // Add vertical space after headings. show heading.where(level: 2): it => { v(4%, weak: true) it } // Do not hyphenate headings. show heading: set text(hyphenate: false) // Show a small maroon circle next to external links. show link: it => { // Workaround for ctheorems package so that its labels keep the default link styling. if type(it.dest) == label { return it } underline(it, offset: 3pt, stroke: 1pt + rgb("#697a21")) // h(1.6pt) // super(box(height: 3.8pt, circle(radius: 1.2pt, stroke: 0.7pt + rgb("#993333")))) } // Display preface as the second page. if preface != none { page(preface) } // Indent nested entires in the outline. set outline(indent: auto) // Display table of contents. if table-of-contents != none { table-of-contents } // Configure heading numbering. set heading(numbering: "1.") // Configure page numbering and footer. set page(footer: context { // Get current page number. let i = counter(page).at(here()).first() // Align right for even pages and left for odd. let is-odd = calc.odd(i) let aln = if is-odd { right } else { left } // Are we on a page that starts a chapter? let target = heading.where(level: 1) if query(target).any(it => it.location().page() == i) { return align(aln)[#i] } // Find the chapter of the section we are currently in. let before = query(target.before(here())) if before.len() > 0 { let current = before.last() let gap = 1.75em let chapter = upper(text(size: 0.68em, current.body)) if current.numbering != none { if is-odd { align(aln)[#chapter #h(gap) #i] } else { align(aln)[#i #h(gap) #chapter] } } } }) // Configure equation numbering. set math.equation(numbering: "(1)") // Display inline code in a small box that retains the correct baseline. show raw.where(block: false): box.with( fill: fill-color.darken(2%), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) // Display block code with padding. show raw.where(block: true): block.with(inset: (x: 5pt, y: 6pt)) // Break large tables across pages. show figure.where(kind: table): set block(breakable: true) set table( // Increase the table cell's padding inset: 7pt, // default is 5pt stroke: (0.5pt + stroke-color) ) // Use smallcaps for table header row. show table.cell.where(y: 0): smallcaps // Wrap `body` in curly braces so that it has its own context. This way show/set rules will only apply to body. { // Start chapters on a new page. show heading.where(level: 1): it => { if chapter-pagebreak { pagebreak() } it } body } // Display bibliography. if bibliography != none { pagebreak() show std-bibliography: set text(0.85em) // Use default paragraph properties for bibliography. show std-bibliography: set par( leading: 0.65em, justify: false, linebreaks: auto, ) bibliography } // Display indices of figures, tables, and listings. let fig-t(kind) = figure.where(kind: kind) let has-fig(kind) = counter(fig-t(kind)).get().at(0) > 0 if figure-index.enabled or table-index.enabled or listing-index.enabled { show outline: set heading(outlined: true) context { let imgs = figure-index.enabled and has-fig(image) let tbls = table-index.enabled and has-fig(table) let lsts = listing-index.enabled and has-fig(raw) if imgs or tbls or lsts { // Note that we pagebreak only once instead of each each // individual index. This is because for documents that only have a couple of // figures, starting each index on new page would result in superfluous // whitespace. pagebreak() } if imgs { outline( title: figure-index.at("title", default: "Index of Figures"), target: fig-t(image), ) } if tbls { outline( title: table-index.at("title", default: "Index of Tables"), target: fig-t(table), ) } if lsts { outline( title: listing-index.at("title", default: "Index of Listings"), target: fig-t(raw), ) } } } } // This function formats its `body` (content) into a blockquote. #let blockquote(body) = { block( width: 100%, fill: fill-color, inset: 2em, stroke: (y: 0.5pt + stroke-color), body, ) } #let lno( lno ) = text(.8em, olive, raw(lno)) #let code(syntaxes: (), body) = sourcecode(syntaxes: syntaxes, numbers-style: lno, body) #let quoted(alignment: left, attr, body) = { set quote(block: true) show quote: set align(alignment) show quote: set pad(x: 3em) show quote: set text(fill: rgb(134,134,134)) quote(attribution: attr, body) } #let fstar = [ F\u{22C6} ]
https://github.com/sicheng1806/typst-book-for-sicheng
https://raw.githubusercontent.com/sicheng1806/typst-book-for-sicheng/main/scr/test/usenote_cn.typ
typst
#import "../basic_pkg/note_CN.typ" #show : doc => note_CN.conf( title: "我的标题", doc ) = 一级标题 #lorem(100) == 二级标题 #lorem(100) #lorem(200) === 三级标题 #lorem(100) = 二级标题 2 #lorem(100)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/symbol_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 13-20 unknown symbol modifier // #emoji.face.garbage
https://github.com/Dioprz/Notes
https://raw.githubusercontent.com/Dioprz/Notes/main/Haskell/Haskell_Programming_from_first_principles/Chapter_2/Chapter_2.typ
typst
= Chapter 2: Hello, Haskell == Tópicos básicos sobre el lenguaje y buenas prácticas === Ejecución del código - Se ejecuta a través de un archivo compilado o importando un módulo a través de su REPL, _GHCi_. - La librería estandar de Haskell es _Prelude_. - En _GHCi_ se usan expresiones que comienzan con `:` para interactuar con la REPL. Algunos de estos comandos son: - `:load`(`:l`). Permite cargar módulos, es decir, archivos `.hs`. - `:module`(`:m`). Quita los módulos cargados y recarga `Prelude`. - `:info`(`:i`). *MUY IMPORTANTE* Brinda la documentación sobre una función. Ejemplo ```haskell ghci> :i (+) type Num :: * -> Constraint class Num a where (+) :: a -> a -> a ... -- Defined in ‘GHC.Num’ infixl 6 + ``` De donde determinamos que el operador suma es, dado un tipo `a` que pertenece a `Num`, una función que toma dos argumentos de este tipo tipo y los envía a otro del mismo tipo. Además dice donde está definida, y que el operador tiene notación (por defecto) infija (infix), es asociativa a izquiera (l de infix _l_), su precedencia es de 6 (en un rango de 0 a 9), y la función se llama `+`. === Sintaxis y bases - *Todo* en Haskell es una _expresión_ o una _declaración_. - Las expresiones pueden ser valores, combinaciones de valores, y/o funciones aplicadas a valores. - Las declaraciones son ligaduras (_bindings_) de alto nivel que nos permiten asignar nombres a las expresiones para referirnos a ellas después. - Definimos la forma normal de una expresión en Haskell de forma análoga a lo forma beta normal de una expresión en el calcula lambda. A las expresiones reducbiles se les llama _redexes_. - Los valores son expresiones que no pueden ser reducidas. Por lo tanto son el punto final de toda reducción. - Haskell no evalúa todo hasta su forma normal por defecto. En cambio solo evalúa hasta su _forma normal debil_ o _weak head normal form (WHNF)_. Esto significa que sólo reemplaza las ligaduras al evaluar, pero no continúa. Ejemplo: ```haskell (\f -> (1, 2 + f)) 2 -- Reduces to (1, 2 + 2) ``` La evaluación de `2 + 2` no se ejecutará hasta que otra expresión lo requiera. - Las funciones prefijas pueden usarse en notación infija rodeando el nombre de la función con backticks: ``` div 1 2 -> 1 `div` 2 ```. Las funciones binarias infijas (operadores) pueden usarse en notación prefija rodeando al operador con paréntesis: ``` 1 + 2 -> (+) 1 2 ```. - Si el nombre de una función es alfanumérico, es una función prefijo por defecto. Si su nombre es un símbolo, es infija por defecto. - Las declaraciones de un módulo se hacen mediante la sintaxis: ```haskell module MyModuleName where ... ``` === Estilo y formato del código - La regla básica de indentación en Haskell es que el código que es parte de una expresión debería estar indentada bajo el comienzo de esa expresión. Más aún, partes de la expresión que están agrupadas deberían estar indentadas al mismo nivel. Ejemplos: ```haskell let x = 3 y = 4 -- or let x = 3 y = 4 -- or foo x = let y = x * 2 z = x ^ 2 in 2 * y * z ``` - Cortar una línea debería reservarse para cuando la línea supera 100 columnas en ancho. === Aritmética en Haskell - Más allá de los operadores convencionales, hay 4 operadores que pueden ser confusos: - `div` y `quot`. Ambos realizan división entera, pero `div` redondea al piso del valor, mientras que `quot` redondea hacia el cero. Ejemplo: ```haskell (/) 10 (-3) == -3.3333 div 10 (-3) == -4 -- rounds down. floor(-3.333)=-4 quot 10 (-3) == -3 -- rounds toward zero. -3 is closer to 0 than -4. ``` - `mod` y `rem`. `rem` retorna el residuo exacto de la operación (que bien podría ser un número negativo), mientras que `mod x n` retorna el número entre `0` y `n-1` correspondiente, en módulo `n`, al residuo. === Números negativos y sobrecarga de operadores - El operador unario `-` en Haskell no es más que azucar sintáctica para `negate`. - El operador `-` tiene dos posibles interpretaciones: - Que es usado como un alias para `negate`, de donde las siguientes expresiones son semánticamente idénticas ```haskell 2000 + (-1234) -- or 2000 + (negate 1234) ``` - Que es la función sustracción, por lo que la siguiente expresión usa a `-` como resta ```haskell 2000 - 1234 ``` === Control de paréntesis - Un operador que está muy presente en el código de Haskell es `($)`. Este operador tiene la menor precedencia de todos los operadores, y se define como `f $ a = f a`. A efectos prácticos, `($)` permite que se evalúe primero todo lo que está a la derecha, pudiendo ser usado para retrasar la aplicación de la función. ```haskell (2^) $ (*30) $ 2+2 -- Will reduce to -- (2^) $ (*30) 4 -- (2^) 120 -- 2^120 ``` - Cuando se quiere referir a una función infija sin aplicar ningún argumento, o cuando se quiere usar como un operador prefijo en vez de infijo, en ambos casos se rodea de paréntesis al operador. - A la sintaxis más concisa que aplica parcialmente argumentos a los operadores infijos, tal como `(2^)` o `(+1)`, se le llama _sectioning_. Cuando la función es conmutativa el resultado no cambia sin importar cómo se aplica el _sectioning_, sin embargo, si la función no conmuta el orden sí importa, ya que: ```haskell (1/) 2 -> 0.5 (/1) 2 -> 2.0 ``` - La resta es un caso especial, ya que, debido a la sobrecarga del operador unario, ```haskell 2 - 1 == (-) 2 1 -- but (-2) 1 -> Error ``` Por lo tanto el sectioning sólo funciona con el operador a derecha `(1-) 4 -> -3`, o para hacerlo por la izquierda, llamando a la función `substract`, ```haskell (substract 2) 1 -> -1 -- instead of (-2) 1 ```.
https://github.com/Lelidle/Q12-cs-scripts
https://raw.githubusercontent.com/Lelidle/Q12-cs-scripts/main/architecture.typ
typst
#import "template.typ": * #import "@preview/truthfy:0.2.0": generate-table, generate-empty #import "@preview/tablex:0.0.6": tablex, cellx, rowspanx, colspanx #import "@preview/codelst:2.0.0": sourcecode #show: setup #set heading ( numbering: "1." ) #let sc = sourcecode.with( numbers-style: (lno) => text( size: 10pt, font: "Times New Roman", fill: rgb(255,255,255), str(lno) ), frame: block.with( stroke: 1pt + rgb("#a2aabc"), radius: 2pt, inset: (x: 10pt, y: 5pt), fill: rgb("555555") ) ) #let hm = h(1mm) #v(1fr) #align(center)[#text(32pt)[Funktionsweise eines Rechners \ #align(center)[#image("images/architecture.png", width: 80%)] ] \ Stable Diffusion Art "Computer Architecture"] #v(1fr) #pagebreak() #set page( header: align(right)[ Funktionsweise eines Rechners - Skript 2inf1 \ ], numbering: "1" ) #show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } #outline(title: "Inhaltsverzeichnis", indent: auto) #pagebreak() = Historisches #grid(rows:1, columns:(50%,50%), gutter:10pt, [Die Entwicklung von Computern erstreckt sich über mehrere Jahrhunderte und umfasst zahlreiche bedeutende Meilensteine. Ursprünglich als mechanische Rechenhilfen konzipiert, begann die Evolution der Computer im antiken Griechenland mit mit sehr primitiven Erfindungen wie dem Abakus - eher noch eine Rechenhilfe. Im 19. Jahrhundert entwickelten sich mechanische Rechenmaschinen wie die #link("https://de.wikipedia.org/wiki/Analytical_Engine")[Analytical Engine] von <NAME> und Ada Lovelace, die als erste Programmiererin gilt. Babbages erste Konstruktion - die Differenzmaschine - war noch auf eine Aufgabe spezialisert, die Analytical Engine dagegen sollte allgemeiner eine Problemlösemaschine sein. ],[ #align(center)[#image("images/analytical_engine.jpg", width:90%)_Analytical Engine, Quelle: Wikipedia_]]) Der Wendepunkt in der Computerentwicklung kam im 20. Jahrhundert mit der Erfindung des Transistors, der die Grundlage für kleinere, effizientere und zuverlässigere Rechner legte. Die Ära der Großrechner begann in den 1940er Jahren mit dem #link("https://de.wikipedia.org/wiki/ENIAC")[ENIAC], gefolgt vom #link("https://de.wikipedia.org/wiki/UNIVAC_I")[UNIVAC], das erstmals für kommerzielle Zwecke eingesetzt wurde. #grid(rows:1, columns:(50%,50%), gutter:10pt, [#align(center)[#image("images/eniac.jpg", width:90%)_ENIAC, Quelle: Wikipedia_] ],[Die bahnbrechende Arbeit von Pionieren wie <NAME> in der Kryptographie und theoretischen Informatik sowie von <NAME>, die den ersten Compiler entwickelte, legte den Grundstein für die moderne Computerwissenschaft. Die Entwicklung der #link("https://de.wikipedia.org/wiki/Integrierter_Schaltkreis")[integrierten Schaltkreise] in den 1950er und 1960er Jahren führte zu kleineren, leistungsfähigeren und kostengünstigeren Computern. Spätestens zu diesem Zeitpunkt nahm die Entwicklung dramatisch an Fahrt auf. ]) In den 1970er Jahren revolutionierte die Einführung des Personal Computers (PC) durch Unternehmen wie Apple und IBM die Computerlandschaft. Die Popularisierung grafischer Benutzeroberflächen und Betriebssysteme wie MS-DOS und später Microsoft Windows trugen zur Verbreitung des Computereinsatzes bei. Die fortlaufende Miniaturisierung von Chips gemäß #link("https://de.wikipedia.org/wiki/Mooresches_Gesetz")[Moores Gesetz] ermöglichte die Entwicklung leistungsfähigerer Prozessoren und Speicher. Jedes Smartphone ist - obwohl täglicher Gebrauchsgegenstand - ein kleines Wunderwerk der Technik. In diesem Skript können wir nur sehr wenig der tatsächlichen Funktionsweise moderner Rechner erkunden. Stattdessen beschäftigen wir uns - neben grundlegender Schaltungslogik - vorwiegend mit einer (virtuellen) #link("https://de.wikipedia.org/wiki/Registermaschine")[Registermaschine]. #pagebreak() = Elektronik == Transistoren Die moderne Elektronik ist untrennbar mit dem Begriff des *Transistors* verbunden. Ein Transistor ist im Wesentlichen ein (ggf. mikroskopisch kleiner) Schalte. Die untenstehende Abbildung zeigt schematisch den Aufbau. #grid(columns: (40%,60%), rows:1, gutter:10pt, [#image("images/transistor.png")],[Sobald die *Spannung zwischen Gate und Source* (also die Potentialdifferenz zwischen G und S) einen bestimmten Wert überschreitet, wird der Transistor, also die Verbindung zwischen Drain und Source, leitend. Man sagt, der *Transistor "schaltet"*. Ein häufiger Schwellenwert, der überschritten werden muss, ist 0,7 V. Wenn die *Spannung zwischen Gate und Source zu klein* bzw. gleich Null ist, dann ist der Transistor nicht leitend, also herrscht zwischen Drain und Source ein sehr großer Widerstand. Man sagt, der Transistor "sperrt". D.h. unser Gate-Anschluss fungiert als Schalter für den Stromfluss zwischen Drain und Source. ]) In der *digitalen Elektronik* interpretiert man Potentialwerte binär, man spricht also nur noch von "hohem Potential" oder "niedrigem Potential" (also "high" oder "low"). Eine typische Größenordnung für ein hohes Potential ist 5 V. Es spielt keine Rolle, ob das Potential an einer Stelle 0,2 V oder 0,4 V beträgt, es ist einfach nur niedrig. Ebenso spielt es keine Rolle, ob es 4,1 V oder 4,7 V beträgt, es ist einfach nur hoch. *Hohes bzw. niedriges Potential* wird dann durch den *Wert 1 bzw. 0* ausgedrückt. In der Informatik denken wir in den seltensten Fällen noch direkt über Transistoren nach (das ist das Feld der Ingenieure und Elektrotechniker), aber auf einem grundlegenden Niveau sind die Realisierungen *logischer Funktionen* interessant, also die Frage: wie können wir beispielsweise eine AND-Beziehung realisieren (z.B. für die Frage, ob zwei boolean Variablen denselben Wert annehmen). Die Verknüpfung zur klassischen Logik ist hier natürlich offensichtlich, im Folgenden findet sich eine sogenannte *Wahrheitstabelle* für einige der logischen Operatoren "und" $and$ bzw. $or$ "oder". #align(center)[ #generate-table($A and B$, $A or B$) ] Wenn wir 0 und 1 wieder wie oben als "Strom fliesst nicht" und "Strom fliesst" interpretieren, so müssten wir also jeweils eine Schaltung schaffen, die der entsprechenden Tabelle entspricht. D.h. für AND brauchen wir eine Schaltung, bei der nur dann Strom fliesst, wenn *beide* Eingabewerte geschaltet werden. Die Physik der Mittelstufe rät uns dann, in irgendeiner Form eine *Reihenschaltung* zu verwenden. Mit einer *Parallelschaltung* können wir beispielsweise eine NOR-Funktion realisieren, d.h. ein "invertiertes Oder" (Schauen wir uns obige Wahrheitstabelle an, so darf dort nur Strom fliessen, wenn beide Eingangswerte auf 0 gesetzt sind). Für diesen Fall hier einmal konkret: Seien $E_1$ und $E_2$ zwei voneinander unabhängige Eingangspotentiale und $A$ das Ausgangspotential, das wir messen wollen. Ist $E_1 = 1$ und $E_2 = 0$, dann leitet der linke Transistor und der rechte sperrt, der *Gesamtwiderstand* der beiden Transistoren ist wegen des leitenden linken Transistors *fast Null* (es ist in der Parallelschaltung nur nötig, dass einer der beiden Zweige gut leitet), fast das ganze Potential fällt an dem ohm'schen Widerstand ab, das Potential im Punkt A ist also nahe bei 0 V, also gilt: $A = 0$ #grid(columns:(50%,50%), rows: 1, gutter:10pt,[#image("images/NOR.png")], [#v(1.5cm)Mit der zugehörigen Wahrheitstabelle: #align(center)[#tablex(rows:5, columns:3, map-rows: (row, cells) => cells.map(c => if c == none { c } else { (..c, fill: if row < 1 {blue.lighten(50%)}) } ), [$E_1$],[$E_2$], [$A$], [0],[0],[1],[0],[1],[0], [1],[0],[0],[1],[1],[0])]]) == Logische Schaltungen *Übersicht über die "klassischen" logischen Funktionen mit zwei Eingangswerten* #align(center)[ #tablex(rows:5, columns:8, map-rows: (row, cells) => cells.map(c => if c == none { c } else { (..c, fill: if row < 1 {blue.lighten(50%)}) } ), [*A*],[*B*],[*AND*],[*NAND*],[*OR*],[*NOR*],[*XOR*],[*XNOR*], [0],[0],[0],[1],[0],[1],[0],[1], [0],[1],[0],[1],[1],[0],[1],[0], [1],[0],[0],[1],[1],[0],[1],[0], [1],[1],[1],[0],[1],[0],[0],[1]) ] Eine mögliche Darstellung in Schaltplänen sieht so aus:(es sind jedoch viele Notationen gebräuchlich): #align(center)[#image("images/schaltungen.png")] Soweit können wir nur einzelne Wahrheitswerte bilden, im Folgenden soll kurz skizziert werden, wie wir auf Basis dieser *Logikgatter* zu "Rechnungen" wie z.B. der Addition von Binärzahlen kommen. == *Halbaddierer und Volladdierer* Ein Halbaddierer kann zwei einstellige Binärzahlen miteinander addieren. Im Gegensatz zu obigen Gattern besitzt er zwei Eingänge *und* zwei Ausgänge. Ein Ausgang ist dafür gedacht den *Übertrag* (also den "Rest") weiterzugeben, der andere gibt die eigentliche Summe weiter. #let r(body) = text(red)[#body] #let b(body) = text(blue)[#body] Ein Halbaddierer wird üblicherweise mit einem #b[AND] und einem #r[XOR]-Gatter realisiert: #grid(columns:(50%,50%), rows:1, gutter:10pt, [#v(0.5cm)#align(center)[#tablex(rows:5, columns:4, map-rows: (row, cells) => cells.map(c => if c == none { c } else { (..c, fill: if row < 1 {blue.lighten(50%)}) } ), [*X*],[*Y*], [#r[*S*]], [#b[*C*]], [0],[0],[#r[0]],[#b[0]], [0],[1],[#r[1]],[#b[0]], [1],[0],[#r[1]],[#b[0]], [1],[1],[#r[0]],[#b[1]])]],[#image("images/halbaddierer.png", width:50%)]) *Beispiel*: $X = 1$ und $Y = 1$ ist der interessante Fall, denn hier tritt der Übertragsfall auf. Das AND-Gatter stellt sicher, dass der Übertrag auf 1 gesetzt wird (dies ist auch der einzige Fall in dem dies passieren kann) und das XOR-Gatter liefert uns die gewünschte $0$ ($1 + 1 = 0$ mit Übertrag 1!) Diese Halbaddierer alleine sind noch nicht wirklich beeindruckend (lässt man die Magie der Elektrotechnik außer Acht). Nützlicher wird bereits der *Volladierer*, der drei einstellige Binärzahlen addieren kann. Er besteht im Wesentlichen aus zwei Halbaddierern und einem OR-Gatter (realisierbar mit ca. 25 Transistoren!). #grid(columns:(30%,70%), rows:1, gutter:10pt, [#align(center)[#tablex(rows:9, columns:5, inset:8pt, map-rows: (row, cells) => cells.map(c => if c == none { c } else { (..c, fill: if row < 1 {blue.lighten(50%)}) } ), [*X*],[*Y*],[*$C_("in")$*], [#r[*S*]], [#b[*$C_("out")$*]], [0],[0],[0],[#r[0]],[#b[0]], [0],[1],[0],[#r[1]],[#b[0]], [1],[0],[0],[#r[1]],[#b[0]], [1],[1],[0],[#r[0]],[#b[1]], [0],[0],[1],[#r[1]],[#b[0]], [0],[1],[1],[#r[0]],[#b[1]], [1],[0],[1],[#r[0]],[#b[1]], [1],[1],[1],[#r[1]],[#b[1]] )]],[#v(0.2mm)#image("images/volladdierer.png")]) Die Benennung des dritten Eingangs als $C_("in")$ legt bereits nahe, dass sich mit Volladierern ganze Addiernetzwerke realisieren lassen, die dann nicht nur einstellige Binärzahlen addieren können. Für jede Stelle der Summe zweier Binärzahlen benötigt man dann einen Volladdierer. Man verbindet jeweils $C_("in")$ des nächstens Volladdierers mit $C_("out")$ des aktuellen: #grid(columns:(70%,30%), rows:1, gutter:10pt, [#image("images/addiererkette.png")],[#image("images/addition.png")]) Diese Architektur wird "Ripple Carry Adder" genannt und ist heutzutage nicht mehr zeitgemäß, veranschaulicht aber das grundlegende Prinzip. Das Problem an diesem Ansatz ist, dass jeder der Volladierer auf den jeweils vorangehenden warten muss, der sogenannte *kritische Pfad* durch diese Schaltung ist also sehr lang. #hinweis(customTitle: "Für Experten")[Etwas moderner sind z.B. "Carry Lookahead"- Ansätze, die versuchen diese Wartezeiten zu reduzieren. Details dazu finden sich z.B. #link("https://en.wikipedia.org/wiki/Carry-lookahead_adder")[hier].] Für einen 64-Bit-Addierer würde man außerdem mit dieser Schaltungslogik bereits 1600 Transistoren benötigen! #align(center)[#image("images/64bitaddition.png", width:30%)] Hier geht es bisher nur um Addition! Es ist also leicht vorstellbar, dass für komplexere Aufgaben noch weitaus mehr Transistoren notwendig sind. Bisher schien das wenig problematisch, denn es wurde das sogenannte *Moore'sche Gesetz* formuliert: "Die Anzahl der Transistoren integrierter Schaltkreise verdoppelt sich im Durchschnitt alle zwei Jahre" #align(center)[#image("images/mooreslaw.png") \ Quelle: #link("https://de.wikipedia.org/wiki/Mooresches_Gesetz")[Wikipedia]] In der Darstellung ist die y-Achse, also die Anzahl der Transistoren logarithmisch skaliert. Damit wird das exponentielle Wachstum durch die Gerade dargestellt, die durch die gegebenen Punkte approximiert werden kann. *Beispiel*: Im Jahr 1971 hatte der Intel 4004 2.250 Transistoren eingebaut, die eine Strukturgröße von $10.000 "nm"$ aufwiesen. Der Apple M1 im Jahr 2020 hatte bereits $16.000.000.000$ Transistoren bei einer Strukturgröße von $5 "nm"$ pro Transistor. Natürlich handelt es sich hier nicht um ein bindendes Gesetz, sondern um eine reine Beobachtung und es bleibt abzuwarten, wie lange der Trend noch fortgeführt werden kann. Bei extrem kleinen Strukturen werden zunehmend Quanteneffekte relevant, die die weitere Verkleinerung verhindern könnten. Moore selbst sagte das Ende seines Gesetzes für ca. 2022 voraus, die Industrie zeigt sich aber selbstsicher und behauptet noch einige Jahre durchhalten zu können. #hinweis[Die Anzahl der Transistoren alleine ist natürlich noch nicht entscheidend dafür, wie leistungsfähig ein Prozessor ist. Die einzelnen Kerne werden zwar auch immer leistungsfähiger, allerdings hat die Ära der Multi-Core-Prozessoren die eigentliche Geschwindigkeitsverbesserung in den letzten 2 Jahrzehnten gebracht. ] Die folgende Abbildung zeigt eine Übersicht über die Verbesserung der Prozessorgeschwindigkeit von einzelnen Kernen: #align(center)[#image("images/singlecore.png", width:75%) \ Quelle: #link("https://www.researchgate.net/figure/Transistor-CPU-Speeds-and-Cooling-Power-Ref-10_fig1_311915885")[ResearchGate]] #pagebreak() == Speicherung von Daten === DRAM Das vorangehende Kapitel lieferte einen sehr kleinen Einblick in die Grundlagen der Rechentechnik. Neben der Berechnung spielt aber natürlich auch die *Speicherung* von Daten eine wesentliche Rolle, wenn man die Architektur eines Rechners verstehen möchte. Wir betrachten hier ein vereinfachtes Modell einer *DRAM-Zelle* (Dynamic Random Access Memory). Eine solche Zelle besteht im Wesentlichen aus einem Kondensator und einem Transistor. Jede Speicherzelle kann dabei genau ein Bit speichern. #grid(columns:2, rows:1, gutter:10pt, [*Lesen bzw. Schreiben der Information*: Der Kondensator C kann geladen (=1) oder ungeladen (=0) sein. Falls an der Wortleitung, also am Gate des Transistors, das Potential "low" herrscht, sperrt der Transistor. Bitleitung und Kondensator sind nicht verbunden. Falls an der Wortleitung, also am Gate des Transistors, das Potential "high" herrscht, leitet der Transistor. Dann befindet sich die Bitleitung auf dem gleichen Potential wie der Kondensator und man kann sein Potential (also die gespeicherte Information 1 bzw. 0) messen oder verändern, also eine Information lesen oder schreiben. ], [#align(center)[#image("images/dramzelle.png") \ #link("https://de.wikipedia.org/wiki/Dynamic_Random_Access_Memory")[Wikipedia]]] ) Mehrere Speicherzellen zusammen bilden eine *Speicherzeile* (Auch *Page* genannt). Wird auf eine Wortleitung ein Signal gelegt, sö können aus allen Speicherzellen der Zeile die darin gespeicherten Informationen gleichzeitig über die Bitleitungen ausgelesen werden, bzw. die auf den Bitleitungen liegenden Signale können simultan in die Zellen dieser Zeile hineingeschrieben werden. Man könnte sich das Ganze also so vorstellen: - *Eine Wortleitung* ist ein Schlüssel, der alle Zellen einer Speicherzeile öffnen kann. - *Mehrere Bitleitungen* sind die Türen, die den Zugang zu den jeweiligen Zellen ermöglichen. #align(center)[#image("images/speicherzeile.png", width:80%)\ Quelle: #link("https://de.wikipedia.org/wiki/Dynamic_Random_Access_Memory")[Wikipedia]] DRAM wird hauptsächlich in "großen" Computern eingesetzt. Die Tatsache, dass die mikroskopischen Kondensatoren z.B. durch den Tunneleffekt an Spannung verlieren ist hier leichter zu kompensieren (im Prinzip wird der RAM periodisch "aufgefrischt"). Allgemein gilt außerdem: wird der Rechner ausgeschalten, so geht die Information im RAM verloren (Moderne Betriebssysteme versuchen hier manchmal Abhilfe zu schaffen, dies funktioniert aber nicht verlässlich). Man nennt RAM im Fachbegriff deswegen auch *flüchtig*. === SRAM In der Welt der kleinen Computer (Mikrocontroller) wird eine alternative Bauweise verwendet, die *Static Random Access Memory*. Der große Vorteil dieser Technologie besteht darin, dass kein Auffrischen notwendig ist. Der Nachteil dagegen, dass diese Bauteile in der Regel deutlich größer sind als Speicherzellen im DRAM. Paradoxerweise ist dies für die Microcontroller-Welt kein Problem, da hier unser RAM nicht im Gigabyte, sondern eher im Megabyte oder Kilobyte Bereich liegen kann. Im Wesentlichen besteht eine SRAM-Zelle aus 6 Transistoren, für Interessierte findet sich untenstehend der Schaltplan für die übliche Bauart. #align(center)[#image("images/sram.png", width: 60%) \ Quelle: #link("https://de.wikipedia.org/wiki/Static_random-access_memory")[Wikipedia]] #pagebreak() == Adressierung und Datenübertragung Neben der eigentlichen Speicherung der Daten muss natürlich auch die Übertragung der Daten geregelt werden, einerseits muss ein Prozessor (also eine irgendwie geartete "Recheneinheit") Daten an einer bestimmten "Stelle" im Speicher anfordern können - andererseits müssen diese Daten dann auch geliefert werden. Die entsprechenden Leitungen werden *Adressbus* (für die Adressen der Speicherzellen) und *Datenbus* genannt. Schematisch dargestellt sieht dies so aus: #align(center)[#image("images/datenadressbus.png")] #hinweis[Hier wird nur schematisch der Aufbau dargestellt, Speicherzellen sind z.B. in der Regel in einem 2D-(oder sogar 3D)Gitter angeordnet und nicht linear. Auch eine Adressbusbreite von 3 ist unüblich, verwendet wurden und werden: $4,8,16,32,48$. (Interessanterweise entsprechen die 48 der 64-Bit Architektur!) In obiger Darstellung lässt sich aber schön darstellen, dass man mit einem Adressbus der Länge 3 wirklich nur 8 Adressen im RAM ansprechen kann!] *Allgemeiner betrachtet* Mit einem Adressbus der Breite $a$ - dabei bedeutet "Breite" letztendlich nur "Anzahl der Leitungen" - kann man $2^a$ Adressen codieren bzw. ansprechen, da wir "nur" $2^a$ Binärzahlen so codieren können. Die Breite des Datenbusses bestimmt die Anzahl an Bits, die pro Adresse abgerufen werden können, hier im Allgemeinen Fall also *d Bit* pro Adresse. Um den Speicher vollständig adressieren zu können, muss er also innerhalb der Größe *$2^a dot d$* bleiben, da ansonsten nicht genug eindeutige Adressen existieren. #hinweis[Dadurch ergibt sich, dass bei einer 32 Bit-Maschine "nur" $2^32$ Adressen angesprochen werden können, das entspricht etwa 4,3 Gigabyte RAM. Die 64 Bit-Maschinen verwenden dagegen "nur" 48 physikalische Leitungen, da wir damit etwa 280 Terabyte RAM unterstützen können, das ist ausreichend :) Die verbleibenden 16 Bits werden "virtuell" verwendet. ] == Zeichencodierungen Neben Zahlen müssen auch Buchstaben, Zeichen und anderes codiert werden. Der "Klassiker" dieser Codierungen ist die *ASCII-Tabelle* (American Standard Code for Information Interchange). Die ursprüngliche Tabelle sieht so aus: #align(center)[#image("images/asciichart.png") \ Quelle: #link("https://en.wikipedia.org/wiki/ASCII")[Wikipedia]] Beispielsweise hat der Buchstabe *e* die Nummer 101, also die Bitfolge $0110 0101$. Jeder Code verwendet dabei nur 7 Bit pro Zeichen. D.h. mit dieser ursprünglichen Codierung können "nur" 128 verschiedene Zeichen codiert werden. Das hat sich als nicht ausreichend herausgestellt. Heute gebräuchlicher ist der sogenannte #link("https://de.wikipedia.org/wiki/Unicode")[*Unicode*-Standard]. Hier werden $2^16 = 65.536$ pro Ebene codiert und es gibt insgesamt 17 Ebenen. Jedes einzelne Zeichen wird also durch die Angabe der Ebene und eine 16 Bit lange Positionsangabe eindeutig beschreiben. *Beispiel*: der Smiley mit Herzchen-Augen hat die Nummer 1f60d. Genaueres findet sich z.B. #link("http://www.unicode.org/charts/")[hier]. = Eine Registermaschine Unser Buch listet als wesentliche Komponenten/Eigenschaften eines grundlegenden "Rechners" (was für uns der Prototyp einer Registermaschine ist): 1. Zentraleinheit(en) mit Steuer- und Rechenwerken (*ALU* - Arithmetic Logic Unit) 2. Speicherelemente (Speicherwerk) 3. Ein- bzw. Ausgabeeinheiten 4. Bus-Systeme zum Datentransport Bis auf die Ein- und Ausgabeeinheiten also genau die Elemente, die zuvor schon in Grundzügen besprochen worden sind. Diese wurde nach *von Neumann* benannt, der diese Definition auf Basis der Arbeit von Zuse festgelegt hat und heißt deswegen *Von-Neumann-Architektur*. #align(center)[#image("images/vonneumann.png", width: 45%) \ Quelle: #link("https://de.wikipedia.org/wiki/Von-Neumann-Architektur")[Wikipedia]] #merke[Die oben dargestellte Struktur und die Erklärung der grundlegenden Funktionsweise der Komponenten sind neben der Programmierung der Minimaschine wesentlich für das Abitur, schriftlich, aber insbesondere auch mündlich!] Schematische Darstellung des Bussystems: #align(center)[#image("images/von_neumann_struktur.png", width: 70%) \ Quelle: #link("https://de.wikipedia.org/wiki/Von-Neumann-Architektur")[Wikipedia]] Ein etwas anderer Überblick, der an die später verwendete Minimaschine angelehnt ist: #align(center)[#image("images/schemaRegistermaschine.png")] Im folgenden werden die einzelnen Komponenten etwas genauer beleuchtet. == ALU Eine arithmetisch-logische-Einheit ist für die eigentliche Rechenarbeit zuständig. Sie hat in der Regel die folgenden Komponenten: 1. *Akkumulator*: Speichert temporär (!) Daten während der Rechenoperationen (es wird z.B. der Wert einer Speicherzelle auf den Wert des Akkumulators addiert und anschließend wieder im Akkumulator abgelegt). 2. *Datenregister*: Hierbei handelt es sich um weitere Speicherorte für Zwischenergebnisse und Werte, die nicht in den "normalen" Speicher geschrieben werden sollen - insbesondere ist die Zugriffsgeschwindigkeit der ALU auf die Register sehr schnell. #hinweis(customTitle: "Für die Experten")[- Viele Architekturen erlauben den Rechenwerken nur die Manipulation der Daten in den Registern und *nicht* an anderen Speicherorten wie dem RAM. - Ein einzelnes Register hat i.d.R. die Größe einer Zweierpotenz, d.h. 8 Bit, 16 Bit, usw. Das limitiert auch die Größe der Zahlen, mit denen wir unmittelbar rechnen können! \ Allgemeiner: Sie sind so groß wie ein "Wort", dass der Prozessor verwenden kann. ] 3. *Funktionseinheit - Befehlsregister*: Steuert die Art der Operationen, die die ALU ausführt. 4. *Statusregister (Flags)*: Liefert Informationen über das Ergebnis der durchgeführten Operation, indem sogenannte flags gesetzt werden. Diese können z.B. anzeigen, ob das Ergebnis null ist, nicht-negativ oder einen Überlauf anzeigen. 5. *Ergebnisregister*: Speichert das Endergebnis der Berechnung, bevor es wieder in den Akkumulator, andere Register (oder den Speicher!) geschoben wird. #pagebreak() == Speicherwerk Das Speicherwerk wird von Von Neumann als gleich große, fortlaufend nummerierte Zellen eingeteilt. Jede Zelle speichert eine folge aus Bits (siehe DRAM oben). Wir werden uns auf 8-Bit Speicherzellen beschränken, dies entspricht also einem Byte (oder 2 Hex-Zahlen - wir werden sehen, dass in der Minimaschine die Inhalte der Speicherzellen wieder hexadezimal dargestellt werden). #merke[In diesen Zellen werden sowohl die *Befehle* als auch die *Daten* eines Programms gespeichert. Dies ist ein offensichtliches Sicherheitsrisiko bzw. eine Problemquelle. Ein Programm kann sich beispielsweise aus Versehen "selbst löschen", indem es seinen Befehlsbereich mit Daten überschreibt.] == Ein- bzw. Ausgabeeinheiten Der am wenigsten mysteriöse Teil der Architektur. Hier sind die typischen Eingabegeräte wie Tastaturen, Mäuse, etc. gemeint. Auf der Ausgabeseite stehen z.B. Monitore, Drucker oder Lautsprecher. == Bus-Systeme Der bereits mehrfach verwendete Begriff *Bus* steht für eine physikalische Verbindung zwischen verschiedenen Komponenten, z.B. Kabel oder Lichtwellenleiter. Diese Verbindungen transportieren die Signale in Form elektromagnetischen Impulsen. Die verschiedenen Kabel werden dann gedanklich nach ihren Aufgaben getrennt. So ergeben sich die bereits erwähnten: 1. *Datenbusse*, die die eigentlichen "Daten" hin und herschieben. 2. *Steuerbusse*, die die Kommunikation zwischen den einzelnen Werken steuern. 3. *Adressbusse*, die zur Übermittlung des Speicherorts für Daten oder Befehle verwendet werden. #hinweis[Auch hier spielen die Begriffe *parallel* und *seriell* wieder eine Rolle. 1. Ein *paralleler* Bus besteht aus mehreren Einzelleitungen, über die mehrere Signale gleichzeitig übertragen werden können, z.B. der Adressbus. 2. Ein *serieller* Bus überträgt die Informationen als Folge einzelner aufeinander folgender Signale. Der universelle serielle Bus (USB) ist der Standard für die Kommunikation mit externen Geräten.] *Für die Experten*: asymptotisch gesehen ist ein serieller Bus in der Regel sogar besser als ein paralleler Bus, da die "Entschlüsselungselektronik" komplexer sein muss und die Vorteile der parallelen Übertragung häufig "auffrisst". == Zusammenfassung Eine Registermaschine besteht aus einem *Arbeitsspeicher* für die Programme und Daten, sowie einer Reihe von *Registern* und (mindestens) einer *ALU*. Wir verwenden im folgenden die folgenden Register: 1. *Befehlszähler BZ*: enthält die Speicheradresse des nächsten zu bearbeitenden Befehl. 2. *Statusregister SR*: enthält die Informationen über das Ergebnis der letzten Operation. 3. *Datenregister A, R1, R2,...*: dienen zur Ablagen der Daten. Das Datenregister Akkumulator *A* enthält dabei im speziellen den Eingabewert für den folgenden Rechenbefehl. = Programmierung mit der Minimaschine Zur Programmierung von Registermaschinen werden *Assembler-Programme* verwendet. Hierbei handelt es sich um Programmiersprachen, die nur die elementaren, maschinennahen Befehle enthalten. Dazu gehören in der Regel: 1. *Transportbefehle* zum Laden der Datenregister, z.B. _LOAD_ oder _STORE_. 2. *Artihmetische Befehle* zur Ausführung von Rechnungen, z.B: _ADD_, _SUB_, _MUL_, etc. 3. *Sprungbefehle*, die zu einer bestimmten "Marke" im Code springen können, z.B. _JMP_. 4. *logische Verknüpfungen*: _AND_, _OR_, etc. 5. *END* oder *HOLD*, damit wir auch aufhören können. Im Folgenden werden wir diese Befehle nach und nach genauer betrachten und damit die sogenannte *Minimaschine* programmieren (die Simulation einer Registermaschine durch Java). (8-Bit Registermaschine) == Aufbau und Verwendung Minimaschine Startet man die Minimaschine, so sieht diese sehr ähnlich aus, wie die obige Veranschaulichung der Von-Neumann-Architektur: #align(center)[#image("images/minimaschine.png", width:75%)] Zusätzlich kann auch der Speicher direkt betrachtet werden, bevor ein Programm geladen wurde steht in jeder Speicherzelle eine $0$: #align(center)[#image("images/ram.png", width:70%)] Scrollt man nach unten, so stellt man fest, dass die Speicherzellen bei $65.536$ enden, d.h. unser virtueller *Adressbus* muss hier 16 Bit haben, da wir im Speicher offenbar $2^16$ Zellen ansteuern können. Bisher passiert noch nicht viel, es muss erst ein Programm geschrieben werden! Dies kann unter "Ablage" -> "Neu" oder "Öffnen" in einem weiteren Fenster geschrieben werden. Hat man sein Programm geschrieben kann man unter "Werkzeuge" -> "assemblieren" das Programm in den Minimaschinen-Speicher laden. #align(center)[#image("images/assemblieren.png", width:50%)] Danach kann mit den Schaltflächen "Ausführen", "Einzelschritt" oder "Mikroschritt" in der CPU-Kontrolle das Programm ausgeführt werden, je nach gewünschter Feingranularität. #hinweis[Nach der vollständigen Ausführung des Programms, kann es nicht sofort neu gestartet werden - zunächst muss die Maschine in ihren Anfangszustand zurückversetzt werden unter "Werkzeuge" -> "CPU rücksetzen" im Fenster "CPU-Kontrolle".] #task[Machen Sie sich mit den verschiedenen Fenstern vertraut und öffnen Sie das bereitgestellte Programm "example.mia". Laden Sie das Programm in die Minimaschine und testen Sie die verschiedenen Ausführungsmodi. Geben Sie an, was das Ziel des Programms ist. Versuchen Sie anschließend die Zahl 40.000 mit dem Befehl _LOADI_ zu laden, betrachten Sie anschließend den Speicher und erläutern Sie, was dort zu sehen ist.] An dieser Stelle bietet es sich an einige Einstellungsmöglichkeiten des Speichers ebenfalls zu testen, unter Werkzeuge finden sich die folgenden Optionen: 1. *Große Darstellung*: für kleine Programme sehr zu empfehlen 2. *Speicher löschen*: um sicherzustellen, dass keine Programmreste enthalten sind, bevor ein neues Programm assembliert wird. 3. *Darstellung hexadezimal*: selbsterklärend 4. *Opcodes anzeigen*: hier wird auch im Speicher die Art des Befehls statt der korrespondierenden Zahl angegeben, Details dazu im nächsten Kapitel. 5. *Speicher editieren*: So könnte man vor der Ausführung noch im Speicher Änderungen einpflegen, wird von uns selten genutzt. #align(center)[#image("images/mmspeicher2.png")] == Aufbau von Maschinenbefehlen und Befehlszyklus Bevor wir konkret mit dem Schreiben von Programmen beginnen muss der *Befehlszyklus* der Minimaschine analysiert werden, also die Abfolge in der Dinge ausgeführt werden, außerdem benötigen wir einen Grundstock von konkreten Befehlen, mit denen wir arbeiten können. Ein einzelner Befehl besteht aus einem *OP-Code* und den *OP-Daten*, also aus einem bestimmten *Operator* und den zugehörigen *Operanden*, also den "Argumenten" dieses Befehls. In der Sprache, die der Minimaschine zugrunde gilt z.B.: - *276* entspricht dem LOAD-Befehl (also laden) - *277* ist der Code für den STORE-Befehl (speichern) - *266* für ADD, also die Addition, usw. #merke[In einem Minimaschinenprogramm kann eine Zahl, z.B. 15 für die Nummer einer *Speicherzelle* stehen, oder für die *Zahl* direkt, das kommt auf den entsprechenden Befehl an. Das heißt der gleiche Operand wird von unterschiedlichen Befehlen auch unterschiedlich interpretiert, z.B.: - *LOAD 15* wird den Wert der in *Speicherzelle 15* steht in den Akkumulator (in der Minimaschine oben links dargestellt) laden. - *LOADI 23* dagegen wird die *Zahl* 23 in den Akkumulator laden, von vielen Befehlen gibt es auch eine "*I-Variante*" Die Verwechselung der beiden Befehle ist eine der größten Fehlerquellen, auch im Abitur. ] Bereits in der vorangegangen Aufgabe haben wir festgestellt, dass Zahlen größer als 65.535 nicht im Speicher stehen können, es handelt sich also um eine 16-Bit Maschine. Ein Befehl besteht also aus einem 16-Bit OP-Code und einer 16-Bit Zahl. Für einen Befehl müssen also 32 Bit aus dem Speicher geladen werden. Die Ausführung des ersten Befehls beginnt immer in der nullten Speicherzelle des Arbeitsspeichers und es beginnt der *Befehlsyklus*, der sich in die folgenden Phasen gliedert. 1. *Befehlsabruf (Fetch-Phase)*: Die ALU ruft den nächsten Befehl aus dem Speicher ab, die Adresse dieses nächsten Befehls findet sich im Befehlszähler (*Instruction Pointer*), dieser wird danach außerdem inkrementiert (nicht zwingend um 1, es hängt davon ab wie "groß" ein Befehl und die zugehörigen Daten sind. Im Falle der Minimaschine wird um 2 erhöht, da jede Speicherzelle 16 Bit umfasst und wir 2 Speicherzellen weiter den nächsten Befehl finden). 2. *Befehlsdekodierung (Decode-Phase)*: Das Steuerwerk dekodiert den Befehl, wird also in eine für die ALU verständliche Form umgewandelt. Es wird sowohl der Befehlstyp als auch die Operanden entschlüsselt. 3. *Befehlsausführung (Execute-Phase)*: Der dekodierte Befehl wird vom Rechenwerk ausgeführt. In dieser Phase werden auch die verschiedenen Statusflags (in der Minimaschine links unten) gesetzt. 4. *Speicherzugriff (Memory-Access-Phase)*: Erfordert der Befehl einen Speicherzugriff, so werden die Daten in dieser Phase geladen. 5. *Ergebnisrückgabe und Weiterleitung (Write Back/Result-Phase)*: Bei den meisten Befehlen wird das Ergebnis an einen bestimmten Speicherort, z.B. Register oder Speicher geschrieben. #hinweis(customTitle: "Für Experten")[Der obige Befehlszyklus wird schon seit etwa 1970 nicht mehr so verwendet, denn er hat ein einschneidendes Problem: die Phase 4 (also der Speicherzugriff) ist zeitlich gesehen mehrere Größenordnungen größer als die Dauer der anderen Phasen. Wenn wir also einen Zyklus abwarten ist z.B. die ALU vergleichsweise lange "arbeitslos". Es gibt viele Ansätze und Technologien, wie dies beschleunigt wird, diese sind aber für das Abitur irrelevant, ein guter Ausgangspunkt für diejenigen die tiefer graben wollen ist das #link("https://de.wikipedia.org/wiki/Pipeline_(Prozessor)")[*Pipelining*].] == Befehlssatz Wir beginnen mit einem kleinen Befehlssatz und beschränken uns zunächst auf *Speicherbefehle* und *Arithmetikbefehle*: #tablex(rows:13, columns:(12%,12%,76%), colspanx(3)[*Speicherbefehle*], [*LOAD*], [Adresse], [Lädt den Wert von der angegebenen Adresse in den Akkumulator], [*LOADI*], [Zahl], [Lädt die angegebene Zahl in den Akkumulator], [*STORE*], [Adresse], [Speichert den Wert des Akkumulators an der angegebenen Adresse], colspanx(3)[*Arithmetikbefehle*], [*ADD*], [Adresse], [Addiert den Wert an der angegebenen Adresse zum Akkumulator.], [*SUB*], [Adresse], [Subtrahiert den Wert an der angegebenen Adresse vom Akkumulator.], [*MUL*], [Adresse], [Multipliziert den Wert an der angegebenen Adresse zum Akkumulator.], [*DIV*], [Adresse], [Dividiert den Wert im Akkumulator durch den Wert an der angegebenen Adresse. (Ganzzahldivision!)], [*ADDI*], [Zahl], [Addiert die angegebene Zahl zum Akkumulator. ], [*SUBI*], [Zahl], [Subtrahiert die angegebene Zahl vom Akkumulator. ], [*MULI*], [Zahl], [Multipliziert die angegebene Zahl zum Akkumulator. ], [*DIVI*], [Zahl], [Dividiert den Akkumulator durch die angegebene Zahl. (Ganzzahldivision!)], ) #pagebreak() == Das erste Programm Mit Hilfe dieses Wissens analysieren wir nun das obige Programm: #sc[```yasm LOADI 25 STORE 100 LOADI 35 STORE 101 LOAD 100 ADD 101 STORE 102 HOLD ```] Zeilenweise gelesen: 1. Lade die *Zahl* 25 in den Akkumulator 2. Speichere die Zahl im Akkumulator in der Speicherzelle mit *Adresse* 100 3.Lade die *Zahl* 35 in den Akkumulator 4. Speichere die Zahl im Akkumulator in der Speicherzelle mit *Adresse* 101 5. Lade die Zahl aus der Speicherzelle 100 in den Akkumulator 6. Addiere die Zahl in der Speicherzelle 101 zur Zahl im Akkumulator 7. Speichere die Zahl im Akkumulator in der Speicherzelle 102 8. Die Maschine hält an und beendet ihre Berechnung (ansonsten produzieren wir bei einem weiteren Schritt ggf. einen Fehler und die Maschine endet in einem Fehlerzustand) Letztendlich werden also nur die beiden Zahlen 25 und 35 addiert und das Ergebnis in der Zelle 102 gespeichert! #merke[Hier zeigt sich wieder ein großes Problem: wir könnten statt "STORE 100" in Zeile 2 natürlich auch z.B. "STORE 4" schreiben. Dadurch überschreiben wir aber unser eigenes Programm! Wenn die Zahl nicht selbst ein valider OP-Code ist stürzt das Programm an dieser Stelle ab.] #align(center)[#image("images/mmerror.png", width:80%)] == Weitere Beispiele === Mittelwert zweier Zahlen #task(customTitle: "Aufgaben")[1. Schreiben Sie ein Programm, das zwei Zahlen in den Speicherzellen 100 und 101 speichert und anschließend den Mittelwert dieser zwei Zahlen in der Speicherzelle 102 ablegt. 2. Erweitern Sie das Programm, sodass es den Mittelwert von drei Zahlen berechnet. #hinweis[Gehen Sie davon aus, dass der Mittelwert eine ganze Zahl ergibt.] ] Die Lösung findet sich auf der nächsten Seite #pagebreak() Für das erste Programm benötigen wir zusätzlich zum bisher betrachteten nur den DIVI-Befehl, um durch die Anzahl, sprich hier 2 teilen zu können. #sc[```yasm LOADI 50 STORE 100 LOADI 40 STORE 101 LOAD 100 ADD 101 DIVI 2 STORE 102 HOLD ```] Für unsere Minimaschine sind auch Kommentare möglich mit vorangestelltem *\#*, um einen besseren Überblick zu behalten: #sc[```yasm #Daten laden LOADI 3 STORE 100 LOADI 5 STORE 101 LOADI 2 STORE 102 #MW berechnen LOAD 100 ADD 101 ADD 102 DIVI 3 STORE 103 HOLD ```] Insbesondere wenn wir mit vielen Eingaben arbeiten ist es natürlich lästig (und fehleranfällig!), am Anfang alle Zahlen immer zu laden und in Zellen abzulegen. Glücklicherweise gibt es auch eine "Abkürzung", man kann sogenannte *Bezeichner* verwenden, das sähe hier z.B. so aus: #sc[```yasm #Programm: LOAD Z1 ADD Z2 ADD Z3 DIVI 3 STORE R HOLD #Daten: Z1: WORD 3 Z2: WORD 5 Z3: WORD 2 R: Word 0 ```] Im eigentlichen Programm wurden die *absoluten Adresse* durch die Label bzw. Bezeichner ersetzt. Diese Daten werden nach dem eigentlichen Programm definiert - die Bezeichner sind dabei frei wählbar.Die Definition der Label bewirkt, dass die durch den *WORD*-Befehl erzeugten Werte nach dem Assemblieren in den Speicherzellen direkt hinter dem Programm abgelegt werden. #hinweis[Ein "Wort" ist hier wieder eine 16-Bit Zahl!] Man muss sich also keine Gedanken mehr über passende Adressbereiche im Speicher machen und überlasst die Organisation des Speichers dem Betriebssystem. #hinweis[Leider ist es nicht unüblich, dass im schriftlichen Abitur die Verwendung von *absoluten* Speicheradressen explizit verlangt wird. Dann müsste hier die erste Variante dieses Programms als Lösung angegeben werden.] === Berechnung der Halbjahresleistung #task[Schreiben Sie ein Programm, dass die Halbjahresleistung in einem Fach in der Oberstufe berechnet, gehen Sie dabei von den folgenden Noten aus: - Ein kleiner Leistungsnachweis - Eine mündliche Note - Eine Abfrage - Eine Klausur Gehen Sie dabei zuerst "naiv" vor und versuchen Sie anschließend das auftretende Problem zu lösen. ] Die naive Lösung könnte z.B. so aussehen: #sc[```yasm #Programm: LOAD UB ADD KA ADD RA DIVI 3 ADD KL DIVI 2 STORE R HOLD #Daten: KL: WORD 9 UB: WORD 13 KA: WORD 9 RA: WORD 10 R: WORD 0 ```] Führt man das obige Programm aus, so wird als Ergebnis $9$ in der Zelle "R" stehen, rechnet man händisch nach, so stimmt dies nicht! Das liegt daran, dass die Nachkommastelle durch Verwendung von DIVI abgeschnitten wird. Liegt der Wert also in einem Bereich, in dem eigentlich aufgerundet wird, wird ein falsches Ergebnis angegeben. Grundsätzlich müsste also bei Werten wie $ 10.5$ oder $6.83$ oder $4.74$ aufgerundet werden. Wir haben keine direkte Möglichkeit mit Dezimalzahlen zu rechnen, deswegen brauchen wir eine andere Lösung. Eine naheliegende Überlegung wäre, einfach zu allen Werten $0.5$ zu addieren, denn dann würden alle Werte im Abrundungsbereich weiterhin zum korrekten Bereich hin abgeschnitten, die Werte im Aufrundungsbereich aber werden über die nächste Ganzzahl geschoben. Das funktioniert aber auch nicht so leicht! Denn wir können $0.5$ nicht addieren, wohl aber 5! D.h. wir können die gesamte Rechnung vorher mit den um Faktor $10$ skalierten Werten durchführen, dann $5$ addieren und danach wieder zurücksskalieren. *Beispiel von oben*: kleiner Leistungsnachweis: $9$, Abfrage: $13$, Unterrichtsbeitrag: $10$, Klausur: $9$ $ (9 + 13 + 10)/3 = 32/3 #h(1cm) (32/3 + 9) : 2 approx 9,83 $ Wird abgeschnitten! Mit der modifizierten Rechnung: $ ((9 + 13 + 10)*10)/3 = 320/3 #h(1cm) (320/3 + 90) : 2 + 5 approx 103,33 $ Teilen wir dieses Ergebnis mit DIVI 10, so erhalten wir die gewünschten 10. Umgesetzt in ein Programm ergibt sich: #sc[```yasm #Programm: LOAD UB ADD KA ADD RA MULI 10 DIVI 3 STORE temp LOAD KL MULI 10 ADD temp DIVI 2 ADDI 5 DIVI 10 STORE R HOLD #Daten: KL: WORD 9 UB: WORD 12 KA: WORD 9 RA: WORD 13 temp: WORD 0 R: WORD 0 ```] #pagebreak() === Division mit Rest Wenn wir schon keine Dezimalzahlen haben, können wir wenigstens wie in der Grundschule rechnen! #task[Schreiben Sie ein Programm, dass für eine gegebenen Division sowohl den Ganzzahlanteil, als auch das Ergebnis ausgibt!] Eine mögliche Lösung sieht wie folgt aus: #sc[```yasm #Programm: LOAD Dividend DIV Divisor STORE Ergebnis MUL Divisor STORE Rest LOAD Dividend SUB Rest STORE Rest HOLD #Daten: Dividend: WORD 23 Divisor: WORD 6 Ergebnis: WORD 0 Rest: WORD 0 ```] #v(2cm) == Erweiterung des Befehlssatzes Nach diesen ersten einfachen Programmen erweitern wir den Befehlssatz zunächst um einige weitere Arithmetikbefehle: #tablex(rows:5, columns:(12%,12%,76%), colspanx(3)[*Arithmetik-Befehle*], [*MOD*], [Adresse], [Dividiert den Wert im Akkumulator durch den Wert der angegebenen Adresse und speichert den Rest im Akkumulator. ], [*CMP*], [Adresse], [Vergleicht den Wert der angegebenen Adresse mit dem Wert im Akkumulator, wie bei der Subtraktion "akku - adresswert" und setzt die Flags. *Im Unterschied zu SUB wird der Wert im Akkumulator nicht geändert*], [*MODI*], [Adresse], [Dividiert den Wert im Akkumulator durch die angegebene Zahl und speichert den Rest im Akkumulator. ], [*CMPI*], [Adresse], [Vergleicht den Wert der angegebenen Adresse mit dem Wert im Akkumulator, wie bei der Subtraktion "akku - zahl" und setzt die Flags.], ) Damit wären natürlich einige der Aufgaben oben einfacher gewesen :) Wesentlich interessanter ist eine weitere Art von Befehlen, die *Sprung-Befehle*. Mit ihnen können wir zu einer bestimmten Anweisung springen, z.B. bedeutet *JMP 6*: In der Execute-Phase wird der Befehlszähler auf 6 gesetzt (statt wie üblich inkrementiert zu werden). Wir setzen die Ausführung des Programms also mit dem Befehl in der Speicherzelle 6 fort. Dieser Sprung-Befehl lässt sich auch mit den oben erwähnten Flags kombinieren: es gibt Befehle, die nur dann springen, falls z.B. das negative-Flag gesetzt ist, eine Übersicht: #tablex(rows:14, columns:(12%,28%,60%), colspanx(3)[*Die relevanten Flags*], [*N*], [Negative-Flag], [Wird gesetzt, wenn der Wert im Akkumulator negativ ist.], [*Z*], [Zero-Flag], [Wird gesetzt, wenn der Wert im Akkumulator Null ist.], [*V*], [Overflow-Flag], [Wird gesetzt, , wenn es bei der vorhergehenden Operation einen Overflow gab, das Ergebnis also den Zahlenbereich überschritten hat. Im Akkumulator steht somit nicht das mathematisch korrekte Ergebnis], colspanx(3)[*Sprungbefehle*], [*JMP*], [Adresse], [Setzt den Befehlszähler auf die angegebene Adresse, das Programm wird somit mit dem nächsten Befehlszyklus dort fortgesetzt. ], [*JMPN*], [Adresse], [Springt, falls das Negative-Flag gesetzt ist (Jump Negative).], [*JMPZ*], [Adresse], [Springt, falls das Zero-Flag gesetzt ist (Jump Zero).], [*JMPP*], [Adresse], [Springt, falls weder das Zero- noch das Negative-Flag gesetzt ist (Jump Positive).], [*JMPV*], [Adresse], [Springt, falls das Overflow-Flag gesetzt ist (Jump Overflow).], [*JMPNN*], [Adresse], [Springt, falls das Negative-Flag nicht gesetzt ist.], [*JMPNZ*], [Adresse], [Springt, falls das Zero-Flag nicht gesetzt ist.], [*JMPNP*], [Adresse], [Springt, falls entweder das Zero- oder das Negative-Flag gesetzt ist.], [*JMPNV*], [Adresse], [Springt, falls das Overflow-Flag nicht gesetzt ist.], ) Im Prinzip simulieren wir damit *bedingte Anweisungen*! Statt direkt eine Variable zu betrachten müssen wir aber sicher sein, dass der Wert im Akumulator ist, mit dem wir vergleichen wollen. *Beispiel*: Viele Rabatte werden erst gewährt, wenn eine gewisse Anzahl an Produkten gekauft worden sind. Das folgende Programm soll einen Rabattrechner darstellen. Erreicht die Anzahl der gekauften Produkte den in „Grenze“ gespeicherten Wert, so sind alle Produkte ab dieser Grenze auf so viel Prozent reduziert, wie es in „Prozent“ gespeichert ist. Der Originalpreis ist in „Preis“ gespeichert und gilt für alle Produkte unterhalb der Grenze. #task[Schreiben Sie ein Programm, dass die obige Aufgabenstellung mit den unten gegebenen Daten löst.] #pagebreak() #sc[```yasm #Daten Preis: WORD 20 Grenze: WORD 10 Prozent: WORD 80 Anzahl: WORD 12 Summe: WORD 0 ```] Die Lösung könnte z.B. so aussehen: #sc[```yasm LOAD Anzahl CMP Grenze JMPNN Rabatt normal: MUL Preis STORE Summe JMP Ende rabatt: SUB Grenze ADDI 1 MUL Preis MUL Prozent DIVI 100 STORE Summe LOAD Grenze SUBI 1 MUL Preis ADD Summe STORE Summe ende: HOLD #Daten Preis: WORD 20 Grenze: WORD 10 Prozent: WORD 80 Anzahl: WORD 12 Summe: WORD 0 ```] === Sortieren dreier Zahlen #task[Schreiben Sie ein Programm, dass drei Zahlen a, b und c in aufsteigender Reihenfolge sortiert.] *Grundlegende Idee*: Um drei Zahlen sortieren zu können, müssen wir zunächst sicherstellen, dass die kleinste Zahl vorne steht, d.h. es wird $a$ mit $b$ und dann $a$ mit $c$ verglichen. Danach kann noch $b$ mit $c$ verglichen werden. Dieses relativ einfache Prinzip erfordert schon einige Schritte in einem Assembler-Programm! EineLösung folgt auf der nächsten Seite. #pagebreak() #sc[```yasm LOAD a CMP b JMPN teil2 #wenn a und b schon sortiert sind überspringen! STORE zw LOAD b STORE a LOAD zw STORE b teil2: LOAD a CMP c JMPN teil3 #wenn a und c schon sortiert sind überspringen! STORE zw LOAD c STORE a LOAD zw STORE c teil3: LOAD b CMP c JMPN ende wenn b und c schon sortiert sind übersprungen! STORE zw LOAD c STORE b LOAD zw STORE c ende: LOADI 0 STORE zw HOLD zw: WORD 0 a: WORD 12 b: WORD 3 c: WORD 119 ```] #pagebreak() == Wiederholungen in Assembler Nachdem wir nun bedingte Anweisungen verwenden können fehlt noch eine wesentliche Struktur der höheren Programmiersprachen, die simuliert werden muss - eine *Wiederholung*. Auch hier gilt wieder: da wir nicht (direkt) mit Variablen arbeiten können, müssen wir sicherstellen, dass zu jeder Zeit der richtige Wert im Akkumulator steht. Im Folgenden wollen wir das folgende Java-Programm simulieren: #sc[```java for(int i = 5; i >= 0; i++) { System.out.print(i); } ```] Es sollen also alle Zahlen von $5$ bis $0$ "geprintet" werden - wobei der print bei uns dem Schreiben in eine bestimmte Speicherzelle entspricht. #task[Schreiben Sie ein Programm, dass in einer Speicherzelle nacheinander die Zahlen von $5$ bis $0$ einträgt.] Im Wesentlichen verwenden wir die Speicherzelle in der unsere Startzahl *i* steht als unsere Zählvariable: #sc[```yasm #for-Modellierung start: LOAD i SUBI 1 STORE i CMPI 0 JMPZ ende JMP start ende: HOLD #Daten i: WORD 5 ```] === Berechnung Fakultät So ist natürlich noch nicht viel Nützliches passiert! Nun sollte in jedem Schritt eine einfache Rechenoperation durchgeführt werden - die *Fakultät* eignet sich dafür (mal wieder) besonders, da wir hier die "Zählvariable" in jedem Schritt auch direkt zum Rechnen verwenden können. So kommen wir mit zwei Speicherzellen aus - *Ergebnis* und *i*. In den entsprechenden Zellen sollten dabei nacheinander die folgenden Werte stehen: #align(center)[ #tablex(rows:6, columns: 2, align:center, [*Ergebnis*],[*i*], [*#b($1$)*], [*#r($5$)*], [*#b($1 dot 5 = 5$)*], [*#r($5-1 = 4$)*], [*#b($5 dot 4 = 20$)*], [*#r($4-1 =3$)*], [*#b($20 dot 3 = 60$)*], [*#r($3-1 = 2$)*], [*#b($60 dot 2 = 120$)*], [*#r($2-1 = 1$)*], [*#b($120 dot 1 = 120$)*], [*#r($1-1 = 0$)*], )] Danach muss abgebrochen werden. #task[Implementieren Sie ein Programm, dass die Fakultät nach dem obigen Schema berechnet.] Die Lösung sieht z.B. so aus: #sc[```yasm #Fakultät LOAD zahl STORE ergebnis start: LOAD zahl SUBI 1 STORE zahl JMPZ ende MUL ergebnis STORE ergebnis JMP start ende: HOLD #Daten zahl: WORD 6 ergebnis: WORD 1 ```] Analog zu Programmen in "Hochsprachen" können auch in Assemblersprachen "Sicherungsmechanismen eingebaut werden". Für die Fakultät z.B.: 1. Wenn die eingegebene Zahl 0 ist wird direkt mit dem Ergebnis 1 abgebrochen. 2. Wenn die eingegebene Zahl negativ ist, wird als Ergebnis $-1$"ausgegeben" - als Fehlermeldung. 3. Wenn es einen "Overflow" gegeben hat soll ebenfalls als Ergebnis $-1$ ausgegeben werden - als Fehlermeldung. #task[Modifizieren Sie ihr Fakultätsprogramm, um die obigen Fälle abzudecken.] #sc[```yasm #Fakultät LOAD zahl JMPZ ende JMPN fehler start: MUL ergebnis JMPV fehler STORE ergebnis LOAD zahl SUBI 1 STORE zahl JMPP start JMP ende fehler: LOADI -1 STORE ergebnis ende: HOLD #Daten zahl: WORD 6 ergebnis: WORD 1 ```] === Berechnung Potenzen Um eine Potenz zu berechnen können wir ähnlich wie bei der Fakultät vorgehen. Der einzige Unterschied ist, dass wir dieses Mal einen "konstanten" Wert haben - die Basis. Wir benötigen also drei Bezeichner, z.B.: *Basis*, *Ergebnis* und *i*. #align(center)[ #tablex(rows:6, columns: 3, align:center, [*Basis*], [*Ergebnis*],[*i*], [$3$],[*#b($1$)*], [*#r($5$)*], [$3$],[*#b($1 dot 3 = 5$)*], [*#r($5-1 = 4$)*], [$3$],[*#b($3 dot 3 = 9$)*], [*#r($4-1 =3$)*], [$3$],[*#b($9 dot 3 = 27$)*], [*#r($3-1 = 2$)*], [$3$],[*#b($27 dot 3 = 81$)*], [*#r($2-1 = 1$)*], [$3$],[*#b($81 dot 3 = 243$)*], [*#r($1-1 = 0$)*], )] Wie zuvor wird abgebrochen, wenn $0$ erreicht wird. #hinweis[Die "Fehlerüberprüfungen" müssen jetzt im Folgenden nicht mehr durchgeführt werden, außer sie werden explizit erwähnt.] #sc[```yasm #Potenz LOAD exp JMPNP ende start: LOAD basis MUL ergebnis STORE ergebnis LOAD exp SUBI 1 STORE exp JMPP start ende: HOLD #Daten basis: WORD 3 exp: WORD 4 ergebnis: WORD 1 ```] == Quersumme einer Zahl #task[Schreiben Sie ein Programm, dass die Quersumme einer Zahl berechnet. _Tipp: Nutzen Sie DIVI und MODI sowie zwei Bezeichner_] #pagebreak() #sc[```yasm #Quersumme LOAD zahl JMPZ ende anfang: MODI 10 ADD ergebnis STORE ergebnis LOAD zahl DIVI 10 STORE zahl JMPP anfang ende: HOLD #Daten zahl: WORD 275 ergebnis: WORD 0 ```] == Zustandsübergangstabelle Der weitere Ablauf eines Programms hängt vom *Zustands des Rechners* ab. Wie dieser Zustand sich während eines Programms ändert kann in einer sogenannten *Zustandsübergangstabelle* dokumentiert werden. Im Abitur wird gelegentlich ein *tabellarischer Verlauf* gefordert. Dann wird mindestens erwartet, dass der *Programmzähler*, der Inhalt des *Statusregisters* und der *Akkumulator* angegeben wird. Verwendet das Programm zusätzlich Speicherzellen (wie oben z.B. "zahl" oder "ergebnis"), die das Verhalten beeinflussen müssen diese ebenfalls angegeben werden. #align(center)[ #tablex(rows:5, columns: 5, align: center, [*Programmzähler*], [*Akkumulator*], [*Statusregister*], [*Ergebnis*],[*Zahl*], [0],[0],[],[0],[275], [2],[275],[],[0],[275], [4],[5],[],[0],[275], [$dots$],[$dots$],[$dots$],[$dots$],[$dots$] )] #pagebreak() = Weitere Aufgaben == Minimaschinenaufgaben #task(customTitle: "Aufgabe 1")[Schreiben Sie ein Programm, das testet, ob eine gegebene Zahl eine Primzahl ist. Verwenden Sie dazu $1$ als Ergebnis für "wahr" und $-1$ als Ergebnis für "falsch". Geben Sie eine Zustandsübergangstabelle an, die den Zustand bei Eingabe einer Primzahl (z.B. $5$) beschreibt.] #task(customTitle: "Aufgabe 2")[Schreiben Sie ein Programm, das den größten gemeinsamen Teiler zweier natürlicher Zahlen bildet. Nutzen Sie dazu den folgenden Algorithmus: 1. Dividiere die größere durch die kleinere Zahl (ganzzahlig mit Rest). 2. Falls der Rest größer als $0$ ist, dann wird der vorhergehende Divisor zum Dividend und der Rest der vorhergehenden Rechnung zum Divisor. 3. Falls der Rest 0 beträgt, dann ist der vorhergehende Divisor der größte gemeinsame Teiler. ] #task(customTitle: "Aufgabe 3")[Schreiben Sie ein Programm, das zwei Zahlen miteinander multipliziert - ohne Verwendung des Befehls _MUL_] #task(customTitle: "Aufgabe 4")[Schreiben Sie ein Programm, das das Maximum dreier Zahlen bestimmt.] #task(customTitle: "Aufgabe 5")[Schreiben Sie ein Programm, das den Binomialkoeffizienten $vec(n, k)$ berechnet.] #task(customTitle: "Aufgabe 6")[Schreiben Sie ein Programm, das die Werte der Eulerschen Phi-Funktion berechnet. Dabei ist $phi(n)$ definiert als die Anzahl der zu $n$ teilerfremden natürlichen Zahlen, die kleiner als $n$ sind. _Tipp: 1 gilt immer als teilerfremd zu $n$_] #pagebreak() == Lösungen #hinweis[Alle Lösungen sind nur Vorschläge. Andere Varianten sind auch denkbar.] *Primzahltest* #sc[```yasm anfang: LOAD zahl MOD teiler JMPZ ok LOAD teiler ADDI 1 STORE teiler CMP zahl JMPNZ anfang LOADI -1 STORE ergebnis HOLD ok: LOADI 1 STORE ergebnis HOLD zahl: WORD 32749 ergebnis: WORD 0 teiler: WORD 2 ```] *größter gemeinsamer Teiler* #sc[```yasm anfang: LOAD gross MOD klein STORE rest JMPZ ausgabe LOAD klein STORE gross LOAD rest STORE klein JMP anfang ausgabe:LOAD klein STORE ggt HOLD #Daten gross: WORD 80 klein: WORD 35 rest: WORD 0 ggt: WORD 0 ```] *Multiplikation ohne MUL* Negative Zahlen machen hier das größte Problem! #sc[```yasm LOAD b JMPP bPos SUB b SUB b bPos: STORE zw anfang: LOAD zw JMPZ fertig SUBI 1 STORE zw LOAD ergebnis ADD a STORE ergebnis JMP anfang fertig: LOAD b JMPP ende LOAD ergebnis SUB ergebnis SUB ergebnis STORE ergebnis ende: HOLD a: WORD 3 b: WORD -8 ergebnis: WORD 0 zw: WORD 0 ```] *Maximum dreier Zahlen* #sc[```yasm LOAD a STORE maximum CMP b JMPP second LOAD b STORE maximum second: LOAD maximum CMP c JMPP end LOAD c STORE maximum end: HOLD a: WORD 51 b: WORD 13 c: WORD 311 maximum:WORD 0 ```] *Binomialkoeffizient* Fleißaufgabe, im Prinzip muss nur dreimal die Fakultät berechnet und dann entsprechend folgender Formel verrechnet werden: $ vec(n,k) = n!/(k! dot (n-k)!) $ #sc[```yasm #n - k berechnen LOAD n SUB k STORE nk #Fakultät von n berechnen LOAD n s1: MUL nfak STORE nfak LOAD n SUBI 1 STORE n JMPP s1 #Fakultät von k berechnen: LOAD k s2: MUL kfak STORE kfak LOAD k SUBI 1 STORE k JMPP s2 #Fakultät von n-k berechnen: LOAD nk s3: MUL nkfak STORE nkfak LOAD nk SUBI 1 STORE nk JMPP s3 #Verrechnung LOAD nkfak MUL kfak STORE r LOAD nfak DIV r STORE r HOLD n: WORD 5 k: WORD 2 nk: WORD 0 nfak: WORD 1 kfak: WORD 1 nkfak: WORD 1 zw: WORD 0 r: WORD 0 ```] *Eulersche Phi-Funktion* Hier gibt es ebenso verschiedene Ansätze, die Eulersche Phi-Funktion ist definiert als: $ phi (n) := abs({a in NN | 1 <= a <= n and g g T (a,n) = 1}) $ Oder anders gesagt: $phi$ berechnet die Anzahl der teilerfremden Zahlen zu $n$. Die Definition legt nahe, dass wir dafür direkt unsere bereits gebastelte ggT-Implementierung als "Funktion" verwenden können. #sc[```yasm LOAD n STORE i ggtber: LOAD i SUBI 1 STORE i CMPI 0 JMPZ ende STORE klein LOAD n STORE gross JMP anfang eval: LOAD ggt CMPI 1 JMPNZ ggtber LOAD phi ADDI 1 STORE phi JMP ggtber anfang: LOAD gross MOD klein STORE rest JMPZ ausgabe LOAD klein STORE gross LOAD rest STORE klein JMP anfang ausgabe:LOAD klein STORE ggt JMP eval ende: HOLD #Daten n: WORD 23 i: WORD 0 gross: WORD 0 klein: WORD 0 rest: WORD 0 ggt: WORD 0 phi: WORD 0 ```] #pagebreak() == Abituraufgaben Für die beiden folgenden Aufgaben aus dem abitur 2023 gilt derselbe Befehlssatz für eine Registermaschine. #align(center)[#image("images/abi23mmsatz.png")] #task[#align(center)[#image("images/abi23mm1_1.png") \ #image("images/abi23mm1_2.png")]] #task[#align(center)[#image("images/abi23mm1.png") \ #image("images/abi23mm2.png")\ #image("images/abi23mm3.png")]] = Exkurs: Ein "echter" Prozessor Damit wir nicht vollständig theoretisch bleiben findet sich hier im folgenden das Funktionsblockschaltbild des Intel 8008 - des ersten 8-Bit-Mikroprozessor von Intel. #align(center)[#image("images/intel8008.png")] Man kann etliche Bauteile entdecken, die wir auch bei der Von-Neumann-Architektur gesehen haben. Das *Register a* entspricht z.B. dem Akkumulator, das *Instruction-Register* entspricht dem Befehlsregister, etc.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/meppp/0.1.0/lib.typ
typst
Apache License 2.0
#import ("table.typ"):meppp-tl-table #import ("template.typ"):meppp-lab-report #let pku-logo(..args) = image("pkulogo.png",..args)
https://github.com/alberto-lazari/computer-science
https://raw.githubusercontent.com/alberto-lazari/computer-science/main/advanced-topics-pl/presentation/notes.md
markdown
# Typst As a programming language ## Source Master thesis: https://www.user.tu-berlin.de/laurmaedje/programmable-markup-language-for-typesetting.pdf ## How does it improve the LaTeX experience? Technical analysis on how it is implemented. Try to be objective ## Programming language analysis Describe the runtime of the language or try to present implementation details, such as how dynamic typing is managed # Modes Three modes are available to interpret typst code: - Code `{ code }` - Markup `[ content ]` - Math `$ math $` By default a typst file is interpreted in markup mode, hence the need to prepend a `#` for code ## Markup Basically just syntactic sugar for functions.. Examples: - `# Heading` -> `#heading("Heading", level: 1)` - `*bold text*` -> `#strong[bold text]` ?? # Functions They are pure and cannot change the state outside of them (except builtin types) Ex: ```typst #let i = 0 #let test(x) = { i += 1 x + i } #test(2) ``` Produces error ``` error: variables from outside the function are read-only and cannot be modified ``` Not actually true, because it's allowed to have stateful parts of the code (useful for counters). That actually returns only content via its `.display()` method, so it can't be used for logic ## Arguments Either: - Positional `fun(a, b, c)` - Named `fun(len: 1em, width: 2px)` Argument sinks are available to allow any argument. An array or dictionary can be spread with `..array` to cast it to the `arguments` type # Compilation It seems that the evaluation is lazy: if a variable or function is never called it never gets evaluated and don't throw errors (unless it's syntax related?) # Clearly defined syntax Very interesting piece (p. 64 of the paper). LaTeX does not have a defined syntax for everything (ex. math mode: `$math\)`) # Fun fact Typst can be used in a simil-interactive mode with ```bash cat << '#quit()' | typst compile /dev/stdin /dev/stdout | pdftotext - - | tac | tail -n +2 | tac ``` Use `#quit()` to trigger the compilation
https://github.com/michelebanfi/typst-terraform
https://raw.githubusercontent.com/michelebanfi/typst-terraform/main/Templates/Notes/main.typ
typst
#import "template.typ": * #import "@preview/quill:0.2.0": * #show: project.with( title: {{PROJECT_NAME}}, authors: ( {{AUTHOR}}, ), ) #outline( indent: auto ) // #set math.equation(numbering: "(1)") #include "Chapters/1.typ" #include "Chapters/2.typ" #include "Chapters/3.typ" #include "Chapters/4.typ"
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/018.%20better.html.typ
typst
better.html Better Bayesian Filtering January 2003(This article was given as a talk at the 2003 Spam Conference. It describes the work I've done to improve the performance of the algorithm described in A Plan for Spam, and what I plan to do in the future.)The first discovery I'd like to present here is an algorithm for lazy evaluation of research papers. Just write whatever you want and don't cite any previous work, and indignant readers will send you references to all the papers you should have cited. I discovered this algorithm after ``A Plan for Spam'' [1] was on Slashdot.Spam filtering is a subset of text classification, which is a well established field, but the first papers about Bayesian spam filtering per se seem to have been two given at the same conference in 1998, one by <NAME> Lin [2], and another by a group from Microsoft Research [3].When I heard about this work I was a bit surprised. If people had been onto Bayesian filtering four years ago, why wasn't everyone using it? When I read the papers I found out why. Pantel and Lin's filter was the more effective of the two, but it only caught 92% of spam, with 1.16% false positives.When I tried writing a Bayesian spam filter, it caught 99.5% of spam with less than .03% false positives [4]. It's always alarming when two people trying the same experiment get widely divergent results. It's especially alarming here because those two sets of numbers might yield opposite conclusions. Different users have different requirements, but I think for many people a filtering rate of 92% with 1.16% false positives means that filtering is not an acceptable solution, whereas 99.5% with less than .03% false positives means that it is.So why did we get such different numbers? I haven't tried to reproduce Pantel and Lin's results, but from reading the paper I see five things that probably account for the difference.One is simply that they trained their filter on very little data: 160 spam and 466 nonspam mails. Filter performance should still be climbing with data sets that small. So their numbers may not even be an accurate measure of the performance of their algorithm, let alone of Bayesian spam filtering in general.But I think the most important difference is probably that they ignored message headers. To anyone who has worked on spam filters, this will seem a perverse decision. And yet in the very first filters I tried writing, I ignored the headers too. Why? Because I wanted to keep the problem neat. I didn't know much about mail headers then, and they seemed to me full of random stuff. There is a lesson here for filter writers: don't ignore data. You'd think this lesson would be too obvious to mention, but I've had to learn it several times.Third, <NAME> Lin stemmed the tokens, meaning they reduced e.g. both ``mailing'' and ``mailed'' to the root ``mail''. They may have felt they were forced to do this by the small size of their corpus, but if so this is a kind of premature optimization.Fourth, they calculated probabilities differently. They used all the tokens, whereas I only use the 15 most significant. If you use all the tokens you'll tend to miss longer spams, the type where someone tells you their life story up to the point where they got rich from some multilevel marketing scheme. And such an algorithm would be easy for spammers to spoof: just add a big chunk of random text to counterbalance the spam terms.Finally, they didn't bias against false positives. I think any spam filtering algorithm ought to have a convenient knob you can twist to decrease the false positive rate at the expense of the filtering rate. I do this by counting the occurrences of tokens in the nonspam corpus double. I don't think it's a good idea to treat spam filtering as a straight text classification problem. You can use text classification techniques, but solutions can and should reflect the fact that the text is email, and spam in particular. Email is not just text; it has structure. Spam filtering is not just classification, because false positives are so much worse than false negatives that you should treat them as a different kind of error. And the source of error is not just random variation, but a live human spammer working actively to defeat your filter.TokensAnother project I heard about after the Slashdot article was <NAME>' CRM114 [5]. This is the counterexample to the design principle I just mentioned. It's a straight text classifier, but such a stunningly effective one that it manages to filter spam almost perfectly without even knowing that's what it's doing.Once I understood how CRM114 worked, it seemed inevitable that I would eventually have to move from filtering based on single words to an approach like this. But first, I thought, I'll see how far I can get with single words. And the answer is, surprisingly far.Mostly I've been working on smarter tokenization. On current spam, I've been able to achieve filtering rates that approach CRM114's. These techniques are mostly orthogonal to Bill's; an optimal solution might incorporate both.``A Plan for Spam'' uses a very simple definition of a token. Letters, digits, dashes, apostrophes, and dollar signs are constituent characters, and everything else is a token separator. I also ignored case.Now I have a more complicated definition of a token: Case is preserved. Exclamation points are constituent characters. Periods and commas are constituents if they occur between two digits. This lets me get ip addresses and prices intact. A price range like $20-25 yields two tokens, $20 and $25. Tokens that occur within the To, From, Subject, and Return-Path lines, or within urls, get marked accordingly. E.g. ``foo'' in the Subject line becomes ``Subject*foo''. (The asterisk could be any character you don't allow as a constituent.) Such measures increase the filter's vocabulary, which makes it more discriminating. For example, in the current filter, ``free'' in the Subject line has a spam probability of 98%, whereas the same token in the body has a spam probability of only 65%.Here are some of the current probabilities [6]:Subject*FREE 0.9999 free!! 0.9999 To*free 0.9998 Subject*free 0.9782 free! 0.9199 Free 0.9198 Url*free 0.9091 FREE 0.8747 From*free 0.7636 free 0.6546 In the Plan for Spam filter, all these tokens would have had the same probability, .7602. That filter recognized about 23,000 tokens. The current one recognizes about 187,000.The disadvantage of having a larger universe of tokens is that there is more chance of misses. Spreading your corpus out over more tokens has the same effect as making it smaller. If you consider exclamation points as constituents, for example, then you could end up not having a spam probability for free with seven exclamation points, even though you know that free with just two exclamation points has a probability of 99.99%.One solution to this is what I call degeneration. If you can't find an exact match for a token, treat it as if it were a less specific version. I consider terminal exclamation points, uppercase letters, and occurring in one of the five marked contexts as making a token more specific. For example, if I don't find a probability for ``Subject*free!'', I look for probabilities for ``Subject*free'', ``free!'', and ``free'', and take whichever one is farthest from .5.Here are the alternatives [7] considered if the filter sees ``FREE!!!'' in the Subject line and doesn't have a probability for it.Subject*Free!!! Subject*free!!! Subject*FREE! Subject*Free! Subject*free! Subject*FREE Subject*Free Subject*free FREE!!! Free!!! free!!! FREE! Free! free! FREE Free free If you do this, be sure to consider versions with initial caps as well as all uppercase and all lowercase. Spams tend to have more sentences in imperative mood, and in those the first word is a verb. So verbs with initial caps have higher spam probabilities than they would in all lowercase. In my filter, the spam probability of ``Act'' is 98% and for ``act'' only 62%.If you increase your filter's vocabulary, you can end up counting the same word multiple times, according to your old definition of ``same''. Logically, they're not the same token anymore. But if this still bothers you, let me add from experience that the words you seem to be counting multiple times tend to be exactly the ones you'd want to.Another effect of a larger vocabulary is that when you look at an incoming mail you find more interesting tokens, meaning those with probabilities far from .5. I use the 15 most interesting to decide if mail is spam. But you can run into a problem when you use a fixed number like this. If you find a lot of maximally interesting tokens, the result can end up being decided by whatever random factor determines the ordering of equally interesting tokens. One way to deal with this is to treat some as more interesting than others.For example, the token ``dalco'' occurs 3 times in my spam corpus and never in my legitimate corpus. The token ``Url*optmails'' (meaning ``optmails'' within a url) occurs 1223 times. And yet, as I used to calculate probabilities for tokens, both would have the same spam probability, the threshold of .99.That doesn't feel right. There are theoretical arguments for giving these two tokens substantially different probabilities (Pantel and Lin do), but I haven't tried that yet. It does seem at least that if we find more than 15 tokens that only occur in one corpus or the other, we ought to give priority to the ones that occur a lot. So now there are two threshold values. For tokens that occur only in the spam corpus, the probability is .9999 if they occur more than 10 times and .9998 otherwise. Ditto at the other end of the scale for tokens found only in the legitimate corpus.I may later scale token probabilities substantially, but this tiny amount of scaling at least ensures that tokens get sorted the right way.Another possibility would be to consider not just 15 tokens, but all the tokens over a certain threshold of interestingness. <NAME> does this in his statistical spam filter [8]. If you use a threshold, make it very high, or spammers could spoof you by packing messages with more innocent words.Finally, what should one do about html? I've tried the whole spectrum of options, from ignoring it to parsing it all. Ignoring html is a bad idea, because it's full of useful spam signs. But if you parse it all, your filter might degenerate into a mere html recognizer. The most effective approach seems to be the middle course, to notice some tokens but not others. I look at a, img, and font tags, and ignore the rest. Links and images you should certainly look at, because they contain urls.I could probably be smarter about dealing with html, but I don't think it's worth putting a lot of time into this. Spams full of html are easy to filter. The smarter spammers already avoid it. So performance in the future should not depend much on how you deal with html.PerformanceBetween December 10 2002 and January 10 2003 I got about 1750 spams. Of these, 4 got through. That's a filtering rate of about 99.75%.Two of the four spams I missed got through because they happened to use words that occur often in my legitimate email.The third was one of those that exploit an insecure cgi script to send mail to third parties. They're hard to filter based just on the content because the headers are innocent and they're careful about the words they use. Even so I can usually catch them. This one squeaked by with a probability of .88, just under the threshold of .9.Of course, looking at multiple token sequences would catch it easily. ``Below is the result of your feedback form'' is an instant giveaway.The fourth spam was what I call a spam-of-the-future, because this is what I expect spam to evolve into: some completely neutral text followed by a url. In this case it was was from someone saying they had finally finished their homepage and would I go look at it. (The page was of course an ad for a porn site.)If the spammers are careful about the headers and use a fresh url, there is nothing in spam-of-the-future for filters to notice. We can of course counter by sending a crawler to look at the page. But that might not be necessary. The response rate for spam-of-the-future must be low, or everyone would be doing it. If it's low enough, it won't pay for spammers to send it, and we won't have to work too hard on filtering it.Now for the really shocking news: during that same one-month period I got three false positives.In a way it's a relief to get some false positives. When I wrote ``A Plan for Spam'' I hadn't had any, and I didn't know what they'd be like. Now that I've had a few, I'm relieved to find they're not as bad as I feared. False positives yielded by statistical filters turn out to be mails that sound a lot like spam, and these tend to be the ones you would least mind missing [9].Two of the false positives were newsletters from companies I've bought things from. I never asked to receive them, so arguably they were spams, but I count them as false positives because I hadn't been deleting them as spams before. The reason the filters caught them was that both companies in January switched to commercial email senders instead of sending the mails from their own servers, and both the headers and the bodies became much spammier.The third false positive was a bad one, though. It was from someone in Egypt and written in all uppercase. This was a direct result of making tokens case sensitive; the Plan for Spam filter wouldn't have caught it.It's hard to say what the overall false positive rate is, because we're up in the noise, statistically. Anyone who has worked on filters (at least, effective filters) will be aware of this problem. With some emails it's hard to say whether they're spam or not, and these are the ones you end up looking at when you get filters really tight. For example, so far the filter has caught two emails that were sent to my address because of a typo, and one sent to me in the belief that I was someone else. Arguably, these are neither my spam nor my nonspam mail.Another false positive was from a vice president at Virtumundo. I wrote to them pretending to be a customer, and since the reply came back through Virtumundo's mail servers it had the most incriminating headers imaginable. Arguably this isn't a real false positive either, but a sort of Heisenberg uncertainty effect: I only got it because I was writing about spam filtering.Not counting these, I've had a total of five false positives so far, out of about 7740 legitimate emails, a rate of .06%. The other two were a notice that something I bought was back-ordered, and a party reminder from Evite.I don't think this number can be trusted, partly because the sample is so small, and partly because I think I can fix the filter not to catch some of these.False positives seem to me a different kind of error from false negatives. Filtering rate is a measure of performance. False positives I consider more like bugs. I approach improving the filtering rate as optimization, and decreasing false positives as debugging.So these five false positives are my bug list. For example, the mail from Egypt got nailed because the uppercase text made it look to the filter like a Nigerian spam. This really is kind of a bug. As with html, the email being all uppercase is really conceptually one feature, not one for each word. I need to handle case in a more sophisticated way.So what to make of this .06%? Not much, I think. You could treat it as an upper bound, bearing in mind the small sample size. But at this stage it is more a measure of the bugs in my implementation than some intrinsic false positive rate of Bayesian filtering.FutureWhat next? Filtering is an optimization problem, and the key to optimization is profiling. Don't try to guess where your code is slow, because you'll guess wrong. Look at where your code is slow, and fix that. In filtering, this translates to: look at the spams you miss, and figure out what you could have done to catch them.For example, spammers are now working aggressively to evade filters, and one of the things they're doing is breaking up and misspelling words to prevent filters from recognizing them. But working on this is not my first priority, because I still have no trouble catching these spams [10].There are two kinds of spams I currently do have trouble with. One is the type that pretends to be an email from a woman inviting you to go chat with her or see her profile on a dating site. These get through because they're the one type of sales pitch you can make without using sales talk. They use the same vocabulary as ordinary email.The other kind of spams I have trouble filtering are those from companies in e.g. Bulgaria offering contract programming services. These get through because I'm a programmer too, and the spams are full of the same words as my real mail.I'll probably focus on the personal ad type first. I think if I look closer I'll be able to find statistical differences between these and my real mail. The style of writing is certainly different, though it may take multiword filtering to catch that. Also, I notice they tend to repeat the url, and someone including a url in a legitimate mail wouldn't do that [11].The outsourcing type are going to be hard to catch. Even if you sent a crawler to the site, you wouldn't find a smoking statistical gun. Maybe the only answer is a central list of domains advertised in spams [12]. But there can't be that many of this type of mail. If the only spams left were unsolicited offers of contract programming services from Bulgaria, we could all probably move on to working on something else.Will statistical filtering actually get us to that point? I don't know. Right now, for me personally, spam is not a problem. But spammers haven't yet made a serious effort to spoof statistical filters. What will happen when they do?I'm not optimistic about filters that work at the network level [13]. When there is a static obstacle worth getting past, spammers are pretty efficient at getting past it. There is already a company called Assurance Systems that will run your mail through Spamassassin and tell you whether it will get filtered out.Network-level filters won't be completely useless. They may be enough to kill all the "opt-in" spam, meaning spam from companies like Virtumundo and Equalamail who claim that they're really running opt-in lists. You can filter those based just on the headers, no matter what they say in the body. But anyone willing to falsify headers or use open relays, presumably including most porn spammers, should be able to get some message past network-level filters if they want to. (By no means the message they'd like to send though, which is something.)The kind of filters I'm optimistic about are ones that calculate probabilities based on each individual user's mail. These can be much more effective, not only in avoiding false positives, but in filtering too: for example, finding the recipient's email address base-64 encoded anywhere in a message is a very good spam indicator.But the real advantage of individual filters is that they'll all be different. If everyone's filters have different probabilities, it will make the spammers' optimization loop, what programmers would call their edit-compile-test cycle, appallingly slow. Instead of just tweaking a spam till it gets through a copy of some filter they have on their desktop, they'll have to do a test mailing for each tweak. It would be like programming in a language without an interactive toplevel, and I wouldn't wish that on anyone.Notes[1] <NAME>. ``A Plan for Spam.'' August 2002. http://paulgraham.com/spam.html.Probabilities in this algorithm are calculated using a degenerate case of Bayes' Rule. There are two simplifying assumptions: that the probabilities of features (i.e. words) are independent, and that we know nothing about the prior probability of an email being spam.The first assumption is widespread in text classification. Algorithms that use it are called ``naive Bayesian.''The second assumption I made because the proportion of spam in my incoming mail fluctuated so much from day to day (indeed, from hour to hour) that the overall prior ratio seemed worthless as a predictor. If you assume that P(spam) and P(nonspam) are both .5, they cancel out and you can remove them from the formula.If you were doing Bayesian filtering in a situation where the ratio of spam to nonspam was consistently very high or (especially) very low, you could probably improve filter performance by incorporating prior probabilities. To do this right you'd have to track ratios by time of day, because spam and legitimate mail volume both have distinct daily patterns.[2] <NAME> and <NAME>. ``SpamCop-- A Spam Classification & Organization Program.'' Proceedings of AAAI-98 Workshop on Learning for Text Categorization.[3] <NAME>, <NAME>, <NAME> and <NAME>. ``A Bayesian Approach to Filtering Junk E-Mail.'' Proceedings of AAAI-98 Workshop on Learning for Text Categorization.[4] At the time I had zero false positives out of about 4,000 legitimate emails. If the next legitimate email was a false positive, this would give us .03%. These false positive rates are untrustworthy, as I explain later. I quote a number here only to emphasize that whatever the false positive rate is, it is less than 1.16%. [5] <NAME>. ``Sparse Binary Polynomial Hash Message Filtering and The CRM114 Discriminator.'' Proceedings of 2003 Spam Conference.[6] In ``A Plan for Spam'' I used thresholds of .99 and .01. It seems justifiable to use thresholds proportionate to the size of the corpora. Since I now have on the order of 10,000 of each type of mail, I use .9999 and .0001.[7] There is a flaw here I should probably fix. Currently, when ``Subject*foo'' degenerates to just ``foo'', what that means is you're getting the stats for occurrences of ``foo'' in the body or header lines other than those I mark. What I should do is keep track of statistics for ``foo'' overall as well as specific versions, and degenerate from ``Subject*foo'' not to ``foo'' but to ``Anywhere*foo''. Ditto for case: I should degenerate from uppercase to any-case, not lowercase.It would probably be a win to do this with prices too, e.g. to degenerate from ``$129.99'' to ``$--9.99'', ``$--.99'', and ``$--''.You could also degenerate from words to their stems, but this would probably only improve filtering rates early on when you had small corpora.[8] <NAME>. ``Statistical Spam Filter Works for Me.'' http://www.sofbot.com.[9] False positives are not all equal, and we should remember this when comparing techniques for stopping spam. Whereas many of the false positives caused by filters will be near-spams that you wouldn't mind missing, false positives caused by blacklists, for example, will be just mail from people who chose the wrong ISP. In both cases you catch mail that's near spam, but for blacklists nearness is physical, and for filters it's textual. [10] If spammers get good enough at obscuring tokens for this to be a problem, we can respond by simply removing whitespace, periods, commas, etc. and using a dictionary to pick the words out of the resulting sequence. And of course finding words this way that weren't visible in the original text would in itself be evidence of spam.Picking out the words won't be trivial. It will require more than just reconstructing word boundaries; spammers both add (``xHot nPorn cSite'') and omit (``P#rn'') letters. Vision research may be useful here, since human vision is the limit that such tricks will approach.[11] In general, spams are more repetitive than regular email. They want to pound that message home. I currently don't allow duplicates in the top 15 tokens, because you could get a false positive if the sender happens to use some bad word multiple times. (In my current filter, ``dick'' has a spam probabilty of .9999, but it's also a name.) It seems we should at least notice duplication though, so I may try allowing up to two of each token, as <NAME> does in SpamProbe.[12] This is what approaches like Brightmail's will degenerate into once spammers are pushed into using mad-lib techniques to generate everything else in the message.[13] It's sometimes argued that we should be working on filtering at the network level, because it is more efficient. What people usually mean when they say this is: we currently filter at the network level, and we don't want to start over from scratch. But you can't dictate the problem to fit your solution.Historically, scarce-resource arguments have been the losing side in debates about software design. People only tend to use them to justify choices (inaction in particular) made for other reasons.Thanks to <NAME>, <NAME>, and <NAME> for reading drafts of this paper, and to Dan again for most of the infrastructure that this filter runs on.Related:A Plan for SpamPlan for Spam FAQ2003 Spam Conference ProceedingsJapanese TranslationChinese TranslationTest of These Suggestions
https://github.com/hei-templates/hevs-typsttemplate-thesis
https://raw.githubusercontent.com/hei-templates/hevs-typsttemplate-thesis/main/03-tail/a-appendix.typ
typst
MIT License
#pagebreak() #counter(heading).update(0) #set heading(numbering:"A") = Appendix #lorem(50)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/foundations-21.typ
typst
Other
// Error: 23-42 cannot access file system from here #show raw: it => eval("[" + it.text + "]") ``` #show emph: _ => image("test/assets/files/giraffe.jpg") _No relative giraffe!_ ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/anti-matter/0.0.2/README.md
markdown
Apache License 2.0
# anti-matter This typst packages allows you to simply mark the end and start of your front matter and back matter to change style and value of your page number without manually setting and keeping track of inner and outer page counters. ## Example ```typst #import "@preview/anti-matter:0.0.2": anti-matter, anti-front-end, anti-inner-end #set page("a4", height: auto) #show heading.where(level: 1): it => pagebreak(weak: true) + it // add a title page and reset the counter #[ #set page(numbering: none) #counter(page).update(0) ] #show: anti-matter #include "front-matter.typ" #anti-front-end() #include "chapters.typ" #anti-inner-end() #include "back-matter.typ" ``` ![An example outline showing the outer roman numbering interrupted by temporary inner arabic numbering][example] ## Features - Marking the start and end of front/end matter. - Specifying the numbering styles for each matter and regular content ## FAQ 1. Why are the pages not correctly counted? - If you are setting your own page header, you must use `anti-header`, see section II in the [manual]. 2. Why is my outline not displaying the correct numbering? - If you configure your own `outline.entry`, you must use `anti-page-at`, see section II in the [manual]. 3. Why does my front/inner/back matter numbering start on the wrong page? - The markers must be on the last page of their respective matter, if you have a `pagebreak` forcing them on the next page it will also incorrectly label that page. - Otherwise please open an issue with a minimal reproducible example. ## Etymology The package name `anti-matter` was choosen as a word play on front/back matter. ## Glossary - [front matter] - The first part of a thesis or book (intro, outline, etc.) - [back or end matter] - The last part of a thesis or book (bibliography, listings, acknowledgements, etc.) [front matter]: https://en.wikipedia.org/wiki/Book_design#Front_matter [back or end matter]: https://en.wikipedia.org/wiki/Book_design#Back_matter_(end_matter) [example]: example.png [manual]: manual.pdf
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/package/example.typ
typst
Apache License 2.0
#import "@preview/example:0.1.0": add #show raw: rect.with(width: 100%, fill: luma(120).lighten(90%)) Input: ```typ #import "@preview/example:0.1.0": add Example package: add(1, 2) = #add(1, 2) ``` Output: #h(2em) Example package: add(1, 2) = #add(1, 2)
https://github.com/BoostCookie/systemd-tshirtd
https://raw.githubusercontent.com/BoostCookie/systemd-tshirtd/main/README.md
markdown
# systemd T-shirt Logo ## Previews **⚠️⚠️⚠️ Do not use the images from these previews! ⚠️⚠️⚠️ \ They have a DARK BACKGROUND, but what you want for a T-shirt is a TRANSPARENT BACKGROUND! \ Please go to [Files](#files) and download the transparent version you want.** ### With Original Logo ![preview of the print with original logo](./preview/tshirtd.origlogo.black.svg) ### With A T-shirtdised Logo ![preview of the print with new logo](./preview/tshirtd.newlogo.black.svg) These are joke systemd logos meant to be printed onto a black t-shirt. The original systemd logo was taken from [https://brand.systemd.io/](https://brand.systemd.io/). ## Files Here are the files to download. | | original logo | tshirtdised logo | | ------- | -------- | ------------- | | **svg** | [transparent](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.origlogo.transparent.svg?job=typst-compile), [black](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.origlogo.black.svg?job=typst-compile) | [transparent](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.newlogo.transparent.svg?job=typst-compile), [black](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.newlogo.black.svg?job=typst-compile) | | **pdf** | [transparent](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.origlogo.transparent.pdf?job=typst-compile), [black](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.origlogo.black.pdf?job=typst-compile) | [transparent](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.newlogo.transparent.pdf?job=typst-compile), [black](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.newlogo.black.pdf?job=typst-compile) | ## Can You Recommend a Print Shop? - I have tried out [https://printplanet.de/](https://printplanet.de/) and unfortunately they fuck it up sometimes. I don't know why it happens but sometimes (two out of four orders) they replace the transparent background from the [source file](https://gitlab.com/BoostCookie/systemd-tshirtd/-/jobs/artifacts/main/raw/tshirtd.origlogo.transparent.svg?job=typst-compile) with complete black (RGB 0, 0, 0). - Apart from that I have tried out [https://www.shirtinator.de](https://www.shirtinator.de), but only for a different logo and a white T-shirt. Let me know if you find a good print shop with good quality T-shirts and good handling of transparent backgrounds.
https://github.com/Blezz-tech/math-typst
https://raw.githubusercontent.com/Blezz-tech/math-typst/main/Варианты/2023.10.08/Задание-16.1.typ
typst
\begin{tcolorbox}[ colback=blue!5!white, colframe=blue!75!black, title=Задание 1.1 ] $15$-го марта планируется взять кредит в банке на 26 месяцев. Условия его возврата таковы: \begin{enumerate}[--] \item $1$-го числа каждого месяца долг возрастает на $3$\% по сравнению с концом предыдущего месяца; \item со $2$-го по $14$-е число каждого месяца необходимо выплатить часть долга; \item $15$-го числа каждого месяца с $1$-го по $25$-й долг должен быть на $40$ тысяч рублей меньше долга на $15$-е число предыдущего месяца; \item к $15$-му числу $26$-го месяца кредит должен быть полностью погашен. \end{enumerate} Какую сумму планируется взять в кредит, если общая сумма выплат после полного его погашения составит $1924$ тысячи рублей? \end{tcolorbox} \begin{tcolorbox}[ colback=white!100!white, colframe=green!75!black, title=Решение 1.1 ] Пусть \begin{equation*} \begin{array}{ll} S - ? & \text{- сумма кредита} \\ S_n = 1924 & \text{- итоговая сумма выалат} \\ r = 0,03 & \text{- кредитная ставка} \\ \end{array} \end{equation*} Составим таблицу выплат \begin{tabular}{|l|l|l|l|} \hline $1$ & $r\cdot S$ & $r\cdot S + 40$ & $S - 40$ \\ \hline $2$ & $r\cdot (S - 40)$ & $r\cdot (S - 40) + 40$ & $S - 2\cdot40$ \\ \hline $3$ & $r\cdot (S - 2\cdot 40)$ & $r\cdot (S - 2\cdot 40) + 40$ & $S - 3\cdot40$ \\ \hline $\dots$ & $\dots$ & $\dots$ & $\dots$ \\ \hline $24$ & $r\cdot (S - 23\cdot 40)$ & $r\cdot (S - 23\cdot 40) + 40$ & $S - 24\cdot40$ \\ \hline $25$ & $r\cdot (S - 24\cdot 40)$ & $r\cdot (S - 24\cdot 40) + 40$ & $S - 25\cdot40$ \\ \hline $26$ & $r\cdot (S - 25\cdot 40)$ & $r\cdot (S - 25\cdot 40) + 40$ & $0$ \\ \hline \end{tabular} $S_n = r\cdot(S + S - 40 + S - 2\cdot 40 \dots S - 23\cdot 40 + S - 24\cdot 40 + S - 25\cdot 40) + 40\cdot 26 = 1924$ Мы видим арифметическую прогрессию: $F = S + S - 40 + S - 2\cdot 40 \dots S - 23\cdot 40 + S - 24\cdot 40 + S - 25\cdot 40$ Найдём сумму арифмитической прогрессии: \begin{equation*} \begin{array}{l} F=\frac{a_1+a_n}{2}\cdot n \\ F=\frac{S + S - 25\cdot 40}{2}\cdot 26 \\ F=(2S - 1000)\cdot 13 \\ F= 26S - 13000 \\ \end{array} \end{equation*} Итого получаем: \begin{equation*} \begin{array}{l} S_n = r(26S - 13000) + 25\cdot 40 + (S - 25\cdot 40) = 1924 \\ 0,03 (26S - 13000) + S = 1924 \\ 3 (26S - 13000) + 100S = 192400 \\ 78S - 39000 + 100S = 192400 \\ 178S = 231400 \\ S = 178 \end{array} \end{equation*} Ответ: $178$ \end{tcolorbox}
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/comment-00.typ
typst
Other
// Line comment acts as spacing. A// you B // Block comment does not act as spacing, nested block comments. C/* /* */ */D // Works in code. #test(type(/*1*/ 1) // , "integer") // End of block comment in line comment. // Hello */ // Nested line comment. /*//*/ Still comment. */ E
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/sol-mt2.typ
typst
MIT License
#import "@local/evan:1.0.0":* = Solutions to practice midterm 2 <ch-sol-mt2> The problem statements are given in @ch-mt1. == Solution to the butterfly (@prob-mt2p1) The butterfly’s position in the $x y$-plane is given by: $ bf(r) (t) = angle.l cos (t) , cos (t) angle.r . $ === Sketch of the trajectory We start actually by sketching the trajectory first (even though this was the last part), since that will make it easier to see what's going on in future parts. The trajectory described by $bf(r) (t) = angle.l cos (t) , cos (t) angle.r$ traces out a straight line in the $x y$-plane because both the $x$- and $y$-coordinates are equal for all $t$. Specifically, the butterfly’s motion follows the line $y = x$, with $t in [0 , 2 pi]$ producing oscillations between $x = 1$ and $x = - 1$. Here is a sketch of the trajectory. #figure( image("figures/mt2-butterfly.png", width: auto), caption: [Butterfly fluttering along the plane. A few more examples of points in the trajectory are marked in green for illustration, but the blue endpoints are the important ones. The green points are a little offset to show both parts of the trajectory, e.g. $bf(r)(pi/2) = (0,0)$ is drawn a little bit left of where it should be.], ) The trajectory is a straight line from $(1,1)$ to $(- 1 , - 1)$ and back following the line $y = x$. === Speed of the butterfly at $t = pi / 3$ The speed of the butterfly is given by the magnitude of its velocity vector, which is the derivative of $bf(r) (t)$ with respect to time $t$. First, compute the velocity $bf(r)'(t)$: $ bf(r)' (t) = (d) / (dif t) angle.l cos (t) , cos (t) angle.r = angle.l - sin (t) , - sin (t) angle.r . $ (This has direction along the line $y=x$, which is what we expect.) The speed at any time $t$ is the magnitude of the velocity vector: $ "Speed" = lr(|bf(r)' (t)|) = sqrt((- sin (t))^2 + (- sin (t))^2) = sqrt(2 sin^2 (t)) = sqrt(2) lr(|sin (t)|) . $ At $t = pi / 3$, we have: $ sin (pi / 3) = sqrt(3) / 2 . $ Thus, the speed at $t = pi / 3$ is: $ "Speed" = sqrt(2) dot sqrt(3) / 2 = sqrt(6) / 2 . $ === Arc length of the butterfly’s trajectory from $t = 0$ to $t = 2 pi$ Note that from the sketch of the trajectory, we can actually find the arc length with no calculus at all. Indeed, "arc length" is a misnomer because the "arc" is just two line segments! From the Pythagorean theorem, distance from $(1,1)$ to $(-1,-1)$ is $ sqrt((1-(-1))^2 + (1-(-1))^2) = sqrt(4+4) = 2sqrt(2). $ So the total distance is $ 2sqrt(2) + 2sqrt(2) = 4sqrt(2). $ Of course, one could also use the arc length formula, and we show how to do so. The arc length of the trajectory is given by the integral of the speed: $ L = int_("start time")^("stop time") lr(|bf(r)' (t)|) dif t . $ We just saw that $lr(|bf(r)' (t)|) = sqrt(2) lr(|sin (t)|)$. Therefore, the arc length from $t = 0$ to $t = 2 pi$ is: $ L = int_0^(2 pi) sqrt(2) lr(|sin (t)|) dif t . $ #warning[ Don't forget about the absolute value! In general, for real $X$, we have $sqrt(X^2) = |X|$. If you forget the absolute value here, you'll end up getting $0$ as the answer, which doesn't make sense because the butterfly certainly traveled more than $0$ distance. Remember, speed (absolute value of velocity vector) should always be nonnegative. ] Because of the absolute value, we can break the integral into two parts. On the interval $[0 , pi]$, $sin (t) >= 0$, and on the interval $[pi , 2 pi]$, $sin (t) <= 0$, so $ L = sqrt(2) (int_0^(pi) sin (t) dif t + int_(pi)^(2 pi) - sin (t) dif t) . $ See @fig-abs-sin for an illustration of this integral. #figure( image("figures/mt2-abs-sin.png", width: auto), caption: [The integral $int_0^(2pi) |sin(t)| dif t$ is two copies of the first hump $int_0^(pi) sin(t) dif t$ (which doesn't have an absolute value on it).], ) <fig-abs-sin> Both integrals are the same, so we compute one and multiply by 2: $ int_0^pi sin (t) dif t = [- cos (t)]_0^pi = - cos (pi) + cos (0) = 1 + 1 = 2 . $ Thus, the total arc length is: $ L = sqrt(2) dot 2 dot 2 = 4 sqrt(2) . $ #pagebreak() == Solution to the level curve (@prob-mt2p2) The first task is to recover the value of $k$ which wasn't given in the statement. First, substitute the point $(1 , 2)$ into the function $f (x , y)$: $ f (1 , 2) = 1^3 + k (2^2) = 1 + 4 k . $ We are told that $f (1 , 2) = 21$, so we set the equation equal to 21: $ 1 + 4 k = 21 ==> 4 k = 20 ==> k = 5 . $ Thus, the function is: $ f (x , y) = x^3 + 5 y^2 . $ Now that we know $f$, we can compute the gradient by taking the partial derivatives: $ nabla f = vec((partial f) / (partial x) , (partial f) / (partial y)) = vec(3x^2 , 10y). $ Now evaluate the gradient at $P = (1 , 2)$: $ nabla f (1 , 2) = vec( 3 (1)^2 , 10 (2) ) = vec(3 , 20) . $ The gradient is always normal to the tangent line, so the tangent line must be of the form $ 3 x + 20 y = t $ for some number $t$. This line passes through $(1,2)$ so we can get $ t = 3 dot 1 + 20 dot 2 = 43. $ Hence the line requested is $ 3 x + 20 y = 43. $ #pagebreak() == Solution to the linear approximation (@prob-mt2p3) We are given the function: $ f (x , y) = x^(5 y) $ and are asked to estimate $f (1.001 , 3.001)$ using linear approximation, starting from the point $(1 , 3)$, at which $ f(1,3) = 1. $ We start by computing $nabla f$. - To get the partial derivative with respect to $x$, use the power rule and chain rule: $ (partial f) / (partial x) = 5 y x^(5 y - 1) . $ - For the partial derivative with respect to $y$, we treat $x$ as a constant: $ (partial f) / (partial y) = x^(5 y) log(x) dot 5 . $ Thus, the gradient of $f (x , y)$ is: $ nabla f (x , y) = ⟨5 y x^(5 y - 1) , 5 x^(5 y) log (x)⟩ . $ The gradient at $(1,3)$ is thus $ nabla f(1,3) = vec(15,0). $ The linear approximation of $f (1.001 , y)$ near the point $(1 , 3)$ can be expressed in terms of the gradient dot the displacement: $ f (1.001 , 3.001) &approx f (1 , 3) + nabla f (1 , 3) dot vec(0.001, 0.001) &= 1 + vec(15,0) dot vec(0.001, 0.001) = 1.015. $ #pagebreak() == Solution to the two-variable function (@prob-mt2p4) Although this is stated as an 18.02 problem, it can actually be solved basically only using 18.01 methods. We'll still present the solution from an 18.02 perspective, but we'll comment many times on places where just 18.01 methods would have been sufficient. === Finding the critical points To find the critical points, we first compute the gradient. The partial derivatives are $ f_x (x , y) &= (partial) / (partial x) (cos (pi x) + y^4 / 4 - y^3 / 3 - y^2) = - pi sin (pi x) . \ f_y (x , y) &= (partial) / (partial y) (cos (pi x) + y^4 / 4 - y^3 / 3 - y^2) = y^3 - y^2 - 2 y . $ Hence $ nabla f(x,y) = vec(-pi sin(pi x), y^3 - y^2 - 2 y). $ Setting this equal to $bf(0)$ lets us solve each equation individually: - $-pi sin(pi x) = 0$ is true whenever $x$ is an integer. - To solve $y^3 - y^2 - 2 y = 0$, factor the equation: $ 0 = y (y^2 - y - 2) = y (y - 2) (y + 1) = 0 . $ So there are infinitely many critical points! The critical points occur when $x$ is any integer and $y = -1$, $y = 0$, $y = 2$. See @fig-mt2-crits. #figure( image("figures/mt2-crits.png", width: auto), caption: [Plot of the critical points of the function in the $x y$-plane as red dots.], ) <fig-mt2-crits> === Classification using second derivative test We now classify each of the points using the second derivative test. Calculate the second derivatives needed: $ A = f_(x x) (x , y) &= (partial^2 f) / (partial x^2) = - pi^2 cos (pi x) , \ B = f_(x y) (x , y) &= (partial^2 f) / (partial x partial y) = 0, \ C = f_(y y) (x , y) &= (partial^2 f) / (partial y^2) = 3 y^2 - 2 y - 2. $ - We have $A = -pi^2$ if $x$ is odd and $A = pi^2$ if $x$ is even. - We always have $B = 0$. - We have $ C = cases( 3(-1)^2 - 2(-1) - 2 &= 3 &" if " y = -1, 3(0)^2 - 2(0) - 2 &= -2 &" if " y = 0, 3(2)^2 - 2(2) - 2 &= 6 &" if " y = 2.) $ We summarize all six cases in the table below. For each entry in the table we also compute $A C - B^2$ and then specify the answer based on the second derivative test. #figure( table( columns: 3, align: left, table.header([], [$x = ..., -4, -2, 0, 2, 4 ...$ is even], [$x = ..., -3, -1, 1, 3 ...$ is odd]), [$y = -1$], [$(A,B,C) = (-pi^2,0,3)$ \ $A C - B^2 = -3pi^2 < 0$ gives *saddle pt*], [$(A,B,C) = (pi^2,0,3)$ \ $A C - B^2 = 3pi^2 > 0$ gives *local min*], [$y = 0$], [$(A,B,C) = (-pi^2,0,-2)$ \ $A C - B^2 = 2pi^2 > 0$ gives *local max*], [$(A,B,C) = (pi^2,0,-2)$ \ $A C - B^2 = -2pi^2 < 0$ gives *saddle pt*], [$y = 2$], [$(A,B,C) = (-pi^2,0,6)$ \ $A C - B^2 = -6pi^2 < 0$ gives *saddle pt*], [$(A,B,C) = (pi^2,0,6)$ \ $A C - B^2 = 6pi^2 > 0$ gives *local min*], ), kind: table ) <table-sol-mt2-critical> === Another approach without the second derivative test You can get the same classification by just looking at the given function too. The point is that the function splits nicely into two halves: if define the one-variable functions $ a(x) &:= cos(pi x) \ b(y) &:= y^4/4 - y^3/3 - y^2 $ then $ f(x,y) = a(x) + b(y). $ In that case, the following result is true: - A point $P = (x,y)$ is a critical point of $f(x,y)$ if $x$ is a critical point of $a(x)$ and $y$ is a critical point of $b(y)$. - If so then, the point $P$ is... - a local minimum of $f$ if $x$ is a local minimum of $a(x)$ and $y$ is a local minimum of $b(y)$. - a local maximum of $f$ if $x$ is a local maximum of $a(x)$ and $y$ is a local maximum of $b(y)$. - a saddle point otherwise. If you have a good conceptual understanding of saddle points, this should be obvious. It's essentially @fig-whysaddle from @sec-saddle-sim. #figure( image("figures/mt2-graph.png", width: auto), caption: [The function $f$ is just the sum of two independent functions, which can be optimized independently.], ) <fig-sol-mt2-graph> This gives us the same table as above, since: - The critical points of $a(x) = cos(pi x)$ are $x = -2, -1, 0, 1, 2, ...$. The minimums are the odd integers when the $cos$ value reaches $-1$, the maximums are the even integers when the $cos$ value reaches $+1$. - The critical points of $b(y) = y^4 / 4 - y^3 / 3 - y^2$ are the roots of $b'(y) = y^3 - y^2 - 2y = y(y+1)(y-2)$, which are the same $y = -1, 0, 2$ we saw before. See @fig-sol-mt2-graph. There are local minimums at $y =-1$ and $y = 2$ and a local maximum at $y = 0$. === The global minimums and maximums First, we evaluate $f$ on every critical point. This is easiest to do if we use the $a$ and $b$ notation from before and compute $ a("even") &= cos(pi dot "even") = 1 \ a("odd") &= cos(pi dot "odd") = -1 \ b(-1) &= (-1)^4/4 - (-1)^3/3 - (-1)^2 = -5/12 \ b(0) &= (0)^4/4 - (0)^3/3 - (0)^2 = 0 \ b(2) &= (2)^4/4 - (2)^3/3 - (2)^2 = -8/3 $ Then we get the six values shown in @table-sol-mt2-extremes. #figure( table( columns: 3, align: left, table.header([], [$x = ..., -4, -2, 0, 2, 4 ...$ is even], [$x = ..., -3, -1, 1, 3 ...$ is odd]), [$y = -1$], [$f("even", -1) = 1 - 5/12 = 7/12$], [$f("odd", -1) = -1 - 5/12 = -17/12$], [$y = 0$], [$f("even", 0) = 1 + 0 = 1$], [$f("odd", 0) = -1 + 0 = -1$], [$y = 2$], [$f("even", 2) = 1 - 8/3 = -5/3$], [$f("odd", 2) = -1 - 8/3 = -11/3$], ), kind: table, caption: [Values of $f$ at the critical points] ) <table-sol-mt2-extremes> There are no inequality constraints at all, so we just think about limit cases $x -> pm oo$ or $y -> pm oo$. When $y -> pm oo$, the quartic $b(y) = y^4 / 4 - y^3 / 3 - y^2$ explodes to infinity. This implies already there cannot be any global maximum. In the case where $x -> pm oo$, the cosine term of $f(x,y)$ will oscillate between $-1$ and $1$, with period $2 pi$. So there are no new smaller values of $f$ that can be obtained here. === Another way to see the global minimums and maximums Because $ f(x,y) = a(x) + b(y) $ the global minimum of $f$ should be the sum of the global minimums of $a$ and $b$, and likewise the global maximum of $f$ should be the sum of the global maximums of $a$ and $b$. So we could have also just used 18.01 methods on $a$ and $b$ individually, as in @fig-sol-mt2-graph. That is: - Because $min a(x) = -1$ and $min b(y) = - 8/3$, the global minimum is $-11/3$. - Because $max a(x) = 1$ and $min b(y) = +oo$, there is no global maximum. Remember, this only works because we could easily divorce $f(x,y)$ into a function in $x$ plus a function in $y$. For most functions $f(x,y)$ like $x y$ or $e^x sin(y)$, this approach is not going to fly. #pagebreak() == Solution to the constrained optimization (@prob-mt2p5) Let $f(x,y,z) = x+2y+2z$. Let $cal(R)$ denote the region $x^2 + y^2 + z^2 <= 100$ (a ball of radius $10$) and let $cal(S)$ denote the boundary $x^2 + y^2 + z^2 = 100$ (a sphere of radius $10$). We follow the steps we described in the recipe in LAMV. 0. $cal(R)$ is three-dimensional and has no limit cases but a two-dimensional boundary $cal(S)$. (Because of the condition $x^2 + y^2 + z^2 <= 100$ and all the squares being nonnegative, none of the variables can go to $pm oo$.) 1. We calculate all the critical points of the objective function $f(x,y,z) = x+2y+2z$. The gradient is $ nabla f = vec(1, 2, 2) $ So there are no critical points, because this gradient is never $0$. 2. The boundary in $cal(S)$ is a sphere, and it cannot easily be handled. We pull out Lagrange multipliers and follow the recipe all the way through again. 0. $cal(S)$ is two-dimensional and has no limit cases or boundary. 1. We search for LM-critical points by letting $g(x,y,z) = x^2+y^2+z^2$, so $cal(S)$ is the level surface $g = 100$. Calculate the gradient of $g$: $ nabla g = vec(2x, 2y, 2z). $ Recall that an LM-critical point is one for which $g(P) = 100$ and _either_ $ nabla f (P) = lambda nabla g (P) " OR " nabla (P) = 0. $ This gradient $nabla g$ could be $bf(0)$ at $(x,y,z) = (0,0,0)$, but this point does not lie on $cal(S)$, so we disregard it. In the main case $nabla f = lambda g$, we seek points such that $ 1 &= lambda dot 2 x \ 2 &= lambda dot 2 y \ 2 &= lambda dot 2 z. $ Our strategy is to kill every variable _except_ $lambda$, by writing $ x &= 1 / (2 lambda) \ y &= 1 / (lambda) \ z &= 1 / (lambda). $ Plugging this back into the constraint equation $x^2 + y^2 + z^2 = 100$ and simplifying gives $ ((1) / (2 lambda))^2 + (1 / lambda)^2 + (1 / lambda)^2 &= 100 \ <==> (9) / (4 lambda^2) = 100 \ <==> lambda^2 = 9 / 400 \ <==> lambda = pm 3 / 20 . $ Putting these two values of $lambda$ in gives $ (x,y,z) = (10/l, 20/3, 20/3) " and " (x,y,z) = (-10/3, -20/3, -20/3)$ These are the two LM-critical points. Evaluating this gives $ f (10 / 3 , 20 / 3 , 20 / 3) = 10 / 3 + 2 dot 20 / 3 + 2 dot 20 / 3 &= 30 \ f (-10 / 3 , -20 / 3 , -20 / 3) = -10 / 3 + 2 dot -20 / 3 + 2 dot -20 / 3 &= -30. $ 2. There are no boundary cases to consider for $cal(S)$. 3. There are no limit cases to consider for $cal(S)$. In conclusion, the maximum value is $30$ and the minimum value is $-30$, at the points $(10/3, 20/3, 20/3)$ and $(-10/3, -20/3, -20/3)$ we found earlier. 3. There are no limit cases to consider for $cal(R)$. #digression[ Note that in fact one can note _a priori_ that any maximum or minimum should occur on the sphere. One way to see this is that if one takes a point strictly inside $cal(R)$ like $P = (6,8,0)$, one can always increase the absolute value of $f$ by scaling $P$ until it lies on the sphere (e.g. $(60, 80, 0)$). Hence there is no loss of generality in assuming maximums and minimums lie on $cal(S)$. So if one is observant enough they can skip straight to the LM on $cal(S)$, ignoring the region $cal(R)$ entirely. ] #pagebreak() == Solution to the tangent plane (@prob-mt2p6) The gradient of the function $f$ $ nabla f = vec(2(x-1), 3(y-1)^2, 4(z-1)^3) $ and so the gradient at the origin is $ nabla f (0,0,0) = vec(-2, 3, -4). $ The tangent plane $cal(H)$ consists of those vectors which are normal to $vec(-2, 3, -4)$. This plane is two-dimensional. So, to find two vectors spanning $cal(H)$, according to the "buy two get one free" result from we just need to give any two linearly independent (i.e. not multiples of each other) vectors which are both perpendicular to $vec(-2, 3, -4)$. There are many valid choices. One such example might be $vec(3, 2, 0)$ and $vec(0, 4, 3)$. These two vectors are clearly not multiples of each other, and $ vec(-2, 3, -4) dot vec(3,2,0) &= (-2) dot 3 + 3 dot 2 + (-4) dot 0 = 0 \ vec(-2, 3, -4) dot vec(0,4,3) &= (-2) dot 0 + 3 dot 4 + (-4) dot 3 = 0 $ so they are indeed tangent vectors contained in $cal(H)$.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/014%20-%20Khans%20of%20Tarkir/011_Bond%20and%20Blood.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Bond and Blood", set_name: "Khans of Tarkir", story_date: datetime(day: 03, month: 12, year: 2014), author: "<NAME>", doc ) #emph[Anafenza, khan of the Abzan Houses, takes the throne—and her vengeance.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("011_Bond and Blood/01.jpg", width: 100%), caption: [Anafenza, the Foremost | Art by <NAME>man], supplement: none, numbering: none) Anafenza always climbed barefoot. Her toes gripped the bark at the base of a sturdy branch, and she crouched there for a moment to steady herself. The leaves of the First Tree gave off a dull minty scent that filled her nostrils. She closed her eyes, and rose to her full height. As she emerged through the cover of the uppermost leaves, the sun's heat was waiting for her. The day was hot, but she enjoyed surveying the city from its highest point. The First Tree grew out of the rooftop plaza of the keep of Mer-Ek Fortress. From Anafenza's position, she could peer down past the keep's massive ramparts to the market below, where merchants scurried about to trade in rumors and wares. Her gaze drifted beyond the walls that protected the capital. Arid wilderness stretched out in every direction. Into the expanse of dunes and dust, a causeway descended from the rock upon which the capital was built. This was where the Salt Road disappeared into the restless sands of the Shifting Wastes, where only the rolling fortified caravans of the merchant houses trekked. It was a world Anafenza knew well, for it was her home for most of her life. #figure(image("011_Bond and Blood/02.jpg", width: 100%), caption: [Plains | Art by <NAME>], supplement: none, numbering: none) She turned her face to the wind, the familiar breath of the desert bringing with it so many memories draped in emotions. She followed her own backward-drifting thoughts, and each path led to the same familiar dark place. Her family was gone. All but one member. She wanted him to remember her as she was almost ten years before. In the morning, she had cut her hair short, and as the hot desert air rushed around her, she became very aware of her bare neck. The only remnants of its former length were the locks that hung from each temple, fluttering wildly when they caught the wind. But she was not the same, and he would see what had become of her. "My khan?" came a voice from below. #emph[Khan] . The thought might have overwhelmed her if her mouth didn't yield to her impulse to smile. "I'm at the top, Kwaro," Anafenza said. Kwaro was Anafenza's captain of the guard, and he had taken to his new position most eagerly. Before Anafenza became khan, the aven veteran had led her honor guard in battle when she was a general of the Abzan army. Despite Anafenza's protests, he insisted in maintaining formalities with the new khan, and every time he addressed her, it was either prefaced or punctuated by "my khan." It was endearing, to a certain degree. "What news?" #figure(image("011_Bond and Blood/03.jpg", width: 100%), caption: [High Sentinels of Arashin | Art by <NAME>man], supplement: none, numbering: none) "The heads of the clan houses are gathered, my khan," said Kwaro. "All of them?" "Every single one, my khan." #emph[The one that matters most] , she thought. The khan descended through the branches of the First Tree. Her first climb had been just two weeks before, when she first entered the plaza with the tree's namesake, on her first day as khan. Although the branches and footholds were already familiar to her, the First Tree somehow felt different than other kin-trees. Khans were buried beneath it—people not bound by blood, but by duty to the clan. Like all kin-trees, however, their names were etched into its trunk. Like all kin-trees, the spirits of ancestors dwelt within. Like all kin-trees, Anafenza considered, the First Tree grew as a reminder that an individual has a sacred duty to family and clan. Anafenza lowered herself from a branch until her feet touched the golden-orange seat of the amber throne. The seat of the khan, a solid piece of ornately carved amber, stood on a stone dais that ringed the First Tree's massive trunk. Anafenza dropped into it, rattling the sword that hung from an arm of the throne. Beside her, brown leather riding boots lay in a heap, and she pulled them on. As she waited for Kwaro to return, she reclined against the back of the throne. It was a solid chunk of carved amber, and its translucent depths seemed to capture and hold the sun's light. Absently, her fingers played along the arms of the throne as she scanned the plaza for a moment. It was empty except for her and a dozen of her honor guard. Although outdoors, the entirety of the space was awash in the shade of the First Tree, and Anafenza was struck by the plaza's illusion of seeming to be both an enclosed chamber, and an open courtyard all at once. The plaza would be dark if not for the various low flames that burned in braziers throughout. She surprised herself by how calm she was. She was cool and collected, prepared to do what must be done, and for the first time, she felt like a khan. The massive wooden doors of the Plaza of the First Tree at last swung open behind the strength of four of her guards. Anafenza was standing in front of the Amber Throne to greet the first delegate as the clan's houses entered. The houses of the Abzan didn't swear fealty to their khan. Rather, they cultivated kinship through blood relations or by binding oaths. Loyalties can change, Anafenza's mother once explained to her, but kinship is a sacred thing. The houses had elected Anafenza to be khan, and they filed into the plaza, one after the other, to profess kinship either by bond or by blood. "Anafenza, Khan of the Abzan," began one of the delegates, a captain of the clan's elite Dragonscale infantry, "House Emesh embraces you as a sister before the First Tree and the eyes of our ancestors." "Marrit of House Emesh, I am your sister, as you are now my sister," Anafenza returned the formality, and the two embraced. The procession continued in kind. Many delegates were veterans of the armies she led to defend Abzan lands. Some were from the ancient merchant houses that now prospered as a result of the safe commerce along the Salt Road. Most were the supporters who put her on the Amber Throne. Some were the detractors who came to avoid becoming political pariahs. One was family. The last delegate approached the khan. He was clad in the polished breastplate of an Abzan warrior, its surface scored to resemble the pattern of dragon scales. A pristine white linen cloak fell from his shoulders. As he walked forward, the fabric rippled behind him. Anafenza waited at the lowest step of dais to receive him. When he stood before her, she looked him over. His hair was gray at the temples, and his face was freshly shaved. When their eyes met, he was smiling. That familiar smile. It was him, and that was the moment she had wanted. The one she craved. The one she fantasized into foregone certainty. As she held his gaze in silence, she waited for it. His smile faded, and his eye grew wide. Recognition. Then fear. Her smile emerged. "You look well. Prosperous," Anafenza said. "Trade is good?" The man just stared, his mouth slightly agape. The khan nodded, and a thick orc stepped behind the delegate. He was the man's height, but twice as wide. At his khan's command, he dropped a heavy hand on the man's shoulder, forcing him to his knees. The plaza was silent, save for the rustle of wind through the leaves of the First Tree. Anafenza ascended the dais to her throne, and slowly drew her sword, the Khan-Blade, from its scabbard. "Please!" the man shrieked. Anafenza extended her arm until the point of the Khan-Blade pressed into the flesh of the man's throat. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Dust got into everything out on the Salt Road. Anafenza woke up once again to the lurch of the colossal wheeled fortress as it creaked into motion behind the power of the behemoth that pulled it, and watched the motes of dust play in the sunlight that filled her room. At thirteen, she had spent most of her life rumbling from city to city throughout the Abzan lands as a member of one of the most prosperous merchant houses in the clan. It was a life built around routine and family. She trained at swords and bows, learned to read the charts and maps that meant survival in the Shifting Wastes, and when in a city, she practiced the art of negotiation and trade, although she lacked the diplomatic finesse for which the rest of her house was known. It was a life infused with dust. #figure(image("011_Bond and Blood/04.jpg", width: 100%), caption: [Siegecraft | Art by <NAME>], supplement: none, numbering: none) Everyone on a rolling fortress came close to snapping at certain times. The close proximity of family, the winds of the Wastes, the heavy footfalls of the enormous beast that pulled the fortress, and the incessant gritty cracking of sand beneath the fortress wheels all worked constantly to wear down one's nerves. Anafenza learned early on that this was natural, and that everyone had their own release. Her mother would ride out alone in front of the fortress on her ibex when conditions permitted. Her father collected dragon bones and carved intricate designs onto their surfaces. For Anafenza, cutting her hair was release enough. Dust clung to it, and she hated waking up on hot mornings with her hair clinging to her neck. One such morning, she reached for the scissors and began the familiar work. When the ritual was complete, her hair no longer hung in her face at the front, and it was off her neck in the back. The hair at her temples she left long, and they hung past her chin. They were her outlet for fidgeting, and she knew they bothered her mother. "There she is," her cousin said, greeting her with a smile as she entered the fortress's cramped study. There were always people there, poring over maps and ledgers, trying to determine the most efficient and profitable trade route. Her cousin, Oret, was the house's cartographer, and since his return from his travels, he had become a fixture there. He was almost ten years older than her, and he had an endless supply of stories from the lands beyond the Abzan. He was also easy to talk to. "Hair's gone, huh?" "It was time," said Anafenza. Oret smiled from behind a thick dark beard. As always, a map was spread out on a table in front of her cousin. Each time she came to visit him, he insisted that she locate their current position on the map. She was good at it, most of the time. "We're two day's from Arashin by way of the Salt Road out of, uh, what city were we just at?" Anafenza twisted up her face and closed her eyes in concentration. All the cities blurred together for her during long trade expeditions. "Kavah," came a low gravelly voice that didn't belong to her cousin. "Two days from Arashin by way of the Salt Road out of Kavah." Anafenza didn't have to open her eyes to know who spoke, but she did, if only to roll them. <NAME>. The name grated on her. It always had. Gvar was a krumar, which meant he was not born in the Abzan. Rather, he was the leftover of an Abzan battle against the Mardu clan, where the Mardu were the losers. Custom dictated that the Abzan care for the children of enemies killed in battle. Gvar, accordingly, returned home with one of Ananfenza's uncles after the battle where his son, her favorite cousin, was killed. "Kavah's where I bought these," said Gvar. He held out a bowl of grapes to Anafenza, who pretended she didn't notice. Gvar and Anafenza were close in age, and therefore, they were expected to be friends. "Very good, Gvar," came Oret's approval when he place a carved wooden model of the fortress correctly on the map. To Anafenza's relief, she didn't have to listen to Gvar open his mouth again, because the trio in the study turned their attention to the arrival of Anafenza's mother, father, and one of her many uncles. They were in the middle of a deep discussion. "Are we not in the business of trade? We should go where business is good," said Anafenza's mother, her voice thick with exasperation. Her uncle held up his hands to playfully shield his face from the assault. "We've already conceded," he said. "Let us just consult our cartographer," her father added. "About what?" said Oret, clearly amused at his elders' display. "A rider arrived. She told us that a shipment of dyes has arrived back in Kavah. I think it's worth our effort to go back for it, especially because the capital is our next stop." "I see." Oret looked over his map, his smile fading. "You know that Arashin is only—" "Two days away!" Anafenza threw in. "Two days away," repeated Oret. "Dust storms look to be building behind us. I must insist we continue to the capital." It was not the answer Anafenza's mother wanted to hear, and the room erupted in argument. Anafenza and Gvar were ushered out. Anafenza winded her way up through the interior of the fortress until her steps brought her to the rooftop plaza, where her family's kin-tree grew. Gvar followed behind. "Do you think we'll go back to Kavah, cousin?" Gvar asked. Anafenza whirled around. "We're not cousins, Gvar! We're not even family! My cousin died fighting your clan! You're only here because there was no one left from your family to care for you, and the Abzan aren't savages." "Then we have something in common." "What are you talking about?" Anafenza threw her arms up in frustration. "Neither of us chose the families we've got." Anafenza looked him in the eye, said nothing, and turned away. She kicked off her boots and scrambled up the trunk of the kin-tree. #emph[Her] kin-tree. Gvar watched her ascent, but she didn't care. She'd be at the top, and he'd be out of sight. The rumble of the fortress's wheels along the road resonated through the branches, but Anafenza had done the climb countless times, and she made it easily to the upper branches. Leaves rustled below her position. "Gvar?" said Anafenza. "Not Gvar," came a whisper. A face emerged. It belonged to Hakrez, the kin-tree warden. In a tradition typical of the Abzan, Hakrez, the family's most skilled warrior, became the kin-tree warden. She was responsible for protecting the tree from harm and preserving the ancestors. She was fearless, fierce, spoke only in whispers, and—to Anafenza—she was equal parts terrifying and amazing. As Hakrez climbed, her eyes never went to the branches. She knew the tree better than anyone. Her eyes stayed on Anafenza. When the two were level, Hakrez began to speak, and Anafenza had to lean close to hear her over the wind. "Where are we?" the kin-tree warden asked. #emph[On the road from Kavah, two days from Arashin] , she would have blurted had it been anyone else asking. Instead, she said nothing. "It's not a trick. Where are we?" said Hakrez. "In a tree." "Our kin-tree." "I'm sorry. Our kin-tree," Anafenza corrected herself. "Which is what?" Anafenza suddenly had the feeling she had done something wrong. "The tree of our family." "The tree of our #emph[kin] , Anafenza. Blood-kin #emph[and] bond-kin. This tree belongs to all of them." Anafenza knew that kin-tree wardens had a special connection to the ancestors' spirits, and that always seemed to give their word an added dimension of wisdom, like the words were somehow passed down through the ages. Hakrez left Anafenza to dwell on her words. Anafenza stayed there for hours, watching the scores of Abzan soldiers march beside the fortress. She realized the fortress hadn't altered course. They were still on the road to Arashin, and she smiled at the prospect of stretching her legs in the markets there. She peered out across the dunes that hemmed in the caravan fortress. Desert stretched out in every direction, and it struck Anafenza that even that close to a city, there was no evidence of civilization. As if to punctuate that, they approached a row of gigantic rib bones jutting out from the sand to the right of the fortress. It was not an uncommon sight in the Shifting Wastes, where the sands swallowed up entire villages, or receded to reveal scoured relics of dragons felled by Abzan ancestors many centuries before. She was watching the ribs as the fortress rolled alongside them when two of the ribs moved. Sand fell away. The dune looked to be collapsing in on itself at first, until Anafenza saw that something was rising out the sand. Matted, black fur emerged, and Anafenza's jaw hung open, her gaze fixed on the rising shape. She was frozen with dread. Not dragon ribs. Tusks. An enormous head followed, its skull only half-covered by strips of rotted flesh. And then a trunk. Anafenza was not the only one to notice, and shouts of warning could be heard throughout the height of the fortress. Below, the infantry escort fell into a defensive position. #figure(image("011_Bond and Blood/05.jpg", width: 100%), caption: [Rotting Mastodon | Art by <NAME>amm], supplement: none, numbering: none) By the time the animated corpse of the mastodon rose to its full height, three more were rising from the sand. The stench of death must have spooked the behemoth that drew the fortress, because it bellowed and stomped. Then chaos erupted. The sand between the mastodons seemed to burst into flame in dozens of places at once. Spheres of light with trails of orange energy skimmed the surface of the sand down toward the fortress. The spheres gave way to reveal countless warriors who descended upon the frightened behemoth. #figure(image("011_Bond and Blood/06.jpg", width: 100%), caption: [Ruthless Ripper | Art by <NAME>ley], supplement: none, numbering: none) "Ambush!" came a voice from the plaza below the kin-tree. "A Sultai war party!" Anafenza saw dozens of archers take positions at the parapet. Arrows flew from their bows, and the Sultai warriors dispersed to avoid the volley. The mastodons lumbered toward the fortress, and the soldiers below were forced to scatter. In the kin-tree, Anafenza felt a sudden whoosh of wind. Dust whirled about before settling into the shape of three humans, clad in the heavy armor of the Abzan. #emph[Ancestors] . They acknowledged Anafenza with a nod, and streaked toward one of the massive shambling undead horrors, tearing into it with their spirit weapons. #figure(image("011_Bond and Blood/07.jpg", width: 100%), caption: [Kin-Tree Invocation | Art by <NAME>], supplement: none, numbering: none) The mastodon collapsed, but the others were at the fortress. The first one slammed into a wall with enough force to split its own skull. Anafenza was almost thrown from the kin-tree, but she was able to cling to the branches and balance herself just before the next mastodon crashed in. The world shook. Another impact. Anafenza couldn't focus, everything went sideways, and the Salt Road rushed up to toward her. A moment later, Anafenza was sprawled out on the sand. She lay there dazed. A heartbeat before, she towered over the sand, and now her face was buried in it. The sounds of violence rang in her skull. She willed the muscles in her neck to turn her head, but searing pain flashed across her cheek as it slid across the gritty sand. She reached up to soothe the pain, and her hand came away sticky and red. She rolled onto her back and looked down at the tops of her bare feet, which were cut up the way she imagined her face must have been. Beyond, the fortress lay on its side, and beside her were the shattered remnants of the kin-tree. The jolt of the fall had torn it free of its soil, and it split upon impact. Broken branches and broken soldiers were scattered all around. Beneath a heavy bough, Anafenza recognized the lifeless body of Hakrez, the kin-tree warden, whose breastplate was caved in. Anafenza's mind raced to parse what had happened, and she remembered the mastodons. The blare of a horn brought Anafenza back. Her muscles surged with energy, and she rose to her feet to see the Sultai retreating beyond the dunes. Cheers did not follow the horn blast, however, and the air remained thick with the sounds of slaughter. Anafenza circled around the fallen fortress to find the commotion, hoping to see the soldiers of her house finishing off the last of the mastodons. There were screams, though. Human ones, and she approached carefully. When she came around a corner, her world fell to pieces. The scene that unfolded before her was a violation against nature. There was a wrongness in it that pricked at both her flesh and her guts. She saw Abzan butchering Abzan. People were trying to scramble out of the fortress through its narrow windows, but before they could get clear, Abzan soldiers were cutting their kin down with sword, axe and halberd. "Mother! Father!" she screamed. "Oret! Please!" Eyes wide, and streaming with tears, Anafenza knelt to scoop up the sword of a dead soldier. When she rose once more, a figure, silhouetted against the sun, loomed over her. "Your parents are dead. As is my bond-father." Through clouded vision, Anafenza recognized Gvar, who bled from a gash at the corner of his eye. Anafenza ignored the orc, and pushed past him. "Anafenza! We were betrayed." Gvar stepped in front of her again. "We have to get out of he—" The word caught in the orc's mouth, as he suddenly lurched forward, nearly knocking Anafenza to the ground. He fell to one knee, and Anafenza saw the feathered shaft of an arrow protruding from his shoulder. More arrows fell around them. "Ancestors damn you, Gvar!" Anafenza grunted as she helped lift him to his feet. "Let's go!" They made for the cover of the Shifting Wastes and kept going. For the better part of the day, they walked in silence. Each step through the sand was an effort, but they continued onward away from the carnage behind them. The hot sand scorched the soles of Anafenza's bare feet, and the sword that rested on her shoulder seemed to get heavier with each footfall. "Want one?" "What?" said Anafenza, her voice cracking as the word left her parched mouth. Gvar's big fist opened to reveal a small mound of crimson grapes. "Eat some," he said. Anafenza stopped and stared in disbelief at the fruit, and then at Gvar. The orc shrugged his shoulders, wincing slightly at the pain. "I know, I know. Just take them." "Thank you," she said between grapes. Gvar smiled and tossed the last grape into his mouth, and the pair resumed their march. As they crested each dune, they hoped to find some indication of civilization. On the road, they were two days from the capital. But across the Shifting Wastes, there was no certainty. "Do you still admire the Abzan?" Anafenza's voice was tinged with bitterness. "Is it the Mardu who are the savages?" She looked at Gvar, who didn't answer. He kept his eyes forward, shielding them from the dust. "Gvar?" Anafenza insisted. "You know," Gvar said at last, "I am Abzan because when I was a child, an Abzan warrior—your uncle—killed my blood-parents in battle, and left me with nobody. Your uncle took me into his house and raised me. Had it been the other way around—had I been born Abzan, and Mardu warriors killed my Abzan parents, I would have been killed with them." He turned to Anafenza. "Our house was betrayed, but our clan will demand justice." They walked until the sun hung low in the cloudless sky. Wind began to pick up, and sand beat mercilessly against any exposed skin. Another dune. At the top, Anafenza peered into the quickly dimming haze. Through squinted eyes, she was able to make out a vague, but unmistakable straight horizontal line that ran parallel to the ground. "A wall!" she blurted. "Gvar, look!" "Your ancestors must love you." Gvar was already striding down the dune toward the wall, and Anafenza was right behind. #figure(image("011_Bond and Blood/08.jpg", width: 100%), caption: [Brave the Sands | Art by Dave Kendall], supplement: none, numbering: none) The wall surrounded an abandoned village, and by the time they passed through a crumbling gate, the edge of the sky was a brilliant orange. The village was nothing more than a handful of dilapidated sandstone dwellings arranged in a circle. "We'll stay in one of these for the night," said Anafenza. "One that won't collapse on us, preferably," said Gvar. "See what you can find. I'll look for the well." Anafenza walked between two of the dwellings, giving both a cursory inspection. Emerging on the other side, she came upon the village's tiny main square. In the center, around which the meager structures had been built, rose a gnarled tree, left pale and stripped of bark by the battering sand. With each gust of wind, its leafless branches clattered. The sight of the abandoned tree against the darkening sky was too much. Anafenza ran over to it, letting her sword drop before collapsing in the sand that had gathered in a pile, obscuring its roots. All she could see was her kin-tree, splintered and dead. Her family was gone. She pressed her forehead against the trunk and stifled a scream in the crook of her arm. Tears came, and they stung her wounded cheeks as they slid down her face. She stayed there until the sun was gone. Until she heard Gvar's shout. "We were followed!" He yelled. "Go!" "Gvar!" Anafenza was on her feet, sword in hand. "I'll be right behind you!" He was struggling. Anafenza could hear it in his voice. And then she heard running. In the darkness, she saw Gvar's wide frame come into view from around a corner. He was breathing heavily, his legs pumping, and he wasn't alone. Two figures were close behind, and Anafenza caught the glint of steel on them. She said nothing, but silently pulled herself into the tree. She watched Gvar fly past beneath her. The pursuers followed. Two humans—and she saw the familiar outline of Abzan heavy armor. Her eyes narrowed, her grip tightened on the hilt of her sword, and she dropped behind the traitors. One of the men turned in time to receive the point of Anafenza's blade below his breastplate. Steel bit into flesh, sinking deep into the man's belly. Some incomprehensible protest gurgled from his mouth, and he collapsed. Gvar and his pursuer spun around to see Anafenza slide her sword free. The remaining attacker raised his own blade, but before he could bring it down, Gvar had him around the neck from behind. The two wrestled to the ground, and the orc rolled onto his back so that the attacker was pinned to him, facing away. Anafenza pressed her bloodied sword against the throat of their incapacitated enemy. "If you struggle, you will die." The man went limp in Gvar's arms. "You will tell us who planned this. All of it," Anafenza said, her voice cool and clear. The man was silent. Anafenza pressed. "If you don't give us a name, we're going to believe it was you. And we plan to hurt that person. Badly." She leaned close to his face to look him in the eye. "So try again." "It was a member of your house," the man managed. "He hired the Sultai." "You can do better," she said. "Who?" "Oret. It was Oret." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("011_Bond and Blood/09.jpg", width: 100%), caption: [Sandsteppe Citadel | Art by <NAME>ley], supplement: none, numbering: none) With the fierce eyes of the veteran of countless battles, Anafenza looked down at her cousin. He looked so small at Gvar's feet. "It seems your maps held secrets only you knew," she said, her voice was cool and unwavering. "But even you must come out to swear kinship to a new khan, Oret." Barely audible, Oret managed, "You were dead." "I am the khan." "Please," Oret resumed his plea. The khan held up a hand to silence him. "Please!" he tried again. "We have found each other again. I am the last family you have!" Gvar erupted. "You dare?" Anafenza looked past Oret to the orc, and her face broke into an amused smile. "Oret, #emph[you] are not my family." The khan flicked her wrist, and the blade flashed. A red line appeared at the side of his face from ear to chin, and Oret screamed. His blood clung to the tip of the Khan-Blade, and she held it over one of the lit braziers at the base of the dais. The blood popped and sizzled in the heat. She turned the sword edge skyward, and she proceeded to drag her own hand along its sharpness. Without shifting her gaze from Oret, she held her fist over the flame and squeezed. Blood dripped out, hissing when it hit the burning coals. "Before the First Tree and the eyes of our ancestors, I disown you, Oret. You are no longer of my blood. I declare you my enemy. If we should meet on the battlefield, you will not leave it. Your spirit will be rootless, wandering alone in agony for all time. Now Gvar, my brother, show him out."
https://github.com/fontlos/FengruCup-template
https://raw.githubusercontent.com/fontlos/FengruCup-template/main/template.typ
typst
MIT License
// 伪加粗, 支持正则表达式, 可自选字重 #let bold(reg: ".", base-weight: none, body) = { show regex(reg): it => { set text(stroke: 0.02857em) set text(weight: base-weight) if base-weight != none it } body } // 针对中文的伪加粗 #let bold-cn(s) = { bold(reg: "[\p{script=Han} !-・〇-〰—]", base-weight: "regular", s) } // Show 全局加粗规则 #let bold-rule(reg: ".", base-weight: none, body) = { show text.where(weight: "bold").or(strong): it => { bold(reg: reg, base-weight: base-weight, it) } body } // 针对中文的 Show 全局加粗规则 #let bold-cn-rule(s) = { bold-rule(reg: "[\p{script=Han} !-・〇-〰—]", base-weight: "regular", s) } // https://github.com/typst/typst/issues/2749 #let _skew(angle, vscale: 1, body) = { let (a, b, c, d) = (1, vscale * calc.tan(angle), 0, vscale) let E = (a + d) / 2 let F = (a - d) / 2 let G = (b + c) / 2 let H = (c - b) / 2 let Q = calc.sqrt(E * E + H * H) let R = calc.sqrt(F * F + G * G) let sx = Q + R let sy = Q - R let a1 = calc.atan2(F, G) let a2 = calc.atan2(E, H) let theta = (a2 - a1) / 2 let phi = (a2 + a1) / 2 set rotate(origin: bottom + center) set scale(origin: bottom + center) box(rotate(phi, scale(x: sx * 100%, y: sy * 100%, rotate(theta, body)))) } // 伪斜体, 支持正则表达式, 考虑到斜体后可能与后面的字重叠, 可自行设置间距 #let italic(reg: "[^ ]", ang: -0.32175, spacing: none, body) = { show regex(reg): _skew.with(ang) body if spacing != none {h(spacing)} } // Show 全局斜体规则 #let italic_rule(reg: "[^ ]", ang: -0.32175, spacing: none, body) = { show text.where(style: "italic").or(emph): it => { italic(reg: reg, ang: ang, spacing: spacing, it) } body } #let frb( title: none, subtitle: none, header: none, author: "", abstract-CN: none, keyword-CN: none, abstract-EN: none, keyword-EN: none, bibliography-file: none, bibliography-title: "参考文献", bibliography-style: "gb-7714-2015-numeric", auto-num-title: true, body ) = { // 设置文档基本内容 set document(author: (author, ), title: title) // 设置页边距 set page( margin: ( top: 2.5cm, bottom: 2.5cm, left: 3cm, right: 2cm, ) ) // 设置正文, 公式与代码块字体 set text(font: ("Times New Roman" ,"SimSun"), size: 12pt) show math.equation: set text(font: "New Computer Modern Math", weight: 400) show raw : set text(font: ("DejaVu Sans Mono", "SimSun"), weight: 400, size: 9pt) // 代码块背景 show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt, ) // 设置封面 v(0.3em) align(left, image("svg/logo.svg", width: 20%)) v(3.5em) align(center, image("svg/name.svg", width: 80%)) v(4em) align(center, text(21pt, title, font: ("Times New Roman", "STZhongsong"), stroke: 0.04em)) v(2em) if subtitle != none{ let subtitle = "——" + subtitle align(right, text(16pt, subtitle, font:("Times New Roman", "STXinwei"))) } // 设置摘要与目录页页码 set page( // 设置页码 footer: align(center ,text(size: 10.5pt, counter(page).display("i"))), ) pagebreak() counter(page).update(1) // 设置段间距 show par: set block(above: 15.75pt, below: 15.75pt) set par( leading: 15.75pt, first-line-indent: 2em, ) // 摘要, 关键字与目录 if abstract-CN != none and keyword-CN != none { align(center, text(16pt, font: "SimHei")[摘要]) [ #abstract-CN #text(font: "SimHei", "关键词:") #keyword-CN ] pagebreak() } if abstract-EN != none and keyword-EN != none { align(center, text(16pt, weight: "bold")[Abstract]) [ #abstract-EN *Keywords: * #strong(keyword-EN) ] pagebreak() } // 目录设置 show outline.entry: it => { it v(0.0em, weak: true) } set par( first-line-indent: 0em, ) align(center, text(16pt, font: "SimHei")[目录]) outline( title: none, depth: 3, indent: 2em, fill: box(width: 1fr, repeat[.#h(0.5em)]) ) // 设置正文页页码与页眉 set page( footer: align(center ,text(size: 10.5pt, counter(page).display("1"))), header-ascent: 14pt, header: { set text(size: 9pt, font: "SimSun") align(center, header) v(-2.6em) line(start:(0%,25%),end:(100%,25%),length:100%,stroke: 0.5pt) }, ) pagebreak() counter(page).update(1) // 主体 // 设置段间距 show par: set block(above: 1.5em, below: 1.5em) // 插入空行以辅助首行缩进 // show heading: it => { // // v(1em) // it; // v(0.5em, weak: true) // h(0em) // } show list: it => { it; v(0em, weak: true) h(0em) } show enum: it => { it; text()[#v(0em, weak: true)]; text()[#h(0em)] } show table: it => { it; text()[#v(0.3em, weak: true)]; text()[#h(0em)] } show math.equation: it => { it; // text()[#v(0.3em, weak: true)]; text()[#h(0em)] } show raw: it => { it; // text()[#v(0.3em, weak: true)]; text()[#h(0em)] } set par( leading: 15.75pt, first-line-indent: 2em, ) // 标题大小 show heading.where(level:1): it =>{ set text(size: 16pt, font:("Times New Roman", "SimHei")) v(1em) align(center, it) v(0.5em, weak: true) h(0em) } show heading.where(level:2): it =>{ set text(size: 14pt, font:("Times New Roman", "SimHei")) v(0.2em) it v(0.0em, weak: true) h(0em) } show heading.where(level:3): it =>{ set text(size: 12pt, font:("Times New Roman", "SimHei")) v(0.2em) it v(0.2em, weak: true) h(0em) } // 是否开启自动标号 if auto-num-title != none { set heading(numbering: (..nums) => { if nums.pos().len()==1 { numbering("一、", nums.pos().at(0)) } else if nums.pos().len()==2 { numbering("(一) ", nums.pos().at(1)) } else if nums.pos().len()==3 { numbering("1.", nums.pos().at(2)) } }) body } else { body } // 结尾参考文献 if bibliography-file != none { pagebreak() bibliography(bibliography-file, title: bibliography-title, style: bibliography-style) } } #let img( path: none, width: 80%, num: none, body ) = { set text(stroke: 0.02857em, size: 10.5pt) figure( image(path, width: width), caption: [#bold(body)], numbering: num ) text()[#v(0.3em, weak: true)]; text()[#h(0em)] }
https://github.com/0x1B05/nju_os
https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/11_真实世界的并发编程.typ
typst
#import "../template.typ": * #pagebreak() = 真实世界的并发编程 == 高性能计算中的并行编程 #link("https://dl.acm.org/doi/10.1145/359327.359336")[CRAY-1 Supercomputer, “the world's most expensive love-seat” 1976, 138 MFLOPS \@ 115kW] === (经典) 高性能计算 _*“A technology that harnesses the power of supercomputers or computer clusters to solve complex problems requiring massive computation.” (IBM)*_ 源自数值密集型科学计算任务 - 物理系统模拟 - 天气预报、航天、制造、能源、制药、…… - 大到宇宙小到量子,有模型就能模拟 - 矿厂 (现在不那么热了) - 纯粹的 hash 计算 - #link("http://www.hpc100.cn/top100/21/")[ HPC-China 100 ] === 高性能计算程序:特点 物理世界具有 “空间局部性” - 一切 “模拟物理世界” 的系统都具有 embarrassingly parallel 的特性 === 高性能计算:关键问题 问题 1:计算任务如何分解 - 通常计算图容易静态切分 (机器-线程两级任务分解) - 生产者-消费者解决一切 - #link("https://hpc-tutorials.llnl.gov/mpi/")[ MPI ] - “a specification for the developers and users of message passing libraries”, [ OpenMP ](https://www.openmp.org/) - “multi-platform shared-memory parallel programming in C/C++ and Fortran” - [ Parallel and Distributed Computation ](https://web.mit.edu/dimitrib/www/pdc.html): Numerical Methods ```c #pragma omp parallel num_threads(128) for (int i = 0; i < 1024; i++) { } ``` 问题 2:海量线程之间的如何同步和通信 - 持久存储 (~PB) → CPU/内存 (~TB) → GPU/显存 (~10GB) → 缓存 (~MB) == 数据中心里的并发编程 === 数据中心程序:特点 > “A network of computing and storage resources that enable the delivery of shared applications and data.” (CISCO) 以数据 (存储) 为中心 - 互联网索引与搜索 - Google - 社交网络 - Facebook/Twitter - 支撑各类互联网应用 - 通信 (微信/QQ)、支付 (支付宝)、游戏/网盘/…… === 数据中心:关键问题 如何实现高可靠、低延迟的多副本分布式存储和计算系统? - 在服务海量地理分布请求的前提下,三者不可兼得: - 数据要保持一致 (Consistency) - 服务时刻保持可用 (Availability) - 容忍机器离线 (Partition tolerance) === 数据中心程序上的单机程序 事件驱动 + 高并发:系统调用密集且延迟不确定 - 网络数据读写 - 持久存储读写 - 单机程序目标:尽可能多地服务并行的请求 - QPS: 吞吐量 - Tail latency: 一个请求慢了,其他请求不能慢 假设有数千/数万个请求同时到达服务器…… - 线程能够实现并行处理 - 但远多于处理器数量的线程导致性能问题 - 切换开销 - 维护开销 === 协程:操作系统 “不感知” 的上下文切换 和线程概念相同 (独立堆栈、共享内存) - 但 “一直执行”,直到 yield() 主动放弃处理器 - 有编译器辅助,切换开销低 - yield() 是函数调用,只需保存/恢复 “callee saved” 寄存器 - 线程切换需要保存/恢复全部寄存器 - 但等待 I/O 时,其他协程就不能运行了…… - 失去了并行 ```c // 只可能是 1122 或 2211 void T1() { send("1"); send("1"); yield(); } void T2() { send("2"); send("2"); yield(); } ``` === Go 和 Goroutine Go: 小孩子才做选择,多处理器并行和轻量级并发我全都要! Goroutine: 概念上是线程,实际是线程和协程的混合体 - 每个 CPU 上有一个 Go Worker,自由调度 goroutines - 执行到 blocking API 时 (例如 sleep, read) - Go Worker 偷偷改成 non-blocking 的版本 - 成功 → 立即继续执行 - 失败 → 立即 yield 到另一个需要 CPU 的 goroutine - 太巧妙了!CPU 和操作系统全部用到 100% 例子 - Fibonacci number from [ The Go Programming Language ](https://books.studygolang.com/gopl-zh/ch9/ch9-08.html) (ch 9.8) === Go 语言中的同步 > Do not communicate by sharing memory; instead, share memory by communicating. ——Effective Go 共享内存 = 万恶之源 - 信号量/条件变量:实现了同步,但没有实现 “通信” - 数据传递完全靠手工 (没上锁就错了) 但 UNIX 时代就有一个实现并行的机制了 - `cat *.txt | wc -l` - 管道是一个天然的生产者/消费者! - 为什么不用 “管道” 实现协程/线程间的同步 + 通信呢? - Channels in Go == 人工智能时代的分布式机器学习 === 机器学习:既计算密集,又数据密集 GPT-3: [ Language models are few-shot learners ](https://arxiv.org/abs/2005.14165) - Transformer 架构 - #link("https://arxiv.org/abs/1706.03762")[ Attention Is All You Need ] - 175B 参数 (~300GB VRAM, FP-16) - GPT-3 single training run cost: ~\$5,000,000 - 美国人断供芯片 = 三体人行为 - 320TB 语料 - 相比图片和视频,还是小弟弟 === 并行化:Dependency Graph is All You Need #image("images/2024-03-18-18-05-30.png") === 计算密集部分 (1):SIMT Single Instruction, Multiple Threads - 一个 PC,控制 32 个执行流同时执行 - 逻辑线程可以更多 - 执行流有独立的寄存器 - x,y,z 三个寄存器用于标记 “线程号”,决定线程执行的动作 #image("images/2024-03-18-18-06-07.png") === 计算密集部分 (2):SIMD Single Instruction, Multiple Data - Tensor 指令 (Tensor Core):混合精度 A×B+C - 单条指令完成 4×4×4 个乘法运算 #image("images/2024-03-18-18-06-32.png") === 计算密集部分 (3):堆更多的处理单元! GH100 Spec - 144 SMs - 18432 CUDA Cores (并行的 Threads) - AVX512: 512bits = 16 x Float32 - 576 Tensor Cores (4 per SM) - 6 HBM3 or HBM2e stacks - 12 512-bit memory controllers - 60 MB L2 cache 这只是一个 GPU - 显存/缓存决定了 GPU 内堆处理器的上限 - 但我们可以有多台机器、每个机器有多台 GPU! 分布式机器学习 === 分布式机器学习 高性能计算 (GPU) + 数据中心计算 [ Scaling distributed machine learning with the parameter server (OSDI'14) ](https://www.usenix.org/conference/osdi14/technical-sessions/presentation/li_mu) #image("images/2024-03-18-18-07-10.png") == 用户身边的并发编程 === Web 2.0 时代 (1999) 人与人之间联系更加紧密的互联网 - “Users were encouraged to provide content, rather than just viewing it.” - 你甚至可以找到一些 “Web 3.0”/Metaverse 的线索 是什么成就了今天的 Web 2.0? - HTML (DOM Tree) + CSS = 终端世界 - 通过 JavaScript 可以改变它 - 通过 JavaScript 可以连接数据中心 - Ajax (Asynchronous JavaScript + XML) 和 \$ - 例子:Jupyter Notebook === 人机交互程序:特点和主要挑战 特点:不太复杂 - 既没有太多计算 - DOM Tree 也不至于太大 (大了人也看不过来) - DOM Tree 怎么画浏览器全帮我们搞定了 - 也没有太多 I/O - 就是一些网络请求 挑战:程序员多 - 零基础的人你让他整共享内存上的多线程 - 恐怕我们现在用的到处都是 bug 吧??? - 框架:不用怕,有我在 - AI: 不用怕,有我在 === 单线程 + 事件模型 尽可能少但又足够的并发 - 一个线程、全局的事件队列、按序执行 (run-to-complete) - 耗时的 API (Timer, Ajax, ...) 调用会立即返回 - 条件满足时向队列里增加一个事件 ``` \$.ajax({ url: "https://jyywiki.cn/hello/jyy", success: function (resp) { console.log(resp); }, error: function (req, status, err) { console.log("Error"); }, }); ``` === 异步事件模型 好处 - 并发模型简单了很多 - 函数的执行是原子的 (不能并行,减少了并发 bug 的可能性) - API 依然可以并行 - 适合网页这种 “大部分时间花在渲染和网络请求” 的场景 - JavaScript 代码只负责 “描述” DOM Tree 坏处 - Callback hell (祖传屎山) - `$.ajax` 嵌套 5 层,可维护性已经接近于零了 === 异步编程:Promise 导致 callback hell 的本质:人类脑袋里想的是 “流程图”,看到的是 “回调”。 The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promise: 流程图的构造方法 (Mozilla-MDN Docs) #image("images/2024-03-18-18-09-36.png") === Promise: 描述 Workflow 的 “嵌入式语言” Chaining ```js loadScript("/article/promise-chaining/one.js") .then( script => loadScript("/article/promise-chaining/two.js") ) .then( script => loadScript("/article/promise-chaining/three.js") ) .then( script => { // scripts are loaded, we can use functions declared there }) .catch(err => { ... } ); ``` Fork-join ```js a = new Promise((resolve, reject) => { resolve("A"); }); b = new Promise((resolve, reject) => { resolve("B"); }); c = new Promise((resolve, reject) => { resolve("C"); }); Promise.all([a, b, c]).then((res) => { console.log(res); }); ``` === Async-Await: 一种计算图的描述语言 async function - 总是返回一个 Promise object - `async_func()` - fork await promise - await promise - join ```js A = async () => await \$.ajax("/hello/a"); B = async () => await \$.ajax("/hello/b"); C = async () => await \$.ajax("/hello/c"); hello = async () => await Promise.all([A(), B(), C()]); hello() .then(window.alert) .catch((res) => { console.log("fetch failed!"); }); ```
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/2-background/ecs.typ
typst
MIT License
#import "../../lib/mod.typ": * == Entity Component System <s.b.ecs> #acr("ECS") is an architectural software design pattern specifically tailored for #acr("DOP"). #acr("DOP") is a design paradigm that focuses on organizing and processing data efficiently, by structuring the layout of data to play well with the caching mechanisms built into modern CPUs. Instead of organizing repeated structures as #acr("AOS"), structures are instead decoupled into its constituent components, grouped into separate in-memory continuous arrays called #acr("SOA"). This approach is characterized by the separation of data storage from behavior and logic at the programming level. ECS architecture is commonly employed in computer games and intensive data analytics to enhance performance. Additionally, it has been utilized in robotic simulation projects such as the Potato simulator, which models large-scale heterogeneous swarm robotics@li2023potato. // At the programming level this is visible by the separation of data storage from behaviour and logic. This architecture is commonly used in computer games and intensive data analytics computations to achieve higher performance. It has also been used in other robotic simulations projects such as @li2023potato, that uses it simulate large scale heterogeneous swarm robotics. At the heart of #acrpl("ECS") are three complementary concepts, from which its name comes from; _entities_, _components_ and _systems_: #term-table( [*Entity*], [A collection of components with unique IDs. Every object in the #acr("ECS") world is an entity. Most often the ID is a single unsigned integer. An entity could be a robot, a camera or a cylinder.], [*Component*], [Data scoped to a single piece of functionality; e.g. position, velocity, rigid body, timer etc.], [*System*], [Functions that operate on the data by querying the #acr("ECS") world for entities and components and updating them.] ) // #table( // columns: (auto, auto, 1fr), // stroke: none, // row-gutter: 0.25em, // // gutter: none, // [*Entity*], marker.arrow.single, [A collection of components with a unique id. Every object in the #acr("ECS") world is an entity. Most often the id a single unsigned integer. An entity could be a robot, a camera or a cylinder.], // [*Component*], marker.arrow.single, [Data scoped to a single piece of functionality. For example position, velocity, rigid body, a timer etc.], // [*System*], marker.arrow.single, [Functions that operate on the data by querying the #acr("ECS") world for entities and components and updating them.] // ) // / Entity: A collection of components with a unique id. Every object in the #acr("ECS") world is an entity. Most often the id a single unsigned integer. An entity could be a robot, a camera or a cylinder. // / Component: Data scoped to a sitable.vline(stroke: (paint: accent, thickness: 0.75pt, cap: "round"))ngle piece of functionality. For example position, velocity, rigid body, a timer etc. // / System: Functions that operate on the data by querying the #acr("ECS") world for entities and components and updating them. It leads to a different approach to software design in comparison to more traditional #acr("OOP") based ways of modelling simulated environments. Instead of using object hierarchies facilitated by inheritance all components are logically laid out in a flat hierarchy, managed by a single instance of some _data store_ structure. This data store is then queried and mutated by systems. All of this leads to a conceptual model which is close to relational database models. In this perspective entities are equivalent to primary keys, components to table columns, and systems to SQL queries@papagiannakis2023project. @f.ecs-entity-component-table shows an example of how the data store structures components into one large table indexed by entity ids. // memory hierarchies / Cache Locality // it is a structural pattern //! This is a guided introduction to Bevy's "Entity Component System" (ECS) //! All Bevy app logic is built using the ECS pattern, so definitely pay attention! //! //! Why ECS? //! * Data oriented: Functionality is driven by data //! * Clean Architecture: Loose coupling of functionality / prevents deeply nested inheritance //! * High Performance: Massively parallel and cache friendly //! //! ECS Definitions: //! //! Component: just a normal Rust data type. Generally scoped to a single piece of functionality //! Examples: position, velocity, health, color, name //! //! Entity: a collection of components with a unique id //! Examples: Entity1 { Name("Alice"), Position(0, 0) }, //! Entity2 { Name("Bill"), Position(10, 5) } //! //! Resource: a shared global piece of data //! Examples: asset storage, events, system state //! //! System: runs logic on entities, components, and resources //! Examples: move system, damage system //! //! Now that you know a little bit about ECS, lets look at some Bevy code! //! We will now make a simple "game" to illustrate what Bevy's ECS looks like in practice. // #note.kristoffer[talk about how ECS changes traditional design] // #ref(<s.m.architecture>) // node hierarchies // The #acr("ECS") architecture is not limited to game engines and simulations. // https://dl.acm.org/doi/10.1145/3286689.3286703 // #acr("AOS") vs #acr("SOA") // // // ```rust // struct Point3d { // position: Vec2, // velocity: Vec2, // } // // type Robots = Vec<Robot>; // ``` // entity similar to a primary key in a relational database #let header = ([`Entity` (*ID*)], [`Transform`], [`Robot`], [`Camera`], [`Velocity2d`], [`Obstacle`], [...]) #let columns = header.map(it => 1fr) // let columns = header.map(it => 1fr).remove(header.len()) #let columns = (1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 0.33fr) #let gray = catppuccin.theme.subtext0 #let table-stroke = gray #let table-fill-with-header = (x, y) => { if y == 0 { gray.lighten(60%) } else if x == 0 { gray.lighten(80%) } } #let cm = emoji.checkmark #set table(stroke: gray) #show raw: it => it #figure( { table(columns: columns, stroke: gray, // stroke: table-stroke, fill: table-fill-with-header, table.header(..header), table.hline(stroke: 1pt), [$a$], [#cm], [], [#cm], [#cm $[0.0, 1.0]$], [], [], [$a+1$], [#cm], [#cm], [], [#cm $[0.2, 0.8]$], [], [], [$a+2$], [#cm], [#cm], [], [#cm $[-0.5, 0.0 ]$], [], [], [$a+3$], [#cm], [], [], [], [#cm], [], [$a+4$], [#cm], [], [], [], [#cm], [] ) v(-1em) text(size: 16pt, $dots.v$) v(-0.75em) table(columns: columns, stroke: gray, fill: (x, y) => if x == 0 { gray.lighten(80%) }, [$a+n$], [#cm], [#cm], [], [#cm $[1.0, 0.0]$], [], [] ) }, caption: [Structural layout of an #acr("ECS") data store. Conceptually it is analogous to a table in relational database. #cm in a component column denotes that the entity has an instance of that component type e.g. entity $a + 2$ has components: ${$ `Transform`, `Robot`, `Velocity2d` $}$] ) <f.ecs-entity-component-table> // In Bevy systems are ordinary functions For this thesis the Bevy Engine is used, as the uderlying framework for both rendering and #acr("ECS") implementation@bevyengine. Its #acr("ECS") implementation utilizes Rusts powerful type system, to encode queries as variadic generic types that are verified at compile time. To get a sense for how queries are expressed using the type system, have a look at @l.example-ecs-query. It showcases how the three concepts of #acr("ECS") blends well together with the Rust language. Systems are ordinary functions, with `Query<...>` arguments. Components are structs and enums implementing the `Component` trait. Entities are simply type aliases for unsigned integers. // ```sql // select Transform, Velocity2d, Robot as _ from world // ``` #listing( [ ```rust fn move_robots(mut query: Query<(&mut Transform, &Velocity2d), With<Robot>>) { for (mut transform, velocity) in &mut query { ... } } ``` ], line-numbering: none, caption: [An example of how bevy uses the Rust type system to implement #acr("ECS") queries with a high level of expressitivity. The constructed type can be read as: "Give me a mutable reference to a `Transform` component, and immutable reference to a `Velocity2d` component. But only for the entities with a `Robot` marker component."] ) <l.example-ecs-query> Executing the system in @l.example-ecs-query against the data store in @f.ecs-entity-component-table would result in an tuple iterator over the cells colored green#swatch(catppuccin.latte.green.lighten(75%)) as shown in @f.ecs-query. // let q-match-data = table.cell.with(fill: green.lighten(75%)) #let q-match-data = table.cell.with(fill: catppuccin.theme.green.lighten(75%)) // // let q-match-filter = table.cell.with(fill: blue.lighten(75%)) #let q-match-filter = table.cell.with(fill: catppuccin.theme.blue.lighten(75%)) #figure({ table(columns: columns, fill: table-fill-with-header, ..header, [$a$], [#cm], [], [#cm], [#cm $[0.0, 1.0]$], [], [], q-match-data[$a+1$], q-match-data[#cm], q-match-filter[#cm], [], q-match-data[#cm $[0.2, 0.8]$], [], [], q-match-data[$a+2$], q-match-data[#cm], q-match-filter[#cm], [], q-match-data[#cm $[-0.5, 0.0]$], [], [], [$a+3$], [#cm], [], [], [], [#cm], [], [$a+4$], [#cm], [], [], [], [#cm], [], ) v(-1em) text(size: 16pt, $dots.v$) v(-0.75em) table(columns: columns, q-match-data[$a+n$], q-match-data[#cm], q-match-filter[#cm], [], q-match-data[#cm $[1.0, 0.0]$], [], [] )}, caption: [ Result of executing the query `Query<(&mut Transform, &Velocity2d), With<Robot>>` against the data store in @f.ecs-entity-component-table. Cells colored green#swatch(catppuccin.latte.green.lighten(75%)) are selected by the query. The cells colored blue #swatch(catppuccin.latte.blue.lighten(75%)) show how the `With<Robot>` constraint limits the query to only select the components on entities ${a + 1, a + 2, a +n}$. ] ) <f.ecs-query> // A powerful feature of the Bevy game engine is that it will automatically schedule systems in parallel across available CPU cores, if it can guarantee that no data races will occur between systems accessing the same components. i.e. no two queries request a `&mut` mutable reference to a component column, that overlaps give any predicate clauses. This analysis is performed based on the query signatures given in systems. A powerful feature of the Bevy Engine is that it automatically schedules systems in parallel across available CPU cores if it can guarantee that no data races will occur between systems accessing the same components. This means no two queries can request a `&mut` mutable reference to a component column that overlaps with any predicate clauses. This analysis is performed at compile time based on the query types provided in the system signatures.
https://github.com/ikushaldave/Typster
https://raw.githubusercontent.com/ikushaldave/Typster/master/README.md
markdown
<p align="center"> <a href="" rel="noopener"> <img width=500px height=auto src="typster-icon.png" alt="Project logo"></a> </p> <h3 align="center">Typster</h3> <div align="center"> [![Status](https://img.shields.io/badge/status-active-success.svg)](https://chrome.google.com/webstore/detail/typster/ffigeilhpmjmppkbfmfedggomhblkjam) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](/LICENSE) </div> --- <p align="center"> A game to improve your typing skills. <br> </p> ## 🧐 About <a name = "about"></a> A typing game which gives you access to three levels based on difficulty and get a score based on your performance . ## ⛏️ Built Using <a name = "built_using"></a> - HTML - CSS - Vanilla Javascript ## ✍️ Authors <a name = "authors"></a> - [@ikushaldave](https://github.com/ikushaldave) - [<NAME>](). - [@celtonlloyd](https://github.com/celtonlloyd) - [<NAME>]() . - [@AlishaSaxena09](https://github.com/AlishaSaxena09) - [<NAME>]() . - [@nnkit](https://github.com/nnnkit) - [Ankit Sinha](), Mentor . ## Download <a name = "Download"></a> - [Version 0.1](https://chrome.google.com/webstore/detail/typster/ffigeilhpmjmppkbfmfedggomhblkjam) ## 🎉 Acknowledgements <a name = "acknowledgement"></a> - Hat tip to anyone who helped us.
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/snark-takeaways.typ
typst
#import "preamble.typ":* #takeaway[SNARK takeaways][ 1. A _SNARK_ can be used to succinctly prove that a piece of computation has been done correctly; specifically, it proves to some Verifier that the Prover had the K(nowledge) of some information that worked as feasible inputs to some computational circuit. 2. The _arithmetization_ of the circuit is a way of converting circuits to arithmetic. Specifically for PLONK (but also other SNARKs, e.g. Groth16), our arithmetization is systems of quadratic equations over $FF_q$, meaning that what PLONK does under the hood is prove that a system of these equations are satisfied. 3. The work under the hood of PLONK comes down to polynomial commitments (specifically KZG). KZG allows PLONK's gate checks and copy checks. 4. The N(oninteractivity) of SNARKs basically come down to the _Fiat-Shamir heuristic_, which is very common in this field. Generally speaking, the "meat" of zkSNARKs are mostly about S(uccinctness) of the AR(guments). ]
https://github.com/ahplev/notes
https://raw.githubusercontent.com/ahplev/notes/main/qm/TIse.typ
typst
#set text( font: "Noto Sans SignWriting Regular", ) #set math.equation(numbering: "1", supplement: [Eq.]) //#show ref: it => { // let eq = math.equation // let el = it.element // if el != none and el.func() == eq { // // Override equation references. // numbering( // el.numbering, // ..counter(eq).at(el.location()) // ) // } else { // // Other references as usual. // it // } //} // = One dimensional Square Well == Even potential - Let $V(-x) = V(x)$, if $phi(x)$ is a solution, then $phi(-x)$ is also a solution - For the eigenvalue $E$, there always exists a set of solutions that are *complete*, and each eigenfunction holds a specific parity. - Solutions to the eigenvalue $E$ are indegenerate == General properties in 1 dimension - for two degenerate solutions $psi_1$ and $psi_2$ belonging to the same eigenvalue, $psi_1 psi_2^' - psi_1^' psi_2 = C$ $ [-planck.reduce^2 / (2 m) d^2/(d x^2) + V] psi_1 = V psi_1 $ <1> $ [-planck.reduce^2 / (2 m) d^2/(d x^2) + V] psi_2 = V psi_2 $ <2> $phi_1 times$ @2 $-$ $phi_2 times$ @1: $ psi_1 psi_2^' - psi_1^' psi_2 = (psi_1 psi_2^' - psi_1^' psi_2)^' = 0 space qed $ - for a poential without singularity, bound states are indegenerate $ psi_1 psi_2^' - psi_1^' psi_2 = C $ for the bound state, $limits(psi)_(x -> oo) = 0$, $C = 0$, $(psi_1^')/psi_1 = (psi_2^')/psi_2$, so they are the same state == Infinite Square Well $ V(x) = cases( 0"," space 0 lt.eq x lt.eq a, oo"," space "otherwise" ) $ boundary conditions $ psi(0) = 0\ psi(a) = 0 $ Indise well, $ psi(x) = A e^(i/planck.reduce p x) + B e^(-i/planck.reduce p x)\ cases( A + B = 0, A e^(i/planck.reduce p a) + B e^(-i/planck.reduce p a) = 0 ) $ $ B = -A\ sin p/planck.reduce a = 0 $ - $psi_n(x) = A_n sin (n pi)/a x, space E_n = (n^2 planck.reduce^2 pi^2)/(2 m a^2)$ $ integral_0^a abs(A_n)^2 sin^2 (n pi)/a x d x &= abs(A_n)^2 / 2 integral_0^a 1 - cos (2 n pi)/a x d x\ &= (abs(A_n)^2 a)/2 = 1 $ - $E_n prop n^2$ $ Delta E_n prop n\ (Delta E_n)/(E_n) prop 1/n $ - $psi_n prop sin (n pi)/a x$ - ground state $E_1, psi_1$ - $psi(x) = sum a_n psi_n (x)$ - density of states $ rho(E) = (delta N)/(delta E) = 1/(d E slash d n)\ E = A n^2\ (d E)/(d n) = 2 A n\ rho(E) = 1/(2 sqrt(E A)) = (a sqrt(2 m))/(2 pi planck.reduce sqrt(E)) $ - $psi(x, t_0) = sqrt(2/a) sin pi/a x$ //Inside the well, time-independent Schrodinger equation //$ -planck.reduce^2 /(2m)(d^2 psi)/(d x^2) = E psi $ //let $k eq.triple sqrt(2m E)/planck.reduce$, we have //$ (d^2 psi)/(d x^2) = -k^2 psi $ //where the general solution is //$ psi(x) = A sin k x + B cos k x $ <sol1> //_A_ and _B_ are, of course, *complex constants*. As for the continuity, //$ psi(0) = psi(a) = 0 $ //plugging into @sol1, //$ A sin 0 + B cos 0 = B = 0 $ //so $psi(x) = A sin k x $. And again //$ A sin k a = 0 $ //which means either $A=0$ (discarded), or $sin k a = 0$, i.e. //$ k a = 0, plus.minus pi, plus.minus 2pi, plus.minus 3pi, dots.h $ //So here comes the quantum number, let's say, $n$, we have //$ k_n = (n pi)/a, space "with" n in II $ //and the energy //$ E_n = (planck.reduce^2 k_n^2)/(2m) = (n^2 pi^2 planck.reduce^2)/(2m a^2) $ //at last, the normalization //$ integral_0^a abs(A)^2 sin^2 (k x) d x = abs(A)^2 a/2 = 1, space space "so" abs(A)^2 = 2/a $ //and the time-independent solutions are //$ psi_n (x) = sqrt(2/a) sin((n pi)/a x) $ == Harmonic Oscillator $ V(x) = 1/2 m omega^2 x^2 $ === Algebraic method $ hat(H) = 1/(2m)[hat(p)^2 + (m omega x)^2] $ $ hat(a)_(plus.minus) eq.triple 1/sqrt(2 planck.reduce m omega)(minus.plus i hat(p) + m omega x) $ $ hat(a)_minus hat(a)_plus &= 1/(2 planck.reduce m omega)(i hat(p) + m omega x)(-i hat(p)+m omega x)\ &= 1/(2planck.reduce m omega)[hat(p)^2 + (m omega x)^2 - i m omega(x hat(p) - hat(p) x)]\ &= 1/(2planck.reduce m omega)[hat(p)^2 + (m omega x)^2]-i/(2planck.reduce)[x, hat(p)] $ $ [x, hat(p)] f(x) &= [x(-i planck.reduce)d/(d x)f - (-i planck.reduce)d/(d x)(x f)] = -i planck.reduce(x (d f)/(d x) - x(d f)/(d x) - f)\ &= i planck.reduce f(x) $ $ [x, hat(p)] = i planck.reduce $ $ hat(a)_minus hat(a)_plus = 1/(planck.reduce omega)hat(H) + 1/2 $ $ hat(H) = planck.reduce omega (hat(a)_- hat(a)_+ - 1/2) $ $ hat(a)_plus hat(a)_minus = 1/(planck.reduce omega)hat(H) - 1/2 $ $ hat(H) = planck.reduce omega (hat(a)_+ hat(a)_- + 1/2) $ $ hat(H) = planck.reduce omega (hat(a)_plus.minus hat(a)_minus.plus plus.minus 1/2) $ <ham> $ hat(H)(hat(a)_+ psi) &= planck.reduce omega(hat(a)_plus hat(a)_minus + 1/2)(hat(a)_plus psi) = planck.reduce omega(hat(a)_+ hat(a)_- hat(a)_+ + 1/2 hat(a)_+)psi\ &= planck.reduce omega hat(a)_+ (hat(a)_- hat(a)_+ + 1/2)psi = hat(a)_+ [planck.reduce omega (hat(a)_+ hat(a)_- + 1 + 1/2)psi]\ &= hat(a)_+ (hat(H) + planck.reduce omega)psi = hat(a)_+ (E + planck.reduce omega)psi = (E + planck.reduce omega)(hat(a)_+ psi) $ $ hat(H)(hat(a)_- psi) &= planck.reduce omega(hat(a)_- hat(a)_+ - 1/2)(hat(a)_- psi) = planck.reduce omega hat(a)_- (hat(a)_+ hat(a)_- - 1/2)psi\ &= hat(a)_- [planck.reduce omega (hat(a)_- hat(a)_+ -1 - 1/2)psi]\ &= hat(a)_- (hat(H) - planck.reduce omega)psi = hat(a)_- (E - planck.reduce omega)psi\ &= (E - planck.reduce omega)(hat(a)_- psi) $ find the ground state with lowest energy such that $ hat(a)_- psi_0 = 0 $ i.e. $ 1/sqrt(2 planck.reduce m omega) (planck.reduce d/(d x) + m omega x) psi_0 = 0\ (d psi_0)/(d x) = -(m omega)/(planck.reduce)x psi_0\ psi_0 (x) = A e^(-(m omega)/(2 planck.reduce)x^2) $ to normalize it $ abs(A)^2 integral_(-oo)^oo e^(-m omega x^2 slash planck.reduce) d x = abs(A)^2 sqrt((pi planck.reduce)/(m omega)) = 1 $ thus $A^2 = sqrt(m omega slash pi planck.reduce)$, so $ psi_0 (x) = ((m omega)/(pi planck.reduce))^(1 slash 4) e^(-(m omega)/(2 planck.reduce)x^2) $ so the interesting part here is that we don't exactly know if $A$ is positive or negative, but rather the $abs(A)^2$, this may be the philosophy of quantum mechanics: we cannot determine the wave function, but the probability distribution, i.e. $abs(psi)^2$ Anyway, with the ground state and ladder operator, we can obtain all eigenstates: $ psi_n (x) = A_n (hat(a)_+)^n psi_0 (x), space "with" E_n = (n + 1/2)planck.reduce omega $ <states> now we are going to calculate the normalization constant ($A_n$) algebraically, we have $ hat(a)_+ psi_n = c_n psi_(n+1), space hat(a)_- psi_n = d_n psi_(n -1) $ <prop> and operator $hat(a)_plus.minus$ is hermitian conjugate of $hat(a)_minus.plus$: $ angle.l f bar.v hat(a)_plus.minus g angle.r &= 1/sqrt(2planck.reduce m omega) integral_(-oo)^oo f^* (minus.plus planck.reduce d/(d x) + m omega x)g d x\ &= 1/sqrt(2planck.reduce m omega) integral_(-oo)^oo (m omega x f)^* g d x + 1/sqrt(2planck.reduce m omega) integral_(-oo)^oo f^* (minus.plus)planck.reduce (d g)/(d x) d x \ &= 1/sqrt(2planck.reduce m omega) integral_(-oo)^oo (m omega x f)^* g d x + 1/sqrt(2planck.reduce m omega) f^* (minus.plus) planck.reduce g bar.v_(-oo)^oo - 1/sqrt(2 planck.reduce m omega) integral_(-oo)^oo (minus.plus)planck.reduce g d f^* \ &= 1/sqrt(2planck.reduce m omega)integral_(-oo)^oo [(plus.minus planck.reduce d/(d x) + m omega x)f]^* g d x \ &= angle.l hat(a)_minus.plus f bar.v g angle.r $ invoking @ham and @states we have $ planck.reduce omega (hat(a)_plus.minus hat(a)_minus.plus plus.minus 1/2) psi_n = [(n + 1/2)planck.reduce omega] psi_n\ hat(a)_+ hat(a)_- psi_n = n psi_n , space hat(a)_- hat(a)_+ psi_n = (n + 1)psi_n $ <32> to utilize the hermitian conjugate, consider the integral $ integral_(-oo)^oo (hat(a)_plus.minus psi_n)^* (hat(a)_plus.minus psi_n) d x = integral_(-oo)^oo (hat(a)_minus.plus hat(a)_plus.minus psi_n)^* psi_n d x $ with @32 and @prop $ &integral_(-oo)^oo (hat(a)_+ psi_n)^* (hat(a)_+ psi_n) d x = abs(c_n)^2 integral abs(psi_(n+1))^2 d x = (n + 1)integral_(-oo)^oo abs(psi_n)^2 d x\ &integral_(-oo)^oo (hat(a)_- psi_n)^* (hat(a)_- psi_n)d x = abs(d_n)^2 integral abs(psi_(n-1))^2 d x = n integral_(oo)^oo abs(psi_n) ^2 d x $ but hey, we haven't make any restrictions on $psi$ this far, since we come from @prop, now we assume that $psi_n$ and $psi_(n plus.minus 1)$ are normalized, and we are finding the relation between the normalized constants, it follows that $ abs(c_n)^2 = n+1$ and $abs(d_n)^2 = n$, and hence $ hat(a)_+ psi_n = sqrt(n+1)psi_(n+1) , space hat(a)_- psi_n = sqrt(n) psi_(n - 1) $ once again we still don't know whether to pick the positive or the negative sign LOL, whatever, finally here it comes $ psi_n = 1/sqrt(n!)(hat(a)_+)^n psi_n $ Orthogonality $ angle.l psi_m bar.v hat(a)_plus hat(a)_- psi_n angle.r &= n angle.l psi_m bar.v psi_n angle.r\ &= angle.l hat(a)_- psi_m bar.v hat(a)_- psi_n angle.r = angle.l hat(a)_+ hat(a)_- psi_m bar.v psi_n angle.r\ &= m angle.l psi_m bar.v psi_n angle.r $ $ angle.l psi_m bar.v psi_n angle.r = delta_(m n) $ === Analytic Method Let's, at least, write the Schrodinger equation once $ -planck.reduce^2/(2m)(d^2 psi)/(d x^2) + 1/2 m omega^2 x^2 psi = E psi $ and someone, somehow, introduced two variables $ xi eq.triple sqrt((m omega)/planck.reduce)x, space K eq.triple (2E)/(planck.reduce omega) $ and how we got to know that we need to do this though, I have no idea, whatever, than the equation reads $ (d^2 psi)/(d xi^2) = (xi^2 - K)psi $ <37> when $xi$ goes infinity with constant energy $ (d^2 psi)/(d xi^2) approx xi^2 psi $ so we have this $ psi(xi) approx A e^(-xi^2 slash 2) + B e^(+xi^2 slash 2) $ clearly $B e^(+xi^2 slash 2)$ results in diverging, so $B$ must be 0; now, quite like the separation of variables, we separate the asymptotic part like this $ psi(xi) = h(xi) e^(-xi^2 slash 2) $ in hopes that $h(xi)$ has a simpler form. $ (d psi)/(d xi) = ((d h)/(d xi) - xi h) e^(-xi^2 slash 2)\ (d^2 psi)/(d xi^2) = ((d^2 h)/(d xi^2) - 2xi (d h)/(d xi) + (xi^2 - 1)h)e^(-xi^2 slash 2) $ @37 than becomes _*Hermite equation*_ $ (d^2 h)/(d xi^2) - 2xi (d h)/(d xi)+ (K-1)h = 0 $ <46> find the power series solution in terms of $xi$ $ h(xi) = sum_(j=0)^oo a_j xi^j\ (d h)/(d xi) = sum_(j = 0)^oo (j+1) a_(j+1) xi^(j)\ (d^2 h)/(d xi^2) = sum_(j=0)^oo (j+1)(j+2)a_(j+2)xi^j $ putting back into @46 $ sum_(j=0)^oo (j+1)(j+2)a_(j+2)xi^j - 2sum_(j=0)^oo (j+1)a_(j+1) xi^(j+1) + (K-1)sum_(j=0)^oo a_j xi^j = 0\ sum_(j = 0)^oo [(j+1)(j+2)a_(j+2) - 2 j a_j + (K-1)a_j]xi^j = 0\ a_(j+2) = (2j+1-K)/((j+1)(j+2)) a_j $ <48> the upper asympotic behavior of this recursion is $ a_(j+2) approx 2/j a_j\ a_j approx C/((j slash 2)!)\ h(xi) approx C sum 1/((j slash 2)!) xi^j approx C sum 1/(j!) xi^(2j) approx C e^(xi^2) $ so this recursion must terminates, i.e. $ exists n, space "s.t." space K = 2n+1 $ again we derived this energy with a different method $ E_n = (n+1/2)planck.reduce omega, space n = 0, 1, 2, dots.h $ the recursion formula @48 is now $ a_(j+2) = (-2(n-j))/((j+1)(j+2))a_j $ $ psi_n(x) = ((m omega)/(pi planck.reduce))^(1/4) 1/sqrt(2^n n!) H_n (xi)e^(-xi^2 / 2) $ First few Hermite polynomials $ &H_0(x) = 1\ &H_1(x) = 2x\ &H_2(x) = 4x^2 - 2\ &H_3(x) = 8x^3 - 12x $ According to rodrigues formula $ H_n (x) = (-1)^n e^(x^2) (d/(d x))^n e^(-x^2) $ generating function $ e^(-t^2 + 2t x) = sum_(n = 0)^oo H_n (x) t^n / (n!) $ $ angle.l H_m bar.v e^(-x^2) H_n angle.r &= integral_(-oo)^oo (-1)^m (d/(d x))^m e^(-x^2) H_n d x\ &= integral_(-oo)^oo (-1)^n H_n d (d/(d x))^(m - 1)e^(-x^2)\ &= (-1)^n H_n (d/(d x))^(m - 1)e^(-x^2) bar.v_(-oo)^oo + integral_(-oo)^oo (-1)^(m-1) (d/(d x))^(m - 1) e^(-x^2) d H_n\ &= integral_(-oo)^oo (-1)^(m-2) (d/(d x))^(m-2) e^(-x^2) d (d/(d x)) H_n\ &= integral_(-oo)^oo (-1)^(m - k) (d/(d x))^(m - k) e^(-x^2) (d/(d x))^k H_n d x $ when $m = n = k$ $ angle.l H_m bar.v e^(-x^2) H_n angle.r &= integral_(-oo)^oo e^(-x^2) n! 2^n d x\ &= 2^n sqrt(pi) n! $ so for the general case $ angle.l H_m bar.v e^(-x^2) H_n angle.r = 2^n sqrt(pi) n! delta_(m n) $ $ (d H_n)/(d x) &= (-1)^n 2 x e^(x^2) (d/(d x))^n e^(-x^2) + (-1)^n e^(x^2) (d/(d x))^(n+1) e^(-x^2)\ &= 2x H_n(x) - H_(n+1)(x) $ == Free Particle $ - planck.reduce^2/(2 m) (d^2 psi)/(d x^2) = E psi\ (d^2 psi)/(d x^2) = -k^2 psi, space k eq.triple sqrt(2 m E)/planck.reduce\ psi(x) = A e^(i k x) + b e^(-i k x)\ $ $ Psi(x, t) = A e^(i k(x - (planck.reduce k)/(2 m)t)) + B e^(-i k (x + (planck.reduce k)/ (2m))) $ a set of orthogonal eigenfunctions $ Psi_k (x, t) = A e^(i k ( x - (planck.reduce k)/(2 m)t)) $ linear combination $ Psi = 1/sqrt(2 pi)integral_(-oo)^oo phi.alt(k)e^(i k (x - (planck.reduce k)/(2 m)t)) d k $ $ cases( Psi(x, 0) = 1/sqrt(2 pi) integral_(-oo)^oo phi.alt(k)e^(i k x) d x"," space "position space", phi.alt(k) = 1/sqrt(2 pi)integral_(-oo)^oo Psi(x, 0) e^(-i k x) d x"," space "momentum space" )\ T = (4 m pi)/(planck.reduce k^2)\ lambda = (2 pi)/k $ $ hat(p)Psi_k = -i planck.reduce d/(d x) Psi_k = p A e^(i k(x - (planck.reduce k)/(2 m)t)) = planck.reduce k A e^(i k(x - (planck.reduce k)/(2 m)t))\ p = planck.reduce k $ this is essentially the *de Broglie formula* === wave packet $ Psi = 1/sqrt(2 pi) integral_(-oo)^oo phi.alt(k)e^(i k x - omega t) d k $ to get the classical velocity, consider a wave packet centered around some momentum $k_0$, so $phi.alt$ is negligible except in the vicinity of $k_0$, we can expand $omega (k)$ into taylor series and keep the leading terms: $ omega(k) approx omega_0 + omega_0^' (k - k_0) $ to center the integral at $k_0$, let $s := k - k_0$ $ Psi & approx 1/(sqrt(2 pi)) integral_(-oo)^oo phi.alt(k_0+s)e^(i[(k_0 + s)x - (omega_0 + omega_0^' s)t]) d s\ &= 1/sqrt(2 pi)e^(i (k_0 x - omega_0 t))integral_(-oo)^oo phi.alt(k_0 + s)e^(i s (x - omega_0^' t)) d s $ the phase velocity $ v_"phase" = omega/k |_(k = k_0) $ and a well-defined group velocity (independent of $k$ inside the integral): $ v_"group" = (d omega)/(d k) |_(k = k_0) $ for the free particle, $omega = (planck.reduce k^2 slash 2 m)$, $v_"classical" = v_"group" = 2 v_"phase"$
https://github.com/gabrielrovesti/UniPD-Swiss-Knife-Notes-Slides
https://raw.githubusercontent.com/gabrielrovesti/UniPD-Swiss-Knife-Notes-Slides/main/Slides/UniPD%20Typst/unipd.typ
typst
MIT License
#import "@preview/polylux:0.3.1": logic, utils #let unipd-red = rgb("#9b0014"); #let unipd-gray = rgb("#484f59"); #let unipd-lightgray = rgb("#fbfef9"); #let unipd-author = state("unipd-author", none) #let unipd-date = state("unipd-date", none) #let unipd-progress-bar = state("unipd-progress-bar", true) #let unipd-theme( aspect-ratio: "16-9", author: none, date: none, progress-bar: true, body, ) = { set page( paper: "presentation-" + aspect-ratio, margin: 0em, header: none, footer: none, ) set text(size: 25pt) show footnote.entry: set text(size: .6em) unipd-progress-bar.update(progress-bar) unipd-author.update(author) unipd-date.update(date) body } #let title-slide(title: "", subtitle: none) = { logic.polylux-slide({ place(image("images/background.svg", width: 100%)) place( bottom + right, dx: -2%, dy: -2%, image("images/logo.svg", width: 30%), ) set text(fill: white) v(15%) align( center, box(inset: (x: 2em), text(size: 46pt, title)), ) if (subtitle != none) { align( center, box(inset: (x: 2em), text(size: 30pt, subtitle)), ) } v(8%) h(7.5%) text(size: 24pt, unipd-author.display()) linebreak() h(7.5%) text(size: 24pt, unipd-date.display()) }) } #let slide( title: none, header: none, footer: none, hide-section: false, new-section: none, body, ) = { let body = pad(x: 2em, y: .1em, body) let progress-barline = locate(loc => { if unipd-progress-bar.at(loc) { let cell = block.with( width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false, ) utils.polylux-progress(ratio => { grid( rows: 2pt, columns: (ratio * 100%, 1fr), cell(fill: unipd-red), cell(fill: unipd-gray), ) }) } else { [] } }) let header-text = { if header != none { header } else if title != none { if new-section != none { utils.register-section(new-section) } set text(fill: white) pad( x: 0.4em, y: 0.2em, grid( columns: (50%, 35%, 15%), align(horizon + left, heading(level: 2, title)), if (hide-section) { box() } else { align(horizon + right, text( fill: unipd-red.lighten(65%), utils.current-section, )) }, align(top + right, image("images/logo_white.svg")), ), ) } else { [] } } let header = { set align(top) block(fill: unipd-red, grid( rows: (auto, auto), progress-barline, header-text, )) } let footer = { set text(size: 10pt) set align(center + bottom) let cell(fill: none, it) = rect( width: 100%, height: 100%, inset: 1mm, outset: 0mm, fill: fill, stroke: none, align(horizon, text(fill: white, it)), ) if footer != none { footer } else { place( bottom, image("images/background_wave.svg", width: 100%), ) show: block.with(width: 100%, height: auto) grid( columns: (25%, 1fr, 15%, 10%), rows: (1.5em, auto), cell(box()), cell(unipd-author.display()), cell(unipd-date.display()), cell(logic.logical-slide.display() + [~/ ~] + utils.last-slide-number), ) } } set page( margin: (top: 3em, bottom: 1.5em, x: 0em), header: header, footer: footer, footer-descent: 0em, header-ascent: .6em, ) logic.polylux-slide(body) } #let focus-slide( background-color: none, background-img: none, body, ) = { let background-color = if background-img == none and background-color == none { unipd-red } else { background-color } set page(fill: background-color, margin: 1em) if background-color != none set page( background: { set image(fit: "stretch", width: 100%, height: 100%) background-img }, margin: 1em, ) if background-img != none set text(fill: white, size: 2em) logic.polylux-slide(align(horizon, body)) }
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/ConsuntivoSprint/SestoSprint.typ
typst
MIT License
#import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost #import "../../functions.typ": rendicontazioneOreAPosteriori, rendicontazioneCostiAPosteriori, glossary == Sesto #glossary[sprint] *Inizio*: Venerdì 29/12/2023 *Fine*: Giovedì 04/01/2024 #rendicontazioneOreAPosteriori(sprintNumber: "06") #rendicontazioneCostiAPosteriori(sprintNumber: "06") === Analisi a posteriori Il consuntivo delinea come le ore effettive siano minori di quelle preventivate, nonostante queste ultime fossero già pressoché la metà di quelle preventivate solitamente (applicazione di una delle misure preventive di RP4 o Impegni universitari). Nonostante il rallentamento del ritmo di evoluzione del progetto, la comunicazione tra i componenti del team è migliorata rispetto allo #glossary[sprint] 5, grazie in particolare al meeting interno effettuato come da regola a fine #glossary[sprint] e ad un meeting di emergenza, sostenuto da 3 componenti del team, che è servito a discutere di criticità legate alla modifica dell'_Analisi dei Requisiti_.
https://github.com/alex-touza/fractal-explorer
https://raw.githubusercontent.com/alex-touza/fractal-explorer/main/paper/src/lib/ctheorems.typ
typst
/* MIT License Copyright (c) 2023 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Store theorem environment numbering #let thmcounters = state("thm", ( "counters": ("heading": ()), "latest": () ) ) #let thmenv(identifier, base, base_level, fmt) = { let global_numbering = numbering return ( ..args, body, number: auto, numbering: "1.1", refnumbering: auto, supplement: identifier, base: base, base_level: base_level ) => { let name = none if args != none and args.pos().len() > 0 { name = args.pos().first() } if refnumbering == auto { refnumbering = numbering } let result = none if number == auto and numbering == none { number = none } if number == auto and numbering != none { result = context { let heading-counter = counter(heading).get() return thmcounters.update(thmpair => { let counters = thmpair.at("counters") // Manually update heading counter counters.at("heading") = heading-counter if not identifier in counters.keys() { counters.insert(identifier, (0, )) } let tc = counters.at(identifier) if base != none { let bc = counters.at(base) // Pad or chop the base count if base_level != none { if bc.len() < base_level { bc = bc + (0,) * (base_level - bc.len()) } else if bc.len() > base_level{ bc = bc.slice(0, base_level) } } // Reset counter if the base counter has updated if tc.slice(0, -1) == bc { counters.at(identifier) = (..bc, tc.last() + 1) } else { counters.at(identifier) = (..bc, 1) } } else { // If we have no base counter, just count one level counters.at(identifier) = (tc.last() + 1,) let latest = counters.at(identifier) } let latest = counters.at(identifier) return ( "counters": counters, "latest": latest ) }) } number = context { global_numbering(numbering, ..thmcounters.get().at("latest")) } } return figure( result + // hacky! fmt(name, number, body, ..args.named()) + [#metadata(identifier) <meta:thmenvcounter>], kind: "thmenv", outlined: false, caption: name, supplement: supplement, numbering: refnumbering, ) } } #let thmbox( identifier, head, ..blockargs, supplement: auto, padding: (top: 0.5em, bottom: 0.5em), namefmt: x => [(#x)], titlefmt: strong, bodyfmt: x => x, separator: [#h(0.1em):#h(0.2em)], base: "heading", base_level: none, ) = { if supplement == auto { supplement = head } let boxfmt(name, number, body, title: auto, ..blockargs_individual) = { if not name == none { name = [ #namefmt(name)] } else { name = [] } if title == auto { title = head } if not number == none { title += " " + number } title = titlefmt(title) body = bodyfmt(body) pad( ..padding, block( width: 100%, inset: 1.2em, radius: 0.3em, breakable: false, ..blockargs.named(), ..blockargs_individual.named(), [#title#name#separator#body] ) ) } return thmenv( identifier, base, base_level, boxfmt ).with( supplement: supplement, ) } #let thmplain = thmbox.with( padding: (top: 0em, bottom: 0em), breakable: true, inset: (top: 0em, left: 1.2em, right: 1.2em), namefmt: name => emph([(#name)]), titlefmt: emph, ) // Track whether the qed symbol has already been placed in a proof #let thm-qed-done = state("thm-qed-done", false) // The configured QED symbol #let thm-qed-symbol = state("thm-qed-symbol", $qed$) // Show the qed symbol, update state #let thm-qed-show = { thm-qed-done.update(true) context [#thm-qed-symbol.get()] } // If placed in a block equation/enum/list, place a qed symbol to its right #let qedhere = metadata("thm-qedhere") // Checks if content x contains the qedhere tag #let thm-has-qedhere(x) = { if x == "thm-qedhere" { return true } if type(x) == content { for (f, c) in x.fields() { if thm-has-qedhere(c) { return true } } } if type(x) == array { for c in x { if thm-has-qedhere(c) { return true } } } return false } // bodyfmt for proofs #let proof-bodyfmt(body) = { thm-qed-done.update(false) body context { if thm-qed-done.at(here()) == false { h(1fr) thm-qed-show } } } #let thmproof(..args) = thmplain( ..args, namefmt: emph, bodyfmt: proof-bodyfmt, ..args.named() ).with(numbering: none) #let thmrules(qed-symbol: $qed$, doc) = { show figure.where(kind: "thmenv"): set block(breakable: true) show figure.where(kind: "thmenv"): set align(start) show figure.where(kind: "thmenv"): it => it.body show ref: it => { if it.element == none { return it } if it.element.func() != figure { return it } if it.element.kind != "thmenv" { return it } let supplement = it.element.supplement if it.citation.supplement != none { supplement = it.citation.supplement } let loc = it.element.location() let thms = query(selector(<meta:thmenvcounter>).after(loc)) let number = thmcounters.at(thms.first().location()).at("latest") return link( it.target, [#supplement~#numbering(it.element.numbering, ..number)] ) } show math.equation.where(block: true): eq => { if thm-has-qedhere(eq) and thm-qed-done.at(eq.location()) == false { grid( columns: (1fr, auto, 1fr), [], eq, align(right + horizon)[#thm-qed-show] ) } else { eq } } show enum.item: it => { show metadata.where(value: "thm-qedhere"): { h(1fr) thm-qed-show } it } show list.item: it => { show metadata.where(value: "thm-qedhere"): { h(1fr) thm-qed-show } it } thm-qed-symbol.update(qed-symbol) doc }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/goto_definition/at_def.typ
typst
Apache License 2.0
#let /* ident after */ f() = 1; #(f()); #(f());
https://github.com/TJ-CSCCG/tongji-slides-typst
https://raw.githubusercontent.com/TJ-CSCCG/tongji-slides-typst/main/theme/utils.typ
typst
MIT License
#import "logic.typ" #import "pdfpc.typ" // SECTIONS #let sections-state = state("polylux-sections", ()) #let register-section(name) = locate(loc => { sections-state.update(sections => { sections.push((body: name, loc: loc)) sections }) }) #let current-section = locate(loc => { let sections = sections-state.at(loc) if sections.len() > 0 { sections.last().body } else { [] } }) #let polylux-outline(enum-args: (:), padding: 0pt) = locate( loc => { let sections = sections-state.final(loc) pad( padding, enum( ..enum-args, ..sections.map(section => link(section.loc, section.body)), ), ) }, ) // PROGRESS #let polylux-progress(ratio-to-content) = locate( loc => { let ratio = logic.logical-slide.at(loc).first() / logic.logical-slide.final(loc).first() ratio-to-content(ratio) }, ) #let last-slide-number = locate(loc => logic.logical-slide.final(loc).first()) // HEIGHT FITTING #let _size-to-pt(size, styles, container-dimension) = { let to-convert = size if type(size) == "ratio" { to-convert = container-dimension * size } measure(v(to-convert), styles).height } #let _limit-content-width(width: none, body, container-size, styles) = { let mutable-width = width if width == none { mutable-width = calc.min(container-size.width, measure(body, styles).width) } else { mutable-width = _size-to-pt(width, styles, container-size.width) } box(width: mutable-width, body) } #let fit-to-height(height, width: none, prescale-width: none, body) = { // Place two labels with the requested vertical separation to be able to // measure their vertical distance in pt. // Using this approach instead of using `measure` allows us to accept fractions // like `1fr` as well. // The label must be attached to content, so we use a show rule that doesn't // display anything as the anchor. let before-label = label("polylux-fit-height-before") let after-label = label("polylux-fit-height-after") [ #show before-label: none #show after-label: none #v(1em) hidden#before-label #v(height) hidden#after-label ] locate( loc => { let before = query(selector(before-label).before(loc), loc) let before-pos = before.last().location().position() let after = query(selector(after-label).before(loc), loc) let after-pos = after.last().location().position() let available-height = after-pos.y - before-pos.y style( styles => { layout( container-size => { // Helper function to more easily grab absolute units let get-pts(body, w-or-h) = { let dim = if w-or-h == "w" { container-size.width } else { container-size.height } _size-to-pt(body, styles, dim) } // Provide a sensible initial width, which will define initial scale parameters. // Note this is different from the post-scale width, which is a limiting factor // on the allowable scaling ratio let boxed-content = _limit-content-width(width: prescale-width, body, container-size, styles) // post-scaling width let mutable-width = width if width == none { mutable-width = container-size.width } mutable-width = get-pts(mutable-width, "w") let size = measure(boxed-content, styles) let h-ratio = available-height / size.height let w-ratio = mutable-width / size.width let ratio = calc.min(h-ratio, w-ratio) * 100% let new-width = size.width * ratio v(-available-height) // If not boxed, the content can overflow to the next page even though it will fit. // This is because scale doesn't update the layout information. // Boxing in a container without clipping will inform typst that content // will indeed fit in the remaining space box( width: new-width, height: available-height, scale(x: ratio, y: ratio, origin: top + left, boxed-content), ) }, ) }, ) }, ) } // SIDE BY SIDE #let side-by-side(columns: none, gutter: 1em, ..bodies) = { let bodies = bodies.pos() let columns = if columns == none { (1fr,) * bodies.len() } else { columns } if columns.len() != bodies.len() { panic("number of columns must match number of content arguments") } grid(columns: columns, gutter: gutter, ..bodies) }
https://github.com/khawarizmus/hijri-week-calendar-proposal
https://raw.githubusercontent.com/khawarizmus/hijri-week-calendar-proposal/main/terms.typ
typst
ISC License
#import "@preview/gloss-awe:0.0.5": * #import "@preview/note-me:0.2.1": * #set quote(quotes: false, block: true) #set terms(separator: [: ]) #let gnote(text) = admonition( title: "Note", color: color.green.darken(40%))[#text] // done / Hijri calendar: A lunar calendar widely used in the Muslim world. It is based on the lunar months, with a year of 12 lunar months lasting either 354 or 355 days, making it shorter than the Gregorian calendar. #label("hijri-calendar") / common year: In the #link("hijri-calendar")[Hijri calendar] a calendar year that has 354 calendar days is a common year. In the Gregorian calendar a calendar year that has 365 calendar days is a common year. / leap year: In the #link("hijri-calendar")[Hijri calendar] a calendar year that has 355 calendar days is a leap year. In the Gregorian calendar a calendar year that has 366 calendar days is a leap year. #gnote[It must not be assumed that the final month (month 12) being 30 days represents a leap-year in all Hijri calendars because non-tabular calendars such as Umm Al-Qura calendar can have the extra day needed to make-up a leap year inserted at the end of any of the other 29-day months] // should we introduce an equivalaent rule for hijri? // Note: A leap year is a calendar year whose year number is divisible by four and is not a centennial year, or a centennial year whose year number is divisible by four hundred. / Hijri week calendar: A calendar based on an unbounded series of contiguous calendar weeks that uses the time scale unit of calendar week as its basic unit to represent a calendar year, according to the rule that the first calendar week of a calendar year is the week including the first Tuesday of that year, and that the last one is the week immediately preceding the first calendar week of the next calendar year #label("hijri-week-calendar") #gnote[ Hijri week calendar (HWC) is not equivalent to a Hijri calendar. This rule is based on the principle that a week belongs to the calendar year to which the majority of its calendar days belong. In the HWC, days of the first and last week of a HWC year may belong to the previous and the next Hijri calendar year respectively. ] / calendar date: A particular calendar day represented by its calendar year, its #link("calendar-month")[calendar month] and its #link("calendar-day-of-month")[calendar day of month].@CitekeyTechreport #label("calendar-date") // // FIXME: the reference style doesn't seem to work // link: [ISO 8601-1:2019, Date and time — Representations for information interchange — Part 1: Basic rules (publicly avaialble informative sections)] / ordinal date: A particular calendar day represented by its calendar year and its #link("calendar-day-of-year")[calendar day of year]. #label("ordinal-date") // link: [ISO 8601-1:2019, Date and time — Representations for information interchange — Part 1: Basic rules (publicly avaialble informative sections)] / Hijri week date: A particular Hijri calendar day represented by the Hijri calendar year to which its #link("hijri-calendar-week")[Hijri calendar week], its #link("hijri-calendar-week-of-year")[Hijri calendar week of year], and its #link("hijri-calendar-day-of-week")[Hijri calendar day of week] #label("week-date") belong. // / calendar day: // Shoudl we define this and do we need to touch on the fact in hijri the start of day is on sunset but we use midnite for now / Hijri calendar week of year: An ordinal number of a #link("hijri-calendar-week")[Hijri calendar week] within a #link("hijri-week-calendar")[HWC] year. #label("week-of-year") \ / Hijri calendar day of week: A day amongst the sequence of #link("hijri-week-calendar")[HWC] days, namely: Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday or Friday. #gnote[ Hijri weeks start on Saturday. ] / calendar day of month: An ordinal number of a calendar day within a calendar month. / calendar day of year: An ordinal number of a calendar day within a calendar year. #label("calendar-day-of-year") // link: [ISO 8601-1:2019, Date and time — Representations for information interchange — Part 1: Basic rules (publicly avaialble informative sections)] // ), / Hijri calendar week: A duration of seven calendar days which begins on Saturday and ends on Friday according to the #link("hijri-week-calendar")[Hijri week calendar]. #label("hijri-calendar-week") // / Hijri calendar month: // Shoudl we define a hijri calendar month? / year: In the #link("hijri-calendar")[Hijri calendar], a year has 354 or 355 days. // // add counterpart for hijri // // The duration is 355 days if the corresponding time interval begins February 28 or earlier in a leap year (3.1.1.21) or March 2 or later in a year immediately preceding a leap year. If the interval begins February 29 (on a leap year), or March 1 of a year preceding a leap year, the end date has to be agreed on. Otherwise the duration is 365 days / first week pivot day: The 4th of Muharram. #label("first-week-pivot-day") / last week pivot day: 3rd day before Hijri year end which is either 26 of Dhu al-Hijja or 27 of Dhu al-Hijja #label("last-week-pivot-day") / year-ending-30: A Hijri year that has the last month Dhu al-Hijja with 30 days #label("year-ending-30") / year-ending-29: A Hijri year that has the last month Dhu al-Hijja with 29 days #label("year-ending-29") // - Year-Ending30 : A Hijri Year that has the last month Dhu Al-Hijjah (month 12) with 30 days. // - Year-Ending29 : A Hijri Year that has the last month Dhu Al-Hijjah (month 12) with 29 days. // - First Week Pivot Day : 4th Muarram (4/1). // - Last Week Pivot Day : 3 days before Hijri Year End (26/12 or 27/12). // - Leap Hijri Year : A Hijri Year with 355 days. // - Common Hijri Year : A Hijri Year with 354 days.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/stonewall/0.1.0/README.md
markdown
Apache License 2.0
# Stonewall: colourful, accurate pride flags colour palette for queer gradients You can use the colour palette with _gradients_ for maximum results! For example the code in `example/example.typ` which is ```typ #import "@preview/stonewall:0.1.0": flags #set page(width: 200pt, height: auto, margin: 0pt) #set text(fill: black, size: 12pt) #set text(top-edge: "bounds", bottom-edge: "bounds") #stack( spacing: 3pt, ..flags.map(((name, preset)) => block( width: 100%, height: 20pt, fill: gradient.linear(..preset), align(center + horizon, smallcaps(name)), )) ) ``` gives the following stack of flags as of v0.1.0 ![](flags.png) To use only one flag you only import the one you want
https://github.com/sahasatvik/typst-theorems
https://raw.githubusercontent.com/sahasatvik/typst-theorems/main/manual_template.typ
typst
MIT License
#let project(title: "", authors: (), url: "", body) = { set page(paper: "a4", numbering: "1", number-align: center) set document(author: authors, title: title) set text(font: "Libertinus Serif", lang: "en") set heading(numbering: "1.1.") set par(justify: true) set list(marker: ([•], [--])) show heading: it => pad(bottom: 0.5em, it) show raw.where(block: true): it => pad(left: 4em, it) show link: it => underline(text(fill: blue, it)) align(center)[ #block(text(weight: 700, 1.75em, title)) ] pad( top: 0.5em, bottom: 2em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(center)[ #author \ #link(url) ]), ), ) outline(indent: true) v(2em) body }
https://github.com/EpicEricEE/typst-marge
https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/tests/parameter/offset/test.typ
typst
MIT License
#import "/src/lib.typ": sidenote #set par(justify: true) #set page(width: 8cm, height: auto, margin: (outside: 4cm, rest: 5mm)) #let sidenote = sidenote.with(numbering: "1") #lorem(4) #sidenote(dy: -5pt)[Moved up a tiny bit.] #lorem(12) #sidenote(dy: 5pt)[Moved down a tiny bit.] #lorem(3) #sidenote[Moved down due to overlap.] #lorem(20) #sidenote(dy: -100%)[Moved up by 100%.]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/ibanator/0.1.0/README.md
markdown
Apache License 2.0
# typst-iban-formatter > Validate and format IBAN numbers according to ISO 13616-1. ## Usage ```typ #import "@preview/ibanator:0.1.0": iban #iban("DE89370400440532013000") ``` <img src="./docs/example.png" width=350px> To disable validation, set the `validate` flag to false: ```typ #iban("DE89370400440532013000", validate: false) ```
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/056.%206631327.html.typ
typst
6631327.html 6,631,372 March 2006, rev August 2009A couple days ago I found to my surprise that I'd been granted a patent. It issued in 2003, but no one told me. I wouldn't know about it now except that a few months ago, while visiting Yahoo, I happened to run into a Big Cheese I knew from working there in the late nineties. He brought up something called Revenue Loop, which Viaweb had been working on when they bought us.The idea is basically that you sort search results not in order of textual "relevance" (as search engines did then) nor in order of how much advertisers bid (as Overture did) but in order of the bid times the number of transactions. Ordinarily you'd do this for shopping searches, though in fact one of the features of our scheme is that it automatically detects which searches are shopping searches.If you just order the results in order of bids, you can make the search results useless, because the first results could be dominated by lame sites that had bid the most. But if you order results by bid multiplied by transactions, far from selling out, you're getting a better measure of relevance. What could be a better sign that someone was satisfied with a search result than going to the site and buying something?And, of course, this algorithm automatically maximizes the revenue of the search engine.Everyone is focused on this type of approach now, but few were in 1998. In 1998 it was all about selling banner ads. We didn't know that, so we were pretty excited when we figured out what seemed to us the optimal way of doing shopping searches.When Yahoo was thinking of buying us, we had a meeting with <NAME> in New York. For him, I now realize, this was supposed to be one of those meetings when you check out a company you've pretty much decided to buy, just to make sure they're ok guys. We weren't expected to do more than chat and seem smart and reasonable. He must have been dismayed when I jumped up to the whiteboard and launched into a presentation of our exciting new technology.I was just as dismayed when he didn't seem to care at all about it. At the time I thought, "boy, is this guy poker-faced. We present to him what has to be the optimal way of sorting product search results, and he's not even curious." I didn't realize till much later why he didn't care. In 1998, advertisers were overpaying enormously for ads on web sites. In 1998, if advertisers paid the maximum that traffic was worth to them, Yahoo's revenues would have decreased.Things are different now, of course. Now this sort of thing is all the rage. So when I ran into the Yahoo exec I knew from the old days in the Yahoo cafeteria a few months ago, the first thing he remembered was not (fortunately) all the fights I had with him, but Revenue Loop."Well," I said, "I think we actually applied for a patent on it. I'm not sure what happened to the application after I left.""Really? That would be an important patent."So someone investigated, and sure enough, that patent application had continued in the pipeline for several years after, and finally issued in 2003.The main thing that struck me on reading it, actually, is that lawyers at some point messed up my nice clear writing. Some clever person with a spell checker reduced one section to Zen-like incomprehensibility: Also, common spelling errors will tend to get fixed. For example, if users searching for "compact disc player" end up spending considerable money at sites offering compact disc players, then those pages will have a higher relevance for that search phrase, even though the phrase "compact disc player" is not present on those pages. (That "compat disc player" wasn't a typo, guys.)For the fine prose of the original, see the provisional application of February 1998, back when we were still Viaweb and couldn't afford to pay lawyers to turn every "a lot of" into "considerable."
https://github.com/jassielof/typst-templates
https://raw.githubusercontent.com/jassielof/typst-templates/main/latex-standard/README.md
markdown
MIT License
# LaTeX base classes ported to Typst This repository contains the *Standard Document Classes for LaTeX version 2e\** ported to Typst. Classes ported being: - `article` - `report` - `book`
https://github.com/lucifer1004/leetcode.typ
https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/solutions/s0001.typ
typst
#import "../helpers.typ": * #let two-sum-ref(arr, target) = { let d = (:) let ans = (-1, -1) for (i, num) in arr.enumerate() { if str(target - num) in d { ans = (d.at(str(target - num)), i) break } else { d.insert(str(num), i) } } ans }
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/convex-hull-attempt-2.typ
typst
#let graham_scan(points) = { // Helper function to calculate cross product let cross_product(o, a, b) = { return (a.at(0) - o.at(0)) * (b.at(1) - o.at(1)) - (a.at(1) - o.at(1)) * (b.at(0) - o.at(0)) } // Sort points lexicographically let sorted_points = points.sorted(key: p => (p.at(0), p.at(1))) let n = sorted_points.len() if n <= 3 { return sorted_points } // Build lower hull let lower = () for p in sorted_points { while lower.len() >= 2 and cross_product(lower.at(-2), lower.at(-1), p) <= 0 { lower.pop() } lower.push(p) } // Build upper hull let upper = () for p in sorted_points.rev() { while upper.len() >= 2 and cross_product(upper.at(-2), upper.at(-1), p) <= 0 { upper.pop() } upper.push(p) } // Concatenate hulls lower.pop() upper.pop() return lower + upper } // Example usage with Cetz #import "@preview/cetz:0.1.2" #let points = ( (0, 0), (1, 1), (2, 2), (3, 1), (4, 0), (3, 3), (2, 4), (1, 3), (2, 1), (10, 10) ) #let hull = graham_scan(points) #let offset_point(p1, p2, offset) = { let dx = p2.at(0) - p1.at(0) let dy = p2.at(1) - p1.at(1) let length = calc.sqrt(dx * dx + dy * dy) let ux = -dy / length let uy = dx / length return (p1.at(0) + offset * ux, p1.at(1) + offset * uy) } #cetz.canvas({ // Plot all points for point in points { cetz.draw.circle(point, stroke: none, radius: 3pt, fill: blue) } // Draw convex hull cetz.draw.line(..hull, close: true, stroke: red) for i in range(hull.len()) { let p1 = hull.at(i) let offset = -0.7 let next = calc.rem(i + 1, hull.len()) let p2 = hull.at(next) let offset_p1 = offset_point(p1, p2, offset) let offset_p2 = offset_point(p2, p1, -offset) cetz.draw.line(offset_p1, offset_p2, stroke: (dash: "dashed", paint: black), name: "segment") cetz.draw.circle("segment.start", fill: red) cetz.draw.circle("segment.end", fill: blue) } })
https://github.com/MultisampledNight/flow
https://raw.githubusercontent.com/MultisampledNight/flow/main/src/gfx/stub.typ
typst
MIT License
#import "stub/draw.typ" #let canvas(..args) = none
https://github.com/suspenss/Undergraduate-mathematics
https://raw.githubusercontent.com/suspenss/Undergraduate-mathematics/main/setup/templates.typ
typst
#let project(title: "", authors: (), body, language: "en", outl : []) = { set document(author: authors, title: title) set page(numbering: "1", number-align: center) set heading(numbering: "1.1 ") set text(font: ("Linux Libertine", "Noto Serif CJK SC"), lang: language, size: 11pt ) show math.equation: set text(font: ("New Computer Modern Math", "Linux Libertine", "Noto Serif CJK SC")) show raw: set text(font: "Fira Code", weight: "medium") show heading: set block(above: 1.4em, below: 1em) show heading.where(level: 1): it => { v(1em) align(center)[#it] } show regex("[“”‘’.,。、?!:;(){}[]〔〕〖〗《 》〈 〉「」【】『』─—_·…\u{30FC}]+"): set text(font: "Noto Serif CJK SC") show outline.entry.where( level: 1 ): it => { v(14pt, weak: true) let no_fill_it = {it.body ;h(1fr); it.page} strong(no_fill_it) } page([ #v(6.18em) #align(center)[ #block(text(weight: 700, 1.75em, title)) ] #v(1em) #align(center)[一个短篇 #datetime.today().display("[year] 年 [month] 月 [day] 日") ] #outl ]) // Main body. set terms(tight: true) show link: underline body } // #let parbk() = {text()[#v(0.0em, weak: true)];text()[#h(0em)]}
https://github.com/qujihan/toydb-book
https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter5.typ
typst
#import "../typst-book-template/book.typ": * #let path-prefix = figure-root-path + "src/pics/" = 数据编码<encoding> #include "chapter5/keycode.typ" #include "chapter5/bincode.typ" #include "chapter5/format.typ" #include "chapter5/summary.typ"
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-13430.typ
typst
Apache License 2.0
#let data = ( ("EGYPTIAN HIEROGLYPH VERTICAL JOINER", "Cf", 0), ("EGYPTIAN HIEROGLYPH HORIZONTAL JOINER", "Cf", 0), ("EGYPTIAN HIEROGLYPH INSERT AT TOP START", "Cf", 0), ("EGYPTIAN HIEROGLYPH INSERT AT BOTTOM START", "Cf", 0), ("EGYPTIAN HIEROGLYPH INSERT AT TOP END", "Cf", 0), ("EGYPTIAN HIEROGLYPH INSERT AT BOTTOM END", "Cf", 0), ("EGYPTIAN HIEROGLYPH OVERLAY MIDDLE", "Cf", 0), ("EGYPTIAN HIEROGLYPH BEGIN SEGMENT", "Cf", 0), ("EGYPTIAN HIEROGLYPH END SEGMENT", "Cf", 0), ("EGYPTIAN HIEROGLYPH INSERT AT MIDDLE", "Cf", 0), ("EGYPTIAN HIEROGLYPH INSERT AT TOP", "Cf", 0), ("EGYPTIAN HIEROGLYPH INSERT AT BOTTOM", "Cf", 0), ("EGYPTIAN HIEROGLYPH BEGIN ENCLOSURE", "Cf", 0), ("EGYPTIAN HIEROGLYPH END ENCLOSURE", "Cf", 0), ("EGYPTIAN HIEROGLYPH BEGIN WALLED ENCLOSURE", "Cf", 0), ("EGYPTIAN HIEROGLYPH END WALLED ENCLOSURE", "Cf", 0), ("EGYPTIAN HIEROGLYPH MIRROR HORIZONTALLY", "Mn", 0), ("EGYPTIAN HIEROGLYPH FULL BLANK", "Lo", 0), ("EGYPTIAN HIEROGLYPH HALF BLANK", "Lo", 0), ("EGYPTIAN HIEROGLYPH LOST SIGN", "Lo", 0), ("EGYPTIAN HIEROGLYPH HALF LOST SIGN", "Lo", 0), ("EGYPTIAN HIEROGLYPH TALL LOST SIGN", "Lo", 0), ("EGYPTIAN HIEROGLYPH WIDE LOST SIGN", "Lo", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT TOP START", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT BOTTOM START", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT START", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT TOP END", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT TOP", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT BOTTOM START AND TOP END", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT START AND TOP", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT BOTTOM END", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT TOP START AND BOTTOM END", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT BOTTOM", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT START AND BOTTOM", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT END", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT TOP AND END", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED AT BOTTOM AND END", "Mn", 0), ("EGYPTIAN HIEROGLYPH MODIFIER DAMAGED", "Mn", 0), )
https://github.com/avonmoll/bamdone-rebuttal
https://raw.githubusercontent.com/avonmoll/bamdone-rebuttal/main/README.md
markdown
MIT No Attribution
# bamdone-rebuttal This is a Typst template for a rebuttal/response letter. It allows authors to respond to feedback given by reviewers in a peer-review process on a point-by-point basis. This template is based heavily on the LaTeX template from Zenke Lab (see [here](https://zenkelab.org/resources/latex-rebuttal-response-to-reviewers-template/)). ## Usage You can use this template in the Typst web app by clicking "Start from template" on the dashboard and searching for `bamdone-rebuttal`. Alternatively, you can use the CLI to kick this project off using the command ``` typst init @preview/bamdone-rebuttal ``` Typst will create a new directory with all the files needed to get you started. ## Configuration This template exports the `rebuttal` function with the following named arguments: - `title`: (content), something like "Response Letter" (the default) or "Rebuttal". - `authors`: (content), list of author names the top of the first column in boldface. - `date`: (content), defaults to `datetime.today().display()` - `paper-size`: Defaults to `us-letter`. Specify a [paper size string](https://typst.app/docs/reference/layout/page/#parameters-paper) to change the page format. Specifying this will configure numeric, IEEE-style citations. The function also accepts a single, positional argument for the body of the letter. In addition, the template exports the `configure` function which accepts the following named arguments corresponding to the text color of various pieces of the letter: - `point-color`: defaults to `blue.darken(30%)`, the text color for reviewers' points - `response-color`: defaults to `black`, the text color for the authors' responses - `new-color`: defaults to `green.darken(30%)`, the text color for changes/additions to the manuscript (i.e., within a `quote` block to show what's changed from the initial submission) The template will initialize your package with a sample call to the `rebuttal` function in a show rule. ```typ // Optional color configuration #let (point, response, new) = configure( point-color: blue.darken(30%), response-color: black, new-color: green.darken(30%) ) // Setup the rebuttal #show: rebuttal.with( authors: [First A. Author and Second B. Author], // date: , // paper-size: , ) // Your content goes below We thank the reviewers... ```
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-aspect_06.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Size cannot be relative because we wouldn't know // // relative to which axis. // // Error: 15-18 expected length or auto, found ratio // #square(size: 50%)
https://github.com/catppuccin/typst
https://raw.githubusercontent.com/catppuccin/typst/main/src/flavors/catppuccin-mocha.typ
typst
MIT License
#let mocha = ( name: "Mocha", emoji: "🌿", order: 3, dark: true, light: false, colors: ( rosewater: ( name: "Rosewater", order: 0, hex: "#f5e0dc", rgb: rgb(245, 224, 220), accent: true, ), flamingo: ( name: "Flamingo", order: 1, hex: "#f2cdcd", rgb: rgb(242, 205, 205), accent: true, ), pink: ( name: "Pink", order: 2, hex: "#f5c2e7", rgb: rgb(245, 194, 231), accent: true, ), mauve: ( name: "Mauve", order: 3, hex: "#cba6f7", rgb: rgb(203, 166, 247), accent: true, ), red: ( name: "Red", order: 4, hex: "#f38ba8", rgb: rgb(243, 139, 168), accent: true, ), maroon: ( name: "Maroon", order: 5, hex: "#eba0ac", rgb: rgb(235, 160, 172), accent: true, ), peach: ( name: "Peach", order: 6, hex: "#fab387", rgb: rgb(250, 179, 135), accent: true, ), yellow: ( name: "Yellow", order: 7, hex: "#f9e2af", rgb: rgb(249, 226, 175), accent: true, ), green: ( name: "Green", order: 8, hex: "#a6e3a1", rgb: rgb(166, 227, 161), accent: true, ), teal: ( name: "Teal", order: 9, hex: "#94e2d5", rgb: rgb(148, 226, 213), accent: true, ), sky: ( name: "Sky", order: 10, hex: "#89dceb", rgb: rgb(137, 220, 235), accent: true, ), sapphire: ( name: "Sapphire", order: 11, hex: "#74c7ec", rgb: rgb(116, 199, 236), accent: true, ), blue: ( name: "Blue", order: 12, hex: "#89b4fa", rgb: rgb(137, 180, 250), accent: true, ), lavender: ( name: "Lavender", order: 13, hex: "#b4befe", rgb: rgb(180, 190, 254), accent: true, ), text: ( name: "Text", order: 14, hex: "#cdd6f4", rgb: rgb(205, 214, 244), accent: false, ), subtext1: ( name: "Subtext 1", order: 15, hex: "#bac2de", rgb: rgb(186, 194, 222), accent: false, ), subtext0: ( name: "Subtext 0", order: 16, hex: "#a6adc8", rgb: rgb(166, 173, 200), accent: false, ), overlay2: ( name: "Overlay 2", order: 17, hex: "#9399b2", rgb: rgb(147, 153, 178), accent: false, ), overlay1: ( name: "Overlay 1", order: 18, hex: "#7f849c", rgb: rgb(127, 132, 156), accent: false, ), overlay0: ( name: "Overlay 0", order: 19, hex: "#6c7086", rgb: rgb(108, 112, 134), accent: false, ), surface2: ( name: "Surface 2", order: 20, hex: "#585b70", rgb: rgb(88, 91, 112), accent: false, ), surface1: ( name: "Surface 1", order: 21, hex: "#45475a", rgb: rgb(69, 71, 90), accent: false, ), surface0: ( name: "Surface 0", order: 22, hex: "#313244", rgb: rgb(49, 50, 68), accent: false, ), base: ( name: "Base", order: 23, hex: "#1e1e2e", rgb: rgb(30, 30, 46), accent: false, ), mantle: ( name: "Mantle", order: 24, hex: "#181825", rgb: rgb(24, 24, 37), accent: false, ), crust: ( name: "Crust", order: 25, hex: "#11111b", rgb: rgb(17, 17, 27), accent: false, ), ), )
https://github.com/kicre/note
https://raw.githubusercontent.com/kicre/note/main/study/毕设/5-19.typ
typst
#import "../../tem/beamer.typ": beamer #show: beamer.with( title: "基于 SAM 大模型的肝脏肿瘤分割软件开发", subtitle: "5-23 答辩", author: "答辩人:王恺 指导老师:刘琨", date: "质量技术监督学院 2020级测控普通班 2024-05-22", ) = 绪论 <绪论> == 研究的背景及意义 <研究的背景及意义> //肝脏肿瘤是全球范围内导致死亡的主要原因之一,计算机断层扫描(CT)是检测和评估肝脏肿瘤的重要影像学方法。为了提高诊断效率和准确性,自动化的图像分割技术应运而生。近年来,深度学习技术在医学图像分割领域取得了显著进展。然而,深度学习方法依赖于大量标注数据进行训练,而医学影像数据的标注成本高昂,需要专业的医学人员参与。 近年来,深度学习在图像处理和计算机视觉领域取得了显著进展,其在医学图像分割任务中展现出了巨大潜力。众多深度学习模型,在该领域取得了优异的结果。这些研究不仅提高了分割的准确性,而且大大缩短了处理时间。 Meta 提出的 Segment Anything Model(SAM),作为一种基于深度学习的全新模型架构,已在多个自然图像处理基准上显示出优异的性能。SAM 的引入为医学图像,特别是复杂的肝脏肿瘤分割任务,提供了新的可能性。 SAM 模型是 Meta AI 提出的一个基于 Transformer 的深度学习模型,它是在超过一亿张图像和相应标记的基础之上训练得来,用于执行零样本学习(Zero-shot Learning)中的图像分割任务,它能够通过接收简单的标注提示(如点、框等),自动产生精确的图像分割,这在处理医学图像中的不同器官和病变(如肝脏肿瘤)时,表现出独特的优势。使用 SAM 模型应用与医学图像处理具有以下优势: - 泛化能力强:SAM通过在大量图像上进行预训练,学习了丰富的视觉特征表示,具备强大的泛化能力,能够应对多样的图像分割任务。 - 少样本学习:在具有少量标注数据的情况下,SAM 仍然能表现出良好的分割效果,这对于医学影像分析尤其重要,因为高质量的医学标注数据往往难以获得。 - 自适应性强:作为一种自适应的模型,SAM 能够根据不同的输入图像和分割任务调整其行为,这使得它在面对肝脏肿瘤这种形态多样、边界模糊的目标时,表现出比传统方法更好的分割精度。 // 在医学图像分析领域,特别是肝脏肿瘤的精确分割中,选择合适的图像分割算法对于提高诊断准确性和疾病管理至关重要。基于SAM大模型的肝脏肿瘤分割软件开发具有重要的临床意义和广阔的应用前景。通过利用SAM模型的高泛化能力和出色的图像处理性能,可以极大地提升肝脏肿瘤的诊断精度,助力医生更有效地制定治疗计划,最终提高患者的生存率。开发此类高效的肝脏肿瘤分割软件不仅能推动医学影像分析技术的进步,也将为全球癌症治疗带来积极的影响。 == 国内外研究现状 - 基于传统方法的分割 - 阈值法 - 主动轮廓法 - 区域生长法。 传统的分割方法噪声敏感,特征选择和提取过程复杂且依赖经验,难以确保正确分割。 - 基于深度学习的分割 - U-Net 及其变种 - 基于卷积对抗神经网络(CNN)的分割方法 - 基于 Transformer 的方法(如SAM) 基于传统深度学习模型的分割方法对数据量需求大,所需数据的标注成本高,尤其是肿瘤分割等任务。泛化能力弱,模型在一个数据集上表现良好,但在其他数据集上性能可能显著下降。 //**CNN**是深度学习技术中最早应用于医学图像分割的算法之一,它通过层叠的卷积层来提取图像特征,已成功应用于多种医学图像处理任务。然而,尽管CNN在特征提取方面表现出色,但其对训练数据的依赖性较大,需要大量精确标注的数据,这在医学领域往往是一个限制因素。此外,CNN模型的泛化能力受限于训练数据的多样性和质量。对数据的训练数据的大量需求增加了其训练开发难度,为该方面的实际应用增加了成本。 //**U-Net**是为医学图像分割特别设计的网络结构,它通过特有的跳跃连接和上采样策略,有效地保留了图像的细节信息,适合于处理样本量较少的医学图像数据。U-Net 及其变种神经网络模型在肝脏肿瘤等复杂结构的分割任务中表现出良好的性能。然而,U-Net 对图像中的噪声和伪影比较敏感,这可能影响其在实际临床应用中的分割准确性。 //近期,基于 Transformer 的 Segment Anything Model(SAM)展示了其在图像分割任务中的卓越潜力。不同于传统的 CNN 和 U-Net,SAM 采用 Transformer 架构处理图像中的长距离依赖,能够捕获更加丰富的上下文信息。SAM的一个显著优势是其零样本学习能力,即在未见过的新图像上,仅通过少量的提示(如点或框)就能实现准确的分割。这一优势特性在处理多变的医学图像,尤其是肝脏肿瘤图像时显得尤为重要,因为这些图像常常包含不规则的肿瘤边界和复杂的背景结构。 //总体来说,虽然多种方法各有优势,SAM 方法由于其强大的零样本学习能力和优异的上下文捕获能力,展现了在医学图像,特别是在肝脏肿瘤分割方面的独特优势。 //////由于过去分割方法的种种缺陷,我们使用了 SAM 大模型进行肝脏肿瘤分割任务的开发,这也是本研究主要的创新点。 == 研究内创新点 <研究内容及创新点> 本文的创新之处在于使用了大型自监督学习模型 SAM 开发肝脏肿瘤分割软件,该研究方法的优势体现在以下几个方面: + 提高肝脏肿瘤分割的准确性和灵活性:利用SAM模型的强大特征提取能力,可以更准确地识别和分割肝脏中的肿瘤组织,特别是在肿瘤边界模糊或与周围组织对比度低的情况下。 + 减少对标注数据的依赖:由于SAM模型基于自监督学习,在训练过程中不完全依赖标注数据,通过利用自监督学习,该软件能够利用未标注的医学图像进一步提升模型的性能和泛化能力。 + 提升分割速度,支持实时应用:针对 SAM 模型的实现进行了微调优化,使得肝脏肿瘤分割软件能够快速处理图像,满足临床环境中对实时或近实时分析的需求。 = 理论技术基础 <技术原理学习> == 肝脏肿瘤 CT 图像 <肝脏肿瘤-ct-图像> 计算机断层扫描(Computed Tomography,CT)技术是一种先进的医学成像技术,通过利用X射线和计算机技术生成身体内部详细的横断面图像。//CT扫描利用旋转的X射线管和对面的探测器阵列从不同角度获取人体的X射线数据。这些数据被计算机处理,重建出二维切片图像。这些切片图像可以通过计算机系统堆叠组合成三维图像,从而提供详细的内部结构视图以供放射科医生查看图像,以识别疾病或异常。生成的报告发送给主治医生,以便进行进一步治疗决策。 #figure(image("腹部.png", width: 13cm), caption: [ 腹部 CT 图像,左上三图为腹部CT图像 MPR 预览,右下为 3D 合成图像预览 ] ) CT 图像的优点有以下几点: + #strong[高分辨率];:能够清晰显示细微结构和病变。 + #strong[快速成像];:现代CT扫描仪能够在几秒钟内完成扫描,适合紧急情况。 + #strong[多平面成像];:能够生成横断面、冠状面和矢状面图像,提供多角度视图。 + #strong[三维重建];:通过多个切片图像的组合,生成精确的三维图像。 //////CT扫描技术在头部和脑部成像、胸部成像、腹部和盆腔成像、骨骼和关节成像、血管成像等医学领域具有广泛应用,用于评估各类肿瘤等多种身体疾病异常如肝脏肿瘤的治疗。 //肝脏肿瘤的分割是医学图像处理中一项具有挑战的任务,CT 图像分割作为一种非侵入性的诊断方法,可以帮助医生更准确地确定肝脏肿瘤的位置、形状和大小,为后续治疗提供重要的参考依据, 但肝脏肿瘤的分割面临以下难点: + #strong[肿瘤形态多样性] //肝脏肿瘤的形态、大小和位置具有高度多样性,导致图像中肿瘤区域的外观各异。肿瘤可能是单个的,也可能是多发的,其形状可以是规则的,也可以是非常不规则的。这种多样性增加了分割的难度。 + #strong[图像噪声和伪影] CT //图像中常常存在噪声和伪影,这些干扰信息会影响图像的清晰度和对比度,进而影响肿瘤区域的准确识别和分割。特别是在低剂量 CT 扫描中,噪声问题更加突出。 + #strong[肝脏结构复杂] //肝脏内部结构复杂,包含血管、胆管等多种解剖结构,这些结构在 CT 图像中可能与肿瘤区域混淆,增加了分割的难度。此外,肝脏边界与周围器官(如胃、肠、肾)接近,界限模糊,进一步增加了分割任务的复杂性。 + #strong[肿瘤与正常组织对比度低] //肿瘤与正常肝脏组织的密度对比度往往较低,特别是一些小肝癌或早期肝癌,难以在 CT 图像中明显区分。这种低对比度使得自动化分割算法难以准确区分肿瘤和正常组织。 + #strong[患者间差异] //不同患者的肝脏形态和肿瘤特征存在显著差异,这种个体差异增加了图像分割算法的泛化难度。一种分割方法可能在某些患者图像上表现良好,但在另一些患者图像上效果不佳。 + #strong[数据标注困难] //高质量的肝脏肿瘤分割需要大量准确的标注数据,这些标注通常由放射科医生手动完成,耗时费力且容易受主观影响。这限制了训练和验证分割算法所需的数据量和质量。 //如上所述,对 CT 图像中的肝脏肿瘤进行分割困难极大,人类极难分辨如图 2.2的微小肿瘤图像,这些肿瘤几乎肉眼不可见。因此,使用 SAM大模型的肝脏肿瘤分割方法具有重要意义。 //#align(right)[ // #figure( // image("肝脏肿瘤示意.png", width: 10cm), // caption: [ // 肝脏肿瘤 CT 图像示意,从左到右依次为原 CT // 图像,肝脏标注,肿瘤标注。 // ] // ) //] == 深度学习基本原理 <深度学习基本原理> 深度学习是机器学习的一个分支,基于多层神经网络模拟人脑处理数据的方式。它涵盖从输入层接收数据,通过多个隐藏层处理,到输出层产生结果的过程。//每个神经元根据权重和偏差处理输入,并通过激活函数引入非线性,使得模型能处理复杂任务。训练神经网络涉及使用损失函数评估预测误差,并通过反向传播和梯度下降等优化算法调整网络参数,以减少误差。此外,为避免过拟合,常用正则化技术如舍弃法(Dropout)。深度学习在图像识别、语音处理等领域展示出显著的应用潜力,通过适当的网络设计和算法优化,可以有效从大量数据中学习复杂的规律。深度学习模型能够从大量数据中自动学习到复杂的特征表示,这一点在图像识别、语音识别等任务中尤为显著。 === Pytorch框架 <pytorch框架> PyTorch 是一个开源的机器学习库,广泛用于计算机视觉和自然语言处理等领域。//它由Facebook的人工智能研究团队开发,并得到了包括微软、Salesforce等多家大公司的支持和贡献。PyTorch是一种强大的深度学习框架,适合从学术研究到商业应用的广泛用途。它的灵活性、用户友好的设计以及强大的社区支持使其成为当前最受欢迎的深度学习框架之一。 //- PyTorch 以其动态计算图(Dynamic Computation // Graphs),即“define-by-run”方法论而闻名。这种方式让每一次的网络操作都可以动态//地改变计算图,提供了极高的灵活性和直观操作方式,使得模型设计和调试更为简单直//接。 //- PyTorch // 提供了丰富的API,这些API设计直观并易于理解,极大地简化了深度学习模型的开发过//程。它支持大量的预定义层,如全连接层、卷积层、池化层等,以及多种损失函数和优//化器,这使得构建复杂的神经网络变得更加容易。 //- PyTorch // 拥有一个活跃的社区,提供大量的教程、工具和预训练模型,这些资源可以帮助用户快//速开始项目并解决遇到的问题。此外,PyTorch // 与许多研究项目和商业应用相结合,形成了一个强大的生态系统。 //- 由于其灵活性和简便性,PyTorch // 在学术界特别受欢迎,成为许多最新研究论文的首选框架。它支持快速实验的特点,使//研究人员能够验证新想法并迅速实现原型。 //- PyTorch 不仅易于使用,而且在性能方面也非常优秀。它可以无缝地运行在 CPU // 和GPU 上,通过优化的C++库支持高效的内存使用和计算速度。 //- PyTorch // 提供了与其他重要科学计算库的接口,如NumPy和SciPy,以及可视化工具如//TensorBoard。此外,它还支持ONNX(Open // Neural Network // Exchange)格式,这使得在不同框架之间转换模型变得更加容易。 本文研究将使用 PyTorch 框架微调 SMA 模型。//在Python环境下,利用Pytorch库构建SAM大模型的基础框架。 === Transformer <transformer> Transformer是一种基于自注意力机制的神经网络架构,最初由Vaswani等人在2017年的论文《Attention Is All You Need》中提出。Transformer模型在自然语言处理(NLP)任务中取得了巨大成功,并被广泛应用于其他领域如计算机视觉(例如VIT, vision Transformer)。 ==== Transformer模型的组成 <transformer模型的组成> #figure(image("./Transformer结构图.png",width: 10cm), caption: [ 图 2.3 Transformer 结构图 ] ) //如图,Transformer模型主要由编码器(Encoder)和解码器(Decoder)两部分组成,每部分由多个相同的层(layers)堆叠而成。每个层主要包含两个子层(sublayers): //==== 1. 编码器(Encoder) //<编码器encoder> //每个编码器层包含以下两个子层: - 自注意力层(Self-Attention Layer)];:计算输入序列中每个位置的注意力分数,捕捉输入序列中的全局依赖关系。\- #strong[前馈神经网络(Feed-Forward Neural Network,FFN)];:对每个位置的输入进行独立的非线性变换。 //每个编码器层的输出会通过残差连接(residual connection)和层归一化(layer normalization)后,传递给下一层。 //==== 2. 解码器(Decoder) //<解码器decoder> //每个解码器层包含三个子层: - #strong[自注意力层(Self-Attention Layer)];:与编码器相同,但只对解码器输入的前缀部分计算注意力分数。 -#strong[编码器-解码器注意力层(Encoder-Decoder Attention Layer)];:将解码器的输入与编码器的输出结合,计算注意力分数,捕捉输入与输出之间的依赖关系。 \- #strong[前馈神经网络(Feed-Forward Neural Network, FFN)]:与编码器相同,对每个位置的输入进行独立的非线性变换。 //同样,每个解码器层的输出也会通过残差连接和层归一化后,传递给下一层。 == (Vision Transformer,VIT) //<vision-transformervit> VIT 模型是 Transformer 模型在 CV 领域的应用,用于把图像映射到特征空间,具体结构如图所示。//将图片输入图像编码器后,首先使用卷积分块缩小尺寸,之后借助 Flatten 函数将分块的图像转换成向量,并与位置信息(position embedding)相加,相加结果经过 Transformer Encoder 处理生成特征图,最后再通过两层卷积对特征图进行降维,得到图像嵌入(Image Bedding)。位置信息是初始为 0 的参数矩阵,用于后续位置更新。SAM模型图像编码器使用了掩码自编码器(masked autoencoders,MAE)方法预训练的 VIT(Vision Transformer)模型。MAE 是一种自监督学习方法,能够将输入的图片分块,并随机进行遮盖,之后借助编码器和解码器重构这些被遮盖的像素。 #figure(image("VIT结构图.png",width: 12cm), caption: [ VIT 结构图 ] ) //=== 自注意力机制(Self-Attention Mechanism) //<自注意力机制self-attention-mechanism> //自注意力机制是Transformer的核心组件,它允许模型在计算每个位置的表示时,考虑整个序列中的其他位置。其工作原理如下: //+ #strong[输入变换];: // - 将输入序列(例如词嵌入)变换为查询(query)、键(key)和值(value)向量: // $ Q = X W_Q , quad K = X W_K , quad V = X W_V $ 其中,$W_Q$, // $W_K$, $W_V$ 是学习到的权重矩阵。 //+ #strong[计算注意力分数];: // - 计算查询与键的点积,并进行缩放和软最大化(softmax),得到注意力分数: // $ upright("Attention") (Q , K , V) = upright("softmax") (frac(Q K^T, sqrt(d_k))) V $ // 其中,$d_k$ 是键向量的维度。 //+ #strong[加权求和];: // - 使用注意力分数对值向量进行加权求和,得到每个位置的新表示。 //=== 多头注意力机制(Multi-Head Attention) //<多头注意力机制multi-head-attention> //为了捕捉不同子空间的信息,Transformer使用了多头注意力机制。具体做法是将查询、键、值向量分成多个头,每个头独立计算注意力,然后将结果拼接在一起,并通过线性变换得到最终的输出: //$ upright("MultiHead") ( Q , K , V ) = upright("Concat") ( upright("head")_1 , dots.h , upright("head")_h ) W_O $ //其中,$upright("head")_i = upright("Attention") ( Q W_(Q_i) , K W_(K_i) , V W_(V_i) )$。 //=== 位置编码(Positional Encoding) //<位置编码positional-encoding> //由于Transformer没有卷积或递归结构,它无法直接捕捉输入序列的位置信息。为此,Transformer在输入中添加了位置编码,提供位置信息。位置编码可以是固定的,也可以是可学习的,其形式通常为: //$ upright("PE")_((p o s , 2 i)) = sin (\) frac(p o s, 10000^(2 i \/ d))) quad upright("PE")_((p o s , 2 i + 1)) = cos (\) frac(p o s, 10000^(2 i \/ d))) $ //其中,$p o s$ 是位置,$i$ 是维度索引。 //=== 总结 //<总结> //Transformer通过自注意力机制和前馈神经网络,在自然语言处理和其他领域中实现了卓越的性能。其核心优势在于能够捕捉全局依赖关系,易于并行计算,并且具有良好的扩展性。自推出以来,Transformer模型已经衍生出许多变种和改进版本,并在许多任务中取得了显著成果。 == 分割大模型(SAM大模型) <分割大模型sam大模型> //本文主要研究通过对 SAM 大模型的微调训练,以适应在医学图像处理,尤其是对腹部 CT 扫描图像的肝脏肿瘤分割。 //=== 背景 <背景> SAM(Segment Anything Model)是近年来出现的一种新型深度学习模型,由 Meta 的 FAIR 实验室提出,旨在通过单一的模型实现对任何对象的高精度分割//。SAM大模型通过大规模数据的预训练和针对特定任务的微调,实现了对不同对象类型的准确识别和分割。 //SAM模型的强大之处在于它借鉴了自然语言处理领域的 Foundation Model。Foundation Model 在预训练阶段学习了大量的语言知识,从而能够在各种语言任务中表现出色。同样地,SAM模型在预训练阶段学习了大量的视觉知识,使其能够适应各种下游图像分割任务。 //////SAM 模型的核心思想是使用提示学习来适应不同的分割问题。提示学习是一种通过给模型提供一些指导信息来帮助其完成任务的方法。在SAM模型中,设计了一种可提示的分割任务,使模型可以根据不同的任务需求进行微调。这种可提示的特性使得SAM模型能够轻松地适应各种复杂的分割问题,例如语义分割、实例分割等。 //为了实现强大的零样本学习能力,SAM模型在预训练阶段使用了大规模的数据集进行训练。通过在大量图像数据上的学习,模型能够提取出通用的视觉特征,从而在面对新的、未见过的图像时,能够快速地进行有效地分割。这种零样本学习能力使得SAM模型在处理新场景、新任务时具有很大的优势,例如将其微调,用于肝脏肿瘤分割软件的开发。 //在网络数据集上预训练的大语言模型具有强大的 zero-shot(零样本)和 few-shot(少样本)的泛化能力,这些“基础模型”可以推广到超出训练过程中的任务和数据分布,这种能力通过“prompt engineering”实现,具体就是输入提示语得到有效的文本输出,使用网络上的大量文本资料库进行缩放和训练后,可以看出这种零样本和少样本的训练的模型比专一性质功能模型效果还要好。数据集越大,效果越明显。 //视觉任务方面也对这种基础模型进行了探索,比如CLIP和ALIGN利用对比学习,将文本和图像编码进行了对齐,通过提示语生成 image encoder,就可以扩展到下游任务,比如生成图像。 SAM通常在自然图像上表现优异,但是在特定领域如医疗影响,遥感图像等,由于训练数据集缺乏这些数据,SAM 的效果并不是理想。因此,在特定数据集上微调 SAM 是十分有必要的。 //=== SAM 模型结构 <sam-模型结构> //如图所示SAM模型结构主要包括以下几个部分: //+ 图像编码器(Image Encoder): //- 接收输入图像并提取图像特征。 //- 通常使用预训练的视觉模型,如 VIT(vision Transformer)。 //#block[ //#set enum(numbering: "1.", start: 2) //+ 提示编码器(Prompt Encoder): //] // //- 处理用户提供的提示信息(如点、框、文本等)。 //- 提取提示信息的特征表示。 // //#block[ //#set enum(numbering: "1.", start: 3) //+ 掩码解码器(Mask Decoder): //] // //- 将图像特征和提示特征进行融合。 //- 生成分割掩码。 // //#block[ //#set enum(numbering: "1.", start: 4) //+ 特征融合与加权(Feature Fusion and Weighting): //] // //- 通过逐元素相乘(element-wise multiplication)对图像特征进行加权。 //- 利用提示特征对图像特征进行调整,提升分割精度。 // //#block[ //#set enum(numbering: "1.", start: 5) //+ 最终输出: //] // //- 生成图像的分割掩码。 #figure(image("SAM结构图.png"), caption: [ 图 2.5 SAM 模型的结构 ] ) ==== SAM 模型运行步骤 <sam-模型运行步骤> - 输入图像(Image):模型接收一幅输入图像。 - 图像编码器(Image Encoder):输入图像经过图像编码器(通常是VIT),提取出高维度的图像特征。 - 提示编码器(Prompt Encoder):用户提供的提示信息(如标记点、框等)经过提示编码器,提取出提示特征。 - 特征融合与加权(Feature Fusion and Weighting):图像特征和提示特征进行融合。具体操作是通过逐元素相乘(element-wise multiplication),使提示特征对图像特征进行加权。 - 掩码解码器(Mask Decoder):融合后的特征通过掩码解码器,生成图像的分割掩码。 - 最终输出(Final Output):输出最终的分割掩码,表示图像中的分割区域。 //==== 图像编码器(Image Encoder) <图像编码器image-encoder> //利用 meta 预训练的 VIT,最低限度适应高分辨率的输入,该编码器在提示编码器(prompt encoder)之前,对每张图像只运行一次。 //输入(c,h,w)的图像,对图像进行缩放,按照长边缩放成1024,短边不够就pad,得到(c,1024,1024)的图像,经过图像编码器(image encoder)处理,得到对图像16倍下采样的特征(feature),大小为(256,64,64)。 //==== 提示编码器(Prompt Encoder) <提示编码器prompt-encoder> //提示编码器分成2类:稀疏的(点,box,文本),稠密的(mask)。 //- 点(point):映射到256维的向量,包含代表点位置的位置编码(positional encoding),加 2 个代表该点是前景/背景的可学习的嵌入(embedding)。 //- 框(box):用一个嵌入对表示(1)可学习的嵌入代表左上角(2)可学习的嵌入代表右下角 //- 文本:通过CLIP模型进行文本编码。 //- 掩码(mask):说用掩码的特征对图像的特征进行加权使特定区域被放大或抑制。 //用输入图像 $1 / 4$ 分辨率的掩码,然后用 (2,2)卷积核步长为 2,输出通道数为4和16,再用 (1,1)卷积核将通道数量升到256。掩码和图像嵌入(iamge embedding)通过逐元素相乘(element-wise),也就是 //== 本章小结 //<本章小结-1> //本章探讨讲述了计算机断层图像扫描扫描(Computed Tomography,CT)、深度学习的基本原理、PyTorch 框架的特点,以及 Transformer 和 SAM(Segment Anything Model)模型的结构与机制。深度学习通过多层神经网络模拟人脑处理数据的方式,从输入层接收数据,经隐藏层处理后,在输出层产生结果。其关键在于使用损失函数评估预测误差,并通过反向传播和梯度下降等优化算法调整网络参数,以减少误差。PyTorch 是一个开源的机器学习库,以动态计算图和易用的 API 著称,广泛应用于计算机视觉和自然语言处理领域。Transformer 是一种基于自注意力机制的神经网络架构,通过编码器和解码器捕捉输入序列的全局依赖关系,易于并行计算且具有良好的扩展性。SAM 模型由 Meta 的 FAIR 实验室提出,旨在通过单一模型实现高精度分割。它通过大规模数据预训练和提示学习,适应各种下游图像分割任务。其结构包括图像编码器、提示编码器、特征融合与加权、掩码解码器和最终输出部分,通过对图像特征和提示特征的融合与加权,生成高精度分割掩码。这些技术和模型展示了深度学习在图像处理领域的强大性能和应用前景,为后续研究奠定了基础。 = 实验研究 <实验研究> == 数据集处理 <准备数据集> 数据集共包括 20 个病例的 CT 图像,每个图像都附有肝脏肿瘤的标注(如表1),便于对数据集的训练与测试。//对数据集进行随机分组,80% 作为训练集,10% 作为验证集,10% 作为测试集。在腹部 CT 图像中,肝脏和相邻的组织器官呈现紧贴的状态,并且它们之间的边界不清晰以及对比度较低,所以 CT 图像在输入到模型之前需要对其进行一些处理,减少无关噪声的干扰,增强图像的对比度。 //除上述处理操作外,数据集还进行了旋转、平移以及缩放,以此提升模型的泛化能力和鲁棒性,避免过拟合情况的发生。 #figure( align(center)[#table( columns: (24.14%, 70.69%, 5.17%), align: (auto,auto,auto,), table.header([文件名], [文件内容], [],), table.hline(), [PATIENT\_DICOM], [DICOM 格式的匿名患者图像], [], [LABELLED\_DICOM], [DICOM 格式分割的各个感兴趣区域对应的标签图像], [], [MASKS\_DICOM], [包含每个 mask 的 DICOM 图像的各个感兴趣区域的名称对应的一组新子文件夹], [], )], caption: [ 数据集内容 ] , kind: table ) 读取数据集并进行数据分割和图像预处理,CT值转换、窗口化、直方图均衡化、归一化、定义增强参数。模型训练和工作过程中的数据存储。 //读取数据:从原始的 DICOM //格式文件中读取数据,并转换成数组格式以便于处理。 // //数据预处理 // //- CT值转换:将CT图像的原始值转换为 Hounsfield Units // (HU),以标准化不同设备和协议下的图像数据。 //- 窗口化:应用窗口化技术以增强图像中特定组织或结构的可视化。 //- 直方图均衡化:使用CLAHE方法改善图像的对比度,特别是对于医学图像中经常存在的低对比度区域。 //- 归一化];:将图像数据缩放到$[0,1]$区间,以便于网络处理。 //- 目标区域提取:只保留包含肝脏的腹部切片,排除其他不相关的图像。 // //数据增强 // //- 定义增强参数:设置旋转、平移、剪切和缩放等增强操作的参数。 //- 应用数据增强:对图像和掩码(mask)应用相同的变换,以增加数据集的多样性并提高模型的泛化能力。 // //数据存储 // //- HDF5格式:将处理后的数据存储为 HDF5 格式,以减少 I/O 操作并方便数据共享。 //- 自定义类:使用 HDF5DatasetWriter 和 HDF5DatasetGenerator 类来管理数据的读写操作。 //////使用HDF5格式存储图像,pythong库处理。 == 模型架构调整 //<模型架构调整> 加载 meta 预训练的 SAM 模型作为基础模型。//加载预训练模型的权重,并设置为微调模式。为了保留预训练模型中已经学习到的有用特征,通常会冻结模型的输入层,只微调模型的顶部层。这可以通过设置模型中某些层的参数不可训练为“True”来实现。冻结输入层可以防止在训练过程中更新这些层的权重,从而保留原始模型的特征表示。只微调顶部层有助于模型适应新任务的特定需求,同时减少训练时间和计算资源。 自定义Prompt Encoder:为了更好地适应肝脏CT图像特征,设计或调整Prompt Encoder部分,增加对解剖结构敏感的特征提取层。 微调 Mask Decoder:在 Mask Decoder 部分,保持原有Transformer架构的基础上,微调最后几层的权重,使其对肝脏和肿瘤边缘更加敏感。 多尺度特征融合:引入多尺度特征融合策略,如U-Net结构中的跳跃连接,结合不同层级的特征来提高分割精度。 //多尺度特征融合策略(Multi-Scale Feature Fusion)是一种在深度学习模型中处理和整合不同尺度的特征,以增强模型对多样性和复杂性数据的适应能力的技术。特别是在图像分割任务中,多尺度特征融合可以帮助模型更好地捕捉细节和全局信息,从而提高分割精度和鲁棒性。 //为什么需要多尺度特征融合? //在图像分割任务中,不同尺度的特征包含不同层次的信息: // 低层次特征:通常包含边缘、纹理等局部信息,有助于捕捉细节。 // 高层次特征:包含语义信息,有助于理解图像的整体结构和上下文关系。 //通过融合不同尺度的特征,可以让模型同时利用这些信息,达到更好的分割效果。多尺度特征融合策略的具体实现 //特征金字塔网络(Feature Pyramid Network, FPN): //FPN 是一种经典的多尺度特征融合方法,通常用于目标检测和图像分割任务。它通过自底向上的特征提取和自顶向下的特征融合,构建了一系列不同尺度的特征图。 //在 FPN 中,每一层的特征图不仅包含该层的特征,还融合了来自更高层次(更细尺度)特征图的信息。 == 训练策略 <训练策略> 迁移学习: 从预训练的SAM模型开始,冻结部分或全部编码器层,仅微调解码器层和可能新增的自定义层。 学习率调度:使用余弦退火学习率调度(Cosine Annealing),初始学习率设为$1^(- 4)$,随着训练进行逐渐降低。 //- 学习率在训练过程中按照余弦函数变化,使得学习率在训练初期较高,逐渐减小到最小值,然后再次升高。 - 公式:$ upright("lr")_t = upright("lr")_min + 1 / 2 ( upright("lr")_0 - upright("lr")_min ) ( 1 + cos ( T_(upright("cur")) / T_(upright("max")) pi ) ) $ //其中,$t e x t l r_t$为第$t$个训练周期(epoch)的学习率,$upright("lr")_0$为初始学习率,$upright("lr")_min$为最小学习率,$T_(upright("cur"))$为当前训练周期(epoch),$T_(upright("max"))$为总的训练周期(epoch)数。 //混合精度训练: 利用混合精度训练加速训练过程并节省 GPU 内存,例如使用 NVIDIA 的 Apex 库。 //数据增强: 实施旋转、翻转、缩放、剪切、亮度变化等数据增强操作,并利用 Rand Augment 等自动化增强策略增加多样性。 使用训练数据集进行迭代训练。在训练过程中,需要监控模型的性能指标如训练损失和验证损失。为了确保模型的泛化能力,可以在每个训练周期结束后使用验证集进行评估。通过细致地微调,提升模型对肝脏肿瘤图像特点的学习能力和分割准确性。 === 损失函数设计 <损失函数设计> Dice Loss + BCE Loss: 使用结合了Dice Loss和二元交叉熵损失(BCE)的复合损失函数,Dice Loss关注区域的重叠程度,BCE则强调分类的准确性。 加权损失: 对肿瘤区域施加更高的权重,因为肿瘤区域相对于正常肝脏组织更为关键,且数量较少,这样可以平衡类别不均衡问题。 ==== Dice 系数 <dice-系数> #strong[定义];:Dice 系数(也称为 Dice 相似系数)是一种用于衡量两个样本集合相似度的统计指标,尤其适用于评估图像分割的精度。 $ upright("Dice") = frac(2 T P, 2 T P + F P + F N) = frac(2 lr(|A sect B|), lr(|A|) + lr(|B|)) $ //- $T P$ (True Positive):真正例数,即正确预测为正类的像素数。 //- $T N$(True Negative):真负例数,即正确预测为负类的像素数。 //- $F P$(False Positive):假正例数,即错误预测为正类的像素数。 //- $F N$(False Negative):假负例数,即错误预测为负类的像素数。 //- $A$ 为预测的二值掩码。 //- $B$ 为真实的二值掩码。 //- $lr(|A sect B|)$ 为预测与真实掩码的交集像素数。 // //#strong[优点];:Dice 系数在处理类别不平衡的数据集时表现优异。它在较小的目标(如肿瘤)分割中,能够更好地反映模型的实际性能。 //#strong[缺点];:Dice 系数相对复杂,计算需要同时考虑预测结果与真实标签,尤其在处理多类别分割任务时,需要分别计算每个类别的 Dice 系数,再求平均值。 ==== 二值交叉熵损失(BCE Loss) <二值交叉熵损失bce-loss> //二值交叉熵损失(Binary Cross-Entropy Loss)用于二分类任务,衡量模型预测值与真实值之间的差异。 //==== 公式 <公式> 对于每个像素的二值交叉熵损失定义如下: $ upright("BCE") (p , g) = - (g log (p) + (1 - g) log (1 - p)) $ //其中,$p$ 是预测值,$g$ 是真实值。 整个图像的 BCE Loss 同样需要通过对所有像素的 BCE 损失求平均得到: $ upright("BCE Loss") = 1 / N sum_(i = 1)^N upright("BCE") (p_i , g_i) $ //其中,$N$ 是图像中的总像素数。 BCE Loss 适用于二分类问题,常用于分割任务中的每个像素分类(如前景和背景的分类)。 //==== 验证与评估 //<验证与评估> //交叉验证: 使用K折交叉验证(如5折)来更稳健地评估模型性能,避免过拟合。 // //性能指标: 主要评估指标包括 Dice 相似系数(Dice Score)、Jaccard //Index、Hausdorff距离、敏感性(Sensitivity)、特异性(Specificity)等。 // //=== 模型优化与后处理 <模型优化与后处理> ////模型融合: 如果资源允许,则可以训练多个模型,并采用模型融合策略提高最终分割的准确性。 后处理算法: 应用形态学操作(如开运算、闭运算)平滑分割边界,去除小孤立区域,或使用条件随机场(CRF)后处理提高边界界定质量。 //== 实验结果 <实验结果> //在搭建好的 SAM 大模型上实施肝脏肿瘤的分割任务,使用常见性能指标,准确度(Accuracy)、Dice 系数评价模型性能。通过这些指标,量化分析模型的分割效果,评估模型的训练效果并与其他分割方案比较。 = 结果分析与性能评估 <结果分析与性能比较> 为了全面评估基于 SAM 大模型的肝脏肿瘤分割软件的性能,选取主流的分割模型作为比较对象,U-Net 等在医学图像分割领域内已有大量成功应用,与之比较,可以更好的评估模型能力。 === 交并比(IOU) <交并比iou> //==== 定义 <定义-1> 交并比(Intersection Over Union, IOU)也称为 Jaccard Index,是一种常用的评估指标,用于衡量预测分割与真实分割之间的重叠程度。用于衡量预测分割结果与真实标注之间的一致性。IOU的计算公式表示如下: $ upright("IoU") (A , B) = lr(|A sect B|) / lr(|A union B|) = frac(sum_i p_i g_i, sum_i p_i + sum_i g_i - sum_i p_i g_i) $ //其中,$p$ 是预测值,$g$ 是真实值。 //IOU 通常用作评估指标,而不是损失函数。它用于衡量分割结果与真实标签的重叠程度,广泛应用于各种分割任务的性能评估。 //在实际应用中,IoU通常用于: //1. #strong[评估分割质量];:通过计算预测的分割结果与真实标注的IoU,可以定量地评估分割算法的性能。 //2. #strong[确定阈值];:在某些任务中,可以通过设定一个IoU阈值来确定预测结果是否被认为是正确的。例如,如果IoU大于0.5,则认为分割是成功的。 //3. #strong[比较不同算法];:IOU可以用来比较不同图像分割算法的性能,帮助选择最优的算法。 //交并比是一个直观且广泛接受的指标,它能够很好地反映分割结果的准确性和完整性。 == 评估模型性能 <评估模型性能> //通过微调训练,SAM 模型能够正确对腹部 CT 扫描图像中的肝脏肿瘤进行分割。//如图所示,肉眼几乎不可辨别分割真值与 SAM 模型分割结果之间的区别,而各其他分割算法均可看到分割结果与分割真值标签有肉眼可见的明显差异。 #figure(image("分割结果演示.png",width: 14cm), caption: [ 分割结果展示 ] ) #figure(image("其他模型分割结果.png"), caption: [ 其他模型的分割结果,从左至右依次为 原 CT 图像、UNet、SegNet、DeepLabv3、FC-DenseNet、堆叠树形结构空洞卷积模型、分割真值标签 ] ) //以上介绍的评估指标中,DICE 系数与 DCE 结合作为模型训练中的损失函数使用,交并比(IOU)用于评估模型性能。交并比(IOU)反映了预测掩码与真实掩码之间的重叠程度,是一个介于0到1之间的值。IOU值越高,表示预测的分割结果与真实标注的一致性越好,通常用于评估分割算法的性能,尤其是在语义分割和实例分割任务中最为常用。 //在本研究中,如图 4.3 所示,通过对 SAM 模型的微调,模型对 CT 图像进行肝脏肿瘤分割的 IOU 指标可以达到 96% 以上,SAM 的预训练能力得到完美发挥,只需少量样本训练仍然能够表现出非常强大的分割能力。高质量的医学标注数据往往难以获得,因此,SAM 模型的强泛化能力对其他医学领域图像分割同样具有重要意义。 #figure(image("IOU折线图.png"), caption: [ 图 4.3 模型训练过程 IOU 结果,横坐标为训练轮次,纵坐标为验证集 IOU 指标 ] ) //表 4.1 展示了不同模型在测试集上的分割性能比较,由 Ronneberger 等使用U-Net 模型给出的分割方法中,IOU值为0.920,Gao Fei等提出的基于堆叠树形聚合结构空洞卷积的肝脏肿瘤分割方法中,IOU 值为0.732,Zhou等使用 U-Net++ 模型提出的肝脏肿瘤分割方法中,IOU值为0.829,以上几种分割方法中,本文提到的基于 SAM的分割方法具有最好的 IOU 指标。 #figure(image("不同模型的肝脏肿瘤分割IOU(交并比).png"), caption: [ 不同模型的肝脏肿瘤分割IOU ] ) //上述结果中可以看出,本研究提出的基于 SAM 的分割方法在主要评估分割结果与真实值相似度的 IOU 指标上优于多种深度学习方法,基于 Transformer Vision 的SAM 模型在医学图像处理中表现优异。但本文研究方法和实验设计仍有提升空间,未来可通过更深入的模型调整和微调训练来改更进一步改善其性能,以提升模型在实际应用中的表现。 //== 结果讨论 <结果讨论> //在本研究中,我们通过对万物分割模型(Segment Anything Model)在数据集上的微调,实现了对腹部 CT 扫描图像的肝脏肿瘤的自动分割。以下是实验结果的深入分析及其在实际应用中的改进方向。 //实验结果显示,基于 Vision Transformer 的 SAM 模型在腹部 CT 扫描图像的数据集上取得了较高准确率,这样的实验结果充分证实了 SAM 模型在肝脏肿瘤分割模型任务中的有效性。 ////与以往的深度学习模型相比,本研究采用的 SAM 模型表现出更高的准确性能和更强的泛化能力。之前对于医学图像分割的研究通常依赖大量的数据集训练,例如 Gao Fei 等提出的基于堆叠树形聚合结构空洞卷积的肝脏肿瘤分割方法中,模型的训练使用了 2012 年至 2017 年在河南省人民医院接受肝癌治疗的 325 例晚期肝细胞肝癌(HCC)患者的CT图像,共获取 6146 张图像,其中 6046 张作为训练集,100 张作为测试集,经过数据增强和扩充后,训练集数据达到了20倍,即20×6046个图像。相比之下,本文提出的 SAM 分割方法训练所使用的数据集仅 20 例匿名患者的 CT 图像,训练成果却取得了远优于前者的分割效果。这进一步证实了 SAM 模型的优越性。 //SAM 作为新生的图像分割模型,诞生之初就被寄予厚望,SAM 模型的提出者 <NAME> 认为,这是计算机视觉领域的 GPT-3 时刻。GPT-3 是一种强大的自然语言处理模型,通过预训练和微调,能够适应各种语言任务。同样地,SAM模型通过预训练和微调,能够适应各种图像分割任务。这意味着,SAM 有可能成为新的计算机视觉领域的发展方向,如 GPT 在语言文字处理领域的引领作用。通过这些讨论分析,我们有信心让 SAM 模型在医学图像分割领域表现出更高的性能和更强的适应性,更好地满足临床应用的需求。 //= 结论 <结论-2> //本研究通过开发基于SAM大模型的肝脏肿瘤分割软件,展示了深度学习在医学图像分割领域的强大潜力。SAM大模型的引入,提高了分割精确度,尤其在处理腹部CT图像中肝脏肿瘤的复杂情况时表现出显著的优势。通过与其他流行模型的性能对比,本研究不仅证明了SAM大模型在肝脏肿瘤分割任务上的有效性,也为未来在此类应用中深度学习模型的优化提供了有价值的参考。 //进一步的分析和实验结果表明,虽然基于 SAM 大模型的分割软件在准确度上取得了优异的成绩,但仍存在计算效率和模型泛化能力方面的挑战。未来的工作可以着重于这些方面,探索更高效的算法或技术来提升模型性能,从而更好地服务于临床诊断和治疗规划。 //尽管 SAM 在肝脏肿瘤分割上显示出前景,但仍需针对医学图像的特点进行进一步优化和调整。未来的研究可以探索如何结合医学专家的知识和SAM的自动学习能力,以提高分割精度,减少需要手动调整的工作。同时,开发面向特定如肝脏肿瘤的深度学习模型,将是推动医学图像处理技术发展的关键。 //综上所述,基于 SAM 模型的肝脏肿瘤分割软件的开发,不仅可以改善现有的图像分割方法,还有助于提高肝脏疾病的诊断效率和准确性。未来的研究应当着重于模型的实际应用和临床转化,以实现医学影像自动化分析的最终目标。 //== 不足 <不足> //+ #strong[数据集局限性];: // 本研究所使用的数据集可能存在样本量不足或样本分布不均的问题,这可能导致模型在某些特定场景下的泛化能力受限。未来的研究可以通过引入更多样本量、更丰富的数据集,以及涵盖更多不同类型的肝脏肿瘤图像来解决这一问题。 //+ #strong[模型复杂性和计算资源需求];: 由于 SAM 模型及其微调过程中涉及复杂的神经网络结构和大量的计算资源,训练和推理的时间和成本较高。在训练过程中冻结了模型的大部分内容,这在实际应用中可能限制其能力发挥。未来可以尝试通过模型压缩、剪枝和量化等技术来减少计算资源需求。 //+ #strong[实际应用验证不足];: // 虽然本研究在测试集上展示了良好的性能,但在实际临床应用中的验证和评估尚不足。未来需要在真实临床环境中进行更多的测试和验证,以确保模型在实际应用中的可靠性和有效性。 //== 展望 //<展望> //+ #strong[多模态数据融合];: // 未来的研究可以探索将不同模态的医学图像(如MRI、CT、超声图像)进行融合,以提升模型的鲁棒性和准确性。多模态数据的融合可以提供更多的病灶信息,有助于更准确的肝脏肿瘤分割。 //+ #strong[模型的迁移学习与领域自适应];: // 可以尝试将本研究的方法迁移到其他类型的医学图像分割任务中,如肺部、脑部等其他器官的肿瘤分割。同时,引入领域自适应技术,使模型能够在不同医院或不同设备生成的图像数据上保持高性能。 //+ #strong[实时分割与嵌入式应用];: // 未来可以探索如何将微调后的SAM模型部署到嵌入式设备或实时系统中,以便在临床实践中实现实时的肝脏肿瘤分割。这需要在模型压缩和加速方面进行深入研究。 //+ #strong[集成学习与模型融合];: // 可以尝试将SAM模型与其他先进的图像分割模型进行集成,利用集成学习的优势,进一步提升分割效果。模型融合技术可以综合多种模型的优点,提高最终分割结果的准确性和稳定性。 //+ #strong[临床合作与反馈];: // 加强与临床专家的合作,通过他们的反馈不断改进和优化模型。这不仅有助于提升模型的实际应用价值,还能确保研究方向和临床需求紧密结合。 = 总结 <总结-1> 尽管本研究在利用 SAM 模型进行肝脏肿瘤分割方面取得了显著成果,但仍存在一些不足和挑战。未来的研究可以通过多模态数据融合、迁移学习、实时分割、集成学习和临床合作等多方面的努力,进一步提升模型性能,扩大其应用范围,最终实现更高效、更准确的医学图像分割系统。 在基于 SAM 大模型的肝脏肿瘤分割软件开发上取得了很好的成效,将来可通过对模型的进一步优化微调与前端开发提升其性能与易用性。我希望在以后的学习中能在该研究方面继续不懈学习和研究,也希望能通过自己的努力能够为医疗领域图像处理奉献力量。
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/math/style.typ
typst
Apache License 2.0
// Test text styling in math. --- // Test italic defaults. $a, A, delta, ϵ, diff, Delta, ϴ$ --- // Test forcing a specific style. $A, italic(A), upright(A), bold(A), bold(upright(A)), \ serif(A), sans(A), cal(A), frak(A), mono(A), bb(A), \ italic(diff), upright(diff), \ bb("hello") + bold(cal("world")), \ mono("SQRT")(x) wreath mono(123 + 456)$ --- // Test forcing math size $a/b, display(a/b), display(a)/display(b), inline(a/b), script(a/b), sscript(a/b) \ mono(script(a/b)), script(mono(a/b))\ script(a^b, cramped: #true), script(a^b, cramped: #false)$ --- // Test a few style exceptions. $h, bb(N), cal(R), Theta, italic(Theta), sans(Theta), sans(italic(Theta))$ --- // Test font fallback. $ よ and 🏳️‍🌈 $ --- // Test text properties. $text(#red, "time"^2) + sqrt("place")$ --- // Test different font. #show math.equation: set text(font: "Fira Math") $ v := vec(1 + 2, 2 - 4, sqrt(3), arrow(x)) + 1 $ --- // Test using rules for symbols #show sym.tack: it => $#h(1em) it #h(1em)$ $ a tack b $
https://github.com/AnsgarLichter/light-cv
https://raw.githubusercontent.com/AnsgarLichter/light-cv/main/lib.typ
typst
MIT License
#import "@preview/fontawesome:0.1.0": * #import "template/settings/styles.typ": * #import "modules/utils.typ": * #import "modules/header.typ": * #import "modules/section.typ": * #import "modules/skills.typ": * #let cv( content ) = { set text( font: body-style.fonts, weight: body-style.weight, size: body-style.size, ) set list( indent: list-style.indent ) set align(left) set page( paper: page-style.paper, margin: page-style.margin ) content } #let header( full-name: [], job-title: [], // Each array item must have a property link, text and icon to be displayed. socials: (), profile-picture: "" ) = { table( columns: header-style.table.columns, inset: 0pt, stroke: none, column-gutter: header-style.table.column-gutter, align: left + horizon, { create-header-info( full-name: full-name, job-title: job-title, socials: socials ) }, { create-header-image( profile-photo: profile-picture ) } ) v(header-style.margins.bottom) } #let section(title) = { v(section-style.margins.top) create-section-title(title) } #let entry( title: "", company-or-university: "", date: "", location: "", logo: "", description: () ) = { v(entry-style.margins.top) table( columns: entry-style.table.columns, inset: 0pt, stroke: none, align: horizon, column-gutter: entry-style.margins.between-logo-and-title, {image(logo)}, table( columns: (1fr), inset: 0pt, stroke: none, row-gutter: entry-style.margins.between-title-and-subtitle, align: auto, { text( size: entry-style.title.size, weight: entry-style.title.weight, fill: entry-style.title.color, title ) text( size: entry-style.company-or-university.size, weight: entry-style.company-or-university.weight, fill: entry-style.company-or-university.color, " @" + company-or-university ) }, { table( columns: 2, inset: 0pt, stroke: none, align: horizon, column-gutter: entry-style.margins.between-time-and-location, {table( columns: 2, inset: 0pt, stroke: none, align: horizon, column-gutter: entry-style.margins.between-icon-and-text, {if date.len() > 0{fa-hourglass-2()}}, {text( size: entry-style.time-and-location.size, weight: entry-style.time-and-location.weight, fill: entry-style.time-and-location.color, date )}, )}, {table( columns: 2, inset: 0pt, stroke: none, align: horizon, column-gutter: entry-style.margins.between-icon-and-text, {if location.len() > 0{fa-location-dot()}}, {text(size: 10pt, location)} )}, ) }, ) ) text()[ #v(3pt) #description ] } #let skill( category: "", skills: () ) = { table( columns: skills-style.columns, inset: 0pt, column-gutter: 0pt, stroke: none, align: (horizon, left), {text(category)}, { render-skills(skills: skills) } ) v(skills-style.margins.between-categories) }
https://github.com/ljgago/typst-chords
https://raw.githubusercontent.com/ljgago/typst-chords/main/examples/single-chords.typ
typst
MIT License
#import "../lib.typ": * #set document(date: none) #set page(width: auto, height: auto, margin: 0pt) #set text(14pt) #let chord = single-chord.with( font: "PT Sans", size: 12pt, weight: "semibold", background: silver ) #rect( stroke: none, radius: 3pt, inset: (x: 10pt, y: 10pt), fill: white, [ #chord[Jingle][G][2] bells, jingle bells, jingle #chord[all][C][] the #chord[way!][G][2] \ #chord[Oh][C][] what fun it #chord[is][G][] to ride \ In a #chord[one-horse][A7][2] open #chord[sleigh,][D7][3] hey! ] )
https://github.com/Amelia-Mowers/typst-tabut
https://raw.githubusercontent.com/Amelia-Mowers/typst-tabut/main/doc/example-snippets/import-csv-raw.typ
typst
MIT License
#import "@preview/tabut:<<VERSION>>": tabut, rows-to-records #import "example-data/supplies.typ": supplies #let titanic = { let titanic-raw = csv("example-data/titanic.csv"); rows-to-records( titanic-raw.first(), // The header row titanic-raw.slice(1, -1), // The rest of the rows ) }
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/manual.typ
typst
Apache License 2.0
#import "/src/lib.typ" #import lib: * #import units: * #import prefixes: * #let example(it, dir) = { set text(size: 1.25em) let (a, b) = ( eval( "#set text(font: \"Linux Libertine\")\n" + it.text, mode: "markup", scope: dictionary(units) + dictionary(prefixes) + dictionary(lib) ), raw(it.text.replace("\\\n", "\\\n"), lang: "typ") ) block( breakable: false, spacing: 0em, pad( left: 1em, stack( dir: dir, ..if dir == ltr { (a, 1fr, par(leading: 0.9em, b), 1fr) } else { (b, linebreak(), a) } ) ) ) metro-reset() } #show raw.where(lang: "example"): it => { example(it, ltr) } #show raw.where(lang: "example-stack"): it => { example(it, ttb) } #show link: set text(blue) #let param(term, t, default: none, description) = { if type(term) != array { term = (term,) } let types = ( ch: "Choice", nu: "Number", li: "Literal", sw: "Switch", "in": "Integer" ) if default != none { if t == "ch" { default = repr(default) } default = [(default: #raw(default))] // default = align(top + right, [(default: #raw(default))]) } t = text(types.at(t, default: t), font: "Source Code Pro") block(breakable: false, { align(horizon, stack( dir: ltr, term.map(t => strong(t + "\n")).join(), h(0.6em), t, 1fr, default ) ) block(pad(description, left: 2em), above: 0.65em) }) } #align(center)[ #text(16pt)[Metro] #link("https://github.com/fenjalien")[fenjalien] and #link("https://github.com/Mc-Zen")[Mc-Zen] \ https://github.com/fenjalien/metro \ Version 0.3.0 \ Requires Typst 0.11+ ] #outline(indent: auto) #pagebreak() #set heading(numbering: "1.1") = Introduction The Metro package aims to be a port of the Latex package siunitx. It allows easy typesetting of numbers and units with options. This package is very early in development and many features are missing, so any feature requests or bug reports are welcome! Metro's name comes from Metrology, the study scientific study of measurement. = Usage #set pad(left: 1em) Typst 0.11.0+ is required. You can import the package using the package manager: ```typ #import "@preview/metro:0.3.0": * ``` Or download the `src` folder and import `lib.typ`: ```typ #import "/src/lib.typ": * ``` // The package provdides the functions: // - `#ang(angle, ..options)` // - `#num(number, ..options)` // - `#unit(unit, ..options)` // - `#qty(number, unit, ..options)` // - `#num-list(numbers, ..options)` // - `#num-product(numbers, ..options)` // - `#num-range(number1, number2, ..options)` // - `#qty-list(numbers, unit, ..options)` // - `#qty-product(numbers, unit, ..options)` // - `#qty-range(number1, number2, unit, ..options)` // - `#complex(number, ..options)` // - `#metro-setup(..options)` == Options ```typ #metro-setup(..options) ``` All provided functions in this package have options that can control how they parse, process and print items. They can normally be given as keyword arguments directly to the function, but this can get tedious if you want the same options to apply throughout the document. You can instead use the `metro-setup` function. Any options given as keyword arguments will then be applied to the relevant subsequent functions in the document. All options and function arguments will use the following types: / Literal: Takes the given value directly. Input type is a string, content and sometimes a number. / Switch: On-off switches. Input type is a boolean. / Choice: Takes a limited number of choices, which are described separately for each option. Input type is a string. / Number: A float or integer. / Integer: An integer. #pagebreak() == Numbers ```typ #num(number, e: none, pm: none, pwr: none, ..options) ``` Parses, processes then prints a number. The number can be given as an integer, a float, a string, as some plain content or math content! The different forms of input should extend to all other functions with arguments that take a number, they will be parsed all the same. However it should be noted that: - When giving a number as an integer or float with an exponent in the number, it will not be seen by Metro (e.g. `3.4e3` will be seen as `3400` and not "3.4 with an exponent of 3"). - When using one of Metro's function within math mode, Typst considers dashes as subtraction symbols which breaks identifier names. So any options with dashes will not be able to be used when in math mode. ```example #num(123)\ #num("1234")\ #num[12345]\ $num(0.123)$\ #num("0,1234")\ #num[.12345]\ #num(e: -4)[3.45]\ #num("-1", e: 10, print-unity-mantissa: false) ``` #param("number", "li")[ The number to format. ] #param("pm", "li", default: "none", [ The uncertainty of the number. ]) #param("e", "li", default: "none", [ The exponent of the number. It can also be given as an integer in the number argument when it is of type string or content. It should be prefixed with an "e" or "E". ```example #num("1e10")\ #num[1E10] ``` ]) #param("pwr", "li", default: "none", [ The power of the number, it will be attached to the top. No processing is currently done to the power. It can also be passed as an integer in the number parameter when it is of type string or content. It should be prefixed after the exponent with an "^". ```example #num("1^2")\ $num(1^2)$ ``` ]) === Options ==== Parsing #param("input-decimal-markers", "Array<Literal>", default: "('\.', ',')")[ An array of characters that indicate the sepration between the integer and decimal parts of a number. More than one inupt decimal marker can be used, it will be converted by the package to the appropriate output marker. ] #param("retain-explicit-decimal-marker", "sw", default: "false")[ Allows a trailing decimal marker with no decimal part present to be printed. ```example #num[10.]\ #num(retain-explicit-decimal-marker: true)[10.] ``` ] #param("retain-explicit-plus", "sw", default: "false")[ Allows a leading plus sign to be printed. ```example #num[+345]\ #num(retain-explicit-plus: true)[+345] ``` ] #param("retain-negative-zero", "sw", default: "false")[ Allows a negative sign on an entirely zero value. ```example #num[-0]\ #num(retain-negative-zero: true)[-0] ``` ] #param("parse-numbers", "sw", default: "auto")[ Turns the entire parsing system on and off. It allows the use of arbitrary values in numbers. When the option is `auto`, numbers will be attempt to be parsed but will quietly stop if it fails to do so. The number will then be printed as given. If the option is `false`, no parsing will even be attempted. If `true`, Metro will panic if the number cannot be parsed. ```example $num(sqrt(3))$\ #metro-setup(parse-numbers: false) $num(sqrt(4))$\ #metro-setup(parse-numbers: true) // Will panic: // $num(sqrt(5))$\ ``` ] ==== Post Processing #param("drop-exponent", "sw", default: "false", [ When `true` the exponent will be dropped (_after_ the processing of exponent) ```example #num("0.01e3")\ #num("0.01e3", drop-exponent: true) ``` ]) #param("drop-uncertainty", "sw", default: "false")[ When `true` the uncertainty will be dropped. ```example #num("0.01", pm: 0.02)\ #num("0.01", pm: 0.02, drop-uncertainty: true)\ ``` ] #param("drop-zero-decimal", "sw", default: "false")[ When `true`, if the decimal is zero it will be dropped before setting the minimum numbers of digits. ```example #num[2.1]\ #num[2.0]\ #metro-setup(drop-zero-decimal: true) #num[2.1]\ #num[2.0]\ ``` ] #param("exponent-mode", "ch", default: "input")[ How to convert the number to scientific notation. Note that the calculated exponent will be added to the given exponent for all options. / input: Does not perform any conversions, the exponent will be displayed as given. / scientific: Converts the number such that the integer will always be a single digit. / fixed: Convert the number to use the exponent value given by the `fixed-exponent` option. / engineering: Converts the number such that the exponent will be a multiple of three. / threshold: Like the `scientific` option except it will only convert the number when the exponent would be outside the range given by the `exponent-thresholds` option. ```example #let nums = [ #num[0.001]\ #num[0.0100]\ #num[1200]\ ] #nums #metro-setup(exponent-mode: "scientific") #nums #metro-setup(exponent-mode: "engineering") #nums #metro-setup(exponent-mode: "fixed", fixed-exponent: 2) #nums ``` #metro-reset() ] #param("exponent-thresholds", "Array<Integer>", default: "(-3, 3)")[ Used to control the range of exponents that won't trigger when the `exponent-mode` is "threshold". The first value is the minimum inclusive, and the last value is the maximum inclusive. ```example-stack #let inputs = ( "0.001", "0.012", "0.123", "1", "12", "123", "1234" ) #table( columns: (auto,)*3, [Input], [Threshold $-3:3$], [Threshold $-2:2$], ..for i in inputs {( num(i), num(i, exponent-mode: "threshold"), num(i, exponent-mode: "threshold", exponent-thresholds: (-2, 2)), )} ) ``` ] #param("fixed-exponent", "Integer", default: "0")[ The exponent value to use when `exponent-mode` is "fixed". When zero, this may be used to remove scientific notation from the input. ```example #num("1.23e4")\ #num("1.23e4", exponent-mode: "fixed", fixed-exponent: 0) ``` ] #param("round-mode", "ch", default: "none")[ How the package should round numerical input. / none: No rounding is performed. ```example #num(1.23456)\ #num(14.23) ``` / figures: Round to a number of significant figures. ```example #metro-setup(round-mode: "figures") #num(1.23456)\ #num(14.23) ``` / places: Round to a number of decimal places. ```example #metro-setup(round-mode: "places") #num(1.23456)\ #num(14.23) ``` ] #param("round-precision", "Integer", default: "2")[ Controls the number of significant figures or decimal places to round to. ```example #metro-setup(round-mode: "places", round-precision: 3) #num(1.23456)\ #num(14.23)\ #metro-setup(round-mode: "figures", round-precision: 3) #num(1.23456)\ #num(14.23)\ ``` ] #param("round-pad", "sw", default: "true")[ Controls when rounding may "extend" a short number to more digits (or figures). ```example #metro-setup(round-mode: "figures", round-precision: 4) #num(12.3)\ #num(12.3, round-pad: false)\ ``` ] #param("round-direction", "ch", default: "nearest")[ Determines which direction a value is rounded toward. / nearest: Gives the common outcome that values round depending on whether the preceding digit is greater or less than 5. ```example #metro-setup(round-mode: "places") #num(0.054)\ #num(0.046) ``` / down: Values are always rounded down. It may be thought of as "truncation". ```example #metro-setup(round-mode: "places", round-direction: "down") #num(0.054)\ #num(0.046) ``` / up: Values are always rounded up. ```example #metro-setup(round-mode: "places", round-direction: "up") #num(0.054)\ #num(0.046) ``` ] #param("round-half", "ch", default: "up")[ Determines how numbers that are exactly half are rounded to the the `"nearest"`. / up: The number is rounded up. ```example #metro-setup(round-mode: "figures", round-precision: 1) #num(0.055)\ #num(0.045)\ ``` / even: The number is rounded to the nearest even part. ```example #metro-setup( round-mode: "figures", round-precision: 1, round-half: "even" ) #num(0.055)\ #num(0.045)\ ``` ] #param("round-minimum", "nu", default: "0")[ There are cases in which rounding will result in the number reaching zero. It may be desirable to show results as below a threshold value. This can be achieved by setting this option to the threshold value. There will be no effect when rounding to a number of significant figures as it is not possible to obtain the value zero in these cases. ```example #metro-setup(round-mode: "places") #num(0.0055)\ #num(0.0045)\ #metro-setup(round-minimum: 0.01) #num(0.0055)\ #num(0.0045)\ ``` ] #param("round-zero-positive", "sw", default: "true")[ When rounding negative numbers to a fixed number of places, a zero value may result. Usually this is expressed as an unsigned value, but in some cases retaining the negative sign may be desirable. This behaviour can be controlled using this option. ```example #metro-setup(round-mode: "places") #num(-0.001)\ #metro-setup(round-zero-positive: false) #num(-0.001) ``` ] #param("minimum-decimal-digits", "Integer", default: "0")[ May be used to pad the decimal component of a number to a given size. ```example #num(0.123)\ #num(0.123, minimum-decimal-digits: 2)\ #num(0.123, minimum-decimal-digits: 4) ``` ] #param("minimum-integer-digits", "Integer", default: "0")[ May be used to pad the integer component of a number to a given size. ```example #num(123)\ #num(123, minimum-integer-digits: 2)\ #num(123, minimum-integer-digits: 4) ``` ] ==== Printing #param("group-digits", "ch", default: "all")[ Whether to group digits into blocks to increase the ease of reading of numbers. Takes the values `all`, `none`, `decimal` and `integer`. Grouping can be acitivated separately for the integer and decimal parts of a number using the appropriately named values. ```example #num[12345.67890]\ #num(group-digits: "none")[12345.67890]\ #num(group-digits: "decimal")[12345.67890]\ #num(group-digits: "integer")[12345.67890] ``` ] #param("group-separator", "li", default: "sym.space.thin")[ The separator to use between groups of digits. ```example #num[12345]\ #num(group-separator: ",")[12345]\ #num(group-separator: " ")[12345] ``` ] #param("group-minimum-digits", "in", default: "5")[ Controls how many digits must be present before grouping is applied. The number of digits is considered separately for the integer and decimal parts of the number: grouping does not "cross the boundary". ```example #num[1234]\ #num[12345]\ #num(group-minimum-digits: 4)[1234]\ #num(group-minimum-digits: 4)[12345]\ #num[1234.5678]\ #num[12345.67890]\ #num(group-minimum-digits: 4)[1234.5678]\ #num(group-minimum-digits: 4)[12345.67890] ``` ] #param("digit-group-size", "in", default: "3")[ Controls the number of digits in each group. Finer control can be achieved using `digit-group-first-size` and `digit-group-other-size`: the first group is that immediately by the decimal point, the other value applies to the second and subsequent groupings. ```example #num[1234567890]\ #num(digit-group-size: 5)[1234567890]\ #num(digit-group-other-size: 2)[1234567890] ``` ] #param("output-decimal-marker", "li", default: ".")[ The decimal marker used in the output. This can differ from the input marker. ```example #num(1.23)\ #num(output-decimal-marker: ",")[1.23] ``` ] #param("exponent-base", "li", default: "10")[ The base of an exponent. ```example #num(exponent-base: "2", e: 2)[1] ``` ] #param("exponent-product", "li", default: "sym.times")[ The symbol to use as the product between the number and its exponent. ```example #num(e: 2, exponent-product: sym.times)[1]\ #num(e: 2, exponent-product: sym.dot)[1] ``` ] #param("output-exponent-marker", "li", default: "none")[ When not `none`, the value stored will be used in place of the normal product and base combination. ```example #num(output-exponent-marker: "e", e: 2)[1]\ #num(output-exponent-marker: "E", e: 2)[1] ``` ] #param("bracket-ambiguous-numbers", "sw", default: "true")[ There are certain combinations of numerical input which can be ambiguous. This can be corrected by adding brackets in the appropriate place. ```example #num(e: 4, pm: 0.3)[1.2]\ #num(bracket-ambiguous-numbers: false, e: 4, pm: 0.3)[1.2] ``` ] #param("bracket-negative-numbers", "sw", default: "false")[ Whether or not to display negative numbers in brackets. ```example #num[-15673]\ #num(bracket-negative-numbers: true)[-15673] ``` ] #param("tight-spacing", "sw", default: "false")[ Compresses spacing where possible. ```example #num(e: 3)[2]\ #num(e: 3, tight-spacing: true)[2] ``` ] #param("print-implicit-plus", "sw", default: "false")[ Force the number to have a sign. This is used if given and if no sign was present in the input. ```example #num(345)\ #num(345, print-implicit-plus: true) ``` It is possible to set this behaviour for the exponent and mantissa independently using `print-mantissa-implicit-plus` and `print-exponent-implicit-plus` respectively. ] #param("print-unity-mantissa", "sw", default: "true")[ Controls the printing of a mantissa of 1. ```example #num(e: 4)[1]\ #num(e: 4, print-unity-mantissa: false)[1] ``` ] #param("print-zero-exponent", "sw", default: "false")[ Controls the printing of an exponent of 0. ```example #num(e: 0)[444]\ #num(e: 0, print-zero-exponent: true)[444] ``` ] #param("print-zero-integer", "sw", default: "true")[ Controls the printing of an integer component of 0. ```example #num(0.123)\ #num(0.123, print-zero-integer: false) ``` ] #param("zero-decimal-as-symbol", "sw", default: "false")[ Whether to show entirely zero decimal parts as a symbol. Uses the symbol stroed using `zero-symbol` as the replacement. ```example #num[123.00]\ #metro-setup(zero-decimal-as-symbol: true) #num[123.00]\ #num(zero-symbol: [[#sym.bar.h]])[123.00] ``` ] #param("zero-symbol", "li", default: "sym.bar.h")[ The symbol to use when `zero-decimal-as-symbol` is `true`. ] #pagebreak() == Units ```typ #unit(unit, ..options) ``` Typsets a unit and provides full control over output format for the unit. The type passed to the function can be either a string or some math content. When using the function in math mode, Typst accepts single characters but multiple characters together are expected to be variables. So Metro defines units and prefixes which be can imported to be used. #pad[ ```typ #import "@preview/metro:0.2.0": unit, units, prefixes #unit($units.kg m/s^2$) // because `units` and `prefixes` here are modules you can import what you need #import units: gram, metre, second #import prefixes: kilo $unit(kilo gram metre / second^2)$ // You can also just import everything instead #import units: * #import prefixes: * $unit(joule / mole / kelvin)$ ``` #unit($units.kg m/s^2$)\ $unit(kilo gram metre / second^2)$\ $unit(joule / mole / kelvin)$ ] When using strings there is no need to import any units or prefixes as the string is parsed. Additionally several variables have been defined to allow the string to be more human readable. You can also use the same syntax as with math mode. ```example-stack // String #unit("kilo gram metre per square second")\ // Math equivalent #unit($kilo gram metre / second^2$)\ // String using math syntax #unit("kilo gram metre / second^2") ``` `per` used as in "metres _per_ second" is equivalent to a slash `/`. When using this in a string you don't need to specify a numerator. ```example-stack #unit("metre per second")\ $unit(metre/second)$\ #unit("per square becquerel")\ #unit("/becquerel^2") ``` `square` and `cubic` apply their respective powers to the units after them, while `squared` and `cubed` apply to units before them. ```example-stack #unit("square becquerel")\ #unit("joule squared per lumen")\ #unit("cubic lux volt tesla cubed") ``` Generic powers can be inserted using the `tothe` and `raiseto` functions. `tothe` specifically is equivalent to using caret `^`. ```example-stack #unit("henry tothe(5)")\ #unit($henry^5$)\ #unit("henry^5") #unit("raiseto(4.5) radian")\ #unit($radian^4.5$)\ #unit("radian^4.5") ``` You can also use the `sqrt` function for half powers. If you want to maintain the square root, you must set the `power-half-as-sqrt` option. ```example $unit(sqrt(H))$\ #unit("sqrt(H)", power-half-as-sqrt: true)\ ``` Generic qualifiers are available using the `of` function which is equivalent to using an underscore `_`. Note that when using an underscore for qualifiers in a string with a space, to capture the whole qualifier use brackets `()`. ```example-stack #unit("kilogram of(metal)")\ #unit($kilogram_"metal"$)\ #unit("kilogram_metal") #metro-setup(qualifier-mode: "bracket") #unit("milli mole of(cat) per kilogram of(prod)")\ #unit($milli mole_"cat" / kilogram_"prod"$)\ #unit("milli mole_(cat) / kilogram_(prod)") ``` === Options #param("inter-unit-product", "li", default: "sym.space.thin", [ The separator between each unit. The default setting is a thin space: another common choice is a centred dot. ```example #unit("farad squared lumen candela")\ #unit("farad squared lumen candela", inter-unit-product: $dot.c$) ``` ]) #param("per-mode", "ch", default: "power", [ Use to alter the handling of `per`. / power: Reciprocal powers ```example #unit("joule per mole per kelvin")\ #unit("metre per second squared") ``` / fraction: Uses the `math.frac` function (also known as `$ / $`) to typeset positive and negative powers of a unit separately. ```example #unit("joule per mole per kelvin", per-mode: "fraction")\ #unit("metre per second squared", per-mode: "fraction") ``` / symbol: Separates the two parts of a unit using the symbol in `per-symbol`. This method for displaying units can be ambiguous, and so brackets are added unless `bracket-unit-denominator` is set to `false`. Notice that `bracket-unit-denominator` only applies when `per-mode` is set to symbol. ```example #metro-setup(per-mode: "symbol") #unit("joule per mole per kelvin")\ #unit("metre per second squared") ``` ]) #param("per-symbol", "li", default: "sym.slash")[ The symbol to use to separate the two parts of a unit when `per-symbol` is `"symbol"`. ```example-stack #unit("joule per mole per kelvin", per-mode: "symbol", per-symbol: [ div ]) ``` ] #param("bracket-unit-denominator", "sw", default: "true")[ Whether or not to add brackets to unit denominators when `per-symbol` is `"symbol"`. ```example-stack #unit("joule per mole per kelvin", per-mode: "symbol", bracket-unit-denominator: false) ``` ] #metro-setup(per-mode: "power") #param("sticky-per", "sw", default: "false")[ Normally, `per` applies only to the next unit given. When `sticky-per` is `true`, this behaviour is changed so that `per` applies to all subsequent units. ```example #unit("pascal per gray henry")\ #unit("pascal per gray henry", sticky-per: true) ``` ] #param("qualifier-mode", "ch", default: "subscript")[ Sets how unit qualifiers can be printed. / subscript: ```example-stack #unit("kilogram of(pol) squared per mole of(cat) per hour") ``` / bracket: ```example-stack #unit("kilogram of(pol) squared per mole of(cat) per hour", qualifier-mode: "bracket") ``` / combine: Powers can lead to ambiguity and are automatically detected and brackets added as appropriate. ```example #unit("deci bel of(i)", qualifier-mode: "combine") ``` / phrase: Used with `qualifier-phrase`, which allows for example a space or other linking text to be inserted. ```example-stack #metro-setup(qualifier-mode: "phrase", qualifier-phrase: sym.space) #unit("kilogram of(pol) squared per mole of(cat) per hour")\ #metro-setup(qualifier-phrase: [ of ]) #unit("kilogram of(pol) squared per mole of(cat) per hour") ``` ] #param("power-half-as-sqrt", "sw", default: "false")[ When `true` the power of $0.5$ is shown by giving the unit sumbol as a square root. This ```example #unit("Hz tothe(0.5)")\ #unit("Hz tothe(0.5)", power-half-as-sqrt: true) ``` ] #metro-reset() #pagebreak() == Quantities ```typ #qty(number, unit, ..options) ``` This function combines the functionality of `num` and `unit` and formats the number and unit together. The `number` and `unit` arguments work exactly like those for the `num` and `unit` functions respectively. ```example #qty(1.23, "J / mol / kelvin")\ $qty(.23, candela, e: 7)$\ #qty(1.99, "per kilogram", per-mode: "symbol")\ #qty(1.345, "C/mol", per-mode: "fraction") ``` === Options #param("allow-quantity-breaks", "sw", default: "false")[ Controls whether the combination of the number and unit can be split across lines. ```example-stack #box(width: 3.25cm)[ Some filler text #qty(10, "m")\ #metro-setup(allow-quantity-breaks: true) Some filler text #qty(10, "m") ] ``` ] #param("quantity-product", "li", default: "sym.space.thin")[ The product symbol between the number and unit. ```example-stack #qty(2.67, "farad")\ #qty(2.67, "farad", quantity-product: sym.space)\ #qty(2.67, "farad", quantity-product: none) ``` ] #param("separate-uncertainty", "ch", default: "bracket")[ When a number has multiple parts, then the unit must apply to all parts of the number. / bracket: Places the entire numerical part in brackets and use a single unit symbol. ```example #qty(12.3, "kg", pm: 0.4) ``` / repeat: Prints the unit for each part of the number. ```example #qty(12.3, "kg", pm: 0.4, separate-uncertainty: "repeat") ``` / single: Prints only one unit symbol: mathematically incorrect. ```example #qty(12.3, "kg", pm: 0.4, separate-uncertainty: "single") ``` ] #pagebreak() == List, Products and Ranges ```typ #num-list(..numbers-options) ``` Lists of numbers may be processed using the `num-list` function. Each number should be given as a positional argument. The numbers are formatted using `num`. ```example #num-list(10, 30, 50, 70) ``` ```typ #num-product(..numbers-options) ``` Runs of products can be created using the `num-product` function. It acts in the same way `num-list` does. ```example #num-product(10, 30) ``` ```typ #num-range(number1, number2, ..options) ``` Simple ranges of numbers can be handled using the `num-range` function. It inserts a phrase or other text between the two numbers. ```example #num-range(10, 30) ``` The above list, product and range functions also have a `qty` variant where the last positional argument will be considered as a unit. ```example #qty-list(10, 30, 45, metre)\ #qty-product(10, 30, 45, metre)\ #qty-range(10, 30, metre)\ ``` The above function names cannot be used in math mode, instead equivalently named functions are provided that have the dash removed (e.g. `num-list` and `numlist`). === Options #param("list-separator", "li", default: "[, ]")[ The separator to place between each item in the a list of numbers. ```example #num-list(0.1, 0.2, 0.3) \ #num-list( list-separator: [; ], 0.1, 0.2, 0.3, ) ``` ] #param("list-final-separator", "li", default: "[ and ]")[ The separator before the last item of a list. ```example #num-list( list-final-separator: [, ], 0.1, 0.2, 0.3 ) \ #num-list( list-separator: [ and ], list-final-separator: [ and ], 0.1, 0.2, 0.3 ) ``` ] #param("list-pair-separator", "li", default: "[ and ]")[ The to use for exactly two items of a list. ```example #num-list(0.1, 0.2) \ #num-list( list-pair-separator: [, and ], 0.1, 0.2 ) ``` ] #param("product-mode", "ch", default: "symbol")[ Products of numbers can be output using either a product symbol or a phrase. / symbol: The symbol in `product-symbol` is used. ```example #num-product(5, 100, 2) ``` / phrase: The phrase in `product-phrase` is used. ```example #num-product(5, 100, 2, product-mode: "phrase") ``` ] #param("product-symbol", "li", default: "sym.times")[ The symbol to use when `product-mode` is `"symbol"`. ```example #num-product(5, 100, 2, product-symbol: sym.dot.c) ``` ] #param("product-phrase", "li", default: "[ by ]")[ The phrase to use when `product-mode` is `"phrase"`. ```example #num-product(5, 100, 2, product-symbol: [ BY ]) ``` ] #param("range-open-phrase", "li", default: "none")[ The phrase to open ranges with. ```example #num-range(10, 12)\ #num-range(5, 100, range-open-phrase: "from ") ``` ] #param("range-phrase", "li", default: "[ to ]")[ The word or symbol to be inserted between the two entries of the range. ```example #num-range(5, 100)\ #num-range(5, 100, range-phrase: sym.dash)\ ``` ] #param(("list-exponents", "product-exponents", "range-exponents"), "ch", default: "individual")[ Controls how lists, products and ranges can be "compressed" by combining the exponent parts. / individual: Leaves the exponent with the matching value. ```example #num-list("5e3", "7e3", "9e3", "1e4")\ #num-product("5e3", "7e3", "9e3", "1e4")\ #num-range("5e3", "7e3") ``` / combine: The first exponent entry is taken and applied to all other entries, with the exponent itself placed at the end. ```example #metro-setup( list-exponents: "combine", product-exponents: "combine", range-exponents: "combine", ) #num-list("5e3", "7e3", "9e3", "1e4")\ #num-product("5e3", "7e3", "9e3", "1e4")\ #num-range("5e3", "7e3") ``` / combine-bracket: Like `"combine"` but the list, product or range is wrapped in brackets, with the exponent outside. ```example #metro-setup( list-exponents: "combine-bracket", product-exponents: "combine-bracket", range-exponents: "combine-bracket", ) #num-list("5e3", "7e3", "9e3", "1e4")\ #num-product("5e3", "7e3", "9e3", "1e4")\ #num-range("5e3", "7e3") ``` ] #param(("list-units", "product-units", "range-units"), "ch", default: "repeat")[ Determines how `qty-list`, `qty-product` and `qty-range` functions print units. / repeat: Each number will be printed with a unit. ```example #qty-list(2, 4, 6, 8, tesla)\ #qty-product(2, 4, metre)\ #qty-range(2, 4, degreeCelsius) ``` / single: The unit will only be placed at the end of the collection. ```example #metro-setup( list-units: "single", product-units: "single", range-units: "single", ) #qty-list(2, 4, 6, 8, tesla)\ #qty-product(2, 4, metre)\ #qty-range(2, 4, degreeCelsius) ``` / bracket: Like `"single"` except brackets are placed around the collection. ```example #metro-setup( list-units: "bracket", product-units: "bracket", range-units: "bracket", ) #qty-list(2, 4, 6, 8, tesla)\ #qty-product(2, 4, metre)\ #qty-range(2, 4, degreeCelsius) ``` // no it doesn't, at least not yet // The option `product-units` also offers the settings *bracket-power* and *power*. // ```example // #qty-product(2, 4, metre, product-units: "bracket-power")\ // #qty-product(2, 4, metre, product-units: "power")\ // ``` ] #param(("list-open-bracket", "product-open-bracket", "range-open-bracket"), "li", default: "sym.paren.l")[ The opening bracket to be used when the collection is placed in brackets. ] #param(("list-close-bracket", "product-close-bracket", "range-close-bracket"), "li", default: "sym.paren.r")[ The closing bracket to be used when the collection is placed in brackets. ] #pagebreak() == Complex Numbers ```typ #complex(real, imag, ..unit-options) ``` Typesets the complex number, the first positional argument will be the real component and the second will be the coefficient of the imaginary component. If the second argument is either of the #link("https://typst.app/docs/reference/layout/angle/")[angle type] or ends in "deg" or "rad", the complex number will be considered to be in polar form and the first argument will be the radius. A unit can be optionally given as the third positional argument. Note that when giving the angle as an angle type in radains, it will be output in degrees by default. This is due to angle types being unit agnostic. This behaviour can be changed with the `complex-angle-unit` option. === Options #param("complex-mode", "ch", default: "input")[ The format in which complex values are printed. / input: The complex value is printed as-given. ```example #complex(1, 1)\ #complex(1, 45deg)\ ``` / cartesian: The output will be formatted in Cartesian form. ```example #metro-setup(complex-mode: "cartesian") #complex(1, 1)\ #complex(1, 45deg, round-mode: "places")\ ``` / polar: The output will be formatted in polar form. ```example #metro-setup(complex-mode: "polar") #complex(1, 1, round-mode: "places", round-pad: false)\ #complex(1, 45deg)\ ``` ] #param("output-complex-root", "li", default: "math.upright(\"i\")")[ The output complex root symbol. ```example #complex(1, 2, output-complex-root: "i")\ #complex(1, 2, output-complex-root: "j")\ ``` ] #param("complex-root-position", "ch", default: "after-number")[ The position of the complex root can be adjusted to place it either before or after the associated numeral in a complex number by using this option. ```example #complex(67, -0.9)\ #complex(67, -0.9, complex-root-position: "before-number")\ ``` ] #param("complex-angle-unit", "ch", default: "degrees")[ The output unit of the angle component of a complex number in polar form. ```example #complex(1, 1rad, ohm)\ #complex(1, 1rad, complex-angle-unit: "radians", ohm) ``` ] #param("complex-symbol-angle", "li", default: "sym.angle")[ The symbol used to denote the angle of a complex number in polar form. ```example #complex(1, 1deg, ohm, complex-symbol-angle: math.upright("A")) ``` ] #param("complex-symbol-degree", "li", default: "sym.degree")[ The symbol use for the units of degrees of a complex number in polar form. ```example #complex(1, 1deg, ohm, complex-symbol-degree: math.upright("d")) ``` ] #param("print-complex-unity", "sw", default: "false")[ When the complex part of a number is exactly 1, it is possible to either print or suppress the value. ```example #complex(0, 1, ohm)\ #complex(0, 1, ohm, print-complex-unity: true)\ ``` ] #pagebreak() == Angles ```typ #ang(..ang-options) ``` Typsets angles. The angle can be given as a single decimal number or 2 to 3 positional arguments of degrees, minutes and second, which is called the "arc format" in this document. ```example #ang(10)\ #ang(12.3)\ #ang("4,5")\ #ang(1, 2, 3)\ #ang(0, 0, 1)\ #ang(10, 0, 0)\ #ang(0, 1)\ ``` === Options #param("angle-mode", "ch", default: "input")[ The format in which angles are printed. / input: The angle is printed as given. ```example #ang(2.67)\ #ang(2, 3, 4)\ ``` / arc: The output will be formatted as an arc (degrees/minutes/seconds). ```example #metro-setup(angle-mode: "arc") #ang(2.67)\ #ang(2,3,4) ``` / decimal: The output will be formatted as a decimal value. ```example #metro-setup(angle-mode: "decimal") #ang(2.67)\ #ang(2,3,4) ``` ] #param("number-angle-product", "li", default: "none")[ The separator between the number and angle symbol. This is independent of the related `quantity-product` option used by the `qty` function. ```example #ang(2.67)\ #ang(2.67, number-angle-product: sym.space) ``` ] #param("angle-separator", "li", default: "none")[ The separation of the different parts of an angle when printed in arc format. ```example #ang(6, 7, 6.5)\ #ang(6, 7, 6.5, angle-separator: sym.space) ``` ] #param("angle-symbol-degree", "li", default: "sym.degree")[ The symbol to use for the degree unit of an arc angle. ] #param("angle-symbol-minute", "li", default: "units.arcminute")[ The symbol to use for the minute unit of an arc angle. ] #param("angle-symbol-second", "li", default: "sym.arcsecond")[ The symbol to use for the second unit of an arc angle. ```example #metro-setup( angle-symbol-degree: math.upright("d"), angle-symbol-minute: math.upright("m"), angle-symbol-second: math.upright("s"), ) #ang(6, 7, 6.5) ``` ] #pagebreak() = Meet the Units The following tables show the currently supported prefixes, units and their abbreviations. Note that unit abbreviations that have single letter commands are not available for import for use in math. This is because math mode already accepts single letter variables. #{ set figure(kind: "Table", supplement: "Table") let generate(..units) = { units.pos().map(x => { let (name, command) = if type(x) == "array" { x } else { (x, x) } (name, raw(command), unit(command)) }).join() } let headers = ([Unit], [Command], [Symbol]) figure( table( columns: 3, stroke: none, table.hline(), ..headers, table.hline(), ..generate( "ampere", "candela", "kelvin", "kilogram", "metre", "mole", "second" ), table.hline(), ), caption: [SI base units.] ) figure( table( columns: 6, stroke: none, table.hline(), ..headers * 2, table.hline(), ..generate( "becquerel", "newton", ("degree Celsius", "degreeCelsius"), "ohm", "coulomb", "pascal", "farad", "radian", "gray", "siemens", "hertz", "sievert", "henry", "steradian", "joule", "tesla", "lumen", "volt", "katal", "watt", "lux", "weber" ), table.hline() ), caption: [Coherent derived units in the SI with special names and symbols.] ) figure( table( columns: 3, stroke: none, table.hline(), ..headers, table.hline(), ..generate( "astronomicalunit", "bel", "dalton", "day", "decibel", "degree", "electronvolt", "hectare", "hour", "litre", ("", "liter"), ("minute (plane angle)", "arcminute"), ("minute (time)", "minute"), ("second (plane angle)", "arcsecond"), "neper", "tonne" ), table.hline(), ), caption: [Non-SI units accepted for use with the International System of Units.] ) figure( table( columns: 3, stroke: none, table.hline(), ..headers, table.hline(), ..generate( "byte", ), table.hline(), ), caption: [Non-SI units.] ) figure( table( columns: 8, stroke: none, table.hline(), ..([Prefix], [Command], [Symbol], [$10^x$]) * 2, table.hline(), ..(( ("quecto", -30), ("deca", 1), ("ronto", -27), ("hecto", 2), ("yocto", -24), ("kilo", 3), ("atto", -21), ("mega", 6), ("zepto", -18), ("giga", 9), ("femto", -15), ("tera", 12), ("pico", -12), ("peta", 15), ("nano", -9), ("exa", 18), ("micro", -6), ("zetta", 21), ("milli", -3), ("yotta", 24), ("centi", -2), ("ronna", 27), ("deci", -1), ("quetta", 30) ).map(x => (x.first(), raw(x.first()), unit(x.first()), num(x.last()))).join()), table.hline(), ), caption: [SI prefixes] ) figure( table( columns: 4, stroke: none, table.hline(), [Prefix], [Command], [Symbol], [$2^x$], table.hline(), ..(( ("kibi", 10), ("mebi", 20), ("gibi", 30), ("tebi", 40), ("pebi", 50), ("exbi", 60), ("zebi", 70), ("yobi", 80), ).map(x => (x.first(), raw(x.first()), unit(x.first()), num(x.last()))).join()), table.hline(), ), caption: [Binary prefixes] ) let ge(..xs) = { let xs = xs.pos() for i in range(0, xs.len()-1, step: 2) { let name = xs.at(i) let abbr = xs.at(i+1) (name, raw(abbr), unit(abbr)) } } page( margin: 1cm, figure( caption: [Unit abbreviations], stack( dir: ltr, table( columns: 3, stroke: none, table.hline(), [Unit], [Abbreviation], [Symbol], table.hline(), ..ge( "femtogram", "fg", "picogram", "pg", "nanogram", "ng", "microgram", "ug", "milligram", "mg", "gram", "g", "kilogram", "kg" ), table.hline(), ..ge( "picometre", "pm", "nanometre", "nm", "micrometre", "um", "millimetre", "mm", "centimetre", "cm", "decimetre", "dm", "metre", "m", "kilometre", "km", ), table.hline(), ..ge( "attosecond", "as", "femtosecond", "fs", "picosecond", "ps", "nanosecond", "ns", "microsecond", "us", "millisecond", "ms", "second", "s", ), table.hline(), ..ge( "femtomole", "fmol", "picomole", "pmol", "nanomole", "nmol", "micromole", "umol", "millimole", "mmol", "mole", "mol", "kilomole", "kmol", ), table.hline(), ..ge( "picoampere", "pA", "nanoampere", "nA", "microampere", "uA", "milliampere", "mA", "ampere", "A", "kiloampere", "kA", ), table.hline(), ..ge( "microlitre", "uL", "millilitre", "mL", "litre", "L", "hectolitre", "hL", ) ), table( columns: 3, stroke: none, table.vline(), table.hline(), [Unit], [Abbreviation], [Symbol], table.hline(), ..ge( "millihertz", "mHz", "hertz", "Hz", "kilohertz", "kHz", "megahertz", "MHz", "gigahertz", "GHz", "terahertz", "THz", ), table.hline(), ..ge( "millinewton", "mN", "newton", "N", "kilonewton", "kN", "meganewton", "MN", ), table.hline(), ..ge( "pascal", "Pa", "kilopascal", "kPa", "megapascal", "MPa", "gigapascal", "GPa", ), table.hline(), ..ge( "milliohm", "mohm", "kilohm", "kohm", "megohm", "Mohm", ), table.hline(), ..ge( "picovolt", "pV", "nanovolt", "nV", "microvolt", "uV", "millivolt", "mV", "volt", "V", "kilovolt", "kV", ), table.hline(), ..ge( "watt", "W", "nanowatt", "nW", "microwatt", "uW", "milliwatt", "mW", "kilowatt", "kW", "megawatt", "MW", "gigawatt", "GW", ), table.hline(), ..ge( "joule", "J", "microjoule", "uJ", "millijoule", "mJ", "kilojoule", "kJ", ), table.hline(), ..ge( "electronvolt", "eV", "millielectronvolt", "meV", "kiloelectronvolt", "keV", "megaelectronvolt", "MeV", "gigaelectronvolt", "GeV", "teraelectronvolt", "TeV", ), table.hline(), ..ge( "kilowatt hour", "kWh" ) ), table( columns: 3, stroke: none, table.vline(), table.hline(), [Unit], [Abbreviation], [Symbol], table.hline(), ..ge( "farad", "F", "femtofarad", "fF", "picofarad", "pF", "nanofarad", "nF", "microfarad", "uF", "millifarad", "mF", ), table.hline(), ..ge( "henry", "H", "femtohenry", "fH", "picohenry", "pH", "nanohenry", "nH", "millihenry", "mH", "microhenry", "uH", ), table.hline(), ..ge( "coulomb", "C", "nanocoulomb", "nC", "millicoulomb", "mC", "microcoulomb", "uC", ), table.hline(), ..ge( "kelvin", "K", "decibel", "dB", "astrnomicalunit", "au", "becquerel", "Bq", "candela", "cd", "dalton", "Da", "gray", "Gy", "hectare", "ha", "katal", "kat", "lumen", "lm", "neper", "Np", "radian", "rad", "sievert", "Sv", "steradian", "sr", "weber", "Wb" ), table.hline(), ..ge( "kilobyte", "kB", "megabyte", "MB", "gigabyte", "GB", "terabyte", "TB", "petabyte", "PB", "exabyte", "EB", "kibibyte", "KiB", "mebibyte", "MiB", "gibibyte", "GiB", "tebibyte", "TiB", "pebibyte", "PiB", "exbibyte", "EiB", ), ) ) ) ) } = Creating The following functions can be used to define custom units, prefixes, powers and qualifiers that can be used with the `unit` function. == Units ```typ #declare-unit(unit, symbol, ..options) ``` Declare's a custom unit to be used with the `unit` and `qty` functions. #param("unit", "string")[The string to use to identify the unit for string input.] #param("symbol", "li")[The unit's symbol. A string or math content can be used. When using math content it is recommended to pass it through `unit` first.] ```example-stack #let inch = "in" #declare-unit("inch", inch) #unit("inch / s")\ #unit($inch / s$) ``` == Prefixes ```typ #create-prefix(symbol) ``` Use this function to correctly create the symbol for a prefix. Metro uses Typst's #link("https://typst.app/docs/reference/math/class/", `math.class`) function with the `class` parameter `"unary"` to designate a prefix. This function does it for you. #param("symbol", "li")[The prefix's symbol. A string or math content can be used. When using math content it is recommended to pass it through `unit` first.] ```typ #declare-prefix(prefix, symbol, power-tens) ``` Declare's a custom prefix to be used with the `unit` and `qty` functions. #param("prefix", "string")[The string to use to identify the prefix for string input.] #param("symbol", "li")[The prefix's symbol. This should be the output of the `create-prefix` function specified above.] #param("power-tens", "nu")[The power ten of the prefix.] ```example-stack #let myria = create-prefix("my") #declare-prefix("myria", myria, 4) #unit("myria meter")\ #unit($myria meter$) ``` == Powers ```typ #declare-power(before, after, power) ``` This function adds two symbols for string input, one for use before a unit, the second for use after a unit, both of which are equivalent to the `power`. #param("before", "string")[The string that specifies this power before a unit.] #param("after", "string")[The string that specifies this power after a unit.] #param("power", "nu")[The power.] ```example-stack #declare-power("quartic", "tothefourth", 4) #unit("kilogram tothefourth")\ #unit("quartic metre") ``` == Qualifiers ```typ #declare-qualifier(qualifier, symbol) ``` This function defines a custom qualifier for string input. #param("qualifier", "string")[The string that specifies this qualifier.] #param("symbol", "li")[The qualifier's symbol. Can be string or content.] ```example-stack #declare-qualifier("polymer", "pol") #declare-qualifier("catalyst", "cat") #unit("gram polymer per mole catalyst per hour") ```
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/casoslov/casy/cas9.typ
typst
#import "/style.typ": * #import "/SK/texts.typ": * #import "../styleCasoslov.typ": * = Deviaty čas #show: rest => columns(2, rest) #nacaloBezKnaza #zalm(83) #zalm(84) #zalm(85) #si #lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)] #lettrine("Pane, zmiluj sa.") #note[(3x)] == Tropáre #note[Berieme tropár, prípadne tropáre podľa predpisu] #primText[I teraz: (Bohorodičník)] #lettrine("Kvôli nám, Dobrý, si sa narodil z Panny a pretrpel si ukrižovanie, * smrťou si rozvrátil smrť a zjavil si vzkriesenie ako Boh. * Neprehliadni tých, ktorých si stvoril svojou rukou. * Prejav svoju lásku k človeku, Milosrdný, * prijmi Bohorodičku, ktorá ťa porodila a modlí sa za nás, * zachráň, Záchranca náš, skormútený ľud.") #zoznam(( "Pre svoje meno nevydávaj nás na večnosť, * a nezrušuj svoju zmluvu! * A neodnímaj od nás svoje milosrdenstvo * pre Abraháma, svojho miláčika, * pre Izáka, svojho sluhu, * a pre Izraela, svojho svätca.", )) #trojsvatePoOtcenas == Kondák #note[Berieme kondák podľa predpisu] #lettrine("Pane, zmiluj sa.") #primText([40x]) #vKazdomCase #ektenia(3) #lettrine("Čestnejšia si ako cherubíni * a neporovnateľne slávnejšia ako serafíni, * bez porušenia si porodila Boha Slovo, * opravdivá Bohorodička, velebíme ťa.") Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami. #prepustenieMaleBezKnaza
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/7e1810-algo_hw/hw9.typ
typst
#import "utils.typ": * == HW9 (Week 11) Due: 2024.05.19 === Question 32.4-1 Compute the prefix function $pi$ for the pattern `ababbabbabbababbabb`. #ans[ $ pi={0,0,1,2,0,1,2,0,1,2,0,1,2,3,4,5,6,7,8} $ ] === Question 32.4-6 Show how to improve KMP-MATCHER by replacing the occurrence of $pi$ in line 5(but now line 10) by $pi'$, where $pi'$ is defined recusively for $q=1,2...,m-1$ by the equation $ pi'[q]=cases(0 quad & "if" pi[q]=0, pi'[pi[q]] quad &"if" pi[q]!=0 "and" P[pi[q]+1]=P[q+1], pi[q] quad & "otherwise") $ Explain why the modified algorithm is correct, and explain in what sense this change constitutes an improvement. #ans[ If $P[q+1]!=T[i] "and" P[pi[q]+1]=P[q+1]!=T[i]$, there's no need to compare $P[pi[q]+1]$ with $T[i]$, because $P[pi[q]+1]$ is the same as $P[q+1]$, so we can directly compare $P[q+1]$ with $T[i]$. This change improves the efficiency of the algorithm. ]
https://github.com/metamuffin/typst
https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/compiler/color.typ
typst
Apache License 2.0
// Test color modification methods. --- // Test CMYK color conversion. #let c = cmyk(50%, 64%, 16%, 17%) #stack( dir: ltr, spacing: 1fr, rect(width: 1cm, fill: cmyk(69%, 11%, 69%, 41%)), rect(width: 1cm, fill: c), rect(width: 1cm, fill: c.negate()), ) #for x in range(0, 11) { box(square(size: 9pt, fill: c.lighten(x * 10%))) } #for x in range(0, 11) { box(square(size: 9pt, fill: c.darken(x * 10%))) } --- // Test gray color modification. // Ref: false #test(luma(20%).lighten(50%), luma(60%)) #test(luma(80%).darken(20%), luma(63.9%)) #test(luma(80%).negate(), luma(20%))
https://github.com/PmaFynn/cv
https://raw.githubusercontent.com/PmaFynn/cv/master/src/content/en/experience.typ
typst
The Unlicense
#import "../../template.typ": * #cvSection("Experience") #cvEntry( title: [Working Student - Quality Assurance], organisation: [TOI TOI & DIXI Group GmbH], //TODO: insert toitoi & dixi group logo here logo: "", date: [08/2024 - Present], location: [Ratingen, Germany], //TODO: more jira tickets (manual), test automation with robot framework, rebuilding ci/cd pipeline (expierence from bachelor) description: list( [Managed and resolved Jira tickets, ensuring thorough quality assurance throughout the process], [Developed automated test scripts using Robot Framework integrated into our CI/CD pipeline to increase test coverage and efficiency], [Collaborated with development teams to identify and resolve software defects promptly], ), tags: ("Jira", "SQL", "Python", "Robot Framework") ) #divider() #cvEntry( title: [Working Student - Web Development], organisation: [TOI TOI & DIXI Group GmbH], //TODO: insert toitoi & dixi group logo here logo: "", date: [01/2024 - 07/2024], location: [Ratingen, Germany], //TODO: add list here -> mainly jira tickets and maintaining old projects and deploying new hyperautomation ones description: list( [Managed and resolved Jira tickets (mainly bug fixes)], ), tags: ("PHP", "Docker" , "Jira", "JavaScript", "Vue", "SQL") ) #divider() #cvEntry( title: [Working Student - Hyperautomation], organisation: [TOI TOI & DIXI Group GmbH], logo: "", date: [07/2023 - 12/2023], location: [Ratingen, Germany], //TODO: write a lot here description: list( [Created a comprehensive inventory of the entire IT landscape /*using no-/low code approaches*/ supporting the transition to a paperless work environment], [Established and solely maintained a resource assessment pipeline for newly acquired companies], [Designed, implemented, and solely maintained an application to gather monthly HR, fleet, etc. reports across global tenantship], [Redesigned and implemented the process by which sales employees obtain relevant company information for specific postal codes], ), tags: ("Power Automate", "Sharepoint", "SQL", "MS Forms") )
https://github.com/liuguangxi/erdos
https://raw.githubusercontent.com/liuguangxi/erdos/master/Problems/typstdoc/erdos_offline.typ
typst
// Global setup #set document( title: [Erdős Unofficial Offline Edition], author: ("<NAME>") ) #set page( paper: "a4" ) #set text( font: "Minion Pro", size: 11pt ) #let main-color = rgb("#03A9F4") #let main-dark-color = rgb("#03A9F4").darken(50%) // Cover #[ #set text(font: "Myriad Pro") #v(8em) #text(size: 36pt)[ #text(fill: main-color)[*Erdős*] ] #v(-2em) #text(size: 36pt)[ *Unofficial Offline Edition* ] #v(-2em) #text(size: 18pt)[ *Problem Set From #link("https://erdos.sdslabs.co")[#text(fill: main-color)[erdos.sdslabs.co]]* ] #v(1em) #text(size: 14pt)[ Compiled by *<NAME>* ] #align(right + bottom)[ #text(size: 14pt)[ Revision #text(fill: main-color)[*v2024.2*] \ August 2024 ] ] ] // Main body setup #set page( header: [ #set align(center) #box(width: 1fr, inset: (y: 5pt), stroke: (bottom: 0.75pt + main-dark-color))[ #smallcaps[Erdős Unofficial Offline Edition] ] ], footer: [ #set align(center) #text(number-type: "old-style")[ Page #counter(page).display("1 of 1", both: true) ] ] ) #counter(page).update(1) #set par( justify: true ) #let problem-heading(number, title) = { let bookmark-title = [Problem \##number: #title] pagebreak() set text(size: 0pt) heading(numbering: none, hide[#bookmark-title]) set text(font: "Myriad Pro", size: 14pt) box( fill: main-dark-color, inset: (x: 8pt, y: 5pt), stroke: (bottom: 1.5pt + main-dark-color) )[ #text(fill: white)[*#number*] ] box( inset: (x: 2pt, y: 5pt), stroke: (bottom: 1.5pt + main-dark-color) )[ #text(fill: main-dark-color)[#h(10pt) *#title*] ] parbreak() } #let problem-tag(tags) = { set text(font: "Minion Pro", fill: white) v(0.5em) for tag in tags { box( fill: main-dark-color, inset: (x: 3pt, top: 3pt, bottom: 5pt) )[*#tag*] h(1em) } parbreak() } // Main body //------------------------------------------------------------------------------ // Problem #1 #problem-heading(1, [Minimum Value]) Let there be a set of $N$ natural numbers $1, 2, 3, dots, N$. We are allowed to insert $+$ or $-$ sign in front of each number and add all the resultant numbers. The minimum non-negative value obtained is denoted as $D(N)$. Find the value of $D(1) + D(2) + dots.c + D(19216812112)$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #2 #problem-heading(2, [Equation]) Let $x$ and $y$ be positive real numbers. Using the equation $y^6 = x^6 + 8x^4 - 6x^2 + 8$, find the integral value of $3345x + 4321y^2$. Your answer should not exceed $10^7$. #problem-tag(("number theory", "polynomial")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #3 #problem-heading(3, [Largest Number]) Find the positive integer $n$ less than $100000$ for which the equation $x^2 = n y^2 + 1$ has the largest fundamental value of $x$. The fundamental value of $(x,y)$ is the smallest positive non-trivial integral solution to the equation. $(1,0)$ is the trivial solution. *Note:* You can ignore those values of $n$ for which there are no fundamental solution to the given equation. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #4 #problem-heading(4, [Palindromes]) Find the sum of numbers less than or equal to $1000000000$ which are palindromes in binary, octal as well as hexadecimal base. #problem-tag(("number theory", "palindrome")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #5 #problem-heading(5, [3 Musketeers]) There are $3$ people A, B and C. Three of them have positive integers written on their hats. One can only see the numbers written on others hats and can not see the number written on his own hat. The number on one of the hats is the sum of the numbers on the other $2$ hats. Now the following event occurs - A was asked about the number on his hat. He replies "Don't know". - B was asked about the number on his hat. He also replies "Don't know". - C was asked about the number on his hat. He also replies "Don't know". - A was asked again the number on his hat. He replies "$65$". Find the product of the three numbers on the hats. #problem-tag(("number theory", "implementation")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #6 #problem-heading(6, [Sum It Up]) Let $A$ be the sum of digits of $3334^3334$ when written in decimal notation and $B$ be the sum of digits of $A$. What is the value of $2013$ times sum of digits of $B$? #problem-tag(("number theory", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #7 #problem-heading(7, [Exponentiation]) $f(x,n) = x^2^1 + x^2^2 + x^2^3 + dots.c + x^2^n.$ You are given that $f(2,10) mod 1000000007 = 180974681$. Calculate $(sum_(x=2)^(10^7) f(x,10^18)) mod 1000000007$. #problem-tag(("number theory", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #8 #problem-heading(8, [Summation of Primes]) Find the sum of digits of all prime numbers below $10^9$. #problem-tag(("number theory", "primes")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #9 #problem-heading(9, [Highly Divisible Number]) What is the smallest number to have over $300$ divisors? #problem-tag(("number theory", "divisors")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #10 #problem-heading(10, [Number Spiral Diagonals]) Starting with the number $1$ and moving to the right in a clockwise direction a $5 times 5$ spiral is formed as follows: #text(fill: main-dark-color, weight: "bold")[ ``` 21 22 23 24 25 20 07 08 09 10 19 06 01 02 11 18 05 04 03 12 17 16 15 14 13 ``` ] It can be verified that the sum of the numbers on the diagonals is $101$. What is the sum of numbers on the diagonals in a $10001 times 10001$ spiral formed in the same way? #problem-tag(("path traversal", "matrices")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #11 #problem-heading(11, [Factorial]) Find $1000000008!$. Give the answer modulo $1000000009$. #problem-tag(("number theory", "modular", "primes")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #12 #problem-heading(12, [Prime Gaps]) A prime gap is the difference between two successive prime numbers. The $n$#super[th] prime gap is the difference between the $(n+1)$#super[th] and the $n$#super[th] prime numbers. Using *12.txt* #text(fill: main-dark-color)[#footnote[ Source: #link("https://erdos.sdslabs.co/storage/files/problems/12.txt")[#text(fill: main-dark-color)[https://erdos.sdslabs.co/storage/files/problems/12.txt]]. This file is also attached to this PDF. ]], find the largest prime gap for all the primes in the file. #problem-tag(("number theory", "primes")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #13 #problem-heading(13, [Pandigital Primes]) A number is said to be pandigital if it contains each of the digits from $0$ to $9$ (and whose leading digit must be nonzero). Find the smallest pandigital prime number. #problem-tag(("number theory", "primes", "pandigital")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #14 #problem-heading(14, [Count Fibonacci]) Find the number of Fibonacci numbers in the file *14.txt* #text(fill: main-dark-color)[#footnote[ Source: #link("https://erdos.sdslabs.co/storage/files/problems/14.txt")[#text(fill: main-dark-color)[https://erdos.sdslabs.co/storage/files/problems/14.txt]]. This file is also attached to this PDF. ]]. #problem-tag(("number theory", " fibonacci")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #15 #problem-heading(15, [Blind Fold]) In a game, played between $2$ players there is a circular field and one of the players is blindfolded, who stands in the center of the field. The other player stands at a fixed point on the circumference of the circular field. On the word *GO*, the blind-folded player starts running towards the edge of the field while the second player's aim is to run in and catch him before he moves out of the circle. If the blind-folded player runs in a random direction with a constant speed $v$ while the second player runs towards the first player with a constant speed $m$ times $v$, what should be the value of $m$ such that the probability that the second player wins is $0.50$? Report answer as $10^6 m$. If answer is not an integer, round it off to the nearest integer. #problem-tag(("probabilities", "calculus")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #16 #problem-heading(16, [GCD]) Find the Greatest Common Divisor of $2^10^10 - 1$ and $2^8^8 - 1$. Since the answer can be very large, enter the answer modulo $1000000007$. #problem-tag(("number theory", "gcd")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #17 #problem-heading(17, [Magical Matrix]) Let $0 < t < u < v$, where $t$, $u$ and $v$ are integers. Now, there is a matrix $Q$ with three rows and $c$ columns where $c > 1$. The matrix is special in a way that each of its columns contains the three numbers $t$, $u$ and $v$ in some order. All the $3$ numbers must appear in every column. Sum of all numbers in row $1$ is $20$, sum in row $2$ is $10$ and in row $3$, the sum is $9$. The rows are numbered $1, 2, 3$ while columns are numbered $1, 2, dots, c$ and each cell in the matrix is denoted by a pair $(i,j)$, where $i = "row"$ and $j = "column"$. Now the cell $(2,c)$ contains $v$. Calculate $sum(Q_(i,j) times (i+j))$ for the whole matrix. #problem-tag(("matrices",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #18 #problem-heading(18, [Game]) Sandeep and Varun are playing a series of games. Each of them contributes Rs $1000$ to start. Varun's chance of winning an individual game is $3$ times that of Sandeep's. They make an agreement that whoever wins $5$ games first can take the entire money with him. After first $3$ games, Varun has won $1$ game and Sandeep has won $2$ games. Now they are bored and do not want to play further. So they want to divide the money on the basis of the result of first $3$ games. Let $x$ be the money Varun gets and $y$ be the money Sandeep gets. Find $x^y$. If $x$ and $y$ are not integers, round them to nearest integer. Since answer can be very large, enter the answer modulo $10^9+7$. #problem-tag(("probabilities", "expectation value")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #19 #problem-heading(19, [Large Exponentiation]) Find the smallest natural number $n$ for which $201413^n mod 2097152 = 1$. Since $n$ can be very large, enter answer as $n mod 1000000007$. #problem-tag(("number theory", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #20 #problem-heading(20, [Fives and Sevens]) How many $20$-digit numbers are there which are formed using only the digits $5$ and $7$ and divisible by both $5$ and $7$. #problem-tag(("number theory", "divisors", "combinatorics")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #21 #problem-heading(21, [Two Squares]) You are given $2$ squares such that sum of their area is $1$. You want to fit these $2$ squares inside a rectangle, without overlap, such that sides of the rectangle are parallel to the sides of the squares. Find the area of smallest such rectangle for which we can always fit the $2$ squares as per the given constraints. Enter answer as $10000000 times "area"$. In case the answer is not an integer, return the answer rounded off to the nearest integer. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #22 #problem-heading(22, [Totient Function]) Let $X$ be the smallest number having $phi.alt(X)$ equal to $10^8$. Find the number of digits in the factorial of $X$. $phi.alt$ stands for Euler's Totient Function. #problem-tag(("number theory", "totient")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #23 #problem-heading(23, [Crack The Safe]) There is a safe with its $10$-digit keypad (as shown below) which is to be cracked. #text(fill: main-dark-color, weight: "bold")[ ``` 9 8 7 6 5 4 3 2 1 0 ``` ] The restriction of the password for that safe is that every pair of neighboring keys in the password is adjacent on the keypad. Adjacent keys are the ones that share a common edge. You know that the password is $10^9$ digits long. Let total number of possible passwords for this safe be $X$. Since $X$ can be very large, enter $X mod 10^9+7$. #problem-tag(("implementation",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #24 #problem-heading(24, [Tangles]) We define the _LEVEL_ of a triangle as in the following image: #align(center)[ #v(5pt) #include "figures/p24_1.typ" #v(5pt) ] Similarly we can define the _LEVEL_ of a hexagram. It's called level $n$ hexagram if it's joined by $12$ triangles, each one is a level $n$ triangle. #align(center)[ #v(5pt) #include "figures/p24_2.typ" #v(5pt) ] Let us define $X(n)$ as the total number of triangles in a level $n$ hexagram. Then $X(n)$ can be written as a polynomial in terms on $n$. Let $Y$ be the product of non-zero coefficients of polynomial $X(n)$. Find the factorial of $Y$. Since answer can be very large, enter the answer modulo $10^9+9$. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #25 #problem-heading(25, [Butter’s Prime Floor]) Let there be functions $f(N) = $ no. of primes $x <= N$ and $g(N) = integral_2^N (dif x)/ln(x)$. Find the value of $floor(g(10^22) - f(10^22))$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #26 #problem-heading(26, [Cartman’s Challenge]) How many polynomials are there of degree $59$ with leading coefficient $1$ which cannot be factored in the field of \ #text(size: 10.5pt)[$4113101149215104800030529537915953170486139623539759933135949994882770404074832568499$]? If your answer is $x$ then input $x mod 1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #27 #problem-heading(27, [When Kenny Guesses]) Let there be an expression $p(x) = floor(theta^3^n)$. The task is to approximate the value of $theta$ so that it gives prime for values from $n = 1$ to $n = 12$. Give the answer correct upto $14$ decimal places. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #28 #problem-heading(28, [Mrs Cartman’s Desire]) Mrs Cartman likes rotational symmetry (everything which is symmetric about the centre). She had a long cherished desire of playing chess. So <NAME> challenges her to solve the following puzzle: She is asked to arrange the non-attacking rooks on the chessboard according to Mrs Cartman's fantasies, only if possible. She is given chessboards of different sizes ($n times n$) and asked what are the total number of ways of arranging $n$ rooks if $n$ varies from $1$ to $61$. Give the answer modulo $1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #29 #problem-heading(29, [Mr. Garrison Prepares for the Night]) Suppose that Mr Slave wants to buy $n$ sandals $s_1, s_2, s_3, s_4, dots, s_n$ and $n$ dresses $d_1, d_2, d_3, d_4, dots, d_n$, where $s_i$ is a must to have bought before buying $s_(i+1)$ and the same with $d_i$. Let the ordered ways to add these $2n$ things to the girl's clothing be $a(n)$, $n$ varies from $1$ to $60$. So calculate #[ #show math.equation: it => [#set align(left); #it] $ inline( a(1) (((2207 + 987 sqrt(5))/2)^(1/16) + ((24476 - 10946 sqrt(5))/2)^(1/21)) + a(2) (((24476 + 10946 sqrt(5))/2)^(1/21) + ((5778 - 2584 sqrt(5))/2)^(1/18)) + \ a(3) (((5778 + 2584 sqrt(5))/2)^(1/18) + ((76 - 34 sqrt(5))/2)^(1/9)) + a(4) (((76 + 34 sqrt(5))/2)^(1/9) + ((47 - 21 sqrt(5))/2)^(1/8)) + dots.c + \ a(60) (((1860498 + 832040 sqrt(5))/2)^(1/30) + ((7881196 - 3524578 sqrt(5))/2)^(1/33)) ) $ ] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #30 #problem-heading(30, [Respect My Authoritah!]) The wizard Cartman decides to color a torus with colors. Let the minimum number of colors required to color the $n$-holed torus be $m(n)$. He has a cube of iron. He asks the blacksmith token to cut it (as in a laser plane is passing through the cube) $n$ times. Let the number of different parts of the cube generated be $x(n)$. But he loves to work with prime numbers and so wants $x(n) - k$ and $x(n) + k$ to be prime. Let the smallest $k$ required to accomplish it be $f(n)$. Your task is to find out $sum_(n=2)^15 (m(n) times f(n))^n$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #31 #problem-heading(31, [When Butter Sums It Up]) The positive real numbers $x_0, x_1, x_2, dots, x_m$ satisfy $x_0 = x_m$ and $x_(i-1) + k/x_(i-1) = k x_i + 1/x_i$. Let $x_0(k,m)$ be its maximum possible value of $x_0$. If $k = 2$ and $m = 59$, find the summation of such $x_0(k,m)$ when you increase $k$ by $1$ and at the same time decrease $m$ by $2$ till both become equal. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #32 #problem-heading(32, [Japanese Robo Awesome-O]) Professor Chaos controls the robot Awesome-O by pressing the forward or back button. He presses the forward button $n$ times and the back button $n$ times, one at a time. It returns back to him after he presses the buttons $2n$ times. Let $a(n,i)$ be the number of ways such that the number of moves in the forward direction do not exceed the number of moves in the backward direction and the number of positive moves in the forward direction equals the number of positive moves in backward direction _exactly_ for $i$ times. Given $a(3,1) = 2$, $a(3,2) = 2$ and $a(3,3) = 1$. Professor Chaos enters an $n times n$ square board. He can traverse from $(0,0)$ to $(n,n)$ in all possible ways but is restricted to $(1,0)$, $(0,1)$ and $(1,1)$ directions only. Let $b(n)$ be the number of steps _on line_ $x = y$ in _all_ possible paths on which Chaos can travel. Given $b(2) = 6$. Let $f(n) = sum_(i=1)^n a(n,i)^2$. Find $sum_(n=1)^10 f(n) times b(n)$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #33 #problem-heading(33, [Angriff der Nazis]) In the quiet little mountain town of South Park, there is a square wheat farm $A B C D$ (sides parallel to N-S & E-W directions) with $A$ being towards North-West and $A\-B\-C\-D$ being in clockwise order. The town is attacked by Nazi Bombers and $5$ bombs are dropped on the field. Each bomb burns the crop in a radius of $12$ km. First bomb is dropped at a point $O$ such that $A O$ is $34$ km, $B O$ is $40$ km and $C O$ is $26$ km. Other bombs are dropped $10$ km north, $15$ km south, $30$ km east and $27$ km west, respectively of $O$. Find the area of unburnt crop in the farm rounded upto $3$ decimal places. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #34 #problem-heading(34, [Jewish Factorials]) Find in how many ways can we write $100!$ as a sum of two or more consecutive positive numbers. Give the answer $mod 1000000009$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #35 #problem-heading(35, [Cartman’s Large Growing Sequence]) Consider the fraction $(A K A)/(L O L) = 0.D B U G D B U G D B U G dots.c$. This is a normal fraction which can be written as recurring decimals. Here, the same alphabets stand for the same digits. Find the sum $S$ of all such fractions with distinct values of the fraction. $S = p/q$ in its most simplified form. Answer $p times q$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #36 #problem-heading(36, [What’s the Answer Makey?]) Mrs. Broflovski, Kyle's mother asked Mr. Makey, "Kyle was visited by three wizards today. If you multiply their ages, you'll get $2450$, and together their age is $2$ less than your age. Can you tell me their ages?" After deep thought, the teacher said "No, I can't." Then Mrs. Broflovski said, "Of course you can't, but if I tell you that the oldest wizard is older than Kyle, you should be able to work out." Give the sum of cubes of ages of the three wizards as well as Kyle. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #37 #problem-heading(37, [The Allowance Problem]) Stan gets his allowance on the $15$th day of every month, he gets $1$ dollar if its a Monday, $2$ dollars if it's a Tuesday, $3$ dollars if its a Wednesday and so on ... $7$ dollars if it's a Sunday. Then on a particular $15$th of a random month, find the expected value $e$ of the money Stan will be receiving. Give the integer after ignoring decimal in $e times 1000000$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #38 #problem-heading(38, [When Mr. Garrison Teaches Geometry]) A hexagon with area $A$ and consecutive sides of lengths $8$, $10$, $8$, $10$, $12$ and $12$ is inscribed in a circle. Let $N = 100A$, ignoring the decimal part which may be represented as $x^k y$, where $x, y, k > 1$. Take $Y$ as the average of all possible $y$s in the above expression and find the $Y$#super[th] prime number. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #39 #problem-heading(39, [XOR ’em Up]) Say $f(n) =$ bitwise XOR of all natural numbers up to a positive integer $n$. Find $f(2^2013) mod 1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #40 #problem-heading(40, [Kyle’s Mysterious Sequences]) For a given integer $n$, Consider the following functions $G(n)$ and $F(n)$ $ G(n) &= sqrt(F(n) - (n-1)^2/n^2 F(n-1) + 1/n^2) \ F(n) &= 8 + (n-2)^2/n^2 F(n-2) \ F(1) &= F(2) = 8 $ Now consider the sequences $ Y(n) &= sum {x | 0 < x < n, n mod x = 0} \ Z(n) &= Z(n-1) + Y(n) \ Z(0) &= Z(1) = 0 $ Find the value of $Z(1/(G(1000000000)-2))$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #41 #problem-heading(41, [Cartman Loves One Direction]) Find the number of occurrences of the digit $1$ in all natural numbers between $123456789$ to $1234567890$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #42 #problem-heading(42, [Medical Marijuana]) Men in South Park are suffering from vulva cancer and are getting doctor's reference for medical marijuana. The demand for the same has gone up. A transport company handling the shipments has $n$ identical articles which are to be shipped in $k$ identical trucks. You simply have to find the total number of ways of distribution of those articles in the trucks. Compute for $n = k = 10000$. Answer $mod 1000000007$. #problem-tag(("number theory", "integer partition", "dp")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #43 #problem-heading(43, [Game of Stacks]) Drake and Josh play a game to take a break from programming. In this game, there is a stack of $N$ sheets. Drake starts first and alternating turns, they remove an odd number of sheets in each turn and put them in a basket which is initially empty. After every turn they note down the count of the sheets in the basket and thus construct an increasing sequence of numbers. But then, Drake wonders, how many distinct games of this kind can they play such that the stack gets empty at last and there are exactly $k$ numbers in the sequence i.e. the game ends after k turns. Josh answers this when $N$ and $k$ were small. But now Drake who is also good in Mathematics asks you the same question with slight complications: $N = 999999$ and $k = 5^p$ can be any number where $(2^(p-1)-1)/p$ is a perfect square, i.e. you have to take the sum for all such $k$! Give your answer $mod 10^9+7$. Note that distinct games generate distinct sequences. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #44 #problem-heading(44, [Power Sum]) Let $k = 4128^6 + 6^4128$. What is $sum_(n=1)^17040384 ("units digit of" k^n + n^k)$? #problem-tag(("number theory", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #45 #problem-heading(45, [One of Us]) Let $a(n)$ be defined as the number of terms in the sequence $2^1,2^2, dots, 2^n$ which begin with digit $1$. Find $lim_(n arrow infinity) a(n)/n$. Give your answer as the largest integer after multiplying by $10^6$. #problem-tag(("calculus",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #46 #problem-heading(46, [When Butter Recurses]) Let us define a series $M$ such that $M(n-1) + M(n+1) = 5F(n)$ where $F(n)$ is the $n$#super[th] term of the Fibonacci sequence with $F(0) = 0$, $F(1) = 1$ and $M(0) = 2$. Find the value of $product_(n=1)^9 M(2^n)$. Give answer $mod 1000000007$. #problem-tag(("number theory", "fibonacci")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #47 #problem-heading(47, [Stan’s Prime Challenge]) What is the number of primes of the form $4k+3$ between $8589934592$ and $17179869184$? #problem-tag(("number theory", "primes")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #48 #problem-heading(48, [Mr Garrison Can’t Get a Period]) Consider $F(n)$ as the last $8$ digits of the $n$#super[th] Fibonacci number. What is the period of $F(n)$? #problem-tag(("number theory", "fibonacci")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #49 #problem-heading(49, [Hyper Sum of Fibonacci Numbers]) Let $F(n)$ be the $n$-th Fibonacci number. That is, $F(n)$ satisfies \ $F(0) = 0, quad F(1) = 1, quad F(n) = F(n-1) + F(n-2) "(if" n >= 2")"$. Let $f_k (n)$ be the function such that \ $f_0(n) = F(n), quad f_k (n) = sum_(i = 1)^n f_(k-1) (i) "(if" k >= 1")"$. You are given that $f_1 (1) = 1$, $f_2 (2) = 3$ and $f_10 (10) = 130965$. Find $f_(10^8)(10^8) mod 1000000007$. #problem-tag(("number theory", "fibonacci", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #50 #problem-heading(50, [Divisibility]) Find the base of a counting system, like decimal($10$), binary($2$) etc., less than $1000000$ in which maximum numbers follow the following property: "If $x$ is divisible by $y$, sum of digits in $x$ will also be divisible by $y$." In case there is more than 1 possible answer, then concatenate the possible answers in ascending order without any spaces in between. For example if the answers are $3$, $21$ and $54$ then your answer should be $32154$. #problem-tag(("number theory", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #51 #problem-heading(51, [Probability of Squares]) Two numbers are chosen at random from $1$ to $10^16$. Let $p$ be the probability that their sum is a perfect square. Find integral part of $10^16 p$. #problem-tag(("probabilities",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #52 #problem-heading(52, [Modular Roots]) Let $y = x * x$. Where $*$ is multiply modulo $N = 4776913109852041418248056622882488319$. You have to find the smallest positive $x$ for $y = 739397$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #53 #problem-heading(53, [Harry and his Magical Boxes]) There are $7$ magical boxes each containing a label depicting a number. The labels of the boxes are given as $5,2,7,8,7,4,6$. <NAME> goes to each jar once and shouts a spell. When Harry shouts a spell near a box with label $x$ he gets a random integer $n$ from the box such that, $1 <= n <= x$. Thus he gets a collection of seven numbers by shouting once near each box. One such collection is $4,2,1,2,6,4,6$. Two collections are same if one is a permutation of other. So $1,2,1,1,1,1,6$ is same as $2,1,1,1,1,1,6$. Now Harry expects you to tell the total number of different collections he can get by repeatedly performing this act. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #54 #problem-heading(54, [Find Tuples]) Let $S$ denote the set of all $6$-tuples $(X_1,X_2,X_3,X_4,X_5,X_6)$ of positive integers such that \ $X_1^2 + X_2^2 + X_3^2 + X_4^2 + X_5^2 = X_6^2$. Consider the set $T = {X_1 X_2 X_3 X_4 X_5 X_6: (X_1,X_2,X_3,X_4,X_5,X_6) in S}$. Find the *HCF* #text(fill: main-dark-color)[#footnote[ Highest Common Factor. ]] of all members of $T$. #problem-tag(("number theory", "gcd")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #55 #problem-heading(55, [Double Devils]) All numbers of the form `6_6_6_0_0_6_6_6_0_0`, where each `_` can be any single digit, are called double devil numbers (for example, $6160630507696864040$ is a double devil number). Let $x$ be the unique number whose square is a double devil number. Find $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #56 #problem-heading(56, [Playing with Subgraphs]) Find the number of distinct sub-graphs of a complete graph of $n$ labelled vertices, such that the sub-graph is a spanning tree connecting all the vertices and the degree of no vertex is more than $3$. Given $n$ equals $314159$, give your answer $mod 1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #57 #problem-heading(57, [Smallest Perimeter]) The sides of a triangle have integer lengths $k$, $m$ and $n$. Assume that $k > m > n$ and ${3^k/10^4} = {3^m/10^4} = {3^n/10^4}$. where ${x}$ denotes the fractional part of a number. Determine the minimum value of the perimeter of the triangle. #problem-tag(("number theory", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #58 #problem-heading(58, [Circle of Death]) Let $n$ be $10$ times the largest integer which cannot be represented as the sum of five non-zero perfect squares. Now, consider yourself standing in a circle of $n$ people (positioned 1 to $n$ around the circle), where every $k$#super[th] ($k = 10$) person is killed from the remaining ones standing except the last one. For example, if $n = 4$ and $k = 2$, then the order in which people will be killed is $2, 4, 3$. Hence person at position $1$ will be the survivor. Let $p$ be the position you will choose so as to survive this game (be the last to be killed). Also, for $n = 40$, let $q$ be the smallest value of $k$ ($>1$) for which people are killed in the same order as they are standing (i.e. $1, 2, 3, dots$). What is $(p times q) mod 1000000009$? #problem-tag(("number theory", "dp")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #59 #problem-heading(59, [Ones and Zeros]) Let $S = 2^a + 2^b + 2^c + 2^d + 2^e$ where $a,b,c,d,e$ are distinct whole numbers. Let $S_n$ be the $n$#super[th] number such that for all $i < n$, $S_i < S_n$ and for $i > n$, $S_i > S_n$. Find $S_2131646 mod 10^9+7$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #60 #problem-heading(60, [Rolling Dice]) Alex has a $7$-sided regular dice. Every side has a distinct value between $1$ to $7$, each with equal probability of coming up in a roll. Alex rolls the dice once. Let the value obtained be equal to $S_1$. Now he rolls the dice $S_1$ number of times. Let the sum of values obtained in these $S_1$ rolls be equal to $S_2$. Now he rolls the dice $S_2$ number of times. Let the sum of the values obtained in these $S_2$ dice rolls be equal to $S_3$. This process is continued for an infinite number of times. Find the expected value of $S_1182014$. If the answer is $x$, give your answer as $floor(x) mod 10^9+7$, where $floor(x)$ denotes the greatest integer less than or equal to $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #61 #problem-heading(61, [Derangements]) There are $n$ people and $n$ houses, such that every person owns exactly one distinct house. Out of these $n$ people, $k$ people are special ($k <= n$). You have to send every person to exactly one house such that no house has more than one person, and no special person goes to his own house. Let $S(n,k)$ be the number of ways of doing this. Find the value of $S(654321,123456)$. Give your answer $mod 10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #62 #problem-heading(62, [Magic in Boxland]) A magician lives in a mysterious Boxland that comprises of eight cities and all of them contain $6$ magic wands. Each wand has been colored with one of $n$ colors, such that no two wands in the same cities are of same color, and no two colors occur together in more than one city. The smallest number $n$ that satisfies this condition is used by the magician to create a ball-box challenge that contains a 2-D array of size $n times n$ of such boxes placed adjacent to each other satisfying following conditions: - Every box that does not contain a ball shares a side with one which does. - Given any pair of boxes that contain balls, there is a sequence of boxes containing balls, starting and ending with the given boxes, such that every two consecutive boxes of the sequence share a side. Find the smallest number of balls that must be there inside those boxes multiplied by $3$. (i.e. $"Answer" = ["Total number of balls inside the array of boxes"] times 3$) #problem-tag(("combinatorics", "graphs", "greedy")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #63 #problem-heading(63, [Seat Yourself]) Let $x$ be the number of students seated around a round table. Then, let $k$ be the number of ways in which they change their seats resulting in an arrangement in which the students are either on the same seat or one of the seats adjacent to the original one. Given that $x$ belongs to the set $(123345857,343139869)$, both not included, find the possible number of values of $k$ which are congruent to $111 mod 5$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #64 #problem-heading(64, [Polynomials]) Consider a polynomial of degree $3m$ such that \ $P(0) = P(3) = P(6) = dots.c = P(3m) = 2$ \ $P(1) = P(4) = P(7) = dots.c = P(3m-2) = 1$ \ $P(2) = P(5) = P(8) = dots.c = P(3m-1) = 0$ \ and $P(3m+1) = 6562$. Find the value of $m$? //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #65 #problem-heading(65, [Identical Boxes]) You are given $2500$ identical boxes and $5000$ identical balls. Find the number of ways in which balls can be distributed such that each box contains at least one ball. Assume the capacity of each box to be infinite. Give your answer $mod 10^9+7$. *Note:* All permutations of boxes are counted as a single way as the boxes are identical. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #66 #problem-heading(66, [Reaching Point]) You have to reach point $(x_2,y_2)$ from $(x_1,y_1)$ by making jumps from one point to another but you have some limitations. You can only move in the direction of the line connecting these two points constantly aiming towards the destination point. Also from one point you can jump to only the next most nearest integral point on the line. For example, $(3,3)$ to $(6,6)$ then path has to be $(3,3) arrow (4,4) arrow (5,5) arrow (6,6)$ and this required $3$ jumps. But now the problem is the a jump comes at a heavy cost. If the total number of jumps made to reach $(x_2,y_2)$ starting from $(x_1,y_1)$ is $n$, then the total cost for the journey is said to be the $("number of trailing zeroes in" n!)^n$. Find the total cost for the journey from $(-10101099, 127898755387)$ to \ $(1137947000140424, 1607032990556) mod 10^9+7$. #problem-tag(("number theory", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #67 #problem-heading(67, [Finding Limits]) $ S_0 &= 3 \ S_1 &= 33 \ S_i &= S_0^(S_(i-1)) "for" i > 1 $ Find $S_x mod 1073741824$ where $x$ tends to infinity. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #68 #problem-heading(68, [A Mixture of Ryski’s Problems]) Ryski was asked compute the sum of the series $ sum_(k=0)^infinity 1/((4k+1)(4k+2)(4k+3)(4k+4)). $ Let this summation be $p$. Ryski also has $2n$ different pens ($n in N, n >= 2$). Each day, he takes $n$ pens with him to school. After some days the following condition was fulfilled: every two pens were together on at least one day. Let the minimum number of days needed for this to happen be $q$. Give the answer as $[p times q times 10^20]$, where $[x]$ denotes the greatest integer less than or equal to x. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #69 #problem-heading(69, [Trio Interchange]) There is a six digit number, which when multiplied with $6$, yields another six digit number, with first three digits of original number as the last three digits of the new number, in the same order, and the last three digits of the original number as the first three digits of the new number, in the same order. Let $S$ be the sum of the digits of that number. Find $S! mod 1000000007$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #70 #problem-heading(70, [Fibonacci Circle]) #align(center)[ #v(5pt) #include "figures/p70.typ" #v(5pt) ] All circles in the picture above are tangent to each other. If radius $R_1 = 2^12$, $R_2 = 2^11$ and $R_3 = 2^10$, calculate $r$, radius of the inner yellow circle. Let $x = floor(r) times 10^14$. We now define a new sequence as \ $F(n) = F(n-1) + F(n-2) + (n-1) quad forall n >= 2$ \ with $F(0) = 0$ and $F(1) = 1$. Calculate sum $(F(0) + F(1) + F(2) + dots.c + F(x-1) + F(x))$ $mod 1000000007$. #problem-tag(("number theory", "geometry")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #71 #problem-heading(71, [Random Selector]) A random number selector can only select one of the nine integers $1, 2, dots, 9$, and it makes these selections with equal probability. Let $p$ be the probability that after $n$ selections ($n > 1$), the product of the $n$ numbers selected will be divisible by $10$. If $n = 5$, find $59049 p$. #problem-tag(("probabilities",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #72 #problem-heading(72, [GitHub]) You are given six characters `G`, `I`, `T`, `H`, `U`, `B` to make a string of length $N$. However there are some limitations: - `I` can not come directly after `G`. - `H` can not come directly after `G` or `B`. - `T` can not come directly after `T` or `U`. - The string should be a palindrome. How many ways are there to form a string of length $N = 7162534$? Submit the answer modulo $1000000007$. #problem-tag(("dp",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #73 #problem-heading(73, [Brute]) $ x^6 + x^3 + x^3 y + y &= 147^157 \ x^3 + x^3 y + y^2 + y + z^9 &= 157^147 $ Let $n$ be the number of solutions for the above system. i.e. if $x = a, y = b, z = c$ is a solution then the number of solutions is incremented by $1$. Give your answer as first six digits of $(n + upright(e))^134$. #text(fill: main-dark-color)[#footnote[ The constant $upright(e)$ is base of the natural logarithm. ]] #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #74 #problem-heading(74, [Mod It]) Let $n$ be the largest positive integer, such that $n!$ can be expressed as the product of $(n - 2014^2015)$ consecutive integers. Let $x$ be equal to $n mod 38980715857$. Find $x mod 8037517$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #75 #problem-heading(75, [No Primes]) Find sum of all $5$-digit natural numbers such that they don't contain any subsequence forming prime number. $2$, $3$, $4$ or even $5$-digit prime numbers are not allowed. #problem-tag(("brute force",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #76 #problem-heading(76, [Erdős]) Given that $e, r, d, o, s$ are real numbers such that \ $e + r + d + o + s = 8$ \ $e^2 + r^2 + d^2+ o^2 + s^2 = 16$ Let $M$ be the maximum value of $s$. Find the number of factors of $30 M$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #77 #problem-heading(77, [Prime Fangs]) In mathematics, a vampire number is a composite natural number $v$, with an even number of digits $n$, that can be factored into two integers $x$ and $y$ each with $n/2$ digits and not both with trailing zeroes, where $v$ contains precisely all the digits from $x$ and from $y$, in any order, counting multiplicity. $x$ and $y$ are called the fangs, e.g. $1260 = 21 times 60$. A prime vampire number is a vampire number whose fangs are its prime factors. $117067 = 167 times 701$ is the first prime vampire number. Calculate the $27$th prime vampire number. #problem-tag(("brute force",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #78 #problem-heading(78, [Golden Path]) Let $x$ be a number such that for $n > x$, the $n$th Fibonacci number has at least one prime divisor that does not divide any $k$th Fibonacci number for all $k < n$. Find the sum of all primes $p < 10^x$ such that for some integer $n$, the expression $n^2 - p times n$ is a prime power. *Note:* A prime power is a number of the form $q^m$ where $q$ is a prime and $m$ is a positive integer. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #79 #problem-heading(79, [Strings]) <p79> Laertes and Roxane play a game together by first drawing a string of `L`s and `R`s into the sand, and then taking turns removing any one of their respective letters (`L` for Laertes and `R` for Roxane) along with the substring to its right. The first player unable to make a move loses the game. Consider the game played with the string `L`. If Laertes goes first, he removes the only `L` and passes to Roxane, who immediately loses, having no valid move. If Roxane goes first, she immediately loses again. So we see that Laertes always has at least one move's worth of an advantage over Roxane. We shall abbreviate this by saying the value of the string `L` is $+1$, from Laertes' point of view. Similarly, the string `R` has value $-1$. A game played with the two separate strings, `L` and `R` (denoted by `L` $+$ `R`) can be shown to have the property that the first player to play loses the game. We shall call the value of such a string $0$, and denote this as `L` $+$ `R` $=0$. Convince yourselves that `LR` $= 0.5$ (try playing the game with `LR` $+$ `LR` $+$ `R`). What is the value of `LRL`? #problem-tag(("strings",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #80 #problem-heading(80, [Piles of Stones]) Laertes and Roxane play another game now as they are tired of drawing in the sand. Instead, they play a game with piles of stones that works as follows: At the beginning of each turn, the player first chooses one of the piles and then removes some number of stones from it (the whole pile may be removed as well, but at least one stone needs to be removed). The turn then passes to the next player. The player that removes the last stone(s) wins. Laertes always goes first. Convince yourself that in a game with three piles of $3$, $4$, and $5$ stones respectively, Laertes will always win if he plays optimally, no matter what Roxane does. Let's say that games with this property have value $1$. Consider $6561$ separate games, with four piles, and the number of stones per pile varies between $1$ and $9$. How many of these games have value $1$? #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #81 #problem-heading(81, [Hide and Seek]) <p81> Laertes and Roxane go to the Senate to play a game of Hide-and-Seek. There are $100$ rooms in the Senate, and Roxane picks one of them and hides there till the game ends. Laertes, at the beginning of every turn, picks one room and searches in it. Since he is human and thus fallible, he only has a $60%$ chance of finding Roxane if she is in fact hiding in the room. If he fails to find her in the room, Roxane's score increases by _one_, and the next turn starts, whereupon Laertes must pick another room to check (he can also check the same room again). Remember, Roxane remains in the room she initially chose. Given that Laertes and Roxane play with perfect strategies, what is the expected value of Roxane's score at the end of the game? The answer must be correct to $1$ place of decimal. #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #82 #problem-heading(82, [Pebble Trouble]) Laertes and Roxane play a game with some black and white pebbles at the beach. They dig twelve small pits in the sand, making a dodecagon. Laertes will place two stones, one black and one white into two adjacent pits in such a way that the white stone is to the left of the black. Laertes cannot then place any stones in the pits next to these. Similarly, Roxane places her stones so that the white one is to the right of the black one. She too cannot use the adjacent pits ever again. The first person who is unable to place their pair of stones loses. If Laertes goes first, convince yourselves that Roxane can always win with perfect play. Consider $1000$ games where the number of pits in the sand varies from $12$ to $1011$. How many of these games can Roxane always win, if Laertes goes first each time? #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #83 #problem-heading(83, [Fresh from the Oven]) Laertes and Roxane have before them a cake, freshly baked by their mother. It has been lightly scored so as to allow it, when cut, to be divided into $M times N$ pieces. The two kids decide to play a game to cut the cake. Laertes will cut any rectangle into two pieces along the vertical lines, and Roxane along the horizontal lines. The game ends when the first who is unable to make a move loses. Laertes always goes first. Consider $256$ games with cakes varying in size from $1 times 1$ to $16 times 16$. How many of these games can Laertes always win, if he plays with perfect strategy? #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #84 #problem-heading(84, [The Gobbler]) <p84> Laertes and Roxane are tired of cutting cakes. They want to eat some now, and they do so by playing a game as follows: On his turn, Laertes must choose any square on the grid and eat it, along with the square immediately below it. On her turn, Roxane must choose any square on the grid and eat it, along with the square to its immediate right. The first person who cannot eat two pieces as described above on any turn loses. Let us describe the squares using the conventional matrix coordinate scheme, with the top-left square being $(0,0)$ and the positive $x$ and $y$ axes extend to the right and down respectively. In cases where taking two different squares results in the same cake upto symmetry, then the square that is closest to the origin is preferred. If the square is still ambiguous, then the one that is closer to the $x$ axis is preferred. Consider the $2 times 1$ cake. It is obvious that no matter who goes first, Laertes can always win by eating the square at $(0,0)$ (and so consequently $(1,0)$). The $2 times 2$ cake is different though. Convince yourself that the first person to start will win, no matter who it is. What are the optimal squares chosen by both players on a $4 times 2$ cake? Assume that Laertes goes first. If you think the sequence is $(a,b), (c,d), (e,f)$, enter $bold(a b c d e f)$. #problem-tag(("games",)) //------------------------------------------------------------------------------ // Problem #85 #problem-heading(85, [The Stymphalean Birds]) #text(size: 14pt)[*The story*] The Stymphalean birds were monsters. They were man-eating birds with beaks of bronze and sharp metallic feathers they could launch at their victims. They had destroyed the local crops and fruit trees before Hercules was tasked with killing them. Athena gave Hercules a rattle that he could use to scare the birds off so he could then shoot them down with his bow. #text(size: 14pt)[*The game*] It turns out that shaking the rattle in a specific way would induce absolute terror in the birds. Let `L` represent shaking the rattle to the left, and `R` to the right. Then, using the game introduced in #link(<p79>)[#text(fill: main-dark-color)[*Problem 79*]], enter the string that has the value $4.740234375$. #problem-tag(("strings",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #86 #problem-heading(86, [The Augean Stables]) #text(size: 14pt)[*The story*] Hercules' task this time is to clean the Augean stables. They are in a right old mess. Hercules eventually hits upon the idea of diverting a nearby river into the stables in order to clean it. This gets rid of the muck but sadly a lot of vegetation has overgrown on the grounds that Hercules will have to weed out the hard way. In order to pass his time, he invites the local farmhand to play a game with him, using the weeds. #text(size: 14pt)[*The game*] Each weed is divided into a certain number of parts, and players take turns cutting off a part. Any section of the plant that is not connected to the ground after a cut is also removed. Play continues until the last person to make a cut wins. Hercules always goes first. Each weed is represented as a graph, with edges representing pieces of the plant that can be cut off in a turn. The node labelled $0$ is the one that is connected to the ground. Now, *here* #text(fill: main-dark-color)[#footnote[ Source: #link("https://erdos.sdslabs.co/storage/files/problems/86.txt")[#text(fill: main-dark-color)[https://erdos.sdslabs.co/storage/files/problems/86.txt]]. This file is also attached to this PDF. ]] are the adjacency matrices of $7$ such weeds. Consider the $127$ games that can be played with some combination of these weeds. For example, Hercules can always win the game played on just weed $1$, but he will always lose the game played with both weeds $1$ and $3$. Find all the combinations of weeds such that Hercules will always lose the game played with them. Enter your input in the following fashion: The combination $(1,3)$ is considered as the binary number $1010000$ (the first and third places are set to $1$), and the combination $(1,6,7)$ is $1000011$. Convert your combinations into binary numbers and enter their sum in decimal. #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #87 #problem-heading(87, [The Flock of Geryon]) #text(size: 14pt)[*The story*] Hercules just got another task. This time he has to steal Geryon's golden cow from the far-off Mediterranean island of Erytheia. Hercules knows that Geryon has a large flock of cows among which there is only one golden cow, which Hercules needs to retrieve. Hercules is tired of fighting and challenges Geryon to a bloodless battle instead. The game Hercules suggests is to be played with the remaining cows. #text(size: 14pt)[*The game*] Each player chooses to eliminate $13$ or $50$ or $63$ cows from the flock at each turn. The player who eliminates the last set of cows gets the golden cow. Geryon is not very good at games, so he does not tell Hercules how many cows are there in his flock, lest he thinks of a winning strategy, however in his foolishness he lets slip that the number lies anywhere between $0$ to $205530$. He also forces Hercules to decide who shall begin the game. Hercules now wants to know what the odds are of him losing the game if he goes first and plays perfectly, given that the number of cows lies anywhere between $0$ and $205530$. Can you help Hercules by finding the probability? The answer must be correct to $4$ decimal places. #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #88 #problem-heading(88, [The Flock of Geryon]) #text(size: 14pt)[*The story*] Animals seem to wreak a lot of havoc in greek myths. The one under consideration is a bull that used to uproot crops and bring down orchard walls in Crete. Hercules is sent to kill it as usual. #text(size: 14pt)[*The game*] The bull is smart however, and it senses that Hercules is after it. It engages in an impromptu game of hide-and-seek (following the same rules as those in #link(<p81>)[#text(fill: main-dark-color)[*Problem 81*]]). Alas, it only has two choices of hiding places. In the first location, Hercules has a $40%$ chance to find the bull, if in fact the bull is there. In the second location, Hercules has a $100%$ chance to find the bull if it is there. The second location is thus a terrible hiding place. But, the bull bets on Hercules dismissing such a location. If Hercules and the bull play with perfect strategies, what is the expected number of turns it will take for Hercules to capture the bull? The answer is a rational number in lowest terms $p/q$, and you are to enter $bold(p\,q)$. #problem-tag(("probabilities",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #89 #problem-heading(89, [The Horses of Diomedes]) #text(size: 14pt)[*The game*] Hercules and Abderus play a game with a cake (as described in #link(<p84>)[#text(fill: main-dark-color)[*Problem 84*]]) of the preliminaries). Hercules eats squares horizontally and Abderus vertically. We define the value of a game as: - $+1$ if Hercules can win no matter who starts, - $-1$ if Abderus can win no matter who starts, - $+upright(i)$ if the first player can always win, and - $-upright(i)$ if the second player can always win. Consider $30$ games, played with cakes of sizes $M times N$, with $1 <= M <= 3$, and $1 <= N <= 10$. What is the sum of the values of these games? If your answer is $a + upright(i) thin b$, enter $bold(a\,b)$. #text(size: 14pt)[*The story*] Oh, why is Abderus important? He was eaten alive by the crazed horses of Diomedes, and in revenge Hercules fed Diomedes to his own horses. This seemed to have calmed the crazed horses and they lived happily ever after in a meadow somewhere. Greek myths can be very weird sometimes. #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #90 #problem-heading(90, [Capture of Cerberus]) #text(size: 14pt)[*The story*] Hercules now has to bring back Cerberus, the three headed dog from the underworld. Cerberus being an intelligent beast, lures Hercules to a game of gates. If Hercules wins, he will come back with him, otherwise, Hercules has to spend the rest of his days in the underworld. #text(size: 14pt)[*The game*] Rules: - There are a total of $N = 18$ gates, some of which are open and some which are closed. - At each turn, the player has to open a closed gate first, and choose to close/open upto $4$ gates to the left of the first chosen gate. (Here total number of changed gates $c = 5$). He can either open a closed gate or close an open one. The player to open the last closed gate wins the game. #text(size: 14pt)[*The trial match*] Hercules requests for a trial match and Cerberus agrees to play a toned down version of the above game, with $N = 5$ and $c = 3$. He sets up the initial configuration as this: `CCCCO` (`C` = closed, `O` = open) Cerberus urges Hercules to go first. Now, no matter what Hercules does, it is easy to see that Cerberus will always be the one to open the last closed gate. Such a position will always cause Hercules to lose, that is, if he goes first. Hercules is wary of losing, and wants to make a list of all initial positions where he will lose if he goes first. How many such configurations are there? #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #91 #problem-heading(91, [The Girdle of Hippolyta]) #text(size: 14pt)[*The story*] Ares had once gifted Hippolyta, the queen of the amazons, a girdle --- a belt. It is this belt that Hercules is now tasked to steal. But, when word of his task spread to the queen herself, she was very impressed with Hercules' bravery and offered to give him the belt if he won a game of skill against her. #text(size: 14pt)[*The game*] Let $s_i = a_j = 1/((2-i/9)j-1)$ be a series for each $i, 0 <= i <= 7$. And consider $I_n = integral_0^infinity (product_(j=1)^n sin(a_j x)/(a_j x)) dif x$ for each $s_i$. As an example, let's play the game with $i = 0$. Here, $I_1 = I_2 = dots.c = I_7$, but $I_7 eq.not I_8$. Each $I_n$ is of the form $p/q upright(pi)$. We say the value of $s_0$ is $8 + p + q$ ($8$ being the first integral to break the pattern). Play the game with all the indicated values of $i$. Add together the values of each $s_i$ and submit this sum modulo $1000000007$ as the answer. #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #92 #problem-heading(92, [The Apples of the Hesperides]) #text(size: 14pt)[*The story*] Hercules has to steal a hundred apples from the Garden of Hesperides. The apple trees are located at a radius of $sqrt(200)$ from the centre $(0,0)$, abundantly distributed (read: infinite amounts) along the circumference. There is a pole at the centre behind which Hercules is hiding from Ladon, the Dragon lord guarding these trees. Hercules can escape from Ladon only if he is hidden from Ladon's line of sight behind the central pole. Ladon is powerful because he can see in all directions. If Ladon sees Hercules at any point of time, he will immediately fly and kill Hercules. #text(size: 14pt)[*Cutting to the chase*] Ladon is travelling to the nearby city of Egypt along a straight line starting from $(0,-80)$, parallel to the $x$-axis, at a speed of $10$ m/s starting at time $t = 0$, nevertheless his all-seeing eye does not tire out from the constant vigilance. Hercules is hiding behind the pole at $(0,0)$ at $t = 0$. Hercules strategizes to pick up the apples located at the circumference, all the while remaining hidden from Ladon's sight, and place them at the centre. But, he can carry only a maximum of $10$ apples at a time. Clearly he needs to make $10$ such trips. He has a speed of $9$ m/s. What is the shortest time Hercules will need to complete his task, (without getting killed midway, obviously)? If x seconds is your answer, enter $floor(x)$. #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #93 #problem-heading(93, [The Ceryneian Hind]) #text(size: 14pt)[*The story*] Hercules' next task is to catch the Ceryneian Hind, which is as fast as the wind. Artemis considers this a sacred animal and will not give it up to Hercules easily. In order to capture it, he must play a game against Artemis. Artemis has carefully assembled a stick figure of her favourite animal for the game. #text(size: 14pt)[*The game*] The figure is made out of sticks which can be either yellow, orange, brown or green. The black line in the figure represents the ground. - At each turn, a player plucks out a stick from the figure. Any "hanging" sticks, i.e. those that have no connection to the ground, either directly, or through other sticks, will fall down and are immediately discarded. - Hercules can only pluck the orange sticks, and Artemis, the brown ones. Both of them can pluck the yellow and green sticks. The one to pluck the last stick wins the game, and gets the Hind. Hercules also spots a number of other interesting creatures and gambles against Artemis to capture them all, playing the same game for each of them. For each game, - *`A`* represents Hercules losing no matter who starts, if Artemis plays intelligently. - *`H`* represents Hercules wins no matter who starts, if he plays intelligently. - *`F`* represents the situation where the first player always loses. - *`S`* represents the situation where the second player always loses. For the $5$ figures given below, enter the string of answers in the order of the labels of these figures. #align(center)[ #v(5pt) #include "figures/p93_1.typ" #v(20pt) #include "figures/p93_2.typ" #v(20pt) #include "figures/p93_3.typ" #v(20pt) #include "figures/p93_4.typ" #v(20pt) #include "figures/p93_5.typ" #v(5pt) ] #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #94 #problem-heading(94, [Vacation]) Ram and Shyam took a vacation at their grandparents' house. During the vacation, they did all activities together. They either played tennis in the evening or practiced Yoga in the morning, ensuring that they did not undertake both the activities on any single day. There were some days when they did nothing. Out of the days that they stayed at their grandparents' house, they were involved in one of the two activities on $22$ days. However, their grandmother while sending an end of vacation report to their parents stated that they did not do anything on $24$ mornings and they did nothing on $12$ evenings. How long was their vacation? Give your answer in days. #problem-tag(("implementation",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #95 #problem-heading(95, [Strange Currency]) In the strange country Oz, the only official coins are $7$-cent coins and $13$-cent coins. What is the largest amount that cannot be paid with these coins if a shop has no change at all? #problem-tag(("modular", "brute force")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #96 #problem-heading(96, [The Game of Marbles]) A box contains two marbles. One black and the other white. In each turn the player takes a marble out at random and notes its colour. After each turn, the marble is replaced in the bag and an extra black marble is added. The player pays Rs. $1$ to play and wins if he/she has taken more white marbles than black marbles at the end. If the game is played for three turns, the probability of the player winning is exactly $7/24$, and so the maximum prize fund that should be allocated for winning in this game should be Rs. $3$ before the organizer would expect to incur a loss. The maximum prize is a whole number and includes the Rs. $1$ to be given by the player, so the player gets Rs. $2$. Find the maximum prize fund to be allocated to a game with sixteen turns. #problem-tag(("probability",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #97 #problem-heading(97, [Triangles]) Let us take two triangles $triangle.stroked.t #h(0pt) A B C$ and $triangle.stroked.t #h(0pt) P Q R$ as shown in figure below. #align(center)[ #v(5pt) #include "figures/p97.typ" #v(5pt) ] In $triangle.stroked.t #h(0pt) A B C$, $angle A D B = angle B D C = angle C D A = 120degree$. $u = 999, v = 899, w = 1099$. $D$ is the internal vertex of $triangle.stroked.t #h(0pt) A B C$. Find the value of $x$. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #98 #problem-heading(98, [Series Dilemma]) If $X_n$ and $Y_n$ denote two sequences of integers defined as follows: $X_0 = 1$ \ $X_1 = 1$ \ $X_(n+1) = X_n + 2 X_(n-1)$ $Y_0 = 1$ \ $Y_1 = 7$ \ $Y_(n+1) = 2 Y_n + 3 Y_(n-1)$ $n = 1, 2, 3, dots$ Thus, the first few terms of the sequences are: $X : 1,1,3,5,11,21,dots$ \ $Y : 1,7,17,55,161,487,dots$ Let the largest number that occurs in both the sequences be $m$. Give the answer as $m times 123^(m+1)$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #99 #problem-heading(99, [Divisibility Test]) Sum of digits of a $5$-digit number is $41$. Let the probability that such a number is divisible by $11$ be $p/q$, where $gcd(p,q) = 1$. Find $q - p$. #problem-tag(("number theory", "probability")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #100 #problem-heading(100, [Quadratic Chaos]) Let $m$ be an integer such that $1 <= m <= 1000$. Find the probability $p$ of selecting at random an integer $m$ such that the quadratic equation $6 x^2 - 5 m x + m^2 = 0$ has at least one integer solution. Give answer as $1000 p$. #problem-tag(("probability",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #101 #problem-heading(101, [Fibonacci Twist]) Find $67$th term of the sequence whose initial terms are as follows: #par(leading: 10pt)[ - $0$th term: power of $3$ in $binom(66,24)$ \ - $1$st term: power of $2$ in $binom(73,27)$ \ - $2$nd term: power of $3$ in $binom(3280,1367)$ \ - $3$rd term: power of $2$ in $binom(3712,2005)$ \ - $4$th term: power of $2$ in $binom(14348,7519)$ \ - $5$th term: $16$ \ - $6$th term: $19$ ] #problem-tag(("implementation",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #102 #problem-heading(102, [Chinese Whispers]) Consider a group of $5011$ friends and a particular person in the group (say L). L has a message to spread around. Define a "whisper" as an instance where a friend passes the message to another friend. Considering all friends to be distinct, L is interested in finding out the number of sequences of $999983$ "whispers" after which he will eventually get the message back. Calculate the answer modulo $1000000007$. *Note:* After a whisper, if A passed the message to B, then only B can whisper to others since only he has the message. Others can't. During the sequence of whispers, there can be a point in time where A would get the message after less than $999983$ whispers. In that case, he again should pass the message to others in order to complete a total of $999983$ whispers. #problem-tag(("dp",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #103 #problem-heading(103, [Sevens and Threes]) Find the sum of all $7$ digit numbers which satisfy the following conditions: + It contains only digits $3$ and $7$. + The number is divisible by $7$. + Last digit of number is $3$. #problem-tag(("number theory", "modular")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #104 #problem-heading(104, [Dr. Antlove]) Dr. Antlove loves ants (obviously) and he cannot stand anything happening to his ants. <NAME> wants to play with him a little. So he challenges him with a trick puzzle. He gives Dr. Antlove a regular polygon with $628318531$ sides with Queen ant in the middle and gives him a triangular (ant-trap) net that can be tied at any three random vertices of the polygon (any three vertices can be chosen as the vertices of the net at random). But Dr. Antlove is busy with a seminar this weekend. So he orders you to get the ant for him. Before moving on you believe it would be better to calculate the probability of your success. All choices of vertices being equally likely, let the probability that you would be able to catch the ant inside that net be $p$. (All vertices are distinct.) Give the answer $= p times 2 times (2 times floor(upright(pi) times 10^8) - 1)$. #problem-tag(("geometry", "probability")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #105 #problem-heading(105, [Vikas and Pizzas]) Vikas has currently ordered a pizza from Domino's. Due to many orders, Domino's did not cut the pizza into slices. He was wondering how many maximum pieces can be made of a pizza with $n$ cuts keeping the pizza fixed at its position. Find the answer when $n = 65536$. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #106 #problem-heading(106, [Back Propagate]) Let the initial terms of a sequence be ${1,1,1,1,2,11,84,676,5477,44407}$. Propagate this sequence backwards to produce $20$ new terms. Find the sum of these $20$ terms (written in simplest fraction form as $p\/q$). What is the value of $(p times q) mod med (10^9+7)$? #problem-tag(("dp",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #107 #problem-heading(107, [Negated Twins]) Let $f(x)$ be a polynomial with integer coefficients such that $f(2) = f(0) = f(1) = f(5) = n$ and $f(-2) = f(-1) = f(-5) = -n$ for some positive integer $n$. Find the smallest possible value of $n$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #108 #problem-heading(108, [Divisor Game]) Consider a two player game. There are $N$ balls marked 1 to $N$. A move consists of removing a ball $n$ and all the remaining balls which are divisors of $n$ (including $1$). The players alternate the moves. The one who takes the last ball wins the game. Let us assume that both players play optimally. Find the probability that the player who starts the game wins it, given that $N$ will be a random integer between $1$ and $infinity$. Let this probability be $x$. Give your answer as $1000000000000 x$. #problem-tag(("games",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #109 #problem-heading(109, [Extension Conundrum]) We have a triangle with side lengths $a = 345678$, $b = 456784$ and $c = 567890$ with vertices named $A$, $B$ and $C$, and $I$ denote the incentre of circle. Line segment $B I$ is extended to meet opposite side of triangle i.e. $A C$ at $K$. Find length of line segment $I K$. *Note:* $a$ is side opposite to vertex $A$, $b$ is opposite to vertex $B$ and $c$ is opposite to vertex $C$. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #110 #problem-heading(110, [L’s Birthday]) L was celebrating his birthday. His mom made a triangular cake as per L's request as he found that round cakes were too mainstream. After the candles were blown, L's friends (who were $9973$ in number) decided that they wanted triangular cake pieces. As L's mom is fair towards his friends, she has the task to divide the cake into $9974$ triangles of equal volume. Like L, even his mom likes a good challenge. So she decided to cut the cake in the following way: She would select a point $P$ on the triangular surface and from $P$ she would trace $9974$ rays which will intersect the sides of the triangular surface and cut through the rays resulting in $9974$ triangular cake pieces of equal volume. But L pointed out that this type of partitioning is not possible for any interior point on the surface. So she is interested in finding out the number of interior points ($P$) wherein such equal partitioning of the cake is possible. #problem-tag(("number theory", "geometry")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #111 #problem-heading(111, [Rectangle has Children]) A rectangle $A$ is said to be the child of rectangle $B$ if following 3 conditions are satisfied: #[ #set enum(numbering: "a.") + $A$ can be completely fit inside $B$ without $A$'s sides touching $B$'s sides. + At Least one side of $A$ should be greater (in length) than both the sides of $B$. + $A$'s and $B$'s sides are positive integers. ] A rectangle with sides of length $22543$ units and $22541$ units has how many children? *Note:* A square is also a rectangle with equal sides. \ *Note:* $A$'s (child) sides need not be parallel to $B$'s sides when $A$ is fit inside $B$. #problem-tag(("geometry", "implementation")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #112 #problem-heading(112, [Rooted Sums]) Find the answer to the following summation: #[ #show math.equation: it => [#set align(left); #it] $ inline( root(5, (11+5sqrt(5))/2) + root(8, (47+21sqrt(5))/2) + root(6, (18+8sqrt(5))/2) - root(16, (2207-987sqrt(5))/2) - \ root(22, (39603-17711sqrt(5))/2) + root(11, (199+89sqrt(5))/2) + root(30, (1860498-832040sqrt(5))/2) + \ root(13, (521+233sqrt(5))/2) - root(12, (322-144sqrt(5))/2) - root(10, (123-55sqrt(5))/2) - root(26, (271443-121393sqrt(5))/2) ) $ ] Let the answer be $x$. Submit the answer as $floor(1000000000 x)$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #113 #problem-heading(113, [Monica’s Candy Fever]) We all know how much Monica loved candies in her childhood. And, her excessive competitiveness is no big secret! There have been various incidents where the Gellars had brought home some candies (say $n$). Monica always wanted to have more candies than Ross. Now, the Gellars actually gave the candies randomly to both of them. Inspite of the randomness, Monica got more candies than Ross every single time! Now, we want to calculate the probability that Monica had more candies than Ross at every instant that the candies were being distributed. Let the probability of that be $F(n)$. Calculate $x = sum_(i=1)^1000000000 F(i)$. Submit $floor(1000000 x)$. #problem-tag(("combinatorics", "probability")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #114 #problem-heading(114, [Revenge with Derangement]) Suppose that there are $N$ persons who are numbered $1,2,dots,N$. Let there be $N$ hats, also numbered $1,2,dots,N$. We have to find the number of ways in which no one gets the hat having same number as his/her number. Let the number of ways to accomplish the above task be $D(N)$. You need to enter the value of $D(N) mod P$. Take $N = 49770435560715869$ and $P = 223092870$. #problem-tag(("combinatorics", "chinese remainder theorem")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #115 #problem-heading(115, [42: The Answer to Everything?]) Represent $42$ as the sum of $N$ positive real numbers $X_1, X_2, dots, X_N$ where $N$ is an integer, such that the product, $P = X_1 X_2 dots.c X_N$ is maximised. Find $floor(P)$ where $floor(thin)$ is greatest integer function. #problem-tag(("calculus",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #116 #problem-heading(116, [Funny Factorial]) In a right angled triangle $A B C$ right angled at $B$, equations of median $A D$ and $C F$ are $y = x + 1$ and $y = 2x + 4$ respectively. Given $A C$ is $60$ units find the last five non zero digit of $X!$ where $X$ is the area of triangle $A B C$. #problem-tag(("geometry", "brute force")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #117 #problem-heading(117, [Expectation Frenzy]) Suppose an $M$-faced fair dice is tossed $N$ times. Whenever the dice is tossed, each face appears with probability $1\/M$. After $N$ throws of the dice, let the expected value of minimum number obtained on the dice be $E$. Enter the value of $floor(10^6 E)$ where $floor(thin)$ is greatest integer function. Take $M = 100$ and $N = 20$. #problem-tag(("probability",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #118 #problem-heading(118, [Analyzing Complexity]) Problems with which we often deals in programming requires us to approximate number of iterations that we are going to perform in loops. Given below is a simple pseudo code for which you need to tell the number of iteration performed in the given nested list: ```c for ( int x1 = 1 ; x1 <= n ; x1++ ) for ( int x2 = x1 ; x2 <= n ; x2++ ) for ( int x3 = x2 ; x3 <= n ; x3++ ) ... ... ... for ( int xm = x(m-1) ; xm <= n ; xm++ ) it++ ; ``` Take initial value of `it` as $0$ and value of `m` and `n` to be $25$ and $26$ respectively. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #119 #problem-heading(119, [Minimum Cubes]) We define $f(x) =$ minimum number of positive perfect cubes that sum up to $x$. For example, \ $f(2) = 2 med (2 = 1^3 + 1^3)$ \ $f(9) = 2 med (9 = 1^3 + 2^3)$ \ $f(17) = 3 med (17 = 1^3 + 2^3 + 2^3)$ Find $sum_(n=1)^(10^6) f(n)$. #problem-tag(("dp",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #120 #problem-heading(120, [Balance the Weight]) You are given a beam balance and $N$ objects where $i$#super[th] object weighs $2^(i-1), 0 < i <= N$. $F(N)$ denotes the no. of ways of placing these objects (one by one) on balance such that the left side is always heavy (after every placement). Find the value of $F(100)$ and give the answer modulo $10^9+7$. #problem-tag(("implementation", "constructive algorithms")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #121 #problem-heading(121, [The Game of Fibonacci and Powers of Two]) You are given a pile of stones. Two people play this game turn by turn. In any turn, a player can remove a number of stones from the pile, say $X$, such that $X$ can be either a non zero Fibonacci number or a power of $2$. The person that empties the pile wins the game. Both the persons play optimally, i.e. they try to make the best possible move that will help them win. If the number of stones in the pile varies between $1$ and $10^6$, in how many cases will the first player lose? #problem-tag(("dp", "games")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #122 #problem-heading(122, [Never Ending Fraction]) Given that $ P_n / Q_n = 0 + 1/(1 + 1/(2 + 1/(dots.c 1/((n-1)+1/n)))) $ for $n > 0$ ($n$ is an integer) where $P_0 = 0$ and $Q_0 = 1$. Calculate $(P_1000 times Q_1000) mod 1000000007$. #problem-tag(("number theory", "recurrence")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #123 #problem-heading(123, [Recurring Roots]) Let $f(x,y) = sqrt(x sqrt((x+1) sqrt((x+2) dots.c sqrt((y-1) sqrt(y)))))$ for $x >= 2$ and $x < y$ where $x$ and $y$ are integers. Also, let $g(x) = T$ where $T$ is the smallest integer such that $x < T$. Let $h(x) = 2^x mod 1000000007$. Find out $h(g(f(g(f(42,111111111111111)),222222222222222)))$. #problem-tag(("number theory", "induction")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #124 #problem-heading(124, [Co-prime judgement]) We define $phi(n)$ as the number of positive integers less than or equal to $n$ that are relatively prime to $n$. Lets define $S(n) = sum phi(d)$ over all the divisors of $n$ (i.e. $d$ divides $n$). Also define $F(n) = sum S(x)$ where $x$ varies from $1$ to $n$. Compute the value of $F(999999) + F(888888)$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #125 #problem-heading(125, [Happy String]) You are given $p$ `a`'s and $q$ `b`'s. You arrange them in the form of a string. If you are able to get a string in which as you move from left to right, the number of `a`'s is strictly greater than `b`, then it is known as a happy string. Let the number of such happy strings be denoted by $"happy"(p,q)$, then find \ $"happy"(200,100) times 201! times (101!\/300!)$. #problem-tag(("probabilities",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #126 #problem-heading(126, [Playing with constraints]) Let $x =$ last $7$ non-zero digit of $99^99 !$. Define $F(n,k) =$ sum of $k$th powers of all divisors of $n$, so for example \ $F(6,2) = 1^2 + 2^2 + 3^2 + 6^2 = 50$. Define further $G(a,b,k)$ as sum of $F(j,k)$ where $j$ varies from $a$ to $b$ both inclusive. You need to enter the value of $G(1,x dot x,2)$ modulo $10^9+7$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #127 #problem-heading(127, [Decamping Twice]) Let $S$ be a set where $ = {1,2,3,4,5,dots,4444444444}$ and $P$ be a subset of $S$ such that $x in P$ but $2x in.not P$. Let $|T|$ be the total number of elements in the set $T$. Find out maximum $|P|$ of all the possible subsets $P$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #128 #problem-heading(128, [Fibonacci Fun]) Given: \ $a_1 dot upright(e)^(x_1) + a_2 dot upright(e)^(x_2) + dots.c + a_30 dot upright(e)^(x_30) = 321123$ \ where $a_i =$ $i$th Fibonacci number, $upright(e)$ is the Euler's number and $x_i$ is a real variable (i.e. $a_1 = 1$, $a_2 = 1$, $a_3 = 2$, ...). Let minimum value of $upright(e)^(2x_1) + upright(e)^(2x_2) + dots.c + upright(e)^(2x_30)$ be $Z$ at $x_i = y_i$ where all $x_i$ satisfy the above condition. Let $k = (y_1 + y_2 + y_3 + dots.c + y_30)^4 \/ Z$. Find the greatest integer $<= 100k$. #problem-tag(("number theory", "fibonacci")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #129 #problem-heading(129, [Fragger and his sequence]) Fibonacci sequence is defined as follow: $F_1 = 1, F_2 = 2, F_i = F_(i-1) + F_(i-2) med (i > 2)$. Every natural number $X$ can be represented in Fibonacci system such that $X$ is sum of one or more distinct Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers. Let $X = A_1 dot F_1 + A_2 dot F_2 + A_3 dot F_3 + dots.c + A_(k-1) dot F_(k-1) + A_k dot F_k$ where $0 <= A_p <= 1 med forall p < k$ and $A_k = 1$. We will represent $X$ in Fibonacci system as $A_k A_(k-1) A_(k-2) dots.c A_1$. For example \ $1 = (1)_F, 2 = (10)_F, 3 = (100)_F, 4 = (101)_F$. If we write representation of all natural numbers in Fibonacci system consecutively we will obtain a new sequence (say fragger sequence) which will look like this: $1,1,0,1,0,0,1,0,1,dots$. You need to count the number of times $1$ appears in the first $10^15$ terms of fragger sequence. #problem-tag(("fibonacci", "dp")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #130 #problem-heading(130, [The Start]) Let $S_n = (sum_(k=1)^n a_k)^2$, where $a_k = (k times (k+2))^(-1)$. Let $S_n = p\/q$, where $p$ and $q$ are positive integers and $gcd(p,q) = 1$. Find the value of $p times q$ for $n = 112358$. #problem-tag(("series", "summation")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #131 #problem-heading(131, [Crazy sum]) Let $f(n) = sum_(d|n) mu(d) h(n/d)$ where $h(x) =$ sum of divisors of $x$. $g(n) = sum_(d|n) mu(d) f(n\/d)$. Find $S = sum_(n=1)^10000000000 g(n) "modulo" 2^64$. *Note:* here $mu(n)$ is Möbius Function. #problem-tag(("series", "summation")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #132 #problem-heading(132, [Functions]) For a complex number $z$, given a function $f(z) = sum_(i=1)^n 1/i^z$. Let $p_j$ be the $j$-th prime number, $g(z) = product_(j=1)^m (1 - p_j^(-z))$. Let $x = lim_(n,m arrow infinity) f(z) times g(z)$. Find the value of $sum_(1<=i<=k,gcd(i,k)=x) 1$, where $k = 354216846978542365$. #problem-tag(("series", "functions")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #133 #problem-heading(133, [The drunk boyfriend]) In a single dimension world, a girl is standing at the point $x = 0$. Her boyfriend is standing at some point $x = x_0$. He is drunk. So, he either takes a step towards her girlfriend or a step away, with equal probability. But he can't go beyond $x = n$, because of a wall placed there. So whenever he reaches $x = n$, he has to go back to $x = (n-1)$. Let the expected number of steps for him to reach his girlfriend be $F(x_0,n)$ where $x_0$ is his starting point. Find the value of $sum_(i=1)^N F(i,N)$ for $N = 10^7$. #problem-tag(("probability",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #134 #problem-heading(134, [Triangles Counting]) Find the sum of all positive integers up to $10^8$ which can be expressed as a hypotenuse of a right angled triangle where other two sides are also positive integer. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #135 #problem-heading(135, [Polynomial Expansion]) We wish to generate $1000000$ pseudo-random numbers $s_k$ in the range $plus.minus 2^19$, using a type of random number generator (known as a Linear Congruential Generator) as follows: ```pascal t := 0 for k = 1 up to k = 1000000: t := (615949*t + 797807) modulo 2^20 s(k) := t - 2^19 ``` "`^`" in the code implies the power operator. Thus: $s_1 = 273519$, $s_2 = -153582$, $s_3 = 450905$, etc. We need to find a polynomial $P(x)$ of lowest possible degree such that $P(i) = s_i$ for all integers $i <= 1000000$. Enter the value of $(P(1) + dots.c + P(1000100))$ modulo $1000000007$. #problem-tag(("polynomial", "binomial")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #136 #problem-heading(136, [Equate It]) Let $a,b,c$ be positive integers such that $a eq.not b eq.not c$ and $a$ divides $b^69$, $b$ divides $c^69$ and $c$ divides $a^69$. Find min $m$ such that that $a b c$ divides $(a+b+c)^m$ for any $a,b,c$ satisfying the above condition. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #137 #problem-heading(137, [<NAME> and Horcrux]) In a two dimensional map Harry initially is standing at some point denoted by character `H`. Also there is a horcrux at some point of map denoted by character `X`. In order to protect that horcrux You-Know-Who has appointed several Death Eaters at certain points of map denoted by character `D`. Harry need to find the horcrux but he is not knowing the exact position of horcrux and hence he will walk in any of the four direction (left, right, top, bottom) with equal probability from his position as long as he stays in map and not go to any place where Death Eaters reside. Points on which Harry can walk will be denoted by `W` in map. Harry is determined to find the horcrux and he will not stop until he finds it. You need to find expected number of steps Harry will take to find the horcrux. There are $20$ maps in "*maps.txt*". For each map first its dimensions are given $m,n$ which indicates map size $m times n$. After which map is given in described format. *NOTE:* There always exist a path between Harry and horcrux for map given in input. Let the sum of expected value for all map be $P$. Enter the value of $"floor"(P times 10^3)$. Link to *maps.txt* #text(fill: main-dark-color)[#footnote[ Source: #link("https://erdos.sdslabs.co/storage/files/problems/137.txt")[#text(fill: main-dark-color)[https://erdos.sdslabs.co/storage/files/problems/137.txt]]. This file is also attached to this PDF. ]]. #problem-tag(("probability", "graph")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #138 #problem-heading(138, [Mul Me]) Let the number of ordered quadruples satisfying this equation be $f(n)$. \ $a dot b dot c dot d <= n$ $f(1) = 1, f(2) = 5$. Find $f(10^12)$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #139 #problem-heading(139, [Sum Me]) Let $F(n) =$ sum of all divisors of $n$. Find the sum of all $n$ such that $F(n) = 2n$ and $1 <= n <= 5 times 10^35$. Report your answer modulo $10^9+7$. #problem-tag(("number theory",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #140 #problem-heading(140, [Bored with GCD]) Define $P(m) = product_(k=1,gcd(k,m)=1)^m k$. Also $F(n)=sum_(i=1)^n (P(i) mod i)$. Find the value of $sum_(i=1)^12 F(10^i) mod 1000000007$. #problem-tag(("number theory", "gcd")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #141 #problem-heading(141, [Complex Summation]) An $n$th root of unity, where $n$ is a positive integer (i.e. $n = 1,2,3,dots$), is a number $z$ satisfying the equation $z^n = 1$. An $n$th root of unity is primitive if it is not a $k$th root of unity for some smaller $k$: \ $z^k eq.not 1 (k = 1,2,3,...,n-1)$. Let $S(n)$ be the sum of all the primitive nth roots of unity. Define $F(n,k)= sum_(i=1)^n i^k S(i)$. Enter the value of $F(10^11,10^3) mod 1000000007$. #problem-tag(("number theory", "algebra", "complex numbers")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #142 #problem-heading(142, [Inequality Marathon]) Let $S = X_1,X_2,X_3,dots,X_k$ where $0 <= X_i <= 1$ for $1 <= i <= k$ and $sum_(i=1)^k X_i = 1$. Also $0 <= P(x) <= 1$ for all $x in S$. Given that $sum_(i=1)^k P(X_i) = 1$. Let us say $T = max(1\/(sum_(i=1)^k X_i^2))$. Also, $F(x) = sum_(i=1)^k P(X_i) log(1\/P(X_i))$ (log with base $2$). Given that $max(F(x)) = 13$. Find $T! mod 1000000007$. #problem-tag(("probability", "inequality")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #143 #problem-heading(143, [Exponential Fibonacci]) Let $F_n$ be the $n$th Fibonacci number where $F_0 = 0$ and $F_1 = 1$. Also let $a = 3^3^43$ and $b = 3^3^42$. If $F_x = gcd(F_a,F_b)$ where $x$ can be represented as $27^y$. If $F_m^3 - F_n^3 = F_y - F_(y\/3)^3$. Find the value of $(m times n) mod 1000000007$. #problem-tag(("fibonacci", "matrix exponentiation")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #144 #problem-heading(144, [Circular paradigm]) Let the number of arrangements of $3n$ identical Type A balls and $3$ identical Type B balls in a circle #text(fill: main-dark-color)[#footnote[ Both rotation and reflection symmetries of arrangements are considered. ]] be $F(n)$. Find $F(100000) times F(100001)$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #145 #problem-heading(145, [Vasu And Houses]) We have a total of $n-1$ persons ($P_1, P_2, dots, P_(n-1)$) and $n$ houses ($H_1, H_2, dots, H_n$). Find the number of ways for $n = 6$ such that each person visits only $1$ house and the following conditions are satisfied: + Each person visits a different house. + Person $P_i$ can't visit House $H_i$. + $P_1$ can't visit House $H_n$. #problem-tag(("derangements",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #146 #problem-heading(146, [A Very Easy Sum]) A number is called special if when prime factorized as $p_1^a_1 p_2^a_2 dots.c p_k^a_k$, then $a_i <= 2$ for all $1 <= i <= k$. Let $S(N)$ be the sum of all special numbers from $1$ to $N$. Given $S(10) = 47$ and $S(10^4) = 41586160$. Enter $S(123456789123456789)$ modulo $10^9+7$. #problem-tag(("number theory", "summations")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #147 #problem-heading(147, [Divisor Sum]) Define $F(n,0) = 1$, $F(n,k) = sum_(d|n) F(d,k-1)$, where $d|n$ means $d$ is a divisor of $n$. Let $S(N,k) = sum_(n=1)^N F(n,k)$. Given $S(9876,234) mod 1000000007 = 208863976$. Enter the value of $S(98765432,2345678) mod 1000000007$. #problem-tag(("number theory", "divisors", "summations")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #148 #problem-heading(148, [Levels in Tree]) Consider a tree with $n$ nodes rooted at node $1$. We define _parent_[$i$] as the parent of $i$th node. For each $2 <= i <= n$, _parent_[$i$] can assume any value from $1$ to $i-1$ with equal probability. Let $F(n)$ the expected value of the sum of levels of all nodes. $1$st node is at level $1$ and for each $2 <= i <= n$, if node $i$ has level $x$, _parent_[$i$] has level $x-1$. Given $F(10) = 29.28968$. Enter your answer as the greatest integer less than or equal to $F(12345678)$. #problem-tag(("probabilities",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #149 #problem-heading(149, [Fibonacci Sum]) Define $F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2), n >= 2$. Define $S(N,K) = sum_(n=0)^N F(1 + n K) mod 1000000009$. Given $S(10^12,100) = 878943097$. Enter the value of $S(221^221^10^18,55^55^10^18)$. #problem-tag(("fibonacci", "modular roots")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #150 #problem-heading(150, [Fun with Expectation]) Consider an array of $n$ numbers where each element can be any non negative $x$ bit number ($0$ to $2^x-1$) with equal probability. Let $F(n,x)$ be the expected value of the sum of bitwise xor of all possible subsequences of the array. E.g. consider the array $1,2,3$. Sum of xor of all possible subsequences of this array \ $= 1 + 2 + 3 + 1$ ^ $2 + 1$ ^ $3 + 2$ ^ $3 + 1$ ^ $2$ ^ $3 = 1 + 2 + 3 + 2 + 1 + 3 + 0 = 12$. \ *Note:* ^ is the bitwise xor operation here. $F(2,2) = 4.5$. Enter your answer as $"floor"(F(29,30) + F(30,29))$. #problem-tag(("probabilities", "bits")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #151 #problem-heading(151, [The Pebble Game]) Given a Directed Acyclic Graph (#link("https://en.wikipedia.org/wiki/Directed_acyclic_graph")[#text(fill: main-dark-color)[DAG]]), at a given instant of time we can do one of the following two operations: + Place pebble on a node, if all its immediate ancestors have a pebble. + Remove pebble from a node. Initially, there are no pebbles on any node of the DAG. Our goal is to minimize the maximum number of pebbles over time such that finally, pebbles are on all leaf nodes (nodes with no outgoing edges). Assume all DAGs of the form: $2$ equal height full binary trees, one kept inverted. The leaves of each binary tree are at the same level. E.g.: This is a DAG made to resemble $2$ binary trees of height $2$. #align(center)[ #v(5pt) #include "figures/p151.typ" #v(5pt) ] Say $F(n) =$ Answer for a DAG similar to $2$ binary trees of height $n$. Find $sum_(i=0)^20 F(i)$. #problem-tag(("graphs",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #152 #problem-heading(152, [Modular Test]) Let $F_p(x) =$ maximum $k$ such that $p^k$ divides $x!$. Let $G_p (x) = p^(F_p (x))$. Let $Q(N) = (N!\/(G_2(N) G_3(N) G_7(N) G_101 (N))) mod 7711956$. Let $S(N) = sum_(n=1)^N Q(10^16 + n times 10^5)$. Enter the value of $S(10^5)$. #problem-tag(("chinese remainder theorem", "factorial")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #153 #problem-heading(153, [Costly Coins]) Akhil has $100000000$ coins in his FlipCart. He spreads them on a table. Initially all of them are facing head. Daga selects any $34117$ coins at random and inverts all of them. Daga repeats this process $1000$ times. What is the expected number of head after the process? Submit the integer part of the expected number (ignoring the part after decimal point). #problem-tag(("expectation",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #154 #problem-heading(154, [Vikas and Cows]) Vikas has a rectangular farm of dimensions $a times b$ in "Amazon" forest. He also has $4$ cows. The $4$ cows are very aggressive. So he ties his cows to the $4$ corners of the farm through ropes. The length of ropes are $r_1, r_2, r_3, r_4$. He wants to maximise the grazing area. But, as the cows are aggressive, he does not want the cows to fight. $F(a,b) =$ Maximum area of the farm that can be grazed by the cows. $S(a,x) = sum_(b=a)^x F(a,b)$. Output $floor(S(4,1000))$. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #155 #problem-heading(155, [Irreconcilable Differences]) Saurv4u and Daenerys were a loving couple. But due to "Irreconcilable Differences", the couple is thinking of "breaking" up. To measure the depth of the differences $D$, Saurv4u has shaded the inner region of the rectangles (The sides of the rectangle are parallel to the Cartesian axes and the center of rectangle is origin) such that the perimeter of rectangle is less than $4 times a$, while Daenerys has shaded (on the same plane) the inner region of all the rectangles (The sides of the rectangle are parallel to the Cartesian axes and the center of rectangle is origin) such that the area of rectangle is less than $(3 times a times a)\/4$. The measure of the depth of differences $D$ is the common area bounded by the two. Given the value of $a = 1000$, find the value of $floor(D/100)$. $floor(x)$ means the greatest integer $<=x$. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #156 #problem-heading(156, [The Next Big Tower]) Princi is playing "Make Towers with Blocks". She wants to make towers and then jump from one tower to the next. The rules of the game are: She has $N$ blocks. She can make any number of towers with them but the heights of the towers must be in a strictly increasing order i.e. height of any two towers must not be equal (so she can jump higher and higher). Now she wants to find the number of ways in which she can make towers like this with $N = 196$ blocks (the different ways for $N = 6$ are shown in the image). Since, she is busy doing her work, you have to find the answer for her. #align(center)[ #v(5pt) #include "figures/p156.typ" #v(5pt) ] #problem-tag(("dp",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #157 #problem-heading(157, [For the love of tomatoes]) Mishra loves to eat tomatoes. He likes tomatoes so much that he shares them with no one (not even, well, no one). Mishra likes to store his tomatoes safely. He puts all his tomatoes in boxes and puts all boxes in a 3D Cartesian space on the coordinates $(i,j,k)$ such that $1 <= i <= N$, $1 <= j <= N$ and $1 <= k <= N$. So there are a total of $N^3$ boxes. Now, adkroxx wants to steal his tomatoes. He has the following information: - Number of tomatoes in each box is different. - Number of tomatoes in any box $A_(i,j,k)$ is $1 <= A_(i,j,k) <= N^3$. - The number of tomatoes in each row along positive $x$ axis is strictly increasing. - The number of tomatoes in each row along positive $y$ axis is strictly increasing. - The number of tomatoes in each row along positive $z$ axis is strictly increasing. Now, before stealing the tomatoes, adkroxx defines $A D K_i$ as the product of all possible values of $A_(i,i,i)$. $P(N)$ is given by: $ P(N) = sum_(i=1)^N A D K_i $ Find $P(N)$ for $N = 216$. Give the answer modulo $10^9+7$. #problem-tag(("brute force",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #158 #problem-heading(158, [Best Hacker in the World]) Foxtrot and Vampire decided to play a game to decide who is a better hacker. They have $n$ tiles in a line out of which $m$ are white rest all are black. Their task is to change all the black tiles with white by following a simple procedure. They can change a black tile with white only if there is atleast one white tile adjacent to that black tile. Now they have $n = 74$ and $m = 13$ and the $13$ positions (indexed $1$) of white tiles are $6,14,19,20,21,24,30,43,58,61,69,70,73$. They want to find the total number of ways in which it can be done. Help Vampire find the answer as he cannot come out in daytime. Report your answer modulo $10^9+7$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #159 #problem-heading(159, [Revenge of The Fox]) After losing to Vampire, Foxtrot wants to take revenge. Vampire has $30$ piles of coins, each contains $N$ number of coins. Every gold coin weighs $10$ grams, while counterfeit coin weighs $9$ grams. Some of the piles contains all counterfeit coins. He have a digital scale capable of accurately weighing any number of coins. He knows that at most $3$ of the $30$ piles are counterfeit. He needs to find the minimum value of $N$ so that, with just one measurement, he can guarantee identifying which (if any) piles are counterfeit. Vampire is busy in some work and says if Foxtrot can solve this for him, he will declare Foxtrot as the best hacker. Find the answer for Foxtrot. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #160 #problem-heading(160, [Such Sum Wow]) Vaibhav is participating in MCA PCIC --- largest international Math competition where he gets this problem: Given $N$ equations of the form: $a_i x_i^2 + b_i x_i + c_i = 0$, $i$ varies from $1$ to $N$, where $a_i = b_i = i$th Fibonacci number and $c_i = (i+2)$th Fibonacci number. Let $g_i = (-1) times (2 a_i x_i + b_i)^2$ for all the equations. $h(N) = sum_(i=1)^N g_i$. Submit $h(N) mod (10^9+7)$ for $N = 987654321342198766$. *Note:* Fibonacci series: _Fib_[$0$] $= 0$, _Fib_[$1$] $= 1$, _Fib_[$i$] $=$ _Fib_[$i-1$] + _Fib_[$i-2$]. Now Vaibhav doesn't like maths, so you have to solve it for him. #problem-tag(("fibonacci",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #161 #problem-heading(161, [Binary Play]) Consider a set $S(N)$ such that $S(N)$ contains all sequences of $0$ and $1$ of length $N$ in which no two $1$'s are adjacent. For example: $S(3) = (000,001,010,100,101)$. Let $A =$ no. of elements in $S(30)$. $B =$ sum of digits of $A$. You have to output no. of $0$'s appearing in $B$#super[th] sequence of $S(30)$ when arranged lexographically. #problem-tag(("fibonacci", "dp")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #162 #problem-heading(162, [One Last Game]) During a game of Mafia, after Verma is killed by Mafia in the first round, he starts getting bored and keeps disturbing others in the game. This irritates everyone else and to keep the game interesting, Akhil asks Adarsh to keep Verma occupied in something else. So Adarsh gives him a $1 times N$ matrix which has $N$ cells. Also, he gives him $M$ colours numbered from $1$ to $M$. Now, Verma can choose any submatrix with even number of cells from the matrix and colour it with one of the $M$ different colours. He can colour as many times as he wants. If Verma tries to recolour any cell which is already coloured, the cell gets coloured in the last colour. Adarsh asks Verma to make as many distinct matrices that he can make such that every cell is coloured. Each matrix is different from other if at least one of the cell has a different colour. Find the number of matrices Verma can make and submit the answer modulo $1000000007$. Take $N = 99999999999999$ and $M = 999999999$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #163 #problem-heading(163, [Bored with Shinigami]) Ryuk is bored with the Shinigami world and goes to the human world to find something interesting. He is fascinated with the GCD function and Fibonacci numbers and starts playing with them. Fibonacci numbers are defined as: $F(n) = F(n-1) + F(n-2) med forall n >= 2$ with $F(0) = 0$ and $F(1) = 1$. Ryuk wants you to find the value of $gcd(F(101^2185 - 17^2185),F(101^4807-17^4807)) mod 1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #164 #problem-heading(164, [Kill the remaining chinese]) Kira has killed all criminals in Japan and has now started killing Chinese criminals. He kills $Z$ criminals every week. Where $X = 100!$ and $X^9449771607341027425 equiv Y med (mod 9449771616229914661)$. $Z = Y mod 1000000008$. As a supporter of Kira, help him by finding $Z$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #165 #problem-heading(165, [L’s Successor]) L is fighting Kira which can be dangerous as Kira has the Death Note. Watari has to decide a successor for L in case L dies. Watari gives a point $(x,y,z)$ in cartesian plane to Mello and Near and they have to play a game such that they take turns. In one turn, the player can change one of the coordinates (say $w$, $w > 0$) to $[w\/2]$ or $[w\/3]$ or $[w\/5]$ #text(fill: main-dark-color)[#footnote[ $[x]$ denotes the greatest integer less than or equal to $x$. ]]. So $(8,9,10)$ can be reduced to $(4,9,10)$ or $(2,9,10)$ or $(1,9,10)$ or $(8,9,3)$ and so on. The person who changes the point to origin wins the game. Watari wants Near to win but he forgot the $z$ coordinate so he randomly selects $z$ between $0$ and $12345$ (both inclusive). So the point is $L(2^60, 2^61, z)$, where $z$ is between $0$ and $12345$ (both inclusive). Given that Near starts play calculate the probability that Near will win the game if both players play optimally. If the answer is of the form $u\/v$ where $u$ and $v$ are coprime you have to input $u+v$ as the answer. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #166 #problem-heading(166, [Apples for Ryuk]) Light Yagami has to buy apples for Ryuk without attracting any unwanted attention towards himself. Interestingly, the number of apples he buys everyday is always a Fermat Number. A Fermat number is a number of the form $2^2^n+1$. $G(N) =$ sum of digits of $N$th Fermat Number modulo $9$. Find the sum of $G(i)$ for all $i$ between $1$ and $999999999999$ (both inclusive). //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #167 #problem-heading(167, [The Perfectionist Yagami]) L gives Light the following challenge and claims that if he is unable to solve it, he is Kira. Help Light deceive L by solving the challenge. A $3$-perfect number is defined as a number whose sum of divisors equals thrice that number. You have to fiind the sum of all $3$-perfect numbers of the form $n = 2^k times 3 times p$ that are less than $10^9$, where $p$ is an odd prime number and $k$ is positive integer. Give the answer modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #168 #problem-heading(168, [L’s Ideology]) L is sure that Light is kira and Misa is second Kira. He randomly selects two permutation of $1$ to $N$ and store it in $A[0],A[1],dots,A[N-1]$ and $B[0],B[1],dots,B[N-1]$. All permutations are equally probable. Now he randomly selects a integer $X$, $0 <= X < N$, and shifts permutation $B$ to left by $X$. For Example --- $[2,3,1,4,5]$ be a permutation, shifting it left by $2$ will result $[1,4,5,2,3]$. He defines another sequence $g[i] = (A[i] times 1) mod B[i] + (A[i] times 2) mod B[i] + (A[i] times 3) mod B[i]$ $+ thin dots.c + (A[i] times B[i]) mod B[i]$. Find expected value of $g[0] + g[1] + dots.c + g[N-1]$ for $N = 1111$. Answer greatest integer of expected value. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #169 #problem-heading(169, [Attendance and Probability]) As we all know adkroxx is a great programmer of our institute. But due to programming he started missing a lot of classes. Now the institute decides to offer him cash reward for good attendance. If he is absent for $4$ consecutive days or late on more than one occasion they will forfeit his prize. During an $n$-day period a ternary string is formed for each day consisting of `L`'s (late), `O`'s (on time), and `A`'s (absent). Adk being a smart kid tries to find out what is the total number of prize string that exists. Although there are eighty-one ternary strings for a $4$-day period that can be formed, exactly forty-seven strings would lead to a prize. Now you have to help adkroxx to find out number of prize strings for $n = 10000007$ and report the answer modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #170 #problem-heading(170, [Magical Distance]) Consider all points with integral positive coordinate $(x,y)$ which lies on the curve $ abs(x^2 - 4 x y - y^2) = 1 $ Let $P_i$ be the coordinate of $i$#super[th] point when all the points satisfying above equation are sorted in ascending order according to their distance from the origin. Let $D_i =$ distance between $(0,0)$ and $P_i$. If $S(n) =sum_(i=1)^n D_i^2$. Enter the value of $S(10^15) mod 1000000009$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #171 #problem-heading(171, [Random Name]) $ g(x) &= 2^(2x^3) - 1 \ f(x) &= sum_(i=1)^x g(floor(x/i))) \ F(x) &= sum_(i=1)^x f(i) $ Find $F(12345678) mod 10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #172 #problem-heading(172, [Polynomial Expansion 2]) Consider $f(x) = 1 + 5x + 6x^2 + 3x^3 + 10x^4 + 11x^5 - 19x^6 - 2x^7$. Consider $g(x) = x^5 - 1$. Let $R(k,x)$ be the remainder obtained when $f(x)^k$ is divided by $g(x)$. Example : $ R(1,x) &= 12 - 14x + 4x^2 + 3x^3 + 10x^4 \ R(2,x) &= -112 - 247x + 352x^2 + 60x^3 + 172x^4 $ Let $S(k,x)$ be the sum of coefficient of $R(k,x)$. You need to enter the value of $S(18^10^18,x)$ modulo $100086841$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #173 #problem-heading(173, [Permutation mania]) Permutation $p$ is an ordered set of integers $p_1,p_2,dots,p_n$ consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We will denote the $i$#super[th] element of permutation $p$ as $p_i$. We will call number $n$ the size or the length of permutation $p_1,p_2,dots,p_n$. We will call position $i$ ($1 <= i <= n$) in permutation $p_1,p_2,dots,p_n$ good, if $abs(p_i-i) = 1$. Your task is to count the number of permutations of size $n$ with exactly $k$ good positions. Give the answer for $n = 1000$ and $k = 700$ modulo $1000000007$. Example: for $n = 3$ and $k = 2$ answer will be 4. $(1,3,2),(3,1,2),(2,1,3),(2,3,1)$ all have exactly $2$ good position. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #174 #problem-heading(174, [Dabba and Dhakan]) Dabba loves Maths and his girlfriend Dhakan, so he either spends his day with dhakan or does maths all day. But he hates spending two consecutive days with dhakan (because she is a dhakan). He wants to make his schedule for his summer vacation as a sequence of doing maths or spending day with dhakan. No of days of his summer vacation can vary from $l$ to $r$. You need to count in how many ways Dabba can select $k$ different schedule of the same number of days for his summer vacations, whose days can vary from $l$ to $r$. For example if $k = 2$, $l = 1$ and $r = 2$, if we define Maths day as ${1}$ and Dhakan's day as ${0}$, here are all possible combination: ${0}, {1}, {00}, {01}, {10}, {11}$. But ${00}$ can not be selected because it has $2$ consecutive Dhakan's day in a row. Now, we need to count in how many ways we can select $k = 2$ schedule of the same length in range $[1,2]$. Here they are: for no. of days $=1$, ${0,1}$; no. of days $= 2$, ${01,10}, {01,11}, {10,11}$. so answer for $k = 2$, $l = 1$ and $r = 2$ will be $4$. He wants you to tell him in how many ways can do that, modulo $1000000007$ for $k = 200$, $l = 1$ and $r = 10^18$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #175 #problem-heading(175, [The Rocking Problem]) Bunty is trying to solve a problem and he is unable to do it so he asks you to solve his problem. Let $F(n)$ is the number of subsets of ${1,2,3,dots,n}$ that contain no consecutive integers modulo $1000000007$. Now you have to report $G(F(100000007))$. Where $G(n) =$ number of binary sequences of length $n$ that have no consecutive $0$'s modulo $1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #184 #problem-heading(184, [Color problem]) Mr. Pink likes summation series and Mr. White likes to take big powers of numbers. In order to satisfy both of them <NAME> want you to evaluate the following sum $ sum_(i=1)^n i^k = 1^k + 2^k + dots.c + n^k $ modulo $10^9+7$ for $n = 10^9$ and $k = 10^6$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #186 #problem-heading(186, [Euler and Fibo]) $ S(a,b) = sum_(k|a,k|b) Phi(k) $ where $k|x$ means $k$ divides $x$, $Phi(n)$ is Euler totient. $ Z_0(n) = sum_(a=1)^n sum_(b >= a)^n S(a,b) $ $F(n) = F(n-1) + F(n-2)$ for $n > 1$, $F(0) = 0$ and $F(1) = 1$. $ Z_1(n) = sum_(a=1)^n sum_(b >= a)^n S(F(a),F(b)) $ Find $Z_0(n)^(Z_1(n)) mod 10^9+7$ for $n = 10^8$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #189 #problem-heading(189, [Night King and The Army of the Dead]) Night king is marching with an army of the dead. The Night King has $N$ deads in his army and they are labelled from $1$ to $N$. <NAME> is trying hard to stop Night King to cross the wall and destroy Westeros. Jon figures out that killing a walker leads to the disintegration of some of his associated wights. If Jon kills the $k$th dead all the dead with a label which divides $k$ will be disintegrated. For $N = 123456789$, what is the minimum number of kills required to clear the army? //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #190 #problem-heading(190, [Semi Prime Sum]) What is the sum of semi-primes up to $10^7$. Semi-prime is a number of the form $a times b$ where $a$ and $b$ are both prime numbers. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #191 #problem-heading(191, [Save Jon Snow]) <NAME> hands Gendry a message, tells him to go to Eastwatch and send a raven to Daenerys to rescue them. Currently, Gendry is at $(0,0)$ and the castle is situated at $(N,N)$. In order to escape the battlefield, he can only move from $(i,j)$ to $(i,j+1)$ or $(i+1,j)$ or $(i+1,j+1)$. Find the number of paths that can be taken by Gendry to reach the castle modulo $10^9+7$ for $N = 10^7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #192 #problem-heading(192, [Colorful Matrix]) Consider a $2000 times 2000$ matrix which is to be filled with $15$ colors. Find the number of ways to color the matrix. Two colorings are same if rotating one of them along the axis perpendicular to the plane (in multiples of $90$ degrees) gives the other. Give the answers modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #193 #problem-heading(193, [Bend the knee or Play]) Jon has a well-shuffled deck of $M = 4999$ white cards and $N = 4999$ green cards. Each permutation of cards in the deck is equally likely. Dany has set some rules for Jon. Every time Jon flips a white card he gets one coin, otherwise he loses one coin.At any moment (even at the beginning), Jon is allowed to stop playing the game and keep the number of coins that he has. During the game-play the balance of coins that Jon has may be negative. Let $k$ be the expected amount of coins Jon will have if Jon plays optimally. Evaluate $[k times 10000] times 123456$. $[x]$ represents the greatest integer $<= x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #194 #problem-heading(194, [Integers on a roll]) Let $F(a) =$ Number of integral points on the equation $x^2 + y^2 = a$. Find the sum of $(a times d times k)^(F(1745542018215^a times 2017^d times 408^k))$ for all values $1 <= a,d,k <= 100$ modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #195 #problem-heading(195, [Flip ’em all]) Consider a row of $N$ cards all facing up. Now a player flips all the multiples of $1$, then $2$ and so on till $N$. Find the number of cards facing up if $N = 12345678987654321$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #196 #problem-heading(196, [Game of Thrones]) In game of thrones you either win or you die. Each one of Jon, Dany, Cersei and Euron are ruling one of the four kingdoms. Ruler who gets to rule two kingdoms sits on the iron throne. Dany decides to attack one of the other kingdoms so that she can sit on the iron throne. But there is a catch. There are three dragons distributed among the $4$ rulers in any possible way. (Dany herself can have all the three dragons or maybe she won't have any!) All the dragons are alike and there is no difference between them. If Dany attacks on a kingdom whose ruler has more dragons than her, she loses. The probability that she sits on the throne is of the form $p\/q$ where $p$ and $q$ are coprimes and $q$ is not equal to zero. Submit the ans $p^q$ modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #197 #problem-heading(197, [Kill the King]) Daenerys has $3$ dragons and $9$ XORgons (a creature that can breathe any number from the range $[0,123456789]$). If multiple XORgons throw numbers to a target at a time then the resulting number will be the XOR of the individual numbers thrown by each XORgon. Surprisingly the night king can be killed by the number $123456789$. Help Tyrion to find out how many ways all $9$ XORgons can throw number to the night king such that night king can be killed. To cut the long story short how many unordered $9$-tuples $(a,b,c,d,e,f,g,h,i)$ are there such that $a and b and c and d and e and f and g and h and i = 123456789$ and $a,b,c,d,e,f,g,h,i$ are numbers from the range $[0,123456789]$. Submit the answer modulo $1000000016000000063$. $and$ represents the bitwise XOR operation. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #198 #problem-heading(198, [XOR Again]) Find the sum of $i and j$ modulo $10^9+7$ for all integers $i$ and $j$ in $[0,1073742824]$. $and$ represents bitwise XOR operation. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #199 #problem-heading(199, [Zero and Big Bits]) Zero is a very powerful person. He has $N$ countries (out of total $197$) under his control all of which are identical to him. Once he counted the number of ways of arranging all the countries in a list of size $197$ (modulo $M$) and stored the number in a computer (in binary format) as Zero likes bits. Zero also likes big numbers: More the number of set bits, the happier Zero will be. His happiness is equal to number of set bits in the number. The answer is his happiness. The world knows only about modular arithmetic with $M = 10^9+7$. Calculate all the values modulo $M$. Here $N = 191$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #200 #problem-heading(200, [Stick to the Bases]) $F(i,j) =$ sum of positive integers (in base $10$) having an identical representation in both base $i$ and base $j$. $F(2,3) = 1$. Let $S(N)$ be the sum of all values of $F(i,j)$ for $2 <= i < j <= N$. Find $S(N) mod 22011663$ for $N = 10^18$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #201 #problem-heading(201, [Tricky Game]) TNBT likes playing with sticks, so once he broke a stick into $3$ pieces and calculated the probability of the pieces forming a triangle with much difficulty. He now wishes to calculate the probability of the pieces *NOT* forming an $N$-sided polygon given the stick was broken into $N$ pieces. Since he found it difficult for $3$ pieces, tell him the answer for $N = 733$. If the probability is $p\/q$ where $gcd(p,q) = 1$, the answer is $[q\/p]$ modulo $10^9+9$. $[x]$ represents the greatest integer $<= x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #202 #problem-heading(202, [Power and Modulo]) $F(k) = 5^k mod 10^(k')$ where $k' = k mod 6$. Let $S(N)$ be the sum of $F(k)$ for all $1 <= k <= N$. Find $S(10^18) mod 10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #203 #problem-heading(203, [Couples]) Swegwan is getting more naughty day by day. Recently he has come to know about the new variety of Sal trees that can share emotions. So he is highly excited about making their couples. He is God so he knows the tree's gender. Because he has enough free time he counts the number of male and female Sal trees now and then. Since it's very hard to know the exact positioning help him find the expected number of probable couples $p$. Every adjacent male and a female tree is a probable couple for Swegwan. According to him, there are $6367$ male trees (`MT`) and $6571$ female trees (`FT`) (all planted in a row). For example, `MT FT MT FT` has $3$ probable couples. Give your answer as $[p times 10^4]$. $[x]$ is the greatest integer $<= x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #204 #problem-heading(204, [Combination Addition]) $ S(N) = sum_(n=0,k=0)^(2k <= n <= N) binom(n-k,k) $ Find $S(10^18)$ modulo $10^9+7$. $binom(n,k)$ represents the binomial coefficient. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #205 #problem-heading(205, [Prime Sum]) $P(N)$ represents the largest prime factor of $N$. Find the sum of $P(k^3+1)$ for $1 <= k <= 10^7$ modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #206 #problem-heading(206, [Finding Primes]) Find the smallest prime number $p$ such that there exist an integer $x$ which satisfies $(x+8)(x+10)(x+12) = p$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #207 #problem-heading(207, [Unlucky base]) Given a number $a$, consider the set $S(a) = {a^i:i>=0}$. You create a sorted sequence $G$ formed by taking any number of distinct elements of the set $S(a)$ and adding them. Let the $k$#super[th] smallest number which can be constructed using this for a given $a$ be denoted as $(a,k)$. Find the answer for $(a,k) = (13,423732713)$, submit your answer modulo $4222236787$. The elements of the sequence $G$ go as follows $1,13,14,169,170,182,183,dots$ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #208 #problem-heading(208, [Just Mod it!]) For all the integers in range $1$ to $10^18$. Find out the number of integers $n$ such that $n^n mod 100 = n$. *Note:* Here, $mod$ refers to the remainder operator and not the relation. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #209 #problem-heading(209, [Harry and Magic Squares]) Harry and Hermione find an ancient square in the forest. Its vertices $V_1$, $V_2$, $V_3$, $V_4$ are each labeled with a number. Hermione hates asymmetry, and she wants all numbers to be equal. Fortunately, Harry carries a magic wand with him. In one spell, he can choose any two adjacent vertices and increase their labels by one (each). He is allowed to use any amount of spells until the numbers become equal. Unfortunately, Harry is not so good at math, and he does not know if it is possible to make them equal. Harry tells you that the initial values of the four numbers can be randomly distributed between $1$ and $1000$. Find the probability that he can use these spells to make all four labels of the vertices equal. Note that there is no restriction on the range of the final values of the magic numbers. If this probability can be expressed as $p\/q$, where $p$ and $q$ are coprime numbers, enter the value of $p$. Examples: Case 1: #text(fill: main-dark-color, weight: "bold")[ ``` 8 6 8 6 ``` ] Here, Harry can apply the spell twice to make the four numbers equal to $8$. Both spells act on the top-right and bottom-right vertices. Case 2: #text(fill: main-dark-color, weight: "bold")[ ``` 1 3 4 5 ``` ] Here, any amount of spells will fail to achieve the end-goal of making all four labels equal. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #210 #problem-heading(210, [Circle and his friend tangent]) Consider two points $A_0$ and $A_1$ which are on a unit circle $C$ centered at origin. Where point $A_0$ is $(1,0)$ and $A_1$ is such that angle between positive direction of $x$-axis and radius vector through $A_1$ is $1degree$. The points $A_i$ ($i >= 2$) are obtained in the following way: Consider vector $V_i = A_(i-1) - A_(i-2)$, if $A_(i-1)$ and $A_(i-2)$ coincide take $V_i$ as the tangent at $A_(i-1)$. $A_i$ is obtained by intersection of circle with line which passes through Point $A_0 (1,0)$ and is parallel to $V_i$. Find the angle between $x$-axis and radius vector through $A_n$ for $n = 123456789987654321$. Give answer in degrees (Only output the integral part of the answer, if your answer is $19.23$ enter $19$ ($19.0$ will be wrong)). //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #212 #problem-heading(212, [Functional Permutations]) Given a permutation $p$ of length $n$, we define the following functions \ $S(p) = {i : p_i > p_(i+1), 1 <= i <= n-1}$, \ $f(p) = "sum of elements of" S(p)$. Let $F(n,k) =$ number of permutations $p$ of length $n$ with $f(p) = k$. Find $F(123,321)$ modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #213 #problem-heading(213, [Lonely Expansion]) Let $f(r,n)$ be the number of co-efficient which appears only once in expansion of $(x_1 + x_2 + dots.c + x_r)^n$. Then, $f(3,2) = 0$ and $f(3,3) = 1$. Let $A(i) = sum_(j=1)^n f(i,j)$ and $B = sum_(i=1)^n A(i)$. Find the value of $B$ modulo $m$ if $n = 1000000000000$ ($10^12$) and $m = 998244353$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #214 #problem-heading(214, [Easy Expressions]) Find the value of the following summation $ sum_(x=1)^(10^12) (x^2+x+1) dot x! $ $x!$ denotes factorial of $x$. Give your answer modulo $3^20$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #215 #problem-heading(215, [Go for Gold]) Sparky is yet again being accused of being a robot. He needs to solve this question to prove his innocence. Given a number $x$ and has defined the following functions: \ $p(x) = x!$ \ $s(x) = 1 + 2 + 3 + dots.c + x$ Find the value of $p(x) mod s(x)$ for $x = 10^9+6$. *Hint*: $10^9+7$ is a prime number. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #216 #problem-heading(216, [Simple Alphabet]) Manas is the smallest Panda on this planet. So he loves writing on the wall. Today Manas is presented with a special wall which is infinitely long and which resembles a notebook with horizontal lines at a distance $10$ units apart. Since he knows only $3$ letters of the english alphabet, `O`, `N`, `I`, he starts writing these characters on this wall in any angle at any position. He writes `O` $677$ times, `N` $733$ times and `I` $779$ times. We define a cut as the intersection of character with the horizontal lines on the wall. Find the expected number of cuts Manas will make. The dimensions of the characters: - `I`: Line segment of length $1$ unit. - `O`: Circle of radius $0.5$ unit. - `N`: Smaller line segments have length $1$ unit and longer line segment has a length $2$ units. If the answer is $p$, give the answer as $floor(10^5 p)$. *Note:* A single character can make multiple cuts, for example, `O` can never make a single cut. *Hint*: #link("https://brilliant.org/wiki/linearity-of-expectation")[#text(fill: main-dark-color)[https://brilliant.org/wiki/linearity-of-expectation]] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #217 #problem-heading(217, [Stick Game]) There are $N$ sticks ($N >= 3$) of same size kept such that they make a regular polygon. Now one of the sticks from the polygon is removed to make it an open polygon. Alex and Bob are playing a game (starting with Alex) in which they perform the following moves. A player chooses a stick and removes it. Now we have two sets of connected sticks that were originally in contact with the removed stick. The one with the smaller length is also removed with along with the selected stick. If both of the sets are of same size any one is removed. The person who can not make a move in their turn loses. Example for $N = 6$: \ One of the sticks is removed and the figure looks like this. #align(center)[ #v(5pt) #include "figures/p217.typ" #v(5pt) ] Now, if the chosen stick is terminal one like $1$ or $5$ then only that particular stick is removed. If some other stick is chosen (say stick numbered $2$) then on removing there will be $2$ sets of connected sticks. The set with less number of sticks gets removed too, and thus the stick with number $1$ will also be removed. You are required to find how many starting positions are there below $N = 10^10^6$ such that Alex loses, assuming that both Alex and Bob play optimally. *Hint*: #link("https://www.topcoder.com/community/competitive-programming/tutorials/algorithm-games")[#text(fill: main-dark-color)[A tutorial on Game Theory]] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #218 #problem-heading(218, [Counting Hexagons]) A regular hexagon with integer length $n$ units is divided in $6n^2$ equilateral triangles with sides of length $1$ unit and this hexagonal lattice formed has a total of $3n^2+3^n+1$ lattice points. For $n = 3$, refer to the image below #align(center)[ #v(5pt) #include "figures/p218.typ" #v(5pt) ] Let $H(n)$ denote the number of regular hexagons that can be formed by connecting any $6$ points. Let $S(n)$ denote the summation of $H(k)$ for $1 <= k <= n$. Given $H(3) = 36$ and $S(10) = 7942$, Calculate $S(10^18)$. Give your answer modulo $10^9+7$. *Hint*: Can you observe any pattern? //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #219 #problem-heading(219, [Divide and Destroy]) Given $n$ and $k$, find the number of a sequences of integers $a_1,a_2,dots,a_(k+1)$ such that $a_(i+1)$ divides $a_i$ for $1 <= i <= k$ and $a_1 = n, a_(k+1) = 1$. Find the answer modulo $10^9+7$ for $(n,k) = (1101^17 times 2019^29, 3 times 367 times 673)$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #220 #problem-heading(220, [Fibonazi]) We define $f(i) = f(i-1) + f(i-2)$ and $F(i) = i^2 f(i)$. Find $(sum_(i=1)^N F(i)) mod 10^9+7$. $N = 10^18, f(1) = 1, f(2) = 1$. *Hint*: #link("https://www.geeksforgeeks.org/matrix-exponentiation")[#text(fill: main-dark-color)[https://www.geeksforgeeks.org/matrix-exponentiation]] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #221 #problem-heading(221, [Harvey’s Shot]) Harvey is set on a mission to test his luck. To test a person's luck there is a circular room which is marked with $180$ points with numbers $1,2,3,dots,180$ written on them on the circumference equidistant from the adjacent points. Harvey stands at the point $1$ on the boundary with a gun in his hand. He shoots the gun aiming inside the circle at any of the marked points from $2$ to $90$ ($90$ included). Assuming an elastic collision between the bullet and the wall the bullet reflects as soon as it touches any point on the circumference. If the bullet reaches the point $1$ it hits Harvey and he dies. The bullet stops when it reaches a point where the number written on it is smaller than that of the number written on the point from which it was reflected. Given that Harvey chooses the point where he shoots randomly, let the probability that Harvey dies in the game be $m/n$ ($m$ and $n$ are coprime). Enter your answer as $m times n$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #222 #problem-heading(222, [Houdini and Picking Cards]) Houdini has a deck consisting of $10^6$ cards, where the $i$-th card (starting with $1$) is labeled with the number $i$. He randomly picks two cards from the deck, and wants to find the probability that one of the card labels is divisible by the other. The probability can be written in the form $m/n$ where $m$ and $n$ are coprime integers. Enter your answer as $m+n$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #223 #problem-heading(223, [Lines and a Point]) You are given a set of lines $S colon.eq x(6a+b) - y(11a+2b) = 3a-183b$ for all real values of $(a,b)$ and a point $(713,732)$. A closed curve is formed by taking the reflection of this point from all the lines in set $S$. Let $A$ be the area enclosed by this curve, find $A/upright(pi)$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #224 #problem-heading(224, [Circles and a Point]) #align(center)[ #v(5pt) #include "figures/p224.typ" #v(5pt) ] Given integer $a = 100$. Consider points $A(2a,0),B(0,2a),C(a,0),D(0,a)$ and a line $A B$. Point $E$ is on the line at point $(x,y)$ and the circles intersect again at point $F$. As point $E$ moves from $A$ to $B$ let the distance traveled by point $F$ be $d$. Find $[d]$. Where $[thin]$ is the greatest integer function. *Note:* A new pair of circles is formed for every location of $E$ using the points $A C E$ and $B D E$. The second point of intersection is labeled $F$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #225 #problem-heading(225, [Totient Fun]) Find the first integer $n$ ($n > 0$) such that $phi(n) = phi(n+1) = phi(n+2)$. Enter the answer modulo $1729$. $phi(n)$ is totient of $n$. You can read about the totient function here: #link("https://en.wikipedia.org/wiki/Euler's_totient_function")[#text(fill: main-dark-color)[Euler Totient Function]] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #226 #problem-heading(226, [The Pass]) The King of Zugzwangtria is dead in a war. Since the king had no successors, his existing marvellous brothers Dratox and Keraze are claiming for the throne. Dratox being the elder has the right on the throne but his younger brother Keraze refuses and threatens to war. The wise ministress Freixola suggests both the players to play a game, whoever wins would get the throne. Both agree to this! The game is as follows: First Dratox picks up a natural number from $1$ to $N$, call it $a$. Then Keraze choses a real number $b$ of the form $a^(1+sqrt(i))/i^sqrt(a)$ (where $i$ is some integer from $1$ to $N$). Then Freixola tries to pass the golden stone through the magical ring. If the stone can possibly pass through the ring then Dratox wins, else Keraze wins. The golden stone is a rigid regular tetrahedron of side length $a$ and the magical ring is a rigid circle of radius $b$ (negligible width). Let $X$ be the total number of $a$'s for which Dratox has a guaranteed win. Enter $X^X mod 10^9+7$, $N = 10^123456789$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #228 #problem-heading(228, [Generating Sets]) For given numbers $n$, $a$ and a set $S$, define the set $a^S = {a^t mod n:t "is in" S}$. For $n = 998244353$ and $S =$ set of natural numbers, find $ sum_(i=1)^n abs(i^S) $ Give answer modulo $10^9+7$. *Note:* $abs(X)$ denote the size of set $X$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #229 #problem-heading(229, [Powerful Roots]) Let $ f(i) = cases( f(i-1)+2f(i-2)+4f(i-3)\,quad & i > 3, i\,quad & i <= 3 ) $ We define a polynomial $P(x) = x^n + a_(n-1) x^(n-1) + dots.c + a_1 x + a_0$ where $a_i = f(2^i) mod M$. Let the roots of $P(x)$ be $b_1,b_2,dots,b_n$. Let $ S(k) = sum_(i=1)^n b_i^k $ Find $S(k) mod M$ for $n = 60, k = 123456789987654321, M = 998244353$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #230 #problem-heading(230, [Points]) There are $K$ points and $M$ lines such that - Every line contains $8$ points. - Every point lies on $8$ lines. - Any two distinct lines intersect in a unique point. - Any two distinct points lie on a unique line. Lines may be straight or curved. What is $K times M$? //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #231 #problem-heading(231, [Maximal Set Reduction]) Let $S = {1,2,3,...,2019}$. Find the maximum value of $x$ such that when any of the $x$ elements are removed from the set then there exist two distinct elements in the remaining set having their sum equal to $2019$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #232 #problem-heading(232, [A Long Walk]) You have a set $S$ that stores distinct points. Let the points consisted in a walk with $30$ teleportations be $(x_0,y_0),(x_1,y_1),dots,(x_30,y_30)$. $(x_0,y_0) = (0,0)$, $(x_30,y_30) = (X,Y)$. For $1 <= i <= 30$, $(x_i,y_i) = (x_(i-1),y_(i-1)+2^(i-1))$ or $(x_i,y_i) = (x_(i-1)+2^(i-1),y_(i-1))$. A walk is called a valid walk when $Y$ lies in the range $[123456789,987654321]$. In a valid walk for $0 <= i <= 29$, insert point $(X-x_i,Y-y_i)$ in set $S$. Find the maximum size of set $S$ by taking $28$ valid walks. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #233 #problem-heading(233, [Manhattan Count]) Let $f(n,x)$ be a function that denotes the number of ways to travel from $(0,0)$ to $(n,n)$ in a 2-dimensional grid without touching/crossing the diagonal formed by the points $(0,x)$ and $(n-x,n)$. From a given point $(a,b)$ you can either travel to $(a+1,b)$ or $(a,b+1)$ in one step. Define $g(n) = sum_(i=1)^n f(n,i)$. Calculate $g(100000) mod 10^9+7$. Example: $f(2,1) = 2$, The two valid paths being #align(center)[ #v(5pt) #include "figures/p233.typ" #v(5pt) ] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #234 #problem-heading(234, [Expected GCD]) You have $2019$ cards in a deck numbered as $1,2,3,dots,2019$. You draw two cards from the deck without replacement. Let $x$ be the expected value of the gcd of the two numbers. Report your answer as $[1000 x]$, where $[x]$ denotes Greatest Integer Function of $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #235 #problem-heading(235, [Divisor Sum]) Let $d(n)$ be the smallest prime divisor of $n$. Calculate $ sum_(k=1)^15120 d(15120!+k) $ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #236 #problem-heading(236, [Frequency Restriction]) Let $f(n,m)$ count the number of sequences $(a_1,a_2,dots,a_m)$ of length $m$ and $1 <= a_i <= n$, such that for each $1 <= i <= n$, $"cnt"(i) <= i$, where $"cnt"(i)$ is the number of times $i$ occurs in the sequence. Find $f(50,1000) mod 10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #237 #problem-heading(237, [Another Permutation Statistics]) Let $a(n)$ be the number of permutations $pi$ of length $n$ satisfying $pi(y) = x$ if and only if $pi(n-x+1) = y$ for all $x$. Find $sum_(k=1)^(10^6) a(k) mod 10^9+7$. Example: $a(4) = 2$ and two permutations are : $2413,3142$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #238 #problem-heading(238, [Power GCD Sum]) Evaluate $ X = sum_(i=1)^n (sum_(d|i) (sum_(gcd(k,i)=d,0<=k<=i) a^k)/(sum_(gcd(k,i)=d,0<=k<=i) a^(-k))) $ for $n = 7777777, a = 788788$. Since $X$ may be large, give your answer as $X mod 10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #239 #problem-heading(239, [Divisor Count]) The function $d(n)$ denotes the number of positive divisors of an integer $n$. For example, $d(6) = 4$, because there are $4$ divisors of $6$ and they are $1$, $2$, $3$ and $6$. We create a function $f(n)$ which denotes _the summation of the number of divisors of the divisors_ of an integer $n$. For example, $f(6) = d(1)+d(2)+d(3)+d(6) = 1+2+2+4 = 9$. Find $sum_(i=1)^2019 f(i!) mod 10^9+7$, where $n!$ means factorial of $n$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #240 #problem-heading(240, [Sieve of Pi-thagoras]) Everybody knows the Sieve of Eratosthenes, but does anyone know the Sieve of Pi-thagoras? In the following pseudocode, assume that "`real`" represents a real number with infinite precision. ```c real sieve_of_pithagoras (integer n) { real ans = 0; for (i = 1; i <= n; i += 1) { for (j = i; j <= n; j += i) { ans += 1 / j^4; } } return ans; } ``` "`^`" in the code implies the power operator. Bunty is a kid living in the year $3019$. He has access to computation power so immense that he can run this code for as large an integer as possible. You challenge Bunty to find a finite integer input $n$ so that it returns at least $r$. Deep down, based on your math skills, you know that this isn't possible for any $r >= r_0$. You are required to find $[10^18 r_0]$ modulo $10^9+7$, where $[x]$ denotes the integral part of $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #241 #problem-heading(241, [Bunty’s Algorithm]) Bunty recently learned about the significance of $d(n)$, the smallest prime divisor of $n$, through which he can quickly extract prime factorisations of numbers! He sits down and drafts an interesting sequence of integers where the integers are bound between the values $2$ to $1,000,000$. To him, a sequence $a_i$ is interesting if $a_i$ is strictly increasing and the corresponding sequence $d(a_i)$ is also strictly increasing. Bunty attempts to write all interesting sequences but soon realises that there are too many of them. Can you, the algorithmist, count the number of interesting sequences modulo $10^9+7$? //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #242 #problem-heading(242, [Unlucky Seven]) Find the remainder obtained when $77 dots.c 7$ ($10^16$ times) is divided by $12345678$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #243 #problem-heading(243, [Determinant]) Let $A_(n times n)$ be a square matrix of order $n = 12345$. The elements of the matrix are defined as $A_(i j) = abs(i - j)$. Find $abs(A) mod 10^9+7$, where $abs(A)$ denotes the determinant of the matrix $A$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #244 #problem-heading(244, [Fun with Divisors Sum]) Let $f(a,b)$ denote the sum of divisors of $a b + 1$ which lies in the range $(a,b)$. For example, $f(3,23) = 5+7+10+14 = 36$. Calculate $sum_(i=1)^(p-1) f(i,p)$ for $p = 1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #245 #problem-heading(245, [Sequence Triples]) Let $f_m$ denote the number of sequence triples $({x_0, x_1, dots, x_m}, {y_0, y_1, dots, y_m}, {z_0, z_1, dots, z_m})$ such that: + $x_0 = y_0 = z_0 = 0$. + Sequences $x_i, y_i, z_i$ are all strictly increasing. + $x_m + y_m + z_m = 4040$. Then calculate $(sum_(i=1)^infinity f_i) mod 10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #246 #problem-heading(246, [Bella Ciao!]) El Professor has a solid plan to heist Royal Mint. Rio needs to hack into its digital security system. Rio chooses a random number between $5$ and $10^10$ (both inclusive). Given two numbers $A = 94069$ and $B = 50549$, the system can be hacked if the number is chosen can be expressed as $A x + B y$, where $x$ and $y$ are non-negative integers. What is the probability Rio hacks into the system? Report your answer as $floor("probability" times 10^12)$, where $floor(x)$ denotes the integer part of $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #247 #problem-heading(247, [Too Difficult]) Given a sequence a consisting of $n$ integers, an inversion is defined as a pair of indices $(i,j)$ such that $i<j$ and $a[i]>a[j]$. Let $"inv"(a)$ denote the total number of inversions in $a$. A permutation $p$ of order $n$ is a sequence $p$ of size $n$ such that for any $1 <= i <= n$, there exists a valid index $j$ such that $p_j = i$. For example, the sequence $p = (1,3,2,4)$ is a permutation of order $4$, and it has $1$ inversion, namely $(2,3)$. Calculate the sum of $"inv"(p)$ over all distinct permutations of order $n = 15$. (Two permutations $p$ and $q$ are different if there is an index $i$ for which $p_i eq.not q_i$.) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #248 #problem-heading(248, [Largest Angle]) Given three points $A(10^17,10^17)$, $B(3 times 10^17,3 times 10^17)$ and $C(X,0)$. If $angle A C B$ is the maximum possible, calculate $floor(sqrt(X))$, where $floor(x)$ denotes the integer part of $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #249 #problem-heading(249, [Mysterious Figure]) One mysterious night a random shape and a box appeared on a square piece of land. Upon close inspection, it was realized that the shape was in fact not at all random and held the passcode for the box. You being the crypto expert were called to open the box. The box read as follows: "The enclosed red area holds the answer". You are provided with the length of the inner squares, which is $98765$. Please find out the passcode, floored down to the nearest integer. #align(center)[ #v(5pt) #include "figures/p249.typ" #v(5pt) ] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #250 #problem-heading(250, [Random Expectations]) Adarsh decided to attend CEN-105 lecture feeling he will learn something new. It turns out the class is extremely boring. He begins writing a random number starting with "$0.$". After the decimal point, he writes a long string of numbers, formed by randomly choosing any prime between $1$ and $9$ repeatedly (ex. $0.7223557333 dots.c$). Let the expected number formed be represented as $p/q$, where $p$ and $q$ are coprime integers, find $p+q$. You can learn about expected value #link("https://brilliant.org/wiki/expected-value")[#text(fill: main-dark-color)[*here*]]. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #251 #problem-heading(251, [Ricket Numbers]) Rick is working on an important mission but Beth has asked him to look after Morty. Rick doesn't want to be disturbed so he wants to keep Morty busy. He knows how much Morty loves challenges and how much he hates numbers, so he asks Morty to "help" him by counting all the rickety numbers upto $12345678$. A number $N$ is said to be Ricket if and only if it is composite and there exists a way to permute all its divisors (except $1$) onto a circle such that the GCD of any two adjacent elements is greater than $1$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #252 #problem-heading(252, [Pegs on Board]) We define $f(R,C)$ as follows: Consider a $2R times 2C$ chessboard. $f(R,C)$ is the number of ways in which you can place $R times C$ pegs on the white coloured squares such that no two pegs are diagonally adjacent to each other. Calculate $f(12345678,87654321)$ modulo $1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #253 #problem-heading(253, [Another Board Game]) Annu wanted to invent a board game to play with his girlfriend Chunnu on their next date. He came across the following problem while trying to look for optimal coloring for his board game. Consider an $N times N$ board where each cell can be coloured black or white. Let $x_i$ denote the number of white cells in the $i$th row and $y_j$ denote the number of white cells in the $j$th column. Define $f(N)$ as the maximum possible value of the sum: $ sum_(i=1)^N x_i (N - y_i) $ Calculate $f(13579)$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #254 #problem-heading(254, [Small permutations]) For a permutation $p$ of size $n$, an index $r$ is called "small" if $p(r) = min(p(1),p(2),dots,p(r))$. Calculate the number of permutations of size $4040$ with exactly $2000$ small indices modulo $1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #255 #problem-heading(255, [Infinite graph]) Let $G = (V,E)$ be an infinite undirected graph whose vertices are ordered pairs of integers, that is $V = ZZ^2$. Given two natural numbers $a$ and $b$, two vertices $(x_1,y_1)$ and $(x_2,y_2)$ share an edge if and only if either one of these conditions hold: 1. $abs(x_1 - x_2) = a$ and $abs(y_1 - y_2) = b$, or 2. $abs(x_1 - x_2) = b$ and $abs(y_1 - y_2) = a$. Let's define the following functions: $f(a,b)$ be $1$ if the graph is connected (there exists a path between any two vertices), and 0 otherwise, and $g(i) = sum_(j=1)^(10^6) f(i,j)$. Evaluate $sum_(i=1)^(10^6) g(i)$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #256 #problem-heading(256, [Many jumps]) Anya is currently at $x_0 = 100$. She will do $10$ jumps as follows: If after $i$ jumps, she is at coordinate $x_i$, then she will jump to some coordinate in the range $[0,x_i]$ chosen uniformly. Let $P([a,b])$ denote the probability that after $10$ jumps Anya lies in the range $[a,b]$. Also, let $ L = lim_(x arrow 0) P([1,1+x]) / x $ Find the value of $floor(L times 10^6)$, where $floor(x)$ denotes the integer part of $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #257 #problem-heading(257, [Subset union]) $X$ is a set of size $202020$. Let $S_1,S_2,dots,S_100$ be subsets of $X$, such that: - For any distinct indices $a,b,c$, the union of $S_a,S_b,S_c$ is not equal to $X$. - For any distinct indices $a,b,c,d$, the union of $S_a,S_b,S_c,S_d$ is equal to $X$. Find the maximum value of $abs(S_1) + abs(S_2) + dots.c + abs(S_100)$. #text(fill: main-dark-color)[#footnote[ $abs(X)$ denote the size of set $X$. ]] //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #258 #problem-heading(258, [Centroids]) Rishak was getting bored during the lockdown. He wanted to text someone special, but his internet was not working, so he started drawing instead. He drew a rectangle $A B C D$ and then labelled $G_1$ as the centroid of $triangle.stroked.t #h(0pt) A B C$ and $G_2$ as the centroid of $triangle.stroked.t #h(0pt) A C D$. The length of $G_1 G_2$ was $377427$. Also, the perimeter of the rectangle $A B C D$ was measured as $3184398$. Can you find out the area of the rectangle? //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #259 #problem-heading(259, [Teleportation]) Nik wants to meet Anya, and so he fires up his teleporter. The teleporter works by independently choosing a random real number between $0$ and $1$ thrice. Suppose the three numbers it chooses are $X$, $Y$ and $Z$. The teleporter then transports Nik to $x = max(X,Y,Z)$. As Anya is smart, she will wait for Nik at the coordinate where the expected distance from her to where Nik lands will be the minimum. If she waits at $x = L$, find $floor(L times 10^9)$, where $floor(x)$ denotes the integer part of $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #260 #problem-heading(260, [Totient sum]) Let $ L = sum_(n=1)^infinity phi(n) / (2020^n-1) $ Here $phi(n)$ is the totient function. It can be shown that $L$ can be represented as $P/Q$, where $P$ and $Q$ are coprime integers, and $Q equiv.not 0 med (mod 1000000007)$. Find the value of $P dot Q^(-1)$ modulo $1000000007$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #261 #problem-heading(261, [Occupying Houses]) There are $65$ houses arranged along a street and numbered from $0$ to $64$. Initially, only the $0$#super[th] and $64$#super[th] houses are occupied and the rest are empty. Then, one by one $63$ buyers come to purchase the remaining houses. Each buyer can choose to occupy a house lying in the center of two consecutive occupied houses. In other words, if the $a$#super[th] and $b$#super[th] houses are occupied and no houses between them are occupied, then the buyer can occupy the $((a+b)/2)$#super[th] house. Calculate the number of ways all the remaining $63$ houses can be occupied modulo $1000000007$. Two ways are different if the order of occupying the houses is different in both ways. (e.g. the $2$#super[nd] person can either occupy the $16$#super[th] house or $48$#super[th] house, both of which are different ways.) #problem-tag(("combinatorics", "recursion")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #262 #problem-heading(262, [Jumping Frogs]) A circular array consists of $7$ points such that the distance between any two neighboring points along the circumference is $1$ unit distance. Two frogs are currently lying on the array. Every second, each frog jumps to one of the adjacent points, with equal probability. Let $f(x)$ be the expected time after which both the frogs occupy the same position in the array if initially, they were $x$ unit distance apart. You are required to find the value of $f(1) dot f(2) dot (3)$. #problem-tag(("probability", "expected value")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #263 #problem-heading(263, [Subset Intersection]) Let $S$ be a set of size $n$. Let $T_k$ be the set of all ordered $k$-tuples $(A_1,A_2,A_3,A_4,dots,A_k)$ where $A_i$ is a subset of $S$, such that $A_1 union A_2 union A_3 union A_4 union dots.c union A_k = S$. Given $n = 2718281828$ and $k = 3141592653$, find the sum of $abs(A_1 sect A_2 sect A_3 sect A_4 sect dots.c sect A_k)^2$ for all $k$-tuples $(A_1,A_2,A_3,A_4,dots,A_k)$ belonging to $T_k$. #text(fill: main-dark-color)[#footnote[ $abs(X)$ denote the size of set $X$. ]] The answer can be huge, so compute it modulo $(10^9+7)$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #266 #problem-heading(266, [The Set 128]) Let $T$ be an array of size $127$ with $T[i] = i$ ($T$ is $0$ indexed). In other words $T = {0, 1, 2, dots, 126}$. Let $M$ be a set of numbers such that: $ M = {a_1/127 + a_2/127^2 + a_3/127^3 + a_4/127^4 : a_i in T, i = 1,2,3,4} $ All the numbers in $M$ are arranged in ascending order. Let $x$ be the $20212021$#super[st] term. Answer the nearest integer of $10^7 x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #267 #problem-heading(267, [Sum it up Rationally!]) Let $F(p)$ be the number of different rational numbers $X$ in the range $(0,1)$ such that when $X$ is written as an irreducible fraction, the numerator and denominator sum to $10^p$. In other words, if $X = a\/b$, such that $a$ and $b$ are coprime, and $a + b = 10^p$. Find summation $F(i)$ from $i = 1$ to $i = 10^10$, modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #268 #problem-heading(268, [Hypothetical Dice]) Jaideep is playing a game with $1234567$-sided dice, its sides are numbered from $1$ to $1234567$ and each side has an equal probability of appearing. First, he rolls a die and if the value obtained on the die was $k$, he takes $k$ dice and rolls all of them. Then find the expected value of the sum of values on all $k+1$ dice. #problem-tag(("probability", "expected value")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #269 #problem-heading(269, [Escaping the Elf]) You are trapped at the center of a big circle of radius $10^9$ units by a mischievous magical elf. Every minute he asks you to choose a direction in which you want to move. In the $i$th minute, you will be allowed to move exactly $i$ units in that direction. However, the elf wants to make it hard for you to escape, so every time you choose any direction he decides whether he wants to allow you to move in the chosen direction or in the direction exactly opposite to your choice. So, if you choose to move towards the left, then the elf can force you to move towards the right, or may allow you to move left. You must take exactly $i$ steps in the ith minute. Find the time in minutes required to escape if both you and the elf play optimally. *Note:* "_Escaping_" refers to reaching a point that is outside of the circle. #problem-tag(("geometry",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #270 #problem-heading(270, [Yet another sum problem]) Let $S = sum_(j=0)^p binom(p,j) binom(p+j,j) 3^j$. Calculate $S mod p^2$ for $p = 10^9+7$. #problem-tag(("combinatorics",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #271 #problem-heading(271, [GCD Fun]) Let $f(x_1,x_2,x_3,dots,x_n) = x_1 x_2 dots.c x_n dot 2^gcd(x_1,x_2,dots,x_n)$. Let $S_n$ be the sum of $f(x_1,x_2,x_3,dots,x_n)$ over all sequences $(x_1,x_2,x_3,dots,x_n)$ where $1 <= x_i <= 10^6$. Find $S_31415$ modulo $10^9+7$. #problem-tag(("gcd",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #272 #problem-heading(272, [The Quirky Binomial]) $ f(n) = sum_(i=0)^floor(n/2) binom(n-2i,2i) $ Find $(sum_(i=0)^(10^6) f(i)) mod med (10^9+7)$. #problem-tag(("binomial coefficient", "observation")) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #280 #problem-heading(280, [777 Strikes Again]) Given $N = 777 dots.c 777$ ($19$ digits). Find the number of values $r$ ($0 <= r <= N$) such that $binom(N,r)$ is divisible by $31$. Since the number of such values can be huge, compute the answer modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #281 #problem-heading(281, [Open Sets]) Let $n = 192837$. For each $i$ from $1$ to $n$, let $x_i$ and $y_i$ be two independently chosen random numbers from $(0,1)$. Let $a_i = min(x_i,y_i)$, $b_i = max(x_i,y_i)$, and $S$ be the intersection of open intervals $(a_i,b_i)$. In other words, $ S = sect.big_(i=1)^n (a_i,b_i) $ It is easy to see that $S$ is itself an open interval. Find the expected length of $S$. It can be shown that the answer can be expressed as $p/q$, where $gcd(p,q) = 1$ and $q equiv.not 0 med (mod 998244353)$. Output $p dot q^(-1) mod 998244353$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #282 #problem-heading(282, [Game Time]) Let $a_(i+1) = (c times a_i + d) mod m$ where $c = 5447196$, $d = 1953840$ and $m = 998244353$ be a pseudo random number generator for $0 <= i <= N-3$ where $N = 100000$ and $a_0 = a_(N-1) = a_N = 0$. One day, Taniya created a game in which there were $N$ blocks arranged sequentially. A player starts at the $1$st block. To go from the $i$th block to the $(i+1)$th block, the player has to take a jump. The jump will succeed with probability $p$, meaning that the player will go to the $(i+1)$th block with probability $p$, otherwise he will have to start from the beginning and will be landed at the $1$st block. The game ends when the player reaches the $N$th block. Further, there is a penalty of $a_i$ coins each time a player lands on block $i$. Taniya was not sure what value to pick for $p$ and so she randomly selected a number from $[0.5, 1]$. Calculate the Expected number of coins a player has to pay before the game ends. It can be shown that the answer can be expressed as $p/q$, where $gcd(p,q) = 1$ and $q equiv.not 0 med (mod m)$. Output $p dot q^(-1) mod m$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #283 #problem-heading(283, [Count the Assignments]) Mark is working on a battleground game where he needs to develop a lobby-making system which assigns players to the teams. Since this game requires extreme teamwork, there needs to be at least $2$ players in each team. However, there is no restriction on the maximum number of players that can be assigned to a particular team. Mark has decided to have $100$ players and $25$ teams in the lobby. He wants to know the number of ways to assign these players to the teams. Since the answer can be large, you are required to find the answer modulo $(10^9+7)$. Two assignments are considered different if it is possible to find a pair of players, who belong to the same team in one assignment and to different teams in another assignment. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #284 #problem-heading(284, [Beautiful Grids]) Let there be a $2718281 times 2718281$ grid of squares with some squares coloured black and others coloured white. It is not possible to have unicoloured grids, i.e. there must be at least one square of each colour in this grid. A grid is called _beautiful_ if it looks the same even when the entire square is rotated by $90degree$ anticlockwise around its center any number of times. A _beautiful_ grid also looks the same when it is reflected across a line joining mid points of opposite sides or a line joining opposite corners. Find the number of possible _beautiful_ grids. Since the answer can be large, compute the answer modulo $(10^9+7)$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #285 #problem-heading(285, [Xor Tree]) You are given a #link("http://courses.ics.hawaii.edu/ReviewICS241/morea/trees/Trees-QA.pdf")[#text(fill: main-dark-color)[rooted tree]] with $2^N$ nodes numbered from $0$ to $2^N-1$. It is rooted at node $0$. For all other nodes $i$, their parent is node $j$ such that $j < i$ and $i$ ^ $j$ is minimised, where ^ denotes the #link("https://en.wikipedia.org/wiki/Bitwise_operation")[#text(fill: main-dark-color)[bitwise XOR]] operator. For example, parent of node $3$ will be node $2$ as: \ $3$ ^ $0 = 3$ \ $3$ ^ $1 = 2$ \ $3$ ^ $2 = 1$ Let $f(N)$ be the sum of all pairwise distances modulo $10^9+7$ for a tree with $2^N$ nodes, where distance between two nodes in a tree is defined as the number of edges in the shortest path between them. $f(1) = 1$, $f(2) = 10$. Find $f(1234567654321)$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #286 #problem-heading(286, [Tiling Game]) Alice and Bob are playing a game on a $n times m$ grid. Initially, the grid is empty. On each move, a player can place either a $1 times 1$ domino, or a $1 times 2$ domino (either vertically or horizontally), such that the new domino does not partially or completely overlap with any previously placed domino. Alice moves first. The player who cannot make a move loses the game. For an $i times j$ board, define $f(i,j) = 1$ if Alice wins with optimal play; 2 if Bob wins with optimal play. Calculate $sum_(i=1)^989898 sum_(j=1)^989898 f(i,j)⋅(i+j)$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #287 #problem-heading(287, [Heptagonal Distances]) Let there be a regular Heptagon inscribed in a circle of radius $357$ units. Find the sum of the square of distances between all pairs of vertices of the Heptagon. In other words, let $v_1,v_2,v_3,dots,v_7$ be the vertices of the Heptagon, and $D_(i,j)$ be the distance between vertex $v_i$ and $v_j$. Find $S = sum_(1 <= i < j <= 7) D_(i,j)^2$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #288 #problem-heading(288, [Stonks]) The stocks of a company were valued at $N = 123456$ on day $0$. Every day for the following $M = 217127$ days, the value either rose by $1$ or decreased by $1$. Note that the value never remained the same. After $M$ days, the final value was observed to be $172213$. Determine the number of distinct ways in which the stock value could have changed over the $M$ days, such that it never exceeded $L = 200000$. Since the number of ways can be huge, print them modulo $10^9+7$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #289 #problem-heading(289, [The Cubone Problem]) A cube of side $12345$ units is inscribed in a right circular cone having ratio of Height to Radius as #box($9876:1$). It is inscribed such that one face of the cube is contained in the base of the cone. Calculate the Radius $R$ of the Cone. You are required to find $[10^5 R]$ where $[x]$ denotes the integral part of $x$. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #299 #problem-heading(299, [Merge it!!!]) You are given an array of integers of length $1000$, the array is given by the following recurrence relation: $a[i] = a[i-1]^a[i-1] mod 100003$ and $a[0] = 2$. You can perform the following operation on it: In one operation you can select any two adjacent elements $X$ and $Y$, remove both of them and place element $X+Y$ in their old position. After performing this operation you score increments by $X+Y$. E.g. if you combine $4$ and $8$, score will increase by $12$. Find the expected value of the final score after performing the operation $999$ times. Report the integer part of your answer. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #300 #problem-heading(300, [Being the CR]) You are the CR of your class. One day, $5000$ students of your class gathered in a row. The professor assigned you to arrange the students in increasing order of their enrollment number. For rearranging students you follow the given strategy: + Start from the beginning of the row. + Inspect the first two students' enrollment numbers and swap them if second student's enrollment number < first student's enrollment number. + Repeat Step 2 for (2#super[nd] student, 3#super[rd] student), (3#super[rd] student, 4#super[th] student) and so on. You decide to follow the above strategy $2022$ times. Find the number of different initial arrangements of students that will lead to a sorted sequence after the whole process. Report the answer modulo $1000000007$. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #301 #problem-heading(301, [Bi-Power]) How many numbers exists between $0$ to $2^N-1$ which are divisible by $3$ and satisfy the divisibilty test for $3$ in their binary representation as well. Report the answer modulo $1000000007$ for $N = 123456789$. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #302 #problem-heading(302, [Tennis Tournament]) In a tennis tournament, $N = 1234567890$ people participate. The organizing committee numbered all the people as $1,2,3,dots,N$ based on their abilities (ability of participant $1$ > ability of participant $2$ > ability of participant $3$ > $dots.c$ > ability of participant $N$). Every participant has the same number (say $M$) of friends in the tournament. A participant calls himself *superior* if his ability is greater than more than half of his friends. For example, if $M = 13$, then a participant will consider himself *superior* if his ability is greater than $6$ of his friends; for $M = 14$, a participant will be *superior* if his ability is greater than $7$ of his friends. Find the maximum possible number of participants that can consider themselves as *superior*. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #303 #problem-heading(303, [Las Vegans]) Jack and John 2 vegans, after getting a job, go to a casino. There are two games in the casino: *Game A:* Both the players run a machine and get a number each. If both numbers have $2$ and $3$ as their only common prime factors (mathematically if $a = 2^u 3^v x$ and $b = 2^w 3^z y$ with $gcd(x,y) = 1$), then they get $2$ points. Else they get no points. *Game B:* Both have a $6$ mm matchstick. They throw it together on a large rules page, where the distance between each line is $6$ cm. On landing each matchstick will either cut a line or not. They get $1$ point if both the matchsticks cut any line. If prize pool of Game A is $1000$ dollars, then what should be the prize pool of B such that both have equal winnings if initial cost is same. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #304 #problem-heading(304, [Radicalism]) Rainboy always hated irrational numbers and he hated radicals even more, to irritate him RadeWoosh came up with a very irritating problem which involved irrational numbers. The problem can be formally stated as below: RadeWoosh wants Rainboy to express $(sqrt(3) - sqrt(2))^(999 dots.c 9 med (18 "digits"))$ as $sqrt(a) - sqrt(b)$ where $a$ and $b$ are consecutive whole numbers and $a > b$. Help Rainboy to find the $a$ modulo $1000000007$. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #305 #problem-heading(305, [Creep Toe]) You are given a circular necklace that has $m times n$ beads. Each bead is initially uncoloured. Let $f(m,n)$ denote the number of ways you can assign colours to the necklace beads where each bead can have one of $m$ ($m >= 2$) colours, using each colour on exactly $n$ beads ($n >= 1$). $2$ Necklaces are considered same if they give the same view after rotating. Find $sum_(n=2)^4 sum_(m=2)^5 f(m,n)$. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #306 #problem-heading(306, [PP vs NP]) Rob is a chess freak but he also likes to play Sudoku. Since he is bad at both the games, he wants to make a new game. In this game he will take a $n times n$ chess board. He will then place all the numbers $1,2,3,dots,n$ in each row and in each column. But to win the game you have to place these numbers in such a way that in each row, all the numbers from $1$ to $n$ are placed and similarly in each column numbers from $1$ to $n$ are placed. Also for each row and column, then numbers on white squares sum to the same amount as the number on black squares. He wants to get the chess board printed. He likes to know for what value of $n$ such a board can be made. In other words, for what value of $n$ such a placement is possible for at least one configuration. Find the sum of all such $n <= 10^123$. Since this number is large, find it modulo $1000000007$. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #307 #problem-heading(307, [Eloquent]) Alice is very confident about her Vocabulary, according to her _lively_ words are those which contain only characters `A`, `B`, `C` and the frequency of each of them should be the same. Alice has a word $S$ of $1999998$ characters (`A`, `B`, `C` each occur $666666 $ times). Now Bob has a word $T$ (which is _lively_ as well) and he wants to know the minimum number of moves he needs to make in order to change the word from $S$ to $T$ in the worst case (irrespective of the words $S$ and $T$). In a single move Bob can only swap neighboring letters. Report the answer divided $2$ modulo $1000000007$. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #308 #problem-heading(308, [Deathnoted]) Tourist is a very curious person by nature. He has a infinite square notebook, on the $i$#super[th] page of the notebook he writes the number of ways he can write $i$ as sum of the area of two squares having integral side lengths. As he is eternal he will keep writing such sum on each day till infinity. His friend Umnik is very curious to find out what the sum of numbers written on all these pages would be. Since the number can be too large, he wants to find the sum of numbers on each page divided by Tourist's lifespan. Mathematically, if $F(i)$ is the number written on each page, he wants to find $lim_(n arrow infinity) (sum_(i=1)^n F(i))/n$. Help Umnik in finding this number. Let this answer be $x$, report the integer part of $10^12 x$. #problem-tag(("numberphile2022",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #310 #problem-heading(310, [Kelvin’s Counting Corundum]) <NAME> has recently invented the kelvin scale. He is curious as to how many numbers from $A = 131003220303$ to $B = 251203160303$ (both inclusive) are co-prime with $273$. Print the answer modulo $61074397$. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #312 #problem-heading(312, [Kuti-Pi’s Wet Farm]) Kuti-Pi has a circular farm of radius $1$ unit. He loves to irrigate his farm. For the next $N$ days, he chooses a random point on his farm and irrigates a circular area concentric with the farm, passing through the chosen point. Let $S$ be the total sum of the areas he has to irrigate in $N$ days. The probability of $S$ being less than $x$ ($0 < x < upright(pi)$) is $P(x,N)$. Calculate $"Ans" = sum_(n=0)^infinity upright(pi)^n P(sqrt(3),n)$. Report $floor("Ans" times 10^5)$. $floor(a)$ denotes the Greatest Integer Function of $a$. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #313 #problem-heading(313, [So Close Yet So Far]) A random point is chosen inside a sphere of radius $1$ unit centred at a point $O$. This process is repeated until the chosen point is closer to $O$ than the previous point. Let $"Ans" =$ expected number of points chosen. Report $floor("Ans" times 10^5)$. $floor(a)$ denotes the Greatest Integer Function of $a$. *Note:* Probability of the radius of a point being $r$ is proportional to $r^2$. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #314 #problem-heading(314, [Let’s be Wholesome]) $S = 1,3,5,7,dots,6969$. A subsequence of length $3$, say ${a,b,c}$, is said to be bad if it satisfies the relation $a < c < b$. Any rearrangement of $S$, say $P$, is said to be wholesome if there exists no bad subsequence of length $3$ in it. Calculate the number of wholesome rearrangements of $S$. Report the answer modulo $10^9+7$. *Note:* A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #315 #problem-heading(315, [Rangeela’s Madness]) There is an infinite 3D space of integer coordinates. Each point is colored by an unknown color, selected out of $666666$ options. The cost of an $L times B times H$ cuboidal region is $10^30 times L + 10^15 times B + H$. Rangeela wants to buy a cuboidal region that definitely has a cuboid inside it with all its corners having the same color but is lazy enough to not check the grid manually. Compute the values of $L$, $B$ and $H$ to minimize the cost incurred by Rangeela. Print $(L + 2 times B + 3 times H)$ modulo $1234567891$. *Note:* $L$, $B$, $H$ denote the number of points, not the edges between the points. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #316 #problem-heading(316, [Murder Attempt \#4473]) Kaido is a sad boy. So, he wants to do some fun things like killing. Luckily for him, his $420420419$ friends decided to play a Squid Game along with him. This version of the Squid Game is described as follows: Everyone stands in a circle facing the centre. They are standing in positions numbered from $1$ to $420420420$ in clockwise sense. They have one gun which is currently held by the person in position $1$. He begins the game by shooting the person in position $2$. Shootings are alternate, if the last shoot was left, the next is right. If it was right, the next is left. After shooting left, the gun is passed on to the left. After shooting right, the gun is passed on to the right. Luckily for him, he has managed to witness the entire massacre and is the last person alive among all his friends. Which position was Kaido sitting on to survive the massacre? #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #317 #problem-heading(317, [Death Sum]) Calculate $ sum_(a_1=1)^n sum_(a_2=1)^(a_1) sum_(a_3=1)^(a_2) dots.c sum_(a_r=1)^(a_(r-1)) 1 $ for $n = 1000005$ and $r = 1000005$. Report the answer modulo $1234567891$. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #318 #problem-heading(318, [Not My Scarf Not My Cap]) There are $2023$ men each having a cap and a scarf of their own. A woman collects caps and scarves of all these $n$ men and distributes each of them a cap and scarf randomly. Find the probability that for every natural number $k < 1011$ there does not exist a subgroup of men of size $k$ such that every man's scarf and cap belongs to someone in the subgroup. The answer will be $p\/q$ (where $p$ and $q$ are co-prime), report it as $p dot q^(-1) mod med (10^9+7)$. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #319 #problem-heading(319, [Super Strings]) Consider all strings of length $n$ made up of characters `a`, `b` and `c`. $A_n$ be the number of strings such that the substring `abc` occurs exactly once. $B_n$ be the number of strings such that one of the substrings `aacc`, `bcab` and `cbba` occurs exactly once and the other two do not occur at all. Find $ sum_(n=100)^1000 (A_(n-1) B_(n+1) A_(n+1)) / (B_n B_(n+2) A_n) $ The answer can be expressed as $a\/b$ such that $a$ and $b$ are co-prime. Report $a + b$. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #321 #problem-heading(321, [Honeycomb]) A regular hexagon of side length $a = 6$ is present inside a larger regular hexagon of side length $b = 18$. Initially, the smaller hexagon is placed such that one of its vertices coincides with that of the larger hexagon. Now, the smaller hexagon starts moving at an angle $theta$ from one of the touching edges such that $tan(theta) = 11 sqrt(3)$. #align(center)[ #v(5pt) #include "figures/p321_1.typ" #v(5pt) ] If any edge of the smaller hexagon touches the larger hexagon, then the smaller hexagon "reflects off" (see GIF for clarification) according to laws of reflection, and the smaller hexagon always stays inside the larger one. However, if any vertex of the smaller hexagon coincides with any vertex of the larger hexagon, then the smaller hexagon stops moving. If the total distance traveled by the centre of the smaller hexagon until it stops moving is $d$, then give the value of $d^2$. *Note:* Data is given such that it will stop moving. Here is a gif demonstrating the motion of the smaller hexagon (please note in this gif, $tan(theta) eq.not 11 sqrt(3)$): #text(fill: main-dark-color)[#footnote[ Source: #link("http://i.imgur.com/w6pTmLj.gif")[#text(fill: main-dark-color)[http://i.imgur.com/w6pTmLj.gif]]. This file is also attached to this PDF. Only several key frames of this gif are given here. ]] #align(center)[ #v(5pt) #include "figures/p321_2_1.typ" #v(5pt) #include "figures/p321_2_2.typ" #v(5pt) #include "figures/p321_2_3.typ" #v(5pt) #include "figures/p321_2_4.typ" #v(5pt) ] #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #322 #problem-heading(322, [<NAME>]) John wants to walk along an infinitely long straight line with integer points. There are mines located at points $0,d,2d,3d,dots$ where $d = 2198200612608$. John occupies the open interval $(0,w)$ in the beginning and $w = 250000000$. Now, he can move along the line with a fixed positive integer stride length $s$ ($s < d$), that is, it can move from interval $(a,a+w)$ to $(a+s,a+w+s)$. John dies if his occupied interval has a mine in it. Let $S_max$ and $S_min$ be the maximum and minimum stride length, required to keep John alive. Evaluate $floor(S_max\/S_min)$. *Note:* $floor(x)$ denotes the Greatest Integer Function of $x$. \ *Note:* It is guaranteed that atleast one valid s exists. #problem-tag(("endgame 9.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #326 #problem-heading(326, [Digits Play]) Let $x$ be the maximum $77$ digit decimal number whose sum of digits is equal to the product of its digits. Answer a $10$-digit number such that the $i$#super[th] digit from the left is ($j mod 10$), where $j$ is the frequency of the digit ($10-i$) in $x$. #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #327 #problem-heading(327, [My Disappointment is Immeasurable and My Day is Ruined]) Compute the following summation: $ 4/upright(pi) sum_(m=0)^n integral_0^infinity (dif x)/(upright(e)^x + upright(e)^(-x))^(2m+1), quad n = 696969 $ Given that the answer is of the form $p/q$, where the greatest common divisor of $p$ and $q$ is $1$, find the value of $x$ where $x equiv p dot q^(-1) mod 1234567891$ and $0 <= x < 1234567891$. #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #329 #problem-heading(329, [Use Calculator]) Consider a number in base $10$, without leading zeros (zero is taken as $0$), written as digits made from identical straight segments. #align(center)[ #v(5pt) #include "figures/p329.typ" #v(5pt) ] Now in each operation, we are allowed to move or even rotate any of these segments such that the final picture obtained is also a number. For example, the number $69$ has total $12$ segments, so it can be changed to $427$, which has $12$ segments too. Let $M(n)$ denote the largest number which can be obtained from $n$ using any number of such operations. Also, let $S(n)$ denote the sum of digits of $n$ in base $10$. Find: $S(sum_(i=0)^N S(M(i)))$. where $N = 10^2023-1$. #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #330 #problem-heading(330, [Pythagorean Quest]) Lucifer and Mamba are trying to construct a right-angled triangle. Lucifer chooses a positive real number randomly for the base and similarly, Mamba chooses a positive real number randomly for the perpendicular. Given that the hypotenuse is smaller than $2003$, what is the probability of the absolute difference of the two chosen numbers being greater than $1$? Print the greatest integer smaller than or equal to (answer $times 10^8$). #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #331 #problem-heading(331, [Colourful Wand]) The sorcerer is crafting a wand for himself that contains $101$ pearls in a specific sequence. Each pearl is magically generated and can be either _red_ or _blue_ in color, with an equal probability for each. The power of the wand is the maximum number of consecutive pearls of the same colour. The expected power of the wand is $x$. $x$ can be represented as $p/q$ such that $gcd(p,q) = 1$. Find $p q^(-1) mod 1234567891$. #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #332 #problem-heading(332, [Chopper]) A very long stick is about to be passed through a special random chopper at speed $1$ m/s. Before passing the stick through the chopper, we put a special mark at some point on the stick. The special random chopper chops the stick at time $t$ after the previous chop (or time $t$ after starting for the first chop) with probability $5 upright(e)^(-5t)$. If the expected value of the length of the stick with the special mark is $p/q$ in meters, where $gcd(p,q) = 1$, find $p dot q^(-1) mod 1000000007$. #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #333 #problem-heading(333, [Another Banger]) You have been given n characters $a_0,a_1,a_2,dots,a_n$. They are arranged in their lexicographical value, i.e. $a_0 < a_1 < a_2 < a_3 < dots.c < a_n$. Now, you have to determine the number of all the strings of length $n = 2702$ such that for every character equal to $a_k$ in the string, $a_k+1,a_k+2,a_k+3,dots,a_n$ must appear before it at least once. Answer the value as modulo $1000000007$. Note that it is not necessary to use all the characters in a string. #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #335 #problem-heading(335, [Power Game]) A number $x$ is called _powerful_ if it has $10^9+7$ digits such that every digit of $x$ is odd, and $x equiv 3125 med (mod 298023223876953125)$. If the total number of _powerful_ natural numbers is $A$, find $A mod 10^9+7$. #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #337 #problem-heading(337, [Tuta Puta]) There are $k$ different types of characters in Tuta-Puta language. You start adding these characters to an empty string. At every addition, you choose any one of these $k$ characters with equal probability. You stop when every type of character occurs odd number of times in the string. What is the expected length of your string if $k = 2282023$ ? Given that the answer is of the form $p/q$, where the greatest common divisor of $p$ and $q$ is $1$, find the value of $x$ where $x equiv p q^(-1) mod med (10^9+7)$ and $0 <= x < 10^9+7$. #problem-tag(("numberphile23",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #342 #problem-heading(342, [Digit Frequency]) Let $x$ be the largest $444$-digit decimal number that satisfies the following properties: - The frequency of each digit in $x >= 111$. - It should be a perfect square. - The frequency of each digit in the square root of $x$ is also $>= 111$. You need to find the sum of digits of its square root. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #343 #problem-heading(343, [Stringer]) Given a string of length $n$ made up of $5$ characters `a`, `b`, `c`, `d` or `e`. Let $S(n)$ denote the number of strings of length $n$ such that any of `ab`, `ac`, `ad`, `eb`, `ec` or `ed` doesn't occur as a substring in the string of size $n$. Calculate $(sum_(i=1)^(10^18) S(i)) mod 1000000007$. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #344 #problem-heading(344, [Lata’s Conundrum]) Lata has been tasked with a problem by her teacher, if she can solve it, she will pass the teacher's course. The problem goes as follows: The teacher will randomly pick a set $S$ of $x$ distinct integers from $0$ to $2^N - 1$ where $N = 1234567891$. In order to pass the class, Lata has to pick a subset of elements from set $S$ known as set $Y$, such that the number found by taking the xor of all the elements in the set $Y$ is present in the set $S-Y$. Note that $Y$ can be an empty set and xor of elements in an empty set is $0$. The teacher is lenient so he will give Lata the chance to choose $x$ i.e. the size of set $S$. Lata must pass the class or her parents will be disappointed in her, she asks for your help to find the minimum $x$ that will ensure that she will pass the class regardless of the set $S$ chosen by the teacher. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #345 #problem-heading(345, [Team Up]) There are $50000$ teams each containing $30$ players with experience points $1,2,dots,30$ and there are $1500$ teams containing $30$ players each with $0$ experience points. One mega team has to be formed from these players. The mega team can have any number of players. Suppose the mega team have $n$ players and the experience point of $i$#super[th] player is $a_i$. Then the score of the mega team is defined as $sum_(i=1)^n 2^(a_i)$. Find the distinct number of mega teams with score $474288 mod 1000000007$. Two Mega teams are considered different, if there is a particular player present in one team and not in another team. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #346 #problem-heading(346, [Game of Numbers]) Ram and Shyam play a game, the game goes as follows: You have been given a number $m$, all the divisors of $m$ are written on $"sigma"(m)$ separate balloons where $"sigma"(m)$ denotes the number of divisors of $m$. At each turn, a player can pop a balloon with the number $x$ on it, if $x$ is divisible by $d$ or $d$ is divisible by $x$ where $d$ is the number on the last balloon popped in the game. Assume that Ram starts the game and the game has alternate turns. On initial turn, Ram can pop any balloon. Let $f(m) = 1$ if Shyam wins else $0$ if Ram wins. If both players play optimally, find $sum_(i=1)^123456789 f(i)$. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #347 #problem-heading(347, [Magic Number]) Athlestan is new to the maths class, his maths tutor assigned him a very hard problem and you need to help him in order for him to pass his class. Athlestan needs to find the smallest $10$ digit number such that the sum of its digits is divisible by $7$ and the number itself is divisible by $3$. You are his only hope, please help him. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #348 #problem-heading(348, [Downfall]) Each cell of a $23 times 23$ grid is colored green, red, or blue. Luke starts at the top-right cell of the grid and walks to the bottom-left cell either by moving one cell to the left, or one cell down. So, he goes through exactly $45$ cells on his walk (including the top-right and bottom-left cells). Find the number of colourings in which Luke is guaranteed to pass through exactly $7$ red cells, exactly $19$ green cells, and exactly $19$ blue cells no matter which path he travels on. Submit your answer modulo $10^9+7$. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #349 #problem-heading(349, [Fibonacci Fusion]) Let $F_0 = 0$, $F_1 = 1$, $F_n = F_(n-1) + F_(n-2)$ for $n > 1$. $ (sum_(i_(N-1)=1)^(i_N) (dots.c ((sum_(i_1=1)^(i_2) ((sum_(i_0=1)^(i_1) F_(i_0)) + F_2)) + F_4) dots.c)) + F_(2N) $ For $N = 10^5$, find the value of the above expression modulo $10^9+7$ for $i_N = N$. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #356 #problem-heading(356, [On A Walk]) Joseph decided to go on a walk! At each step he either moves one step ahead or one step back. He starts from origin and intends to reach the point $j$ in n steps. Furthermore he should never cross the origin and reach the negative area. We define $Q(j,n)$ as the number of ways to reach point $j$ in $n$ steps. For $j = 26$ and $n = 123456$. Find $Q(j,n) mod 1000000007$. #problem-tag(("endgame 10.0",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #358 #problem-heading(358, [Diagonal Dominance]) You are given an $n times n$ matrix filled with the numbers $1,2,3,dots,n^2$. The matrix is arranged such that every row (from left to right) and every column (from top to bottom) is sorted in strictly increasing order. Let $a_(i j)$ denote the number at the intersection of the $i$-th row and $j$-th column. For each $i$ where $1<=i<=n$, define $b_i$ as the number of distinct entries that can appear in the diagonal position $a_(i i)$. Your task is to find the sum $b_1+b_2+dots.c+b_n$ for $n=1000$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #359 #problem-heading(359, [Android 17]) Let $S(n)$ denote the number of x such that $1<=x<n$ and $x^23 equiv 1 thin (mod n)$. For example, $S(4)=1$ because $1^23 equiv 1 thin (mod 4)$, but $2^23 equiv 0 thin (mod 4)$ and $3^23 equiv 3 thin (mod 4)$. Let $F(k)$ denote the number of $n$ between $1$ and $10^18$ such that $S(n)=k$. Find the summation $(sum_(n=10^9)^infinity F(n)) mod thin (10^9+7)$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #360 #problem-heading(360, [<NAME> Phi]) Let $C(n)$ be $sum (phi.alt(a) times b)$ taken over ordered pairs $(a,b)$ of positive integers for which $a times b$ divides $n$. Let $F(k)=sum_(i=1)^k C(i)/i$. Let $x=sum_(k=1)^infinity F(k)/(k times 2^k)$. Output $floor(x times 10^5)$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #361 #problem-heading(361, [Hyperoperation]) Find $a^a^a^a^a^a^dots.up$ till _infinite_ modulo $n$, where $n=7908922576125228087$ and $a=321298371289423$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #362 #problem-heading(362, [Big Josephus]) There are $n$ balloons in a cyclic room numbered from $1$ to $n$ (Balloon $2$ comes after $1$, Balloon $3$ comes after $2$, ..., Balloon $1$ comes after Balloon $n$). You start at $1$. Every turn you skip one balloon and pop the next balloon until there is only one balloon left. Let $F(n)$ denote the number on the last remaining balloon. Find the sum of $F(1)+F(2)+F(3)+dots.c+F(182721378)$ and submit the answer modulo $10^9+7$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #363 #problem-heading(363, [Are you my Dad?]) Young Jake walked into a bar. There were $n$ men inside the bar, one of whom was Jake's Dad, whom he had never met. He makes a guess on who is his father among the $n$ men and asks him, "Are you my Dad?". If he finds his dad, he returns home with his dad. Otherwise, the man $A$ whom Jake asked takes pity on him. Then, man $A$ guesses from the other $n-1$ men who might be his dad. The man $A$ takes Jake to his guessed person $B$ and asks him if he is Jake's dad. If the guessed man $B$ is Jake's dad, they go home; otherwise, man $B$ takes Jake from man $A$ and continues to guess who might be Jake's father like man $A$ did. At the point when the current man who Jake is with makes a guess on a person who has already been checked, Jake leaves the current man, goes back to the bar entry, and again guesses who might be his dad. (Jake will never guess the same person or let any other man guess the same person that has already been checked before.) This process continues until Jake finds his Dad. What is the expected number of times Jake says, "Are you my Dad?" when $n=400$? Let $M=10^9+7$. It can be shown that the answer can be expressed as an irreducible fraction $p/q$, where $p$ and $q$ are integers and $q equiv.not 0 thin (mod M)$. Output the integer equal to $p dot q^(-1) mod M$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #364 #problem-heading(364, [Nice Fractions]) There is a monster who is destroying planet Earth. To counter them, there is a special force of heroes. The heroes are numbered according to their strengths. The strength of the $k$-th hero is the $k$-th largest number in the set $ S = {x | x = inline(sum_(i=1)^20 a_i/6^i), 0<=a_i<=5 "for each" 1<=i<=20}. $ Find the strength of the hero who is weaker than $553453543$ heroes. Let $M=10^9+7$. It can be shown that the answer can be expressed as an irreducible fraction $p/q$, where $p$ and $q$ are integers and $q equiv.not 0 thin (mod M)$. Output the integer equal to $p dot q^(-1) mod M$. In other words, output such an integer $x$ that $0<=x<M$ and $x dot q equiv p thin (mod M)$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #365 #problem-heading(365, [Watch your Enemy]) In geometry, a tesseract or $4$-cuboid is a four-dimensional hypercuboid, analogous to a two-dimensional rectangle and a three-dimensional cuboid. We have a Tesseract with dimensions $a$, $b$, $c$, and $d$. Bob and Alice are playing a game with the Tesseract. In one move, a player can perform the following action: They choose one dimension $s$ out of the four of the Tesseract. They change the dimension to $i$ units. This move is only allowed if: $ gcd(s, s-i) = s-i "and" i<s "and" i>0 $ For example, they can change the dimension of length $8$ to a dimension of length $7$, $6$ or $4$. Both players are smart, so it is assumed they play optimally. The player who cannot perform a move loses. Let $F(n)$ indicate the number of sets of dimensions $(a,b,c,d)$ where $1<=a,b,c,d<=n$ such that Alice wins if Bob starts the game. Two sets are considered different if any one of the dimensions is not the same in both sets. For example, $(1,2,1,1)$ and $(2,1,1,1)$ are different sets. Find $F(324325346214122) mod 987654321$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #366 #problem-heading(366, [Prime Dices]) You have a set of dice, where each die has a number of sides that corresponds to a prime number less than $10^7$. For example, the set includes dice with $2,3,5,7$ and other prime numbers of sides. A die is chosen randomly from this set. After selecting the die, you keep tossing it until every face of the die has appeared at least once. For instance, for a $3$-sided die, you might toss the die multiple times until you have seen all three faces ($1$, $2$ and $3$) at least once. The sequence of tosses could look something like $2,1,1,2,3$, which means it took $5$ tosses to see all three faces. Your task is to find the expected number of tosses required to see all faces of the die you picked. Report the result modulo $10^9+7$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #367 #problem-heading(367, [Circular Dilemma]) Consider a rectangle with dimensions $l=1234567891$ and $b=1987654321$. A point is selected uniformly at random within the rectangle. From this point, a circle is drawn with a radius chosen uniformly between $0$ and the maximum possible radius that allows the circle to remain entirely within the rectangle. What is the expected value of the $"area of circle"/pi mod thin (10^9+7)$? #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Problem #368 #problem-heading(368, [Skill Issue]) In a knockout tournament with $n=2^k$ players, each player's skill is independently drawn from a uniform distribution on the interval $[0,1]$. When two players with skills $S_1$ and $S_2$ compete, the "lead" of the game is given by $|S_1-S_2|$, and the player with the higher skill advances to the next round. The organizers aim to minimize the total sum of the leads across all matches in the tournament. For example, if there are $4$ players with skills $0.3,0.6,0.4,0.5$, an optimal pairing strategy might be to match players with skills $0.6$ and $0.5$ and players with skills $0.3$ and $0.4$, resulting in a total lead sum of $(0.6-0.5)+(0.4-0.3)+(0.6-0.4)=0.4$. Given $k=12345678987654321$, find the expected sum of leads modulo $10^9+7$. #problem-tag(("numberphile24",)) //------------------------------------------------------------------------------
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/exers/p.typ
typst
#import "../cfg.typ": * #show: cfg
https://github.com/connachermurphy/typst-slides
https://raw.githubusercontent.com/connachermurphy/typst-slides/main/sample_slides.typ
typst
MIT License
#import "template_slides.typ": * #import "@preview/tablex:0.0.5": tablex, cellx #set math.equation(numbering: "(1)") #set figure.caption(position: top) #let title = "Sample Slide Deck" #let title_short = "Murphy (In Progress)" #let date = "November 20, 2023" #let author = "<NAME>" // #let accent_color = blue // #let accent_color = eastern #let accent_color = olive // Don't want to indent if a slide is entirely bullets // #set enum(indent: 5pt) // #set enum(indent: 5pt) // #set list(indent: 5pt) #show: presentation.with(title, author, date) #slide(heading: "A standard slide.", title_short: title_short, lab: "first-slide")[ - An insightful bullet point - An even more insightful bullet point ] #divider(heading: "Divider Slide") #slide(heading: "Yet another slide" + linkbox("first-slide", fill: accent_color)[back to other slide], title_short: title_short)[ Lots of insightful content #linkbox("first-slide", fill: accent_color)[back to other slide] #stylebox( color_bar: accent_color, color_fill: accent_color )[ Here is a box I use for theorems and definitions. ] ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A000.typ
typst
Apache License 2.0
#let data = ( ("YI SYLLABLE IT", "Lo", 0), ("YI SYLLABLE IX", "Lo", 0), ("YI SYLLABLE I", "Lo", 0), ("YI SYLLABLE IP", "Lo", 0), ("YI SYLLABLE IET", "Lo", 0), ("YI SYLLABLE IEX", "Lo", 0), ("YI SYLLABLE IE", "Lo", 0), ("YI SYLLABLE IEP", "Lo", 0), ("YI SYLLABLE AT", "Lo", 0), ("YI SYLLABLE AX", "Lo", 0), ("YI SYLLABLE A", "Lo", 0), ("YI SYLLABLE AP", "Lo", 0), ("YI SYLLABLE UOX", "Lo", 0), ("YI SYLLABLE UO", "Lo", 0), ("YI SYLLABLE UOP", "Lo", 0), ("YI SYLLABLE OT", "Lo", 0), ("YI SYLLABLE OX", "Lo", 0), ("YI SYLLABLE O", "Lo", 0), ("YI SYLLABLE OP", "Lo", 0), ("YI SYLLABLE EX", "Lo", 0), ("YI SYLLABLE E", "Lo", 0), ("YI SYLLABLE WU", "Lm", 0), ("YI SYLLABLE BIT", "Lo", 0), ("YI SYLLABLE BIX", "Lo", 0), ("YI SYLLABLE BI", "Lo", 0), ("YI SYLLABLE BIP", "Lo", 0), ("YI SYLLABLE BIET", "Lo", 0), ("YI SYLLABLE BIEX", "Lo", 0), ("YI SYLLABLE BIE", "Lo", 0), ("YI SYLLABLE BIEP", "Lo", 0), ("YI SYLLABLE BAT", "Lo", 0), ("YI SYLLABLE BAX", "Lo", 0), ("YI SYLLABLE BA", "Lo", 0), ("YI SYLLABLE BAP", "Lo", 0), ("YI SYLLABLE BUOX", "Lo", 0), ("YI SYLLABLE BUO", "Lo", 0), ("YI SYLLABLE BUOP", "Lo", 0), ("YI SYLLABLE BOT", "Lo", 0), ("YI SYLLABLE BOX", "Lo", 0), ("YI SYLLABLE BO", "Lo", 0), ("YI SYLLABLE BOP", "Lo", 0), ("YI SYLLABLE BEX", "Lo", 0), ("YI SYLLABLE BE", "Lo", 0), ("YI SYLLABLE BEP", "Lo", 0), ("YI SYLLABLE BUT", "Lo", 0), ("YI SYLLABLE BUX", "Lo", 0), ("YI SYLLABLE BU", "Lo", 0), ("YI SYLLABLE BUP", "Lo", 0), ("YI SYLLABLE BURX", "Lo", 0), ("YI SYLLABLE BUR", "Lo", 0), ("YI SYLLABLE BYT", "Lo", 0), ("YI SYLLABLE BYX", "Lo", 0), ("YI SYLLABLE BY", "Lo", 0), ("YI SYLLABLE BYP", "Lo", 0), ("YI SYLLABLE BYRX", "Lo", 0), ("YI SYLLABLE BYR", "Lo", 0), ("YI SYLLABLE PIT", "Lo", 0), ("YI SYLLABLE PIX", "Lo", 0), ("YI SYLLABLE PI", "Lo", 0), ("YI SYLLABLE PIP", "Lo", 0), ("YI SYLLABLE PIEX", "Lo", 0), ("YI SYLLABLE PIE", "Lo", 0), ("YI SYLLABLE PIEP", "Lo", 0), ("YI SYLLABLE PAT", "Lo", 0), ("YI SYLLABLE PAX", "Lo", 0), ("YI SYLLABLE PA", "Lo", 0), ("YI SYLLABLE PAP", "Lo", 0), ("YI SYLLABLE PUOX", "Lo", 0), ("YI SYLLABLE PUO", "Lo", 0), ("YI SYLLABLE PUOP", "Lo", 0), ("YI SYLLABLE POT", "Lo", 0), ("YI SYLLABLE POX", "Lo", 0), ("YI SYLLABLE PO", "Lo", 0), ("YI SYLLABLE POP", "Lo", 0), ("YI SYLLABLE PUT", "Lo", 0), ("YI SYLLABLE PUX", "Lo", 0), ("YI SYLLABLE PU", "Lo", 0), ("YI SYLLABLE PUP", "Lo", 0), ("YI SYLLABLE PURX", "Lo", 0), ("YI SYLLABLE PUR", "Lo", 0), ("YI SYLLABLE PYT", "Lo", 0), ("YI SYLLABLE PYX", "Lo", 0), ("YI SYLLABLE PY", "Lo", 0), ("YI SYLLABLE PYP", "Lo", 0), ("YI SYLLABLE PYRX", "Lo", 0), ("YI SYLLABLE PYR", "Lo", 0), ("YI SYLLABLE BBIT", "Lo", 0), ("YI SYLLABLE BBIX", "Lo", 0), ("YI SYLLABLE BBI", "Lo", 0), ("YI SYLLABLE BBIP", "Lo", 0), ("YI SYLLABLE BBIET", "Lo", 0), ("YI SYLLABLE BBIEX", "Lo", 0), ("YI SYLLABLE BBIE", "Lo", 0), ("YI SYLLABLE BBIEP", "Lo", 0), ("YI SYLLABLE BBAT", "Lo", 0), ("YI SYLLABLE BBAX", "Lo", 0), ("YI SYLLABLE BBA", "Lo", 0), ("YI SYLLABLE BBAP", "Lo", 0), ("YI SYLLABLE BBUOX", "Lo", 0), ("YI SYLLABLE BBUO", "Lo", 0), ("YI SYLLABLE BBUOP", "Lo", 0), ("YI SYLLABLE BBOT", "Lo", 0), ("YI SYLLABLE BBOX", "Lo", 0), ("YI SYLLABLE BBO", "Lo", 0), ("YI SYLLABLE BBOP", "Lo", 0), ("YI SYLLABLE BBEX", "Lo", 0), ("YI SYLLABLE BBE", "Lo", 0), ("YI SYLLABLE BBEP", "Lo", 0), ("YI SYLLABLE BBUT", "Lo", 0), ("YI SYLLABLE BBUX", "Lo", 0), ("YI SYLLABLE BBU", "Lo", 0), ("YI SYLLABLE BBUP", "Lo", 0), ("YI SYLLABLE BBURX", "Lo", 0), ("YI SYLLABLE BBUR", "Lo", 0), ("YI SYLLABLE BBYT", "Lo", 0), ("YI SYLLABLE BBYX", "Lo", 0), ("YI SYLLABLE BBY", "Lo", 0), ("YI SYLLABLE BBYP", "Lo", 0), ("YI SYLLABLE NBIT", "Lo", 0), ("YI SYLLABLE NBIX", "Lo", 0), ("YI SYLLABLE NBI", "Lo", 0), ("YI SYLLABLE NBIP", "Lo", 0), ("YI SYLLABLE NBIEX", "Lo", 0), ("YI SYLLABLE NBIE", "Lo", 0), ("YI SYLLABLE NBIEP", "Lo", 0), ("YI SYLLABLE NBAT", "Lo", 0), ("YI SYLLABLE NBAX", "Lo", 0), ("YI SYLLABLE NBA", "Lo", 0), ("YI SYLLABLE NBAP", "Lo", 0), ("YI SYLLABLE NBOT", "Lo", 0), ("YI SYLLABLE NBOX", "Lo", 0), ("YI SYLLABLE NBO", "Lo", 0), ("YI SYLLABLE NBOP", "Lo", 0), ("YI SYLLABLE NBUT", "Lo", 0), ("YI SYLLABLE NBUX", "Lo", 0), ("YI SYLLABLE NBU", "Lo", 0), ("YI SYLLABLE NBUP", "Lo", 0), ("YI SYLLABLE NBURX", "Lo", 0), ("YI SYLLABLE NBUR", "Lo", 0), ("YI SYLLABLE NBYT", "Lo", 0), ("YI SYLLABLE NBYX", "Lo", 0), ("YI SYLLABLE NBY", "Lo", 0), ("YI SYLLABLE NBYP", "Lo", 0), ("YI SYLLABLE NBYRX", "Lo", 0), ("YI SYLLABLE NBYR", "Lo", 0), ("YI SYLLABLE HMIT", "Lo", 0), ("YI SYLLABLE HMIX", "Lo", 0), ("YI SYLLABLE HMI", "Lo", 0), ("YI SYLLABLE HMIP", "Lo", 0), ("YI SYLLABLE HMIEX", "Lo", 0), ("YI SYLLABLE HMIE", "Lo", 0), ("YI SYLLABLE HMIEP", "Lo", 0), ("YI SYLLABLE HMAT", "Lo", 0), ("YI SYLLABLE HMAX", "Lo", 0), ("YI SYLLABLE HMA", "Lo", 0), ("YI SYLLABLE HMAP", "Lo", 0), ("YI SYLLABLE HMUOX", "Lo", 0), ("YI SYLLABLE HMUO", "Lo", 0), ("YI SYLLABLE HMUOP", "Lo", 0), ("YI SYLLABLE HMOT", "Lo", 0), ("YI SYLLABLE HMOX", "Lo", 0), ("YI SYLLABLE HMO", "Lo", 0), ("YI SYLLABLE HMOP", "Lo", 0), ("YI SYLLABLE HMUT", "Lo", 0), ("YI SYLLABLE HMUX", "Lo", 0), ("YI SYLLABLE HMU", "Lo", 0), ("YI SYLLABLE HMUP", "Lo", 0), ("YI SYLLABLE HMURX", "Lo", 0), ("YI SYLLABLE HMUR", "Lo", 0), ("YI SYLLABLE HMYX", "Lo", 0), ("YI SYLLABLE HMY", "Lo", 0), ("YI SYLLABLE HMYP", "Lo", 0), ("YI SYLLABLE HMYRX", "Lo", 0), ("YI SYLLABLE HMYR", "Lo", 0), ("YI SYLLABLE MIT", "Lo", 0), ("YI SYLLABLE MIX", "Lo", 0), ("YI SYLLABLE MI", "Lo", 0), ("YI SYLLABLE MIP", "Lo", 0), ("YI SYLLABLE MIEX", "Lo", 0), ("YI SYLLABLE MIE", "Lo", 0), ("YI SYLLABLE MIEP", "Lo", 0), ("YI SYLLABLE MAT", "Lo", 0), ("YI SYLLABLE MAX", "Lo", 0), ("YI SYLLABLE MA", "Lo", 0), ("YI SYLLABLE MAP", "Lo", 0), ("YI SYLLABLE MUOT", "Lo", 0), ("YI SYLLABLE MUOX", "Lo", 0), ("YI SYLLABLE MUO", "Lo", 0), ("YI SYLLABLE MUOP", "Lo", 0), ("YI SYLLABLE MOT", "Lo", 0), ("YI SYLLABLE MOX", "Lo", 0), ("YI SYLLABLE MO", "Lo", 0), ("YI SYLLABLE MOP", "Lo", 0), ("YI SYLLABLE MEX", "Lo", 0), ("YI SYLLABLE ME", "Lo", 0), ("YI SYLLABLE MUT", "Lo", 0), ("YI SYLLABLE MUX", "Lo", 0), ("YI SYLLABLE MU", "Lo", 0), ("YI SYLLABLE MUP", "Lo", 0), ("YI SYLLABLE MURX", "Lo", 0), ("YI SYLLABLE MUR", "Lo", 0), ("YI SYLLABLE MYT", "Lo", 0), ("YI SYLLABLE MYX", "Lo", 0), ("YI SYLLABLE MY", "Lo", 0), ("YI SYLLABLE MYP", "Lo", 0), ("YI SYLLABLE FIT", "Lo", 0), ("YI SYLLABLE FIX", "Lo", 0), ("YI SYLLABLE FI", "Lo", 0), ("YI SYLLABLE FIP", "Lo", 0), ("YI SYLLABLE FAT", "Lo", 0), ("YI SYLLABLE FAX", "Lo", 0), ("YI SYLLABLE FA", "Lo", 0), ("YI SYLLABLE FAP", "Lo", 0), ("YI SYLLABLE FOX", "Lo", 0), ("YI SYLLABLE FO", "Lo", 0), ("YI SYLLABLE FOP", "Lo", 0), ("YI SYLLABLE FUT", "Lo", 0), ("YI SYLLABLE FUX", "Lo", 0), ("YI SYLLABLE FU", "Lo", 0), ("YI SYLLABLE FUP", "Lo", 0), ("YI SYLLABLE FURX", "Lo", 0), ("YI SYLLABLE FUR", "Lo", 0), ("YI SYLLABLE FYT", "Lo", 0), ("YI SYLLABLE FYX", "Lo", 0), ("YI SYLLABLE FY", "Lo", 0), ("YI SYLLABLE FYP", "Lo", 0), ("YI SYLLABLE VIT", "Lo", 0), ("YI SYLLABLE VIX", "Lo", 0), ("YI SYLLABLE VI", "Lo", 0), ("YI SYLLABLE VIP", "Lo", 0), ("YI SYLLABLE VIET", "Lo", 0), ("YI SYLLABLE VIEX", "Lo", 0), ("YI SYLLABLE VIE", "Lo", 0), ("YI SYLLABLE VIEP", "Lo", 0), ("YI SYLLABLE VAT", "Lo", 0), ("YI SYLLABLE VAX", "Lo", 0), ("YI SYLLABLE VA", "Lo", 0), ("YI SYLLABLE VAP", "Lo", 0), ("YI SYLLABLE VOT", "Lo", 0), ("YI SYLLABLE VOX", "Lo", 0), ("YI SYLLABLE VO", "Lo", 0), ("YI SYLLABLE VOP", "Lo", 0), ("YI SYLLABLE VEX", "Lo", 0), ("YI SYLLABLE VEP", "Lo", 0), ("YI SYLLABLE VUT", "Lo", 0), ("YI SYLLABLE VUX", "Lo", 0), ("YI SYLLABLE VU", "Lo", 0), ("YI SYLLABLE VUP", "Lo", 0), ("YI SYLLABLE VURX", "Lo", 0), ("YI SYLLABLE VUR", "Lo", 0), ("YI SYLLABLE VYT", "Lo", 0), ("YI SYLLABLE VYX", "Lo", 0), ("YI SYLLABLE VY", "Lo", 0), ("YI SYLLABLE VYP", "Lo", 0), ("YI SYLLABLE VYRX", "Lo", 0), ("YI SYLLABLE VYR", "Lo", 0), ("YI SYLLABLE DIT", "Lo", 0), ("YI SYLLABLE DIX", "Lo", 0), ("YI SYLLABLE DI", "Lo", 0), ("YI SYLLABLE DIP", "Lo", 0), ("YI SYLLABLE DIEX", "Lo", 0), ("YI SYLLABLE DIE", "Lo", 0), ("YI SYLLABLE DIEP", "Lo", 0), ("YI SYLLABLE DAT", "Lo", 0), ("YI SYLLABLE DAX", "Lo", 0), ("YI SYLLABLE DA", "Lo", 0), ("YI SYLLABLE DAP", "Lo", 0), ("YI SYLLABLE DUOX", "Lo", 0), ("YI SYLLABLE DUO", "Lo", 0), ("YI SYLLABLE DOT", "Lo", 0), ("YI SYLLABLE DOX", "Lo", 0), ("YI SYLLABLE DO", "Lo", 0), ("YI SYLLABLE DOP", "Lo", 0), ("YI SYLLABLE DEX", "Lo", 0), ("YI SYLLABLE DE", "Lo", 0), ("YI SYLLABLE DEP", "Lo", 0), ("YI SYLLABLE DUT", "Lo", 0), ("YI SYLLABLE DUX", "Lo", 0), ("YI SYLLABLE DU", "Lo", 0), ("YI SYLLABLE DUP", "Lo", 0), ("YI SYLLABLE DURX", "Lo", 0), ("YI SYLLABLE DUR", "Lo", 0), ("YI SYLLABLE TIT", "Lo", 0), ("YI SYLLABLE TIX", "Lo", 0), ("YI SYLLABLE TI", "Lo", 0), ("YI SYLLABLE TIP", "Lo", 0), ("YI SYLLABLE TIEX", "Lo", 0), ("YI SYLLABLE TIE", "Lo", 0), ("YI SYLLABLE TIEP", "Lo", 0), ("YI SYLLABLE TAT", "Lo", 0), ("YI SYLLABLE TAX", "Lo", 0), ("YI SYLLABLE TA", "Lo", 0), ("YI SYLLABLE TAP", "Lo", 0), ("YI SYLLABLE TUOT", "Lo", 0), ("YI SYLLABLE TUOX", "Lo", 0), ("YI SYLLABLE TUO", "Lo", 0), ("YI SYLLABLE TUOP", "Lo", 0), ("YI SYLLABLE TOT", "Lo", 0), ("YI SYLLABLE TOX", "Lo", 0), ("YI SYLLABLE TO", "Lo", 0), ("YI SYLLABLE TOP", "Lo", 0), ("YI SYLLABLE TEX", "Lo", 0), ("YI SYLLABLE TE", "Lo", 0), ("YI SYLLABLE TEP", "Lo", 0), ("YI SYLLABLE TUT", "Lo", 0), ("YI SYLLABLE TUX", "Lo", 0), ("YI SYLLABLE TU", "Lo", 0), ("YI SYLLABLE TUP", "Lo", 0), ("YI SYLLABLE TURX", "Lo", 0), ("YI SYLLABLE TUR", "Lo", 0), ("YI SYLLABLE DDIT", "Lo", 0), ("YI SYLLABLE DDIX", "Lo", 0), ("YI SYLLABLE DDI", "Lo", 0), ("YI SYLLABLE DDIP", "Lo", 0), ("YI SYLLABLE DDIEX", "Lo", 0), ("YI SYLLABLE DDIE", "Lo", 0), ("YI SYLLABLE DDIEP", "Lo", 0), ("YI SYLLABLE DDAT", "Lo", 0), ("YI SYLLABLE DDAX", "Lo", 0), ("YI SYLLABLE DDA", "Lo", 0), ("YI SYLLABLE DDAP", "Lo", 0), ("YI SYLLABLE DDUOX", "Lo", 0), ("YI SYLLABLE DDUO", "Lo", 0), ("YI SYLLABLE DDUOP", "Lo", 0), ("YI SYLLABLE DDOT", "Lo", 0), ("YI SYLLABLE DDOX", "Lo", 0), ("YI SYLLABLE DDO", "Lo", 0), ("YI SYLLABLE DDOP", "Lo", 0), ("YI SYLLABLE DDEX", "Lo", 0), ("YI SYLLABLE DDE", "Lo", 0), ("YI SYLLABLE DDEP", "Lo", 0), ("YI SYLLABLE DDUT", "Lo", 0), ("YI SYLLABLE DDUX", "Lo", 0), ("YI SYLLABLE DDU", "Lo", 0), ("YI SYLLABLE DDUP", "Lo", 0), ("YI SYLLABLE DDURX", "Lo", 0), ("YI SYLLABLE DDUR", "Lo", 0), ("YI SYLLABLE NDIT", "Lo", 0), ("YI SYLLABLE NDIX", "Lo", 0), ("YI SYLLABLE NDI", "Lo", 0), ("YI SYLLABLE NDIP", "Lo", 0), ("YI SYLLABLE NDIEX", "Lo", 0), ("YI SYLLABLE NDIE", "Lo", 0), ("YI SYLLABLE NDAT", "Lo", 0), ("YI SYLLABLE NDAX", "Lo", 0), ("YI SYLLABLE NDA", "Lo", 0), ("YI SYLLABLE NDAP", "Lo", 0), ("YI SYLLABLE NDOT", "Lo", 0), ("YI SYLLABLE NDOX", "Lo", 0), ("YI SYLLABLE NDO", "Lo", 0), ("YI SYLLABLE NDOP", "Lo", 0), ("YI SYLLABLE NDEX", "Lo", 0), ("YI SYLLABLE NDE", "Lo", 0), ("YI SYLLABLE NDEP", "Lo", 0), ("YI SYLLABLE NDUT", "Lo", 0), ("YI SYLLABLE NDUX", "Lo", 0), ("YI SYLLABLE NDU", "Lo", 0), ("YI SYLLABLE NDUP", "Lo", 0), ("YI SYLLABLE NDURX", "Lo", 0), ("YI SYLLABLE NDUR", "Lo", 0), ("YI SYLLABLE HNIT", "Lo", 0), ("YI SYLLABLE HNIX", "Lo", 0), ("YI SYLLABLE HNI", "Lo", 0), ("YI SYLLABLE HNIP", "Lo", 0), ("YI SYLLABLE HNIET", "Lo", 0), ("YI SYLLABLE HNIEX", "Lo", 0), ("YI SYLLABLE HNIE", "Lo", 0), ("YI SYLLABLE HNIEP", "Lo", 0), ("YI SYLLABLE HNAT", "Lo", 0), ("YI SYLLABLE HNAX", "Lo", 0), ("YI SYLLABLE HNA", "Lo", 0), ("YI SYLLABLE HNAP", "Lo", 0), ("YI SYLLABLE HNUOX", "Lo", 0), ("YI SYLLABLE HNUO", "Lo", 0), ("YI SYLLABLE HNOT", "Lo", 0), ("YI SYLLABLE HNOX", "Lo", 0), ("YI SYLLABLE HNOP", "Lo", 0), ("YI SYLLABLE HNEX", "Lo", 0), ("YI SYLLABLE HNE", "Lo", 0), ("YI SYLLABLE HNEP", "Lo", 0), ("YI SYLLABLE HNUT", "Lo", 0), ("YI SYLLABLE NIT", "Lo", 0), ("YI SYLLABLE NIX", "Lo", 0), ("YI SYLLABLE NI", "Lo", 0), ("YI SYLLABLE NIP", "Lo", 0), ("YI SYLLABLE NIEX", "Lo", 0), ("YI SYLLABLE NIE", "Lo", 0), ("YI SYLLABLE NIEP", "Lo", 0), ("YI SYLLABLE NAX", "Lo", 0), ("YI SYLLABLE NA", "Lo", 0), ("YI SYLLABLE NAP", "Lo", 0), ("YI SYLLABLE NUOX", "Lo", 0), ("YI SYLLABLE NUO", "Lo", 0), ("YI SYLLABLE NUOP", "Lo", 0), ("YI SYLLABLE NOT", "Lo", 0), ("YI SYLLABLE NOX", "Lo", 0), ("YI SYLLABLE NO", "Lo", 0), ("YI SYLLABLE NOP", "Lo", 0), ("YI SYLLABLE NEX", "Lo", 0), ("YI SYLLABLE NE", "Lo", 0), ("YI SYLLABLE NEP", "Lo", 0), ("YI SYLLABLE NUT", "Lo", 0), ("YI SYLLABLE NUX", "Lo", 0), ("YI SYLLABLE NU", "Lo", 0), ("YI SYLLABLE NUP", "Lo", 0), ("YI SYLLABLE NURX", "Lo", 0), ("YI SYLLABLE NUR", "Lo", 0), ("YI SYLLABLE HLIT", "Lo", 0), ("YI SYLLABLE HLIX", "Lo", 0), ("YI SYLLABLE HLI", "Lo", 0), ("YI SYLLABLE HLIP", "Lo", 0), ("YI SYLLABLE HLIEX", "Lo", 0), ("YI SYLLABLE HLIE", "Lo", 0), ("YI SYLLABLE HLIEP", "Lo", 0), ("YI SYLLABLE HLAT", "Lo", 0), ("YI SYLLABLE HLAX", "Lo", 0), ("YI SYLLABLE HLA", "Lo", 0), ("YI SYLLABLE HLAP", "Lo", 0), ("YI SYLLABLE HLUOX", "Lo", 0), ("YI SYLLABLE HLUO", "Lo", 0), ("YI SYLLABLE HLUOP", "Lo", 0), ("YI SYLLABLE HLOX", "Lo", 0), ("YI SYLLABLE HLO", "Lo", 0), ("YI SYLLABLE HLOP", "Lo", 0), ("YI SYLLABLE HLEX", "Lo", 0), ("YI SYLLABLE HLE", "Lo", 0), ("YI SYLLABLE HLEP", "Lo", 0), ("YI SYLLABLE HLUT", "Lo", 0), ("YI SYLLABLE HLUX", "Lo", 0), ("YI SYLLABLE HLU", "Lo", 0), ("YI SYLLABLE HLUP", "Lo", 0), ("YI SYLLABLE HLURX", "Lo", 0), ("YI SYLLABLE HLUR", "Lo", 0), ("YI SYLLABLE HLYT", "Lo", 0), ("YI SYLLABLE HLYX", "Lo", 0), ("YI SYLLABLE HLY", "Lo", 0), ("YI SYLLABLE HLYP", "Lo", 0), ("YI SYLLABLE HLYRX", "Lo", 0), ("YI SYLLABLE HLYR", "Lo", 0), ("YI SYLLABLE LIT", "Lo", 0), ("YI SYLLABLE LIX", "Lo", 0), ("YI SYLLABLE LI", "Lo", 0), ("YI SYLLABLE LIP", "Lo", 0), ("YI SYLLABLE LIET", "Lo", 0), ("YI SYLLABLE LIEX", "Lo", 0), ("YI SYLLABLE LIE", "Lo", 0), ("YI SYLLABLE LIEP", "Lo", 0), ("YI SYLLABLE LAT", "Lo", 0), ("YI SYLLABLE LAX", "Lo", 0), ("YI SYLLABLE LA", "Lo", 0), ("YI SYLLABLE LAP", "Lo", 0), ("YI SYLLABLE LUOT", "Lo", 0), ("YI SYLLABLE LUOX", "Lo", 0), ("YI SYLLABLE LUO", "Lo", 0), ("YI SYLLABLE LUOP", "Lo", 0), ("YI SYLLABLE LOT", "Lo", 0), ("YI SYLLABLE LOX", "Lo", 0), ("YI SYLLABLE LO", "Lo", 0), ("YI SYLLABLE LOP", "Lo", 0), ("YI SYLLABLE LEX", "Lo", 0), ("YI SYLLABLE LE", "Lo", 0), ("YI SYLLABLE LEP", "Lo", 0), ("YI SYLLABLE LUT", "Lo", 0), ("YI SYLLABLE LUX", "Lo", 0), ("YI SYLLABLE LU", "Lo", 0), ("YI SYLLABLE LUP", "Lo", 0), ("YI SYLLABLE LURX", "Lo", 0), ("YI SYLLABLE LUR", "Lo", 0), ("YI SYLLABLE LYT", "Lo", 0), ("YI SYLLABLE LYX", "Lo", 0), ("YI SYLLABLE LY", "Lo", 0), ("YI SYLLABLE LYP", "Lo", 0), ("YI SYLLABLE LYRX", "Lo", 0), ("YI SYLLABLE LYR", "Lo", 0), ("YI SYLLABLE GIT", "Lo", 0), ("YI SYLLABLE GIX", "Lo", 0), ("YI SYLLABLE GI", "Lo", 0), ("YI SYLLABLE GIP", "Lo", 0), ("YI SYLLABLE GIET", "Lo", 0), ("YI SYLLABLE GIEX", "Lo", 0), ("YI SYLLABLE GIE", "Lo", 0), ("YI SYLLABLE GIEP", "Lo", 0), ("YI SYLLABLE GAT", "Lo", 0), ("YI SYLLABLE GAX", "Lo", 0), ("YI SYLLABLE GA", "Lo", 0), ("YI SYLLABLE GAP", "Lo", 0), ("YI SYLLABLE GUOT", "Lo", 0), ("YI SYLLABLE GUOX", "Lo", 0), ("YI SYLLABLE GUO", "Lo", 0), ("YI SYLLABLE GUOP", "Lo", 0), ("YI SYLLABLE GOT", "Lo", 0), ("YI SYLLABLE GOX", "Lo", 0), ("YI SYLLABLE GO", "Lo", 0), ("YI SYLLABLE GOP", "Lo", 0), ("YI SYLLABLE GET", "Lo", 0), ("YI SYLLABLE GEX", "Lo", 0), ("YI SYLLABLE GE", "Lo", 0), ("YI SYLLABLE GEP", "Lo", 0), ("YI SYLLABLE GUT", "Lo", 0), ("YI SYLLABLE GUX", "Lo", 0), ("YI SYLLABLE GU", "Lo", 0), ("YI SYLLABLE GUP", "Lo", 0), ("YI SYLLABLE GURX", "Lo", 0), ("YI SYLLABLE GUR", "Lo", 0), ("YI SYLLABLE KIT", "Lo", 0), ("YI SYLLABLE KIX", "Lo", 0), ("YI SYLLABLE KI", "Lo", 0), ("YI SYLLABLE KIP", "Lo", 0), ("YI SYLLABLE KIEX", "Lo", 0), ("YI SYLLABLE KIE", "Lo", 0), ("YI SYLLABLE KIEP", "Lo", 0), ("YI SYLLABLE KAT", "Lo", 0), ("YI SYLLABLE KAX", "Lo", 0), ("YI SYLLABLE KA", "Lo", 0), ("YI SYLLABLE KAP", "Lo", 0), ("YI SYLLABLE KUOX", "Lo", 0), ("YI SYLLABLE KUO", "Lo", 0), ("YI SYLLABLE KUOP", "Lo", 0), ("YI SYLLABLE KOT", "Lo", 0), ("YI SYLLABLE KOX", "Lo", 0), ("YI SYLLABLE KO", "Lo", 0), ("YI SYLLABLE KOP", "Lo", 0), ("YI SYLLABLE KET", "Lo", 0), ("YI SYLLABLE KEX", "Lo", 0), ("YI SYLLABLE KE", "Lo", 0), ("YI SYLLABLE KEP", "Lo", 0), ("YI SYLLABLE KUT", "Lo", 0), ("YI SYLLABLE KUX", "Lo", 0), ("YI SYLLABLE KU", "Lo", 0), ("YI SYLLABLE KUP", "Lo", 0), ("YI SYLLABLE KURX", "Lo", 0), ("YI SYLLABLE KUR", "Lo", 0), ("YI SYLLABLE GGIT", "Lo", 0), ("YI SYLLABLE GGIX", "Lo", 0), ("YI SYLLABLE GGI", "Lo", 0), ("YI SYLLABLE GGIEX", "Lo", 0), ("YI SYLLABLE GGIE", "Lo", 0), ("YI SYLLABLE GGIEP", "Lo", 0), ("YI SYLLABLE GGAT", "Lo", 0), ("YI SYLLABLE GGAX", "Lo", 0), ("YI SYLLABLE GGA", "Lo", 0), ("YI SYLLABLE GGAP", "Lo", 0), ("YI SYLLABLE GGUOT", "Lo", 0), ("YI SYLLABLE GGUOX", "Lo", 0), ("YI SYLLABLE GGUO", "Lo", 0), ("YI SYLLABLE GGUOP", "Lo", 0), ("YI SYLLABLE GGOT", "Lo", 0), ("YI SYLLABLE GGOX", "Lo", 0), ("YI SYLLABLE GGO", "Lo", 0), ("YI SYLLABLE GGOP", "Lo", 0), ("YI SYLLABLE GGET", "Lo", 0), ("YI SYLLABLE GGEX", "Lo", 0), ("YI SYLLABLE GGE", "Lo", 0), ("YI SYLLABLE GGEP", "Lo", 0), ("YI SYLLABLE GGUT", "Lo", 0), ("YI SYLLABLE GGUX", "Lo", 0), ("YI SYLLABLE GGU", "Lo", 0), ("YI SYLLABLE GGUP", "Lo", 0), ("YI SYLLABLE GGURX", "Lo", 0), ("YI SYLLABLE GGUR", "Lo", 0), ("YI SYLLABLE MGIEX", "Lo", 0), ("YI SYLLABLE MGIE", "Lo", 0), ("YI SYLLABLE MGAT", "Lo", 0), ("YI SYLLABLE MGAX", "Lo", 0), ("YI SYLLABLE MGA", "Lo", 0), ("YI SYLLABLE MGAP", "Lo", 0), ("YI SYLLABLE MGUOX", "Lo", 0), ("YI SYLLABLE MGUO", "Lo", 0), ("YI SYLLABLE MGUOP", "Lo", 0), ("YI SYLLABLE MGOT", "Lo", 0), ("YI SYLLABLE MGOX", "Lo", 0), ("YI SYLLABLE MGO", "Lo", 0), ("YI SYLLABLE MGOP", "Lo", 0), ("YI SYLLABLE MGEX", "Lo", 0), ("YI SYLLABLE MGE", "Lo", 0), ("YI SYLLABLE MGEP", "Lo", 0), ("YI SYLLABLE MGUT", "Lo", 0), ("YI SYLLABLE MGUX", "Lo", 0), ("YI SYLLABLE MGU", "Lo", 0), ("YI SYLLABLE MGUP", "Lo", 0), ("YI SYLLABLE MGURX", "Lo", 0), ("YI SYLLABLE MGUR", "Lo", 0), ("YI SYLLABLE HXIT", "Lo", 0), ("YI SYLLABLE HXIX", "Lo", 0), ("YI SYLLABLE HXI", "Lo", 0), ("YI SYLLABLE HXIP", "Lo", 0), ("YI SYLLABLE HXIET", "Lo", 0), ("YI SYLLABLE HXIEX", "Lo", 0), ("YI SYLLABLE HXIE", "Lo", 0), ("YI SYLLABLE HXIEP", "Lo", 0), ("YI SYLLABLE HXAT", "Lo", 0), ("YI SYLLABLE HXAX", "Lo", 0), ("YI SYLLABLE HXA", "Lo", 0), ("YI SYLLABLE HXAP", "Lo", 0), ("YI SYLLABLE HXUOT", "Lo", 0), ("YI SYLLABLE HXUOX", "Lo", 0), ("YI SYLLABLE HXUO", "Lo", 0), ("YI SYLLABLE HXUOP", "Lo", 0), ("YI SYLLABLE HXOT", "Lo", 0), ("YI SYLLABLE HXOX", "Lo", 0), ("YI SYLLABLE HXO", "Lo", 0), ("YI SYLLABLE HXOP", "Lo", 0), ("YI SYLLABLE HXEX", "Lo", 0), ("YI SYLLABLE HXE", "Lo", 0), ("YI SYLLABLE HXEP", "Lo", 0), ("YI SYLLABLE NGIEX", "Lo", 0), ("YI SYLLABLE NGIE", "Lo", 0), ("YI SYLLABLE NGIEP", "Lo", 0), ("YI SYLLABLE NGAT", "Lo", 0), ("YI SYLLABLE NGAX", "Lo", 0), ("YI SYLLABLE NGA", "Lo", 0), ("YI SYLLABLE NGAP", "Lo", 0), ("YI SYLLABLE NGUOT", "Lo", 0), ("YI SYLLABLE NGUOX", "Lo", 0), ("YI SYLLABLE NGUO", "Lo", 0), ("YI SYLLABLE NGOT", "Lo", 0), ("YI SYLLABLE NGOX", "Lo", 0), ("YI SYLLABLE NGO", "Lo", 0), ("YI SYLLABLE NGOP", "Lo", 0), ("YI SYLLABLE NGEX", "Lo", 0), ("YI SYLLABLE NGE", "Lo", 0), ("YI SYLLABLE NGEP", "Lo", 0), ("YI SYLLABLE HIT", "Lo", 0), ("YI SYLLABLE HIEX", "Lo", 0), ("YI SYLLABLE HIE", "Lo", 0), ("YI SYLLABLE HAT", "Lo", 0), ("YI SYLLABLE HAX", "Lo", 0), ("YI SYLLABLE HA", "Lo", 0), ("YI SYLLABLE HAP", "Lo", 0), ("YI SYLLABLE HUOT", "Lo", 0), ("YI SYLLABLE HUOX", "Lo", 0), ("YI SYLLABLE HUO", "Lo", 0), ("YI SYLLABLE HUOP", "Lo", 0), ("YI SYLLABLE HOT", "Lo", 0), ("YI SYLLABLE HOX", "Lo", 0), ("YI SYLLABLE HO", "Lo", 0), ("YI SYLLABLE HOP", "Lo", 0), ("YI SYLLABLE HEX", "Lo", 0), ("YI SYLLABLE HE", "Lo", 0), ("YI SYLLABLE HEP", "Lo", 0), ("YI SYLLABLE WAT", "Lo", 0), ("YI SYLLABLE WAX", "Lo", 0), ("YI SYLLABLE WA", "Lo", 0), ("YI SYLLABLE WAP", "Lo", 0), ("YI SYLLABLE WUOX", "Lo", 0), ("YI SYLLABLE WUO", "Lo", 0), ("YI SYLLABLE WUOP", "Lo", 0), ("YI SYLLABLE WOX", "Lo", 0), ("YI SYLLABLE WO", "Lo", 0), ("YI SYLLABLE WOP", "Lo", 0), ("YI SYLLABLE WEX", "Lo", 0), ("YI SYLLABLE WE", "Lo", 0), ("YI SYLLABLE WEP", "Lo", 0), ("YI SYLLABLE ZIT", "Lo", 0), ("YI SYLLABLE ZIX", "Lo", 0), ("YI SYLLABLE ZI", "Lo", 0), ("YI SYLLABLE ZIP", "Lo", 0), ("YI SYLLABLE ZIEX", "Lo", 0), ("YI SYLLABLE ZIE", "Lo", 0), ("YI SYLLABLE ZIEP", "Lo", 0), ("YI SYLLABLE ZAT", "Lo", 0), ("YI SYLLABLE ZAX", "Lo", 0), ("YI SYLLABLE ZA", "Lo", 0), ("YI SYLLABLE ZAP", "Lo", 0), ("YI SYLLABLE ZUOX", "Lo", 0), ("YI SYLLABLE ZUO", "Lo", 0), ("YI SYLLABLE ZUOP", "Lo", 0), ("YI SYLLABLE ZOT", "Lo", 0), ("YI SYLLABLE ZOX", "Lo", 0), ("YI SYLLABLE ZO", "Lo", 0), ("YI SYLLABLE ZOP", "Lo", 0), ("YI SYLLABLE ZEX", "Lo", 0), ("YI SYLLABLE ZE", "Lo", 0), ("YI SYLLABLE ZEP", "Lo", 0), ("YI SYLLABLE ZUT", "Lo", 0), ("YI SYLLABLE ZUX", "Lo", 0), ("YI SYLLABLE ZU", "Lo", 0), ("YI SYLLABLE ZUP", "Lo", 0), ("YI SYLLABLE ZURX", "Lo", 0), ("YI SYLLABLE ZUR", "Lo", 0), ("YI SYLLABLE ZYT", "Lo", 0), ("YI SYLLABLE ZYX", "Lo", 0), ("YI SYLLABLE ZY", "Lo", 0), ("YI SYLLABLE ZYP", "Lo", 0), ("YI SYLLABLE ZYRX", "Lo", 0), ("YI SYLLABLE ZYR", "Lo", 0), ("YI SYLLABLE CIT", "Lo", 0), ("YI SYLLABLE CIX", "Lo", 0), ("YI SYLLABLE CI", "Lo", 0), ("YI SYLLABLE CIP", "Lo", 0), ("YI SYLLABLE CIET", "Lo", 0), ("YI SYLLABLE CIEX", "Lo", 0), ("YI SYLLABLE CIE", "Lo", 0), ("YI SYLLABLE CIEP", "Lo", 0), ("YI SYLLABLE CAT", "Lo", 0), ("YI SYLLABLE CAX", "Lo", 0), ("YI SYLLABLE CA", "Lo", 0), ("YI SYLLABLE CAP", "Lo", 0), ("YI SYLLABLE CUOX", "Lo", 0), ("YI SYLLABLE CUO", "Lo", 0), ("YI SYLLABLE CUOP", "Lo", 0), ("YI SYLLABLE COT", "Lo", 0), ("YI SYLLABLE COX", "Lo", 0), ("YI SYLLABLE CO", "Lo", 0), ("YI SYLLABLE COP", "Lo", 0), ("YI SYLLABLE CEX", "Lo", 0), ("YI SYLLABLE CE", "Lo", 0), ("YI SYLLABLE CEP", "Lo", 0), ("YI SYLLABLE CUT", "Lo", 0), ("YI SYLLABLE CUX", "Lo", 0), ("YI SYLLABLE CU", "Lo", 0), ("YI SYLLABLE CUP", "Lo", 0), ("YI SYLLABLE CURX", "Lo", 0), ("YI SYLLABLE CUR", "Lo", 0), ("YI SYLLABLE CYT", "Lo", 0), ("YI SYLLABLE CYX", "Lo", 0), ("YI SYLLABLE CY", "Lo", 0), ("YI SYLLABLE CYP", "Lo", 0), ("YI SYLLABLE CYRX", "Lo", 0), ("YI SYLLABLE CYR", "Lo", 0), ("YI SYLLABLE ZZIT", "Lo", 0), ("YI SYLLABLE ZZIX", "Lo", 0), ("YI SYLLABLE ZZI", "Lo", 0), ("YI SYLLABLE ZZIP", "Lo", 0), ("YI SYLLABLE ZZIET", "Lo", 0), ("YI SYLLABLE ZZIEX", "Lo", 0), ("YI SYLLABLE ZZIE", "Lo", 0), ("YI SYLLABLE ZZIEP", "Lo", 0), ("YI SYLLABLE ZZAT", "Lo", 0), ("YI SYLLABLE ZZAX", "Lo", 0), ("YI SYLLABLE ZZA", "Lo", 0), ("YI SYLLABLE ZZAP", "Lo", 0), ("YI SYLLABLE ZZOX", "Lo", 0), ("YI SYLLABLE ZZO", "Lo", 0), ("YI SYLLABLE ZZOP", "Lo", 0), ("YI SYLLABLE ZZEX", "Lo", 0), ("YI SYLLABLE ZZE", "Lo", 0), ("YI SYLLABLE ZZEP", "Lo", 0), ("YI SYLLABLE ZZUX", "Lo", 0), ("YI SYLLABLE ZZU", "Lo", 0), ("YI SYLLABLE ZZUP", "Lo", 0), ("YI SYLLABLE ZZURX", "Lo", 0), ("YI SYLLABLE ZZUR", "Lo", 0), ("YI SYLLABLE ZZYT", "Lo", 0), ("YI SYLLABLE ZZYX", "Lo", 0), ("YI SYLLABLE ZZY", "Lo", 0), ("YI SYLLABLE ZZYP", "Lo", 0), ("YI SYLLABLE ZZYRX", "Lo", 0), ("YI SYLLABLE ZZYR", "Lo", 0), ("YI SYLLABLE NZIT", "Lo", 0), ("YI SYLLABLE NZIX", "Lo", 0), ("YI SYLLABLE NZI", "Lo", 0), ("YI SYLLABLE NZIP", "Lo", 0), ("YI SYLLABLE NZIEX", "Lo", 0), ("YI SYLLABLE NZIE", "Lo", 0), ("YI SYLLABLE NZIEP", "Lo", 0), ("YI SYLLABLE NZAT", "Lo", 0), ("YI SYLLABLE NZAX", "Lo", 0), ("YI SYLLABLE NZA", "Lo", 0), ("YI SYLLABLE NZAP", "Lo", 0), ("YI SYLLABLE NZUOX", "Lo", 0), ("YI SYLLABLE NZUO", "Lo", 0), ("YI SYLLABLE NZOX", "Lo", 0), ("YI SYLLABLE NZOP", "Lo", 0), ("YI SYLLABLE NZEX", "Lo", 0), ("YI SYLLABLE NZE", "Lo", 0), ("YI SYLLABLE NZUX", "Lo", 0), ("YI SYLLABLE NZU", "Lo", 0), ("YI SYLLABLE NZUP", "Lo", 0), ("YI SYLLABLE NZURX", "Lo", 0), ("YI SYLLABLE NZUR", "Lo", 0), ("YI SYLLABLE NZYT", "Lo", 0), ("YI SYLLABLE NZYX", "Lo", 0), ("YI SYLLABLE NZY", "Lo", 0), ("YI SYLLABLE NZYP", "Lo", 0), ("YI SYLLABLE NZYRX", "Lo", 0), ("YI SYLLABLE NZYR", "Lo", 0), ("YI SYLLABLE SIT", "Lo", 0), ("YI SYLLABLE SIX", "Lo", 0), ("YI SYLLABLE SI", "Lo", 0), ("YI SYLLABLE SIP", "Lo", 0), ("YI SYLLABLE SIEX", "Lo", 0), ("YI SYLLABLE SIE", "Lo", 0), ("YI SYLLABLE SIEP", "Lo", 0), ("YI SYLLABLE SAT", "Lo", 0), ("YI SYLLABLE SAX", "Lo", 0), ("YI SYLLABLE SA", "Lo", 0), ("YI SYLLABLE SAP", "Lo", 0), ("YI SYLLABLE SUOX", "Lo", 0), ("YI SYLLABLE SUO", "Lo", 0), ("YI SYLLABLE SUOP", "Lo", 0), ("YI SYLLABLE SOT", "Lo", 0), ("YI SYLLABLE SOX", "Lo", 0), ("YI SYLLABLE SO", "Lo", 0), ("YI SYLLABLE SOP", "Lo", 0), ("YI SYLLABLE SEX", "Lo", 0), ("YI SYLLABLE SE", "Lo", 0), ("YI SYLLABLE SEP", "Lo", 0), ("YI SYLLABLE SUT", "Lo", 0), ("YI SYLLABLE SUX", "Lo", 0), ("YI SYLLABLE SU", "Lo", 0), ("YI SYLLABLE SUP", "Lo", 0), ("YI SYLLABLE SURX", "Lo", 0), ("YI SYLLABLE SUR", "Lo", 0), ("YI SYLLABLE SYT", "Lo", 0), ("YI SYLLABLE SYX", "Lo", 0), ("YI SYLLABLE SY", "Lo", 0), ("YI SYLLABLE SYP", "Lo", 0), ("YI SYLLABLE SYRX", "Lo", 0), ("YI SYLLABLE SYR", "Lo", 0), ("YI SYLLABLE SSIT", "Lo", 0), ("YI SYLLABLE SSIX", "Lo", 0), ("YI SYLLABLE SSI", "Lo", 0), ("YI SYLLABLE SSIP", "Lo", 0), ("YI SYLLABLE SSIEX", "Lo", 0), ("YI SYLLABLE SSIE", "Lo", 0), ("YI SYLLABLE SSIEP", "Lo", 0), ("YI SYLLABLE SSAT", "Lo", 0), ("YI SYLLABLE SSAX", "Lo", 0), ("YI SYLLABLE SSA", "Lo", 0), ("YI SYLLABLE SSAP", "Lo", 0), ("YI SYLLABLE SSOT", "Lo", 0), ("YI SYLLABLE SSOX", "Lo", 0), ("YI SYLLABLE SSO", "Lo", 0), ("YI SYLLABLE SSOP", "Lo", 0), ("YI SYLLABLE SSEX", "Lo", 0), ("YI SYLLABLE SSE", "Lo", 0), ("YI SYLLABLE SSEP", "Lo", 0), ("YI SYLLABLE SSUT", "Lo", 0), ("YI SYLLABLE SSUX", "Lo", 0), ("YI SYLLABLE SSU", "Lo", 0), ("YI SYLLABLE SSUP", "Lo", 0), ("YI SYLLABLE SSYT", "Lo", 0), ("YI SYLLABLE SSYX", "Lo", 0), ("YI SYLLABLE SSY", "Lo", 0), ("YI SYLLABLE SSYP", "Lo", 0), ("YI SYLLABLE SSYRX", "Lo", 0), ("YI SYLLABLE SSYR", "Lo", 0), ("YI SYLLABLE ZHAT", "Lo", 0), ("YI SYLLABLE ZHAX", "Lo", 0), ("YI SYLLABLE ZHA", "Lo", 0), ("YI SYLLABLE ZHAP", "Lo", 0), ("YI SYLLABLE ZHUOX", "Lo", 0), ("YI SYLLABLE ZHUO", "Lo", 0), ("YI SYLLABLE ZHUOP", "Lo", 0), ("YI SYLLABLE ZHOT", "Lo", 0), ("YI SYLLABLE ZHOX", "Lo", 0), ("YI SYLLABLE ZHO", "Lo", 0), ("YI SYLLABLE ZHOP", "Lo", 0), ("YI SYLLABLE ZHET", "Lo", 0), ("YI SYLLABLE ZHEX", "Lo", 0), ("YI SYLLABLE ZHE", "Lo", 0), ("YI SYLLABLE ZHEP", "Lo", 0), ("YI SYLLABLE ZHUT", "Lo", 0), ("YI SYLLABLE ZHUX", "Lo", 0), ("YI SYLLABLE ZHU", "Lo", 0), ("YI SYLLABLE ZHUP", "Lo", 0), ("YI SYLLABLE ZHURX", "Lo", 0), ("YI SYLLABLE ZHUR", "Lo", 0), ("YI SYLLABLE ZHYT", "Lo", 0), ("YI SYLLABLE ZHYX", "Lo", 0), ("YI SYLLABLE ZHY", "Lo", 0), ("YI SYLLABLE ZHYP", "Lo", 0), ("YI SYLLABLE ZHYRX", "Lo", 0), ("YI SYLLABLE ZHYR", "Lo", 0), ("YI SYLLABLE CHAT", "Lo", 0), ("YI SYLLABLE CHAX", "Lo", 0), ("YI SYLLABLE CHA", "Lo", 0), ("YI SYLLABLE CHAP", "Lo", 0), ("YI SYLLABLE CHUOT", "Lo", 0), ("YI SYLLABLE CHUOX", "Lo", 0), ("YI SYLLABLE CHUO", "Lo", 0), ("YI SYLLABLE CHUOP", "Lo", 0), ("YI SYLLABLE CHOT", "Lo", 0), ("YI SYLLABLE CHOX", "Lo", 0), ("YI SYLLABLE CHO", "Lo", 0), ("YI SYLLABLE CHOP", "Lo", 0), ("YI SYLLABLE CHET", "Lo", 0), ("YI SYLLABLE CHEX", "Lo", 0), ("YI SYLLABLE CHE", "Lo", 0), ("YI SYLLABLE CHEP", "Lo", 0), ("YI SYLLABLE CHUX", "Lo", 0), ("YI SYLLABLE CHU", "Lo", 0), ("YI SYLLABLE CHUP", "Lo", 0), ("YI SYLLABLE CHURX", "Lo", 0), ("YI SYLLABLE CHUR", "Lo", 0), ("YI SYLLABLE CHYT", "Lo", 0), ("YI SYLLABLE CHYX", "Lo", 0), ("YI SYLLABLE CHY", "Lo", 0), ("YI SYLLABLE CHYP", "Lo", 0), ("YI SYLLABLE CHYRX", "Lo", 0), ("YI SYLLABLE CHYR", "Lo", 0), ("YI SYLLABLE RRAX", "Lo", 0), ("YI SYLLABLE RRA", "Lo", 0), ("YI SYLLABLE RRUOX", "Lo", 0), ("YI SYLLABLE RRUO", "Lo", 0), ("YI SYLLABLE RROT", "Lo", 0), ("YI SYLLABLE RROX", "Lo", 0), ("YI SYLLABLE RRO", "Lo", 0), ("YI SYLLABLE RROP", "Lo", 0), ("YI SYLLABLE RRET", "Lo", 0), ("YI SYLLABLE RREX", "Lo", 0), ("YI SYLLABLE RRE", "Lo", 0), ("YI SYLLABLE RREP", "Lo", 0), ("YI SYLLABLE RRUT", "Lo", 0), ("YI SYLLABLE RRUX", "Lo", 0), ("YI SYLLABLE RRU", "Lo", 0), ("YI SYLLABLE RRUP", "Lo", 0), ("YI SYLLABLE RRURX", "Lo", 0), ("YI SYLLABLE RRUR", "Lo", 0), ("YI SYLLABLE RRYT", "Lo", 0), ("YI SYLLABLE RRYX", "Lo", 0), ("YI SYLLABLE RRY", "Lo", 0), ("YI SYLLABLE RRYP", "Lo", 0), ("YI SYLLABLE RRYRX", "Lo", 0), ("YI SYLLABLE RRYR", "Lo", 0), ("YI SYLLABLE NRAT", "Lo", 0), ("YI SYLLABLE NRAX", "Lo", 0), ("YI SYLLABLE NRA", "Lo", 0), ("YI SYLLABLE NRAP", "Lo", 0), ("YI SYLLABLE NROX", "Lo", 0), ("YI SYLLABLE NRO", "Lo", 0), ("YI SYLLABLE NROP", "Lo", 0), ("YI SYLLABLE NRET", "Lo", 0), ("YI SYLLABLE NREX", "Lo", 0), ("YI SYLLABLE NRE", "Lo", 0), ("YI SYLLABLE NREP", "Lo", 0), ("YI SYLLABLE NRUT", "Lo", 0), ("YI SYLLABLE NRUX", "Lo", 0), ("YI SYLLABLE NRU", "Lo", 0), ("YI SYLLABLE NRUP", "Lo", 0), ("YI SYLLABLE NRURX", "Lo", 0), ("YI SYLLABLE NRUR", "Lo", 0), ("YI SYLLABLE NRYT", "Lo", 0), ("YI SYLLABLE NRYX", "Lo", 0), ("YI SYLLABLE NRY", "Lo", 0), ("YI SYLLABLE NRYP", "Lo", 0), ("YI SYLLABLE NRYRX", "Lo", 0), ("YI SYLLABLE NRYR", "Lo", 0), ("YI SYLLABLE SHAT", "Lo", 0), ("YI SYLLABLE SHAX", "Lo", 0), ("YI SYLLABLE SHA", "Lo", 0), ("YI SYLLABLE SHAP", "Lo", 0), ("YI SYLLABLE SHUOX", "Lo", 0), ("YI SYLLABLE SHUO", "Lo", 0), ("YI SYLLABLE SHUOP", "Lo", 0), ("YI SYLLABLE SHOT", "Lo", 0), ("YI SYLLABLE SHOX", "Lo", 0), ("YI SYLLABLE SHO", "Lo", 0), ("YI SYLLABLE SHOP", "Lo", 0), ("YI SYLLABLE SHET", "Lo", 0), ("YI SYLLABLE SHEX", "Lo", 0), ("YI SYLLABLE SHE", "Lo", 0), ("YI SYLLABLE SHEP", "Lo", 0), ("YI SYLLABLE SHUT", "Lo", 0), ("YI SYLLABLE SHUX", "Lo", 0), ("YI SYLLABLE SHU", "Lo", 0), ("YI SYLLABLE SHUP", "Lo", 0), ("YI SYLLABLE SHURX", "Lo", 0), ("YI SYLLABLE SHUR", "Lo", 0), ("YI SYLLABLE SHYT", "Lo", 0), ("YI SYLLABLE SHYX", "Lo", 0), ("YI SYLLABLE SHY", "Lo", 0), ("YI SYLLABLE SHYP", "Lo", 0), ("YI SYLLABLE SHYRX", "Lo", 0), ("YI SYLLABLE SHYR", "Lo", 0), ("YI SYLLABLE RAT", "Lo", 0), ("YI SYLLABLE RAX", "Lo", 0), ("YI SYLLABLE RA", "Lo", 0), ("YI SYLLABLE RAP", "Lo", 0), ("YI SYLLABLE RUOX", "Lo", 0), ("YI SYLLABLE RUO", "Lo", 0), ("YI SYLLABLE RUOP", "Lo", 0), ("YI SYLLABLE ROT", "Lo", 0), ("YI SYLLABLE ROX", "Lo", 0), ("YI SYLLABLE RO", "Lo", 0), ("YI SYLLABLE ROP", "Lo", 0), ("YI SYLLABLE REX", "Lo", 0), ("YI SYLLABLE RE", "Lo", 0), ("YI SYLLABLE REP", "Lo", 0), ("YI SYLLABLE RUT", "Lo", 0), ("YI SYLLABLE RUX", "Lo", 0), ("YI SYLLABLE RU", "Lo", 0), ("YI SYLLABLE RUP", "Lo", 0), ("YI SYLLABLE RURX", "Lo", 0), ("YI SYLLABLE RUR", "Lo", 0), ("YI SYLLABLE RYT", "Lo", 0), ("YI SYLLABLE RYX", "Lo", 0), ("YI SYLLABLE RY", "Lo", 0), ("YI SYLLABLE RYP", "Lo", 0), ("YI SYLLABLE RYRX", "Lo", 0), ("YI SYLLABLE RYR", "Lo", 0), ("YI SYLLABLE JIT", "Lo", 0), ("YI SYLLABLE JIX", "Lo", 0), ("YI SYLLABLE JI", "Lo", 0), ("YI SYLLABLE JIP", "Lo", 0), ("YI SYLLABLE JIET", "Lo", 0), ("YI SYLLABLE JIEX", "Lo", 0), ("YI SYLLABLE JIE", "Lo", 0), ("YI SYLLABLE JIEP", "Lo", 0), ("YI SYLLABLE JUOT", "Lo", 0), ("YI SYLLABLE JUOX", "Lo", 0), ("YI SYLLABLE JUO", "Lo", 0), ("YI SYLLABLE JUOP", "Lo", 0), ("YI SYLLABLE JOT", "Lo", 0), ("YI SYLLABLE JOX", "Lo", 0), ("YI SYLLABLE JO", "Lo", 0), ("YI SYLLABLE JOP", "Lo", 0), ("YI SYLLABLE JUT", "Lo", 0), ("YI SYLLABLE JUX", "Lo", 0), ("YI SYLLABLE JU", "Lo", 0), ("YI SYLLABLE JUP", "Lo", 0), ("YI SYLLABLE JURX", "Lo", 0), ("YI SYLLABLE JUR", "Lo", 0), ("YI SYLLABLE JYT", "Lo", 0), ("YI SYLLABLE JYX", "Lo", 0), ("YI SYLLABLE JY", "Lo", 0), ("YI SYLLABLE JYP", "Lo", 0), ("YI SYLLABLE JYRX", "Lo", 0), ("YI SYLLABLE JYR", "Lo", 0), ("YI SYLLABLE QIT", "Lo", 0), ("YI SYLLABLE QIX", "Lo", 0), ("YI SYLLABLE QI", "Lo", 0), ("YI SYLLABLE QIP", "Lo", 0), ("YI SYLLABLE QIET", "Lo", 0), ("YI SYLLABLE QIEX", "Lo", 0), ("YI SYLLABLE QIE", "Lo", 0), ("YI SYLLABLE QIEP", "Lo", 0), ("YI SYLLABLE QUOT", "Lo", 0), ("YI SYLLABLE QUOX", "Lo", 0), ("YI SYLLABLE QUO", "Lo", 0), ("YI SYLLABLE QUOP", "Lo", 0), ("YI SYLLABLE QOT", "Lo", 0), ("YI SYLLABLE QOX", "Lo", 0), ("YI SYLLABLE QO", "Lo", 0), ("YI SYLLABLE QOP", "Lo", 0), ("YI SYLLABLE QUT", "Lo", 0), ("YI SYLLABLE QUX", "Lo", 0), ("YI SYLLABLE QU", "Lo", 0), ("YI SYLLABLE QUP", "Lo", 0), ("YI SYLLABLE QURX", "Lo", 0), ("YI SYLLABLE QUR", "Lo", 0), ("YI SYLLABLE QYT", "Lo", 0), ("YI SYLLABLE QYX", "Lo", 0), ("YI SYLLABLE QY", "Lo", 0), ("YI SYLLABLE QYP", "Lo", 0), ("YI SYLLABLE QYRX", "Lo", 0), ("YI SYLLABLE QYR", "Lo", 0), ("YI SYLLABLE JJIT", "Lo", 0), ("YI SYLLABLE JJIX", "Lo", 0), ("YI SYLLABLE JJI", "Lo", 0), ("YI SYLLABLE JJIP", "Lo", 0), ("YI SYLLABLE JJIET", "Lo", 0), ("YI SYLLABLE JJIEX", "Lo", 0), ("YI SYLLABLE JJIE", "Lo", 0), ("YI SYLLABLE JJIEP", "Lo", 0), ("YI SYLLABLE JJUOX", "Lo", 0), ("YI SYLLABLE JJUO", "Lo", 0), ("YI SYLLABLE JJUOP", "Lo", 0), ("YI SYLLABLE JJOT", "Lo", 0), ("YI SYLLABLE JJOX", "Lo", 0), ("YI SYLLABLE JJO", "Lo", 0), ("YI SYLLABLE JJOP", "Lo", 0), ("YI SYLLABLE JJUT", "Lo", 0), ("YI SYLLABLE JJUX", "Lo", 0), ("YI SYLLABLE JJU", "Lo", 0), ("YI SYLLABLE JJUP", "Lo", 0), ("YI SYLLABLE JJURX", "Lo", 0), ("YI SYLLABLE JJUR", "Lo", 0), ("YI SYLLABLE JJYT", "Lo", 0), ("YI SYLLABLE JJYX", "Lo", 0), ("YI SYLLABLE JJY", "Lo", 0), ("YI SYLLABLE JJYP", "Lo", 0), ("YI SYLLABLE NJIT", "Lo", 0), ("YI SYLLABLE NJIX", "Lo", 0), ("YI SYLLABLE NJI", "Lo", 0), ("YI SYLLABLE NJIP", "Lo", 0), ("YI SYLLABLE NJIET", "Lo", 0), ("YI SYLLABLE NJIEX", "Lo", 0), ("YI SYLLABLE NJIE", "Lo", 0), ("YI SYLLABLE NJIEP", "Lo", 0), ("YI SYLLABLE NJUOX", "Lo", 0), ("YI SYLLABLE NJUO", "Lo", 0), ("YI SYLLABLE NJOT", "Lo", 0), ("YI SYLLABLE NJOX", "Lo", 0), ("YI SYLLABLE NJO", "Lo", 0), ("YI SYLLABLE NJOP", "Lo", 0), ("YI SYLLABLE NJUX", "Lo", 0), ("YI SYLLABLE NJU", "Lo", 0), ("YI SYLLABLE NJUP", "Lo", 0), ("YI SYLLABLE NJURX", "Lo", 0), ("YI SYLLABLE NJUR", "Lo", 0), ("YI SYLLABLE NJYT", "Lo", 0), ("YI SYLLABLE NJYX", "Lo", 0), ("YI SYLLABLE NJY", "Lo", 0), ("YI SYLLABLE NJYP", "Lo", 0), ("YI SYLLABLE NJYRX", "Lo", 0), ("YI SYLLABLE NJYR", "Lo", 0), ("YI SYLLABLE NYIT", "Lo", 0), ("YI SYLLABLE NYIX", "Lo", 0), ("YI SYLLABLE NYI", "Lo", 0), ("YI SYLLABLE NYIP", "Lo", 0), ("YI SYLLABLE NYIET", "Lo", 0), ("YI SYLLABLE NYIEX", "Lo", 0), ("YI SYLLABLE NYIE", "Lo", 0), ("YI SYLLABLE NYIEP", "Lo", 0), ("YI SYLLABLE NYUOX", "Lo", 0), ("YI SYLLABLE NYUO", "Lo", 0), ("YI SYLLABLE NYUOP", "Lo", 0), ("YI SYLLABLE NYOT", "Lo", 0), ("YI SYLLABLE NYOX", "Lo", 0), ("YI SYLLABLE NYO", "Lo", 0), ("YI SYLLABLE NYOP", "Lo", 0), ("YI SYLLABLE NYUT", "Lo", 0), ("YI SYLLABLE NYUX", "Lo", 0), ("YI SYLLABLE NYU", "Lo", 0), ("YI SYLLABLE NYUP", "Lo", 0), ("YI SYLLABLE XIT", "Lo", 0), ("YI SYLLABLE XIX", "Lo", 0), ("YI SYLLABLE XI", "Lo", 0), ("YI SYLLABLE XIP", "Lo", 0), ("YI SYLLABLE XIET", "Lo", 0), ("YI SYLLABLE XIEX", "Lo", 0), ("YI SYLLABLE XIE", "Lo", 0), ("YI SYLLABLE XIEP", "Lo", 0), ("YI SYLLABLE XUOX", "Lo", 0), ("YI SYLLABLE XUO", "Lo", 0), ("YI SYLLABLE XOT", "Lo", 0), ("YI SYLLABLE XOX", "Lo", 0), ("YI SYLLABLE XO", "Lo", 0), ("YI SYLLABLE XOP", "Lo", 0), ("YI SYLLABLE XYT", "Lo", 0), ("YI SYLLABLE XYX", "Lo", 0), ("YI SYLLABLE XY", "Lo", 0), ("YI SYLLABLE XYP", "Lo", 0), ("YI SYLLABLE XYRX", "Lo", 0), ("YI SYLLABLE XYR", "Lo", 0), ("YI SYLLABLE YIT", "Lo", 0), ("YI SYLLABLE YIX", "Lo", 0), ("YI SYLLABLE YI", "Lo", 0), ("YI SYLLABLE YIP", "Lo", 0), ("YI SYLLABLE YIET", "Lo", 0), ("YI SYLLABLE YIEX", "Lo", 0), ("YI SYLLABLE YIE", "Lo", 0), ("YI SYLLABLE YIEP", "Lo", 0), ("YI SYLLABLE YUOT", "Lo", 0), ("YI SYLLABLE YUOX", "Lo", 0), ("YI SYLLABLE YUO", "Lo", 0), ("YI SYLLABLE YUOP", "Lo", 0), ("YI SYLLABLE YOT", "Lo", 0), ("YI SYLLABLE YOX", "Lo", 0), ("YI SYLLABLE YO", "Lo", 0), ("YI SYLLABLE YOP", "Lo", 0), ("YI SYLLABLE YUT", "Lo", 0), ("YI SYLLABLE YUX", "Lo", 0), ("YI SYLLABLE YU", "Lo", 0), ("YI SYLLABLE YUP", "Lo", 0), ("YI SYLLABLE YURX", "Lo", 0), ("YI SYLLABLE YUR", "Lo", 0), ("YI SYLLABLE YYT", "Lo", 0), ("YI SYLLABLE YYX", "Lo", 0), ("YI SYLLABLE YY", "Lo", 0), ("YI SYLLABLE YYP", "Lo", 0), ("YI SYLLABLE YYRX", "Lo", 0), ("YI SYLLABLE YYR", "Lo", 0), )
https://github.com/Besthope-Official/backend
https://raw.githubusercontent.com/Besthope-Official/backend/master/24autumn/README.md
markdown
# 24年秋季学期 这一学期的安排(坑) 回来吧我的执行力 ## 活动发起: 编程百日挑战 - 每天在 git 社区发一条 commit - 每天在 OJ 上切一道题目 开始时间就定在学期初 哪怕水题, 让他水!!! 时间差不多贯穿一个小学期 - 坚持下来的都是神人了 - 奖品, 看看能不能争取些经费搞些外设(?) ## 后端教学项目 my-xx-admin 等效于24秋季学期的后端训练营 面向新生和大二 - 登录注册的用户管理 预防针打好 - 这回要做的更加硬编码一些 - 学长不负责辅导高数/高代/大物 第一周拿来配环境 后续开会 涵盖的知识点 - Git workflow (1 week) - clone, fork, commit, push, branch, pull request, merge - 基础的后端框架知识 (2 weeks) - me 只讲 python django(暴政) - 数据库 (2 weeks) - MySQL/PostgreSQL + Redis 大概五周时间讲完最基础的东西 太多怕消化不完, 可以多留一些时间来互动 大概 11 月初完成后端的训练营, 跳过国庆的周日, 然后后续到 12 月份的时间自由支配(开发) 目标: 争取做出来的东西可以直接用作某个项目的模块 - 然后可以~~拉去做牛马了~~ 题外话: 部长在学计算机网络, 所以这学期会一起研究 TCP 编程, 看看能不能手搓一个玩具版后端框架(C++写写看) ## 日常开发: SWUFE-OJ 你财为了百年校庆翻新了一大批设施, 那我们也要趁着这大好元年(bushi)上线我们奇点的产品贡献给学院 这学期的任务: - 后端接口重构 - 竞赛模块/评论接口开发加油 - 前端页面开发加油 加油教学, 调动一切有生力量加速开发 参与开发的同学争取一下通博楼工位 我的目标: 这学期常驻通博楼 ## 常驻内容: 技术分享 找一个好玩的开源项目在例会上分享出来 部长坐台, or 组员上 ## 强调单元测试的重要性 优化开发流程的重要一步 测试驱动开发 TDD - 明确实际应用需求 - 设计 corner cases - 根据 API 设计来 code 测试用例 可能的项目: 压力测试 ## 搭建你的电子学习笔记系统 选择太多也是一种苦恼. - With Pads: OneNote - VSCode/Typora + markdown - 顺带搭建你自己的博客 blog - Obsidian - Jupyter Notebook 个人安利: Typst 简单来说, 就是*又新又好*: - 兼具 Latex 的阅读体验和 Markdown 的写作体验 - 轻量化, vsc 里配置好插件即可食用, 不像 Latex 编译缓慢 - 高度定制化, 有类似前端编程的范式
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/pattern-spacing_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test with spacing set to `(-10pt, -10pt)` #let pat(..args) = pattern(size: (30pt, 30pt), ..args)[ #square(width: 100%, height: 100%, stroke: 1pt, fill: blue) ] #set page(width: 100pt, height: 100pt) #rect(fill: pat(spacing: (-10pt, -10pt)), width: 100%, height: 100%, stroke: 1pt)
https://github.com/schmidma/typst-workshop
https://raw.githubusercontent.com/schmidma/typst-workshop/main/examples/10-arguments.typ
typst
Creative Commons Zero v1.0 Universal
You find the documentation in the #link("https://typst.app/docs/reference/", [Official Reference]). #quote( block: true, attribution: "Typst Examples Book", [ That's right, links, quotes and lots of other document elements are created with functions. ] )
https://github.com/justmejulian/typst-documentation-template
https://raw.githubusercontent.com/justmejulian/typst-documentation-template/main/presentation/presentation.typ
typst
#import "@preview/polylux:0.3.1": * #import themes.university: * #set text(font: "Helvetica Neue") #let author = "<NAME>" #let title = "WatchOS Velocity Recording" #let subtitle = "VT1" #let date = datetime.today().display() #show: university-theme.with( short-author: subtitle, short-title: date, color-a: rgb("#0064A6"), color-b: rgb("#5C9CC6"), color-c: rgb("#FFF"), ) #title-slide( authors: (author), title: title, subtitle: subtitle, date: date, institution-name: "ZHAW School of Engineering", logo: image("zhaw-logo.png", width: 50mm) ) #slide(title: [Slide title], new-section: [The section])[ #lorem(40) ] #focus-slide(background-color: rgb("#0064A6"))[ *Another variant with an image in background...* ] #matrix-slide[ left ][ middle ][ right ] #matrix-slide(columns: 1)[ top ][ bottom ]
https://github.com/Otto-AA/dashy-todo
https://raw.githubusercontent.com/Otto-AA/dashy-todo/main/lib/todo.typ
typst
MIT No Attribution
#import "side-margin.typ": calculate-page-margin-box #let to-string(content) = { if type(content) == str { content } else if content.has("text") { content.text } else if content.has("children") { content.children.map(to-string).join("") } else if content.has("body") { to-string(content.body) } else if content == [ ] { " " } } #let todo(body, position: auto) = ( context box({ assert(position in (auto, left, right), message: "Can only position todo on the left or right side currently") let text-position = here().position() let side = position if position == auto { if text-position.x > page.width / 2 { side = right } else { side = left } } let page-margin-box = calculate-page-margin-box(side) let shift-y = .5em let outer-box-inset = 4pt let dx = page-margin-box.x - text-position.x place(dx: dx, dy: -shift-y)[ #box(inset: outer-box-inset, width: page-margin-box.width)[ #box(stroke: orange, width: 100%)[ #place({ // defaults for right side let line-size = dx let line-x = -line-size let tick-x = -line-size // overwrites for left side if side == left { line-size = calc.abs(dx) - page-margin-box.width + outer-box-inset line-x = page-margin-box.width - outer-box-inset * 2 tick-x = calc.abs(dx) - outer-box-inset } place(line(length: line-size, start: (line-x, shift-y), stroke: orange)) place(line(length: 4pt, start: (tick-x, shift-y), angle: -90deg, stroke: orange)) }) // the todo message #box(body, inset: 0.2em) ] // invisible figure, s.t. we can reference it in the outline // probably depends on https://github.com/typst/typst/issues/147 for a cleaner solution #hide( box( height: 0pt, width: 0pt, figure( none, kind: "todo", supplement: [TODO], caption: to-string(body), outlined: true, ), ), ) ] ] }) )
https://github.com/pacokleitz/cv
https://raw.githubusercontent.com/pacokleitz/cv/main/cv.typ
typst
MIT License
#show heading: set text(font: "Linux Biolinum") // Uncomment the following lines to adjust the size of text // The recommend resume text size is from `10pt` to `12pt` // #set text( // size: 12pt, // ) // Feel free to change the margin below to best fit your own CV #set page( margin: (x: 0.9cm, y: 1.3cm), ) // For more customizable options, please refer to official reference: https://typst.app/docs/reference/ #set par(justify: true) #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} = <NAME> <EMAIL> | #link("https://github.com/pacokleitz")[github.com/pacokleitz] | #link("https://kpaco.dev")[kpaco.dev] | #link("https://linkedin.com/in/pacokleitz")[linkedin.com/in/pacokleitz] Polyvalent software engineer specializing in DevOps and Site Reliability Engineering. Committed to optimizing efficiency and bolstering reliability across Cloud Infrastructure, Software, and Machine Learning domains. Skilled in implementing scalable solutions and automation to enhance system performance. == Work Experience #chiline() #link("https://kili-technology.com")[*Kili Technology*] #h(1fr) 09/2023 -- Present \ DevOps/SRE Engineer #h(1fr) Remote / Paris, France \ - Reduced GCP and Azure cloud infrastructure expenses by 60% through implementation of cost-saving measures. - Collaborated with clients to facilitate on-premise deployment of Kili's data labeling solution. - Orchestrated configuration and deployment of key infrastructure components. - Implemented monitoring jobs and alerts to track critical resource expiration, enhancing system reliability. #link("https://troops.fr")[*Troops*] #h(1fr) 09/2022 -- 09/2023 \ DevOps/SRE Engineer #h(1fr) Remote / Lyon, France \ - Led upgrades and maintenance of Kubernetes (EKS) cluster components, ensuring system performance and security. - Expanded observability with Datadog monitoring, enabling proactive issue resolution. - Strengthened Kubernetes cluster security with Kyverno policies and vulnerability scans. - Streamlined operations through efficient CI/CD processes. - Established disaster recovery strategy for all AWS resources. #link("https://ircad.fr")[*IRCAD*] #h(1fr) 09/2021 -- 09/2022 \ Software Engineer #h(1fr) Strasbourg, France \ - Spearheaded the development of a web platform for evaluating the performance of machine learning models. - Pioneered experiments involving semi-synthetic dataset generation. - Led the training and benchmarking efforts for a range of computer vision models. - Facilitated the integration of multiple machine learning models into a unified web service. == Education #chiline() *University of Strasbourg* #h(1fr) \ Master of Software Science and Engineering #h(1fr) \ - Specialized in distributed systems, large-scale data processing, formal methods, advanced algorithms, compilers, software architecture, advanced programming, cybersecurity, and research in blockchain consensus. *University of Strasbourg* #h(1fr) \ Bachelor of Computer Science #h(1fr) \ - Studied algorithms and data structures, cryptography, parallel programming, functional programming, logic programming, local networks, network algorithms, artificial intelligence, analysis, and linear algebra. == Skills #chiline() *DevOps:* Kubernetes, Terraform, Ansible, Docker, AWS, GCP, Azure, Datadog, CI/CD, ArgoCD, Nginx, Postgres, Git, Linux \ *Programming:* Go, Python, Rust, TypeScript, Bash, C, SQL \ *Areas:* Distributed Systems, Back-End Development, Machine Learning, AI, Blockchain == Certifications #chiline() - #link("https://www.credly.com/badges/f63dc989-0b2d-4a0f-9d08-96ebdcd5a316")[Certified Kubernetes Administrator (CKA)] == Languages #chiline() - French: Native proficiency - English: Fluent (Professionally) - German: Proficient (Bilingual school education)
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/biology/lec5.typ
typst
#import "template.typ": * #show: template.with( title: "Lecture 5", subtitle: "7.016" ) = Carbohydrates #define( title: "Glycoprotein" )[ A protein covalently attached to a carbohydrate. ] #define( title: "Polysaccharide" )[ A long chain of carbohydrate groups. ] Other names for carbohydrates are *sugars* and *saccharides*. Suffixes for carbs end in -ose, while prefixes start with glyco- #define( title: "Glycosidic Bond" )[ The name for a bond between carbohydrate units in a chain. ]
https://github.com/fufexan/cv
https://raw.githubusercontent.com/fufexan/cv/typst/modules_ro/experience.typ
typst
#import "../src/template.typ": * #show link: underline #cvSection("Experiență") #cvEntry( title: [Contract], society: [NixOS Foundation], logo: "../src/logos/nixos.svg", date: [2021, 2022], location: [La distanță], description: list( [A luat parte într-o echipă de participanți pentru a face packaging în #link("https://nixos.org")[Nix] aplicațiilor NGI (Next Generation Internet) pentru programul #link("https://summer.nixos.org")[Summer of Nix], dar și pentru a îmbunătăți documentația generală a Nix/NixOS], [A îmbunătățit documentația în anumite părți ale #link("https://nixos.wiki")[NixOS Wiki]], [A creat flake-uri disponibile în mod public în #link("https://github.com/ngi-nix")[organizația NGI-Nix]], ) ) #cvEntry( title: [Mentorat], society: [Digital Nation], logo: "../src/logos/dn.jpg", date: [2019 - 2020], location: [La distanță], description: list( [A participat ca beneficiar în programul #link("https://generatiatech.ro")[Generația Tech]], [A învățat dezvoltare PHP utilizând teme și plugin-uri WordPress, cu ajutorul unor mentori pricepuți], [A învățat dezvoltare back-end și front-end în JavaScript, gestionare și integrare Firebase], [A fost ambasador pentru grupul local al județului Alba. A participat în gestionare, administrare, logistică și activități de grup], ) )
https://github.com/fabriceHategekimana/master
https://raw.githubusercontent.com/fabriceHategekimana/master/main/src/module.typ
typst
#import "@preview/curryst:0.3.0": rule, proof-tree #import "@preview/ctheorems:1.1.2": * #set par(first-line-indent: 2em) #import "@preview/indenta:0.0.3": fix-indent #show: fix-indent() #show: thmrules #let Definition = thmbox( "definition", "Definition", base_level: 1, stroke: rgb("#e94845") + 1pt ) #let Exemple = thmbox( "exemple", "Exemple", base_level: 1, stroke: rgb("#e94845") + 1pt ) #let type_context(body, ..entrees) = { let entries = entrees.pos().join(", ") $ Gamma entries tack.r body $ } #let eval(name, conclusion, ..premices) = { rule( name: name, conclusion, ..premices ) } #let t_num(exp) = rule( "T-NUM", $exp : "int"$, $exp in NN$ ) #let typing(name, conclusion, ..premices) = { rule( name: name, conclusion, ..premices ) } #let typing_c(name, conclusion, ..premices) = { rule( name: name, type_context(conclusion), ..premices ) } #let t_num(exp) = rule( "T-NUM", $exp : "int"$, $exp in NN$ ) #let t_true = rule( name: "T-TRUE", type_context("true : bool") ) #let t_false = rule( name: "T-FALSE", type_context("false : bool") )
https://github.com/lbsekr/provadis-typst-template
https://raw.githubusercontent.com/lbsekr/provadis-typst-template/main/main.typ
typst
#import "template.typ": Template, code #import "@preview/glossarium:0.3.0": gls #let translations = json("translations.json").at("de") #show: Template.with( bib: arguments("sources.bib", style: "frontiers"), appendix: ( [ #heading("Wichtiger Anhang",supplement: [#translations.appendix]) #lorem(100) ], [ #heading("Weiterer Wichtiger Anhang",supplement: [#translations.appendix]) <ref> #lorem(100) ] ), show_lists_after_content: false, confidental_clause: true, abbreviation_entries: ( ( key: "oidc", short: "OIDC", long: "Open ID Connect" ), ), glossary_entries: ( ( key: "haus", short: "Haus", long: "Konstruktion bestehend aus 4 Wänden und einem Dach" ), ), ai_entries: ( ( "OpenAI ChatGPT", "Schreib meine Bachelorarbeit", "Bachelorarbeit schreiben lassen und lieber Fortnite zocken" ), ( "Google Gemini", "Gib mir Motivationstipps", "Die Nerven beibehalten" ) ), abstract: [Im Nachfolgenden Text lesen Sie eine sehr gute Arbeit über ein sehr gutes Thema welches ich sehr gut bearbeitet habe.], preface: [bitte bitte bitte bitte bewerten sie gut] ) = Einleitung #lorem(15) Wenn ich @oidc zum ersten mal erwähne wird es ausgeschrieben. \ Beim zweiten Mal wird @oidc nur abgekürzt. Übrigens gibt es eine @haus #pagebreak() = Grundlagen #lorem(100) == Unterpunkt #lorem(100) #figure( image("img/provadis.png", width: 80%), caption: [A curious figure.], ) <glacier> #pagebreak() #code( ```java class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ```, supplement: translations.codeausschnitt, caption: [java hello world.], ) <glacier> == Unterpunkt @Effectiv92:online #lorem(100) === Unter-Unterpunkt #lorem(100) === Unter-Unterpunkt #pagebreak() == Unterpunkt #lorem(100) === Unter-Unterpunkt #figure( table( columns: 4, [t], [1], [2], [3], [y], [0.3s], [0.4s], [0.8s], ), caption: [Timing results], ) #lorem(100) = Zusammenfassung #lorem(100)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/gentle-clues/0.4.0/README.md
markdown
Apache License 2.0
# gentle-clues Simple admonitions for typst. Add predefined or define your own. Inspired from [mdbook-admonish](https://tommilligan.github.io/mdbook-admonish/). ## Usage `#import " @preview/gentle-clues:0.4.0: info, success, warning, error` Writing this, ```typst #info[Whatever you want to say] ``` turns into this. ![Screenshot of the info clue](screenshot_info-clue.png) ### Change header title language You can change the default language for the header titles by ```typst #gc_header-title-lang.update("de") ``` At the moment valid options are: "en","de" and "fr" ### Available Clues The follwing clues/admonitions (+ some aliases) are available at the moment. `abstract`, `info`, `question`, `memo`, `task`, `idea`, `tip`, `quote`, `success`, `warning`, `error`, `example`. [See here for more Information](https://github.com/jomaway/typst-admonish/blob/main/docs.pdf) ### Define your own But it is very easy to define your own. ```typst //Define it #let ghost-admon(..args) = clue( title: "Buuuuh", _color: gray, icon: emoji.ghost, ..args ) // Use it #ghost-admon[Huuuuuh.] ``` The icon can be an `emoji`, `symbol` or `.svg`-file. ### Reference Here the full reference to the admonish function. ```typst clue( body, title: none, // Default: none, or string icon: "assets/flag.svg", // can be a file or an symbol|emoji _color: "gray", // `_` due to naming conflicts with the type color. width: auto, radius: 2pt, // radius of the right side. For no radius set to 0pt. inset: 1em, // inset of the content, header-inset not yet supported header-inset: 0.5em, // define header inset. ) ``` ## License MIT # Changelog ## v0.4.0 - Added french header titles. Use with `#gc_header-title-lang.update("fr")` - Fixed minor border issues - Added an task-counter (disable with `gc_enable-task-counter.update(false)`) *Colors:* - Changed default color to `navy` - Changed border-color - Fixed bug that it was sometimes no longer visible after `typst 0.9.0` update. - Default is now the same as `bg-color` - Set via color-dict `border` field. - Added support for gradients: `#clue(_color: gradient.linear(..color.map.crest))` - *Breaking:* Removed string color_profiles. - Changed some predefined colors. ## v0.3.0 - renamed entry files and base template - default `header-inset` is `0.5em` now. - added `gc_header-title-lang` state, which defines the language of the title. - Update with `#gc_header-title-lang.update("en")` - Accepts `"de"` or `"en"` at the moment. - Using new `type` checks which requires typst version `0.8.0` - renamed Parameter `color` to `_color` due to naming conflicts with the color type. ## v0.2.0 - set header inset. `#admonish(header-inset: 0.5em)` - custom color: `#admonish(color: (stroke: luma(150), bg: teal))` - new example admonition: `#example[Testing]` #example(header-inset: 0.8em)[Testing]
https://github.com/linxuanm/math-notes
https://raw.githubusercontent.com/linxuanm/math-notes/master/real-analysis/1-real-numbers.typ
typst
#import "../setup.typ": * #show: lecenv #show: thmrules = Real Numbers
https://github.com/ivaquero/book-control
https://raw.githubusercontent.com/ivaquero/book-control/main/16-模型预测控制器.typ
typst
#import "@local/scibook:0.1.0": * #show: doc => conf( title: "模型预测控制器", author: ("ivaquero"), header-cap: "现代控制理论", footer-cap: "github@ivaquero", outline-on: false, doc, ) = 二维动态系统 对轨迹追踪问题 - 误差 $∫e^2 dd(t)$越小,追踪越好 - 输入 $∫u^2 dd(t)$越小,能耗越低 于是,整体代价函数为 $ J = ∫_0^(⊤) q e^2 + r u^2 dd(t) $ 拓展至 MIMO 情况,则有 $ dv(𝒙, t) &= 𝑨 𝒙 + 𝑩 𝒖 \ 𝒀 &= 𝑪 𝒙 $ 其代价函数中的变量,只有$𝒛$ $ min J = underbrace(𝒛^(⊤) 𝑸 𝒛, "二次型") + underbrace(𝑪^(⊤) 𝒛, "线性") $ <cost-quad> 对某二维系统 $ dv(, t) vec(delim: "[", 𝒙_1, 𝒙_2) &= 𝑨 vec(delim: "[", 𝒙_1, 𝒙_2) + 𝑩 vec(delim: "[", 𝒖_1, 𝒖_2)\ vec(delim: "[", y_1, y_2) &= vec(delim: "[", 𝒙_1, 𝒙_2) $ 又参考值 $ 𝑹 = vec(delim: "[", r_1, r_2) = vec(delim: "[", 0, 0) $ 则系统误差为 $ 𝑬 = vec(delim: "[", e_1, e_2) = vec(delim: "[", y_1-r_1, y_2-r_2 ) = vec(delim: "[", 𝒙_1, 𝒙_2) $ 此时,有 $ J &= ∫_0^x 𝑬^(⊤) 𝑸 𝑬 + 𝒖^(⊤) 𝑹 𝒖 dd(t) \ &= q_1 𝒙_1^2 + q_2 𝒙_2^2 + r_1 𝒖_1^2 + r_2 𝒖_2^2 $ <cost-quad2> 其中,$q_i$和$r_i$为权重系数。 = 模型预测控制器 == 滚动时域优化 模型预测控制器,通过模型预测系统在未来某一时间段内的表现,进行优化控制。 对离散系统 $ 𝒙_(k+1) = 𝑨 𝒙_k + 𝑩 𝒖_k $ 其计算$𝒙_(k+1)$的大致步骤为 1. 估计/测量$k$时刻系统状态; 2. 基于代价函数进行最优化控制。离散化@eqt:cost-quad2,得 $ J = ∑_k^(N-1) (𝒆^(⊤)_k 𝑸 𝒆_k + 𝒖^(⊤)_k 𝑹 𝒖_k) + 𝒆^(⊤)_N 𝑭 𝒆_N $ <cost-mpc> 3. 以$𝒖_k^*$作为输入,重复第2步,进行继续循环; == 代价函数推导 MPC 问题的一个难点就是最小化代价函数的计算。目前的思路是将@eqt:cost-mpc 转化为二次型,这里令 $ 𝑿_k = [𝒙_((k|k)), 𝒙_((k+1|k)), …, 𝒙_((k+N|k))]^(⊤) \ 𝑼_k = [𝒖_((k|k)), 𝒖_((k+1|k)), …, 𝒖_((k+N-1|k))]^(⊤) $ 于是,@eqt:cost-mpc 变为条件式 $ min J = ∑_(i=k)^(N-1) ( underbrace(𝒙^(⊤)_(k+i|k) 𝑸 𝒙_(k+i|k), "误差的加权和") + underbrace(𝒖^(⊤)_(k+i|k) 𝑹 𝒖_(k+i|k), "输入的加权和") ) + underbrace(𝒙^(⊤)_(k+N) 𝑭 𝒙_(k+N), "终端误差") $ <cost-mpc2> 为将@eqt:cost-mpc2 化为@eqt:cost-quad 形式,即只有一个变量的形式,做如下代换 $ cases( 𝒙_((k|k)) = 𝒙_k, 𝒙_((k+1|k)) = 𝑨 𝒙_k + 𝑩 𝒖_(k|k), …, 𝒙_((k+N|k)) = 𝑨^N 𝒙_k + 𝑨^(N-1) 𝑩 𝒖_(k|k) + … + 𝑩 𝒖_(k+N-1|k)) $ 其简写如下。其中,$𝑪$的零行向量个数为$n$,取决于初始状态。 $ 𝑿_(k+1) = 𝑴 𝑿_k + 𝑪 𝑼_k $ <mc> 其中 $ 𝑴 = mat(delim: "[", 𝑰; 𝑨; 𝑨^2; ⋮; 𝑨^N), 𝑪 = mat(delim: "[", 0, 0, …, 0; ⋮, ⋮, ⋮, ⋮; 0, 0, …, 0; 𝑩, 0, ⋯, ⋮; 𝑨 𝑩, 𝑩, ⋯, ⋮; ⋮, ⋮, ⋮, ⋮; 𝑨^(N-1) 𝑩, 𝑨^(N-2) 𝑩, ⋯, 𝑩) $ 将@eqt:cost-mpc2 展开,得 $ J = 𝒙_k^(⊤) macron(𝑸) 𝒙_k + 𝑼_k^(⊤) macron(𝑹) 𝑼_k $ 其中 $ macron(𝑸) = dmat(delim: "[", Q, Q, ⋱, F), space macron(𝑹) = dmat(delim: "[", R, R, ⋱, R) $ 代入@eqt:mc,得 $ J &= 𝒙_k^(⊤) underbrace(𝑴^(⊤) macron(𝑸) 𝑴, "𝑮") 𝒙_K + 𝒙_k^(⊤) underbrace(𝑴^(⊤) macron(𝑸) 𝑪, "𝑬") 𝑼_k + 𝑼_k^(⊤) underbrace(𝑪^(⊤) macron(𝑸) 𝑴, "𝑬") 𝒙_k + 𝑼_k^(⊤) ( underbrace(𝑪^(⊤) macron(𝑸) 𝑪 + macron(𝑹), "𝑯") ) 𝑼_k \ &= 𝒙_k^(⊤) 𝑮 𝒙_k + 2 𝒙_k^(⊤) 𝑬 𝑼_k + 𝑼_k^(⊤) 𝑯 𝑼_k $
https://github.com/elouan660/Portes_Ouvertes
https://raw.githubusercontent.com/elouan660/Portes_Ouvertes/main/doc-template.typ
typst
#let Exercice(titre, auteur, date, contenu) = [ #set page( footer: align(right,text(size: 7pt, weight: "thin")[#auteur]), ) #align(left, text(size: 12pt, weight: "regular",)[#date]) \ #set text( font: "Open Sans" ) #show heading: titre => [ #if titre.level == 1 [ #set align(center) #set text(size: 13pt) \ #titre ] else if titre.level == 2 [ #set align(left) #set text(size: 11pt) \ _#underline[#titre]_ ] else [ #set align(left) #set text(size: 11pt) \ #titre ] ] #align(center, text(size: 17pt, weight: "bold")[ #titre]) \ #contenu ]
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/exers/i.typ
typst
#import "../cfg.typ": * #show: cfg $ "Find" lim_(x -> 0) (a^x - 1)/x $ $(a^x - 1)/x = ((e^(x ln a) - 1) ln a)/(x ln a)$ $((e^x - 1) ln a)/x ->_(x -> 0) ln a$ $((e^(x ln a) - 1) ln a)/(x ln a) ->_(x -> 0) ln a$
https://github.com/deadManAlive/ui-thesis-typst-template
https://raw.githubusercontent.com/deadManAlive/ui-thesis-typst-template/master/primer/cover.typ
typst
#import "../config.typ": cfg #let cover = [ #set align(center) #set text( size: 14pt ) #image( "assets/makara_color.png", width: 2.5cm, ) *UNIVERSITAS INDONESIA* #v(2em) *#upper(cfg.title)* #v(6em) *SKRIPSI* #v(6em) *#upper(cfg.name)* *#cfg.npm* #v(6em) *#upper(cfg.faculty)* *#upper(cfg.program)* #v(2em) *#upper(cfg.location)* *#upper(cfg.time)* ]