Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Created November 21, 2020 05:02
Show Gist options
  • Save Gerst20051/77e24c4181cfac208161279bc0273500 to your computer and use it in GitHub Desktop.
Save Gerst20051/77e24c4181cfac208161279bc0273500 to your computer and use it in GitHub Desktop.
PHP Age Counting
<?php
// Your goal is to count how many items exist that have an age equal to or greater than 50, and print this final value.
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$json_data = json_decode($data, true);
$items = explode(', ', $json_data['data']);
$count = array_reduce($items, function ($count, $item) {
if (strpos($item, 'age=') !== false) {
$age = explode('=', $item)[1];
if ($age >= 50) return $count + 1;
}
return $count;
}, 0);
print_r($count); // 128
?>
@isinghking007
Copy link

Can you please explain the code

@matheusdelima
Copy link

Follow the most simple and performatic solution.

"<?php

$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

$response = json_decode($data, true);
$items = explode(', ', $response['data']);
$count = 0;

foreach($items as $item){
if(str_starts_with($item, 'age=') === true && filter_var($item, FILTER_SANITIZE_NUMBER_INT) >= 50)
$count++;
}

return $count;"

@itsmems007
Copy link

it is working?

@Mrvisva
Copy link

Mrvisva commented Apr 7, 2021

yes bro, It's working.

@matheusdelima
Copy link

Thanks Mrvisva

@ZhekeJ
Copy link

ZhekeJ commented Apr 13, 2021

Thank you

@webpriest
Copy link

Great solution. It worked for me when I modified the if statement that checks the age: if ($age >= 50) $count++; The result confirms 128

@steven-jackson-dev
Copy link

steven-jackson-dev commented Dec 14, 2021

Regex solution:

$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

$sj_response = json_decode($data, true);
print_r(preg_match_all('/(age)=[5-9][0-9]/', $sj_response['data']));

@Anjank06
Copy link

Python solution for Age Counting problem by Coderbyte

import pandas as pd
import NumPy as np
import requests

r = requests.get("https://coderbyte.com/api/challenges/json/age-counting")

items = r.json()["data"].split(', ')

for data in items:
splitdata = data.split("=")
if splitdata[0].strip() == "age" and int(splitdata[1]) >= 50:
count+=1

print(count)

@LarrySul
Copy link

LarrySul commented Feb 28, 2022

<?php 

  $ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  $data = curl_exec($ch);
  curl_close($ch);

 $response = json_decode($data, true);

$result = explode(',', $response['data']);

$count = 0;

foreach($result as $value){

  
  if(strpos($value, 'age=') !== false && filter_var($value, FILTER_SANITIZE_NUMBER_INT )>= 50){
     $count++;
  } 
}

echo $count;


?>

@AjayAstro
Copy link

I want java solution for this :'-(

@kanandachristian
Copy link

I need this code for javascript

@steven-jackson-dev
Copy link

steven-jackson-dev commented Jun 19, 2022

I need this code for javascript

A derivative of my regex solution.
You need to run it through a proxy service due to CORS

fetch("https://corsproxy.io/?https://coderbyte.com/api/challenges/json/age-counting")
.then(response => response.text())
.then(result => {
const pattern = /(age)=[5-9][0-9]/g;
let count = 0;
while (match = pattern.exec(result)) count++;
console.log(count);
}).catch(error => console.log('error', error));

@meshimee
Copy link

= 50) count++; } echo $count; ?>

@asfo
Copy link

asfo commented Sep 2, 2022

I need this code for javascript

A derivative of my regex solution. You need to run it through a proxy service due to CORS

fetch("https://corsproxy.io/?https://coderbyte.com/api/challenges/json/age-counting") .then(response => response.text()) .then(result => { const pattern = /(age)=[5-9][0-9]/g; let count = 0; while (match = pattern.exec(result)) count++; console.log(count); }).catch(error => console.log('error', error));

You don't need to do all of that.

You can just do:
console.log(result.match(/(age)=[5-9][0-9]/g).length);

And that's it.

Here is the final inside CoderByte for NodeJS in the simpler way I found

const https = require('https');
https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
  let data = '';
  resp.on('data', (chunk) => data += chunk);
  resp.on('end', () => console.log(JSON.parse(data).data.match(/(age)=[5-9][0-9]/g).length));
});

@brunojhovany
Copy link

Python solution for Age Counting problem by Coderbyte

import pandas as pd import NumPy as np import requests

r = requests.get("https://coderbyte.com/api/challenges/json/age-counting")

items = r.json()["data"].split(', ')

for data in items: splitdata = data.split("=") if splitdata[0].strip() == "age" and int(splitdata[1]) >= 50: count+=1

print(count)

Here another example using pandas

import requests
import numpy as np
import pandas as pd

r = requests.get('https://coderbyte.com/api/challenges/json/age-counting%27')
print(len(r.json()['data']))
# split data by ", "
data = r.json()['data'].split(", ")
# Load to DataFrame
df = pd.DataFrame([sub.split("=") for sub in data],columns=['key', 'age'])
# Find all age values in column "key"
dfAge = df.loc[df['key'] == 'age']
# convert column values to int
dfAge['age'] = dfAge['age'].astype(int)
# find in age column all >= 50
dfAge = dfAge.loc[dfAge['age'] >= 50]


print(len(dfAge))

@asfo
Copy link

asfo commented Dec 11, 2022

Hi, Guys. I think above all solutions are not correct for the test of coderbyte.com. It is no main problem that getting the counts of age. You must be focused on this text : "Once your function is working, take the final output string and intersperse it character-by-character with your CallengeToken. Your ChallengeToken: 03h2blxr49". What is the solution?

No, it's not, I literally run my code inside CoderByte and everything is oky.

@abhihulk26
Copy link

/tmp/397740317/main.py:14: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
dfAge['age'] = dfAge['age'].astype(int)

5660
128

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment