Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avi Singh Homework 1 #12

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.Rproj.user
.Rhistory
.RData
.Ruserdata
13 changes: 13 additions & 0 deletions hw-1.Rproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Version: 1.0

RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default

EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8

RnwWeave: Sweave
LaTeX: pdfLaTeX
363 changes: 223 additions & 140 deletions index.html

Large diffs are not rendered by default.

Binary file modified index.pdf
Binary file not shown.
98 changes: 80 additions & 18 deletions index.qmd
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
---
title: "Homework 1"
author: "[Insert your name here]{style='background-color: yellow;'}"
author: "[Avi Singh]{style='background-color: yellow;'}"
toc: true
title-block-banner: true
title-block-style: default
# format: html
#format: html
format: pdf
---

Expand Down Expand Up @@ -64,7 +64,7 @@ In this question, we will walk through the process of _forking_ a `git` reposito
```
Follow the instrutions in order to make sure that `renv` is configured correctly.

4. Work on the _reminaing part_ of this assignment as a `.qmd` file.
4. Work on the _remaining part_ of this assignment as a `.qmd` file.

- Create a `PDF` and `HTML` file for your output by modifying the YAML frontmatter for the Quarto `.qmd` document

Expand Down Expand Up @@ -118,6 +118,20 @@ For the following questions, provide your answers in a code cell.

1. Sort the values of `my_vec_double` in ascending order.

```{r}
typeof(my_vec) # 1. The data type is character

my_vec_double <- as.double(my_vec) # 2. Converting data types
my_vec_int <- as.integer(my_vec)

typeof(my_vec_double) # Verifying the types of vectors are what we want
typeof(my_vec_int)

my_vec_bool <- ifelse(my_vec_double >= 0, FALSE, TRUE)
summary(my_vec_bool)["FALSE"] # 3. Count number of False occurrences (4)
my_vec_double_sorted = sort(my_vec_double) # 4. Sort values of my_vec_double
```


<br><br><br><br>
<br><br><br><br>
Expand All @@ -144,6 +158,13 @@ $$
\end{bmatrix}
$$

```{r}
mat1 <- matrix(c(1,2,3,4,5,6,7,8,9),nrow=3, ncol=3, byrow = TRUE) # Create first matrix
mat2row1 <- 1:100
mat2row2 <- (mat2row1)^2
mat2data <- c(mat2row1, mat2row2)
mat2 <- matrix(mat2data, nrow = 2, ncol = 100, byrow = TRUE) # Create second matrix
```
::: {.callout-warning}
## Tip

Expand Down Expand Up @@ -180,16 +201,16 @@ mean(M)

2. Write a function `row_wise_scan` which scans the entries of `M` one row after another and outputs the number of elements whose value is $\ge 0$. You can use the following **starter code**

```R
```{R}
row_wise_scan <- function(x){
n <- nrow(x)
m <- ncol(x)

# Insert your code here
count <- 0
for(...){
for(...){
if(...){
for(i in 1:n){
for(value in x[i,]){
if(value>=0){
count <- count + 1
}
}
Expand All @@ -202,11 +223,17 @@ row_wise_scan <- function(x){

3. Similarly, write a function `col_wise_scan` which does exactly the same thing but scans the entries of `M` one column after another

```R
```{R}
col_wise_scan <- function(x){
count <- 0

... # Insert your code here
m <- ncol(x)
for(i in 1:m){
for(value in x[,i]){
if(value>=0){
count <- count + 1
}
}
}

return(count)
}
Expand All @@ -215,6 +242,8 @@ You can check if your code is doing what it's supposed to using the function her

4. Between `col_wise_scan` and `row_wise_scan`, which function do you expect to take shorter to run? Why?

* I would expect row_wise_scan to take shorter to run since R handles row-wise operations faster than column-wise.

5. Write a function `time_scan` which takes in a method `f` and a matrix `M` and outputs the amount of time taken to run `f(M)`

```R
Expand All @@ -227,24 +256,56 @@ time_scan <- function(f, M){
return(total_time_taken)
}
```
```{R}
time_scan <- function(f, M){
initial_time <- Sys.time()
f(M)
final_time <- Sys.time()

total_time_taken <- final_time - initial_time
return(total_time_taken)
}
```

Provide your output to

```R
```{R}
list(
row_wise_time = time_scan(row_wise_scan, M),
col_wise_time = time_scan(row_wise_scan, M)
col_wise_time = time_scan(col_wise_scan, M)
)
```
Which took longer to run?

row_wise_time took longer to run

6. Repeat this experiment now when:
* `M` is a $100 \times 100$ matrix
* `M` is a $1000 \times 1000$ matrix
* `M` is a $5000 \times 5000$ matrix
```{r}
M_100 <- generate_matrix(100)
M_1000 <- generate_matrix(1000)
M_5000 <- generate_matrix(5000)
list(
row_wise_time = time_scan(row_wise_scan, M_100),
col_wise_time = time_scan(col_wise_scan, M_100)
)
list(
row_wise_time = time_scan(row_wise_scan, M_1000),
col_wise_time = time_scan(col_wise_scan, M_1000)
)
list(
row_wise_time = time_scan(row_wise_scan, M_5000),
col_wise_time = time_scan(col_wise_scan, M_5000)
)

```

What can you conclude?

* Generally speaking, row_wise_time takes longer to run, and the amount of time it takes to run increases with dimensions of M

<br><br><br><br>
<br><br><br><br>
---
Expand All @@ -259,9 +320,10 @@ sessionInfo()

[^footnote]: If your code is right, the following code should evaluate to be `TRUE`

```R
sapply(1:100, function(i) {
x <- generate_matrix(100)
row_wise_scan(x) == col_wise_scan(x)
}) %>% sum == 100
```
```{R}
library(tidyverse)
sapply(1:100, function(i) {
x <- generate_matrix(100)
row_wise_scan(x) == col_wise_scan(x)
}) %>% sum == 100
```
4 changes: 2 additions & 2 deletions index_files/libs/bootstrap/bootstrap.min.css

Large diffs are not rendered by default.

131 changes: 14 additions & 117 deletions index_files/libs/quarto-html/quarto.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const sectionChanged = new CustomEvent("quarto-sectionChanged", {
});

window.document.addEventListener("DOMContentLoaded", function (_event) {
const tocEl = window.document.querySelector('nav.toc-active[role="doc-toc"]');
const tocEl = window.document.querySelector('nav[role="doc-toc"]');
const sidebarEl = window.document.getElementById("quarto-sidebar");
const leftTocEl = window.document.getElementById("quarto-sidebar-toc-left");
const marginSidebarEl = window.document.getElementById(
Expand All @@ -33,9 +33,6 @@ window.document.addEventListener("DOMContentLoaded", function (_event) {
tab.addEventListener("shown.bs.tab", fireSlideEnter);
});

// fire slideEnter for tabby tab activations (for htmlwidget resize behavior)
document.addEventListener("tabby", fireSlideEnter, false);

// Track scrolling and mark TOC links as active
// get table of contents and sidebar (bail if we don't have at least one)
const tocLinks = tocEl
Expand Down Expand Up @@ -278,7 +275,7 @@ window.document.addEventListener("DOMContentLoaded", function (_event) {
const convertToMenu = () => {
for (const child of el.children) {
child.style.opacity = 0;
child.style.overflow = "hidden";
child.style.display = "none";
}

const toggleContainer = window.document.createElement("div");
Expand Down Expand Up @@ -381,7 +378,7 @@ window.document.addEventListener("DOMContentLoaded", function (_event) {
const convertToSidebar = () => {
for (const child of el.children) {
child.style.opacity = 1;
child.style.overflow = null;
clone.style.display = null;
}

const placeholderEl = window.document.getElementById(
Expand Down Expand Up @@ -423,21 +420,18 @@ window.document.addEventListener("DOMContentLoaded", function (_event) {
const marginChildren = window.document.querySelectorAll(
".column-margin.column-container > * "
);

nexttick(() => {
let lastBottom = 0;
for (const marginChild of marginChildren) {
const top = marginChild.getBoundingClientRect().top + window.scrollY;
if (top < lastBottom) {
const margin = lastBottom - top;
marginChild.style.marginTop = `${margin}px`;
}
const styles = window.getComputedStyle(marginChild);
const marginTop = parseFloat(styles["marginTop"]);

lastBottom = top + marginChild.getBoundingClientRect().height + marginTop;
let lastBottom = 0;
for (const marginChild of marginChildren) {
const top = marginChild.getBoundingClientRect().top;
if (top < lastBottom) {
const margin = lastBottom - top;
marginChild.style.marginTop = `${margin}px`;
}
});
const styles = window.getComputedStyle(marginChild);
const marginTop = parseFloat(styles["marginTop"]);

lastBottom = top + marginChild.getBoundingClientRect().height + marginTop;
}

// Manage the visibility of the toc and the sidebar
const marginScrollVisibility = manageSidebarVisiblity(marginSidebarEl, {
Expand Down Expand Up @@ -659,99 +653,6 @@ window.document.addEventListener("DOMContentLoaded", function (_event) {
highlightReaderToggle(isReaderMode());
});

// grouped tabsets
window.addEventListener("pageshow", (_event) => {
function getTabSettings() {
const data = localStorage.getItem("quarto-persistent-tabsets-data");
if (!data) {
localStorage.setItem("quarto-persistent-tabsets-data", "{}");
return {};
}
if (data) {
return JSON.parse(data);
}
}

function setTabSettings(data) {
localStorage.setItem(
"quarto-persistent-tabsets-data",
JSON.stringify(data)
);
}

function setTabState(groupName, groupValue) {
const data = getTabSettings();
data[groupName] = groupValue;
setTabSettings(data);
}

function toggleTab(tab, active) {
const tabPanelId = tab.getAttribute("aria-controls");
const tabPanel = document.getElementById(tabPanelId);
if (active) {
tab.classList.add("active");
tabPanel.classList.add("active");
} else {
tab.classList.remove("active");
tabPanel.classList.remove("active");
}
}

function toggleAll(selectedGroup, selectorsToSync) {
for (const [thisGroup, tabs] of Object.entries(selectorsToSync)) {
const active = selectedGroup === thisGroup;
for (const tab of tabs) {
toggleTab(tab, active);
}
}
}

function findSelectorsToSyncByLanguage() {
const result = {};
const tabs = Array.from(
document.querySelectorAll(`div[data-group] a[id^='tabset-']`)
);
for (const item of tabs) {
const div = item.parentElement.parentElement.parentElement;
const group = div.getAttribute("data-group");
if (!result[group]) {
result[group] = {};
}
const selectorsToSync = result[group];
const value = item.innerHTML;
if (!selectorsToSync[value]) {
selectorsToSync[value] = [];
}
selectorsToSync[value].push(item);
}
return result;
}

function setupSelectorSync() {
const selectorsToSync = findSelectorsToSyncByLanguage();
Object.entries(selectorsToSync).forEach(([group, tabSetsByValue]) => {
Object.entries(tabSetsByValue).forEach(([value, items]) => {
items.forEach((item) => {
item.addEventListener("click", (_event) => {
setTabState(group, value);
toggleAll(value, selectorsToSync[group]);
});
});
});
});
return selectorsToSync;
}

const selectorsToSync = setupSelectorSync();
for (const [group, selectedName] of Object.entries(getTabSettings())) {
const selectors = selectorsToSync[group];
// it's possible that stale state gives us empty selections, so we explicitly check here.
if (selectors) {
toggleAll(selectedName, selectors);
}
}
});

function throttle(func, wait) {
let waiting = false;
return function () {
Expand All @@ -764,7 +665,3 @@ function throttle(func, wait) {
}
};
}

function nexttick(func) {
return setTimeout(func, 0);
}