Published
Edited
Sep 4, 2022
2 stars
Insert cell
# 57 Programming Challenges (p1)
- Upto 14 Exercises from the Book by Brian P Hogan
- Also implements self challenges on top of the exercises
- Extensive use of the Observable Inputs
- Solutions in Multiple ways are tried out
Insert cell
Insert cell
Insert cell
viewof name = Inputs.text({label:"Your Name",placeholder:"Enter your name"})
Insert cell
`Hello, ${name}, nice to meet you!!!`
Insert cell
### Self Challenge 1
Add a drop down or selection of Olympic Athletes in the name textbox
- Bring in the data
- Check where the names
- Add accessor to text box
Insert cell
athletes = FileAttachment("athletes.csv").csv({typed:true})
Insert cell
Inputs.table(athletes) //
Insert cell
viewof selectedName = Inputs.text({label:"Selected Names",placeholder:"select your name", datalist: athletes.map(d => d.name)})
Insert cell
`Hi ${selectedName} how is your game now?`

Insert cell
### Challenge 2
-Bringing in the some functions to find the length of the input name
Insert cell
`What is the length of the Name?
${selectedName} has a ${selectedName.length} character length`
Insert cell
Insert cell
athletes[0].name
Insert cell
newAthlete = athletes.map((d) => ({
name : d.name,
country: d.country,
length: d.name.length,
weight: d.weight
}))
Insert cell
Plot.plot({
marks:[
Plot.dot(newAthlete,{x:'length',y:'weight'})
]
})
Insert cell
### Challenge 3
Printing Quotes and its author name in single line
Insert cell
viewof quote = Inputs.text({label:"quotation",placeholder:"Enter the quote here"})
Insert cell
viewof author= Inputs.text({label:"Author",placeholder:"Enter the author name here"})
Insert cell
`${author} says ${quote}`
Insert cell
### Self Challenge 3
There are so many dataset where there are quotes and their authors, so when searching found it in Kaggle. Challenge is to list the authors, and when a author is selected, filter the quotes by the author and show the first 3 quotes
Insert cell
//Very raw dataset... Will be used for the Data cleaning challenge...
quotes = d3.csv("https://raw.githubusercontent.com/simranjeet97/Quotes-Analysis/master/quotes.json")
Insert cell
//Sufficiently Clean dataset, still contains duplicates
quotes_unique = FileAttachment("quotes_unique.json").json()
Insert cell
quoteCleaned = quotes_unique.map((d) =>({
Author : d.Author.split(',')[0].trim().replace('. ','.'),
quote: d.Quote
}))
Insert cell
viewof quoteAuthor = Inputs.text({label:"Author",datalist:quoteCleaned.map((d) => d.Author)})
Insert cell
//get the quote and show here. We can immediately see the challenge it poses....
quoteCleaned.find((d) => d.Author.includes(quoteAuthor)).quote
Insert cell
//How can I forget filter???
quoteCleaned.filter((d)=> d.Author.includes(quoteAuthor)).map((d) => d.quote).slice(0,3)
Insert cell
### Challenge 4 MadLib
Create form asking for multiple words that are part of English Grammar and make a random sentences.
Insert cell
viewof madlib = Inputs.form({
noun:Inputs.text({label:"noun",placeholder:"Enter a Noun here"}),
verb: Inputs.text({label:"verb",placeholder:"Enter a verb here"}),
adjective: Inputs.text({label:"adjective",placeholder:"Enter a adjective here"}),
adverb: Inputs.text({label:"adverb",placeholder:"Enter a adverb here"})
})
Insert cell
`Do You ${madlib.verb} your ${madlib.adjective} ${madlib.noun} very ${madlib.adverb}`
Insert cell
### Challenge 5 Simple Math
The code below includes the self challenges like
- Ensuring the user has input only numbers, and they are positive within certain limit.
Insert cell
viewof first = Inputs.text({label:"1st Num", type:"number",min:0,max:10000})
Insert cell
viewof second = Inputs.text({label:"2nd Num", type:"number", min:0, max:10900})
Insert cell
viewof operation = Inputs.radio(["add","subtract","multiply","divide"],{label:"operations"})
Insert cell
{
if (operation == "add"){
return `Sum of ${first} and ${second} is ${+first + +second}.`
}else if(operation =='subtract'){
return `Difference of ${first} and ${second} is ${first - second}.`
}else if(operation =='multiply'){
return `Product of ${first} and ${second} is ${first * second}.`
}else if(operation =='divide'){
return `Dividing of ${first} by ${second} is ${first / second}.`
}
}
Insert cell
### Challenge 6 Retirement Calculator
- Date of Birth input from the user
- Retirement age input from user
Insert cell
viewof dob = Inputs.date()
Insert cell
viewof retAge = Inputs.text({label:"Retirement Age",type:"number",max:75,min:0,placeholder:"Enter Retirement Age"})
Insert cell
viewof YearNow = new Date(Date.now()).getFullYear()
Insert cell
viewof birthYear = dob.getFullYear()
Insert cell
{
var available = retAge - (new Date(Date.now()).getFullYear() - dob.getFullYear())
if (available > 0){
return `You have ${available} years before retirement. Work hard.`
} else{
return `Your time is up. Retire to your home before they find you are a Relic.`
}
}
Insert cell
Mathematical Operations start
### Challenge 7 Calculating Area
Insert cell
viewof areaData = Inputs.form({
width : Inputs.text({label:"width",placeholder:"What is the room width?",type:"number"}),
length : Inputs.text({label:"length",placeholder:"What is the room length?",type:"number"}),
conversion : Inputs.text({label:"Conversion Factor",placeholder:"Sq ft to Sq meter conversion value?",type:"float"}),
})
Insert cell
{return [`You have entered ${areaData.width} feet and ${areaData.length} feet as room dimension`,
`Area is ${areaData.width * areaData.length} sqFeet`,
`Area is ${areaData.width * areaData.length * areaData.conversion} sqFeet`]
}
Insert cell
Insert cell
viewof party = Inputs.range([1,25],{label:"people",value:5,step:1})
Insert cell
viewof pizza = Inputs.range([1,500],{label:"pizzas",value:5,step:1})
Insert cell
viewof pizPieces = Inputs.range([1,5],{label:"Pieces",value:2,step:1})
Insert cell
viewof numPieces = Inputs.radio([4,6,8,10],{label:"Pieces in Pizza",value:2})
Insert cell
`${party} people with ${pizza} pizzas each having ${pizPieces} pieces`
Insert cell
{
const totPieces = pizza * numPieces;
const consumed = party * pizPieces;
const leftOver = totPieces - consumed;
return `There are ${leftOver} leftover Pizza Slices`
}
Insert cell
### Self Challenge 8
- Create dataset based on the number of Pizzas, number of People
- Plot the Bar / Scatter plot to see the relationship
Insert cell
people_number = d3.range(1,5)
Insert cell
pizza_number = d3.range(1,5)
Insert cell
pizza_pieces = d3.range(1,6)
Insert cell
myData = {
var leftOver = []
for(let num of people_number){
for(let piz of pizza_number){
for(let pie of pizza_pieces){
leftOver.push({
totPieces: piz * 8, //lets keep the number of pizza pieces const at 8
totconsum : num * pie,
left: (piz * 8) - (num * pie)
})
}
}
}
return leftOver
}
Insert cell
Inputs.table(myData)
Insert cell
Plot.plot({
marks:[
Plot.dot(myData,{x:"totPieces",y:"left",fill:"red"}), //simple linear relationship..
]
})
Insert cell
### Challenge 9 Paint Calculator
- 1 gallon covers 350 sqft
- get length and width (use the earlier data to calculate area)
Insert cell
viewof gallon = Math.ceil(areaData.length * areaData.width/ 350)
Insert cell
viewof roomType = Inputs.radio(["rectangle","circle","triangle"],{label:"Room Shape"})
Insert cell
Insert cell
### Challenge 10 Self-checkout
Insert cell
viewof cOut = Inputs.form({
price1 : Inputs.text({label:"price1",placeholder:"What is the 1st material price?",type:"number"}),
qty1 : Inputs.text({label:"Qty1",placeholder:"What is the qty Purchased?",type:"number"}),
price2 : Inputs.text({label:"price2",placeholder:"What is the 2nd material price?",type:"number"}),
qty2 : Inputs.text({label:"Qty2",placeholder:"What is the qty Purchased?",type:"number"}),
price3 : Inputs.text({label:"price3",placeholder:"What is the 3rd material price?",type:"number"}),
qty3 : Inputs.text({label:"Qty3",placeholder:"What is the qty Purchased?",type:"number"}),
})
Insert cell
subtot = {
return cOut.price1 * cOut.qty1 + cOut.price2 * cOut.qty2 + cOut.price3 * cOut.qty3
}
Insert cell
`Subtotal: ${subtot},
Tax : ${subtot * 5.5 / 100},
Total : ${subtot * 105.5 / 100}` //that is neat
Insert cell
Insert cell
Insert cell
viewof sourceCurr = Inputs.text({label:"from Currency", datalist:Object.entries(latest_rates).map(d => d[0])})
Insert cell
viewof convCurr = Inputs.text({label:"To Currency", datalist:Object.entries(latest_rates).map(d => d[0])})
Insert cell
fromRate = latest_rates[sourceCurr.toUpperCase()]
Insert cell
toRate = latest_rates[convCurr.toUpperCase()]
Insert cell
viewof currAmt = Inputs.text({label:"Amount",type:"number",placeholder:"Input Amount",value:0,min:0})
Insert cell
`${currAmt} ${sourceCurr} at exchange rate of ${fromRate} and ${convCurr}s at exchange rate of ${toRate} is ${convert} ${convCurr}s` //Rounding it to next nearest penny
Insert cell
convert = {
return ((currAmt * fromRate) / (toRate)).toFixed(2)
}
Insert cell
Insert cell
viewof sInt = Inputs.form({
principle : Inputs.text({label:"amount",placeholder:"What is the amount?",type:"number"}),
rate : Inputs.text({label:"rate",placeholder:"What is the interest rate?",type:"number"}),
time : Inputs.text({label:"tenure",placeholder:"What is the tenure of investment?",type:"number"}),
comp : Inputs.text({label:"Compound",placeholder:"How many time interest is compounded everyYear?",type:"number"}),
})
Insert cell
simInt = {
return sInt.principle * sInt.rate * sInt.time / 100
}
Insert cell
compInt = {
const interim = (1 + (sInt.rate * 0.01 / sInt.comp)) ** (sInt.comp * sInt.time)
return (sInt.principle * interim).toFixed(2)
}
Insert cell
`After ${+sInt.time} years at ${+sInt.rate}, the investment will be worth ${simInt + +sInt.principle}`
Insert cell
`After ${+sInt.time} years at ${+sInt.rate} compounding at ${sInt.comp} times a year, the investment will be worth ${compInt}`
Insert cell
## Exercise 14 Tax Calculator
Following has been implemented
- Decision is done with If statement.
- The output is rounded to the nearest cent using the toFixed(2) method.
- State can be entered either as full name or abbreviation. The case also can be user choice, the code inside will convert the same.
### Additional challenge
- The tax for the all states is generated randomly, and used in the calculation
- Created a search option for the state
Insert cell
import {stateToAbbr} from "@nyuvis/graphical-encoding-exercise"
Insert cell
stateToAbbr
Insert cell
stateFull = Object.keys(stateToAbbr)
Insert cell
stateAbbr = Object.values(stateToAbbr)
Insert cell
abbrState = {
const abbr = {};
for(let i = 0; i < 59; i++){
abbr[stateAbbr[i].toLowerCase()] = stateFull[i].toLowerCase()
}
return abbr
}
Insert cell
abbrTax = {
const abbr = {};
for(let i = 0; i < 59; i++){
abbr[stateAbbr[i].toLowerCase()] = +(0.15 + Math.random()).toFixed(2)
}
return abbr
} //there is a simpler way
Insert cell
new Map(Object.entries(stateToAbbr)) //Map takes all the array elements and converts them together. No need for map()
Insert cell
Object.entries(stateToAbbr)
Insert cell
taxState = {
const state = billInv.state.toLowerCase()
if (Object.values(abbrState).includes(state)){
const abbr = stateToAbbr[state].toLowerCase()
return abbrTax[abbr]
}
if (Object.keys(abbrState).includes(state)){
return abbrTax[state]
}
}
Insert cell
viewof billInv = Inputs.form({
amount : Inputs.text({label:"Order Amount",placeholder:"What is order amount?",type:"number"}),
state : Inputs.select(stateAbbr,{label:"State",placeholder:"Which State?",type:"string"})
})
Insert cell
nameType = {
const state = billInv.state.toLowerCase()
if (Object.values(abbrState).includes(state)){
return 'Full Name'
}
if (Object.keys(abbrState).includes(state)){
return 'Abbreviation'
}
}
Insert cell
tax = {
//Since the user can enter either the full or abbreviation, both needs to be coded
const state = billInv.state.toLowerCase()
if(state == 'wi' || state == 'wisconsin'){
return 0.55
}
}
Insert cell
subTotal = +billInv.amount
Insert cell
Total = +(subTotal + taxState).toFixed(1)
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more