r/dailyprogrammer • u/Cosmologicon 2 3 • Nov 11 '19
[2019-11-11] Challenge #381 [Easy] Yahtzee Upper Section Scoring
Description
The game of Yahtzee is played by rolling five 6-sided dice, and scoring the results in a number of ways. You are given a Yahtzee dice roll, represented as a sorted list of 5 integers, each of which is between 1 and 6 inclusive. Your task is to find the maximum possible score for this roll in the upper section of the Yahtzee score card. Here's what that means.
For the purpose of this challenge, the upper section of Yahtzee gives you six possible ways to score a roll. 1 times the number of 1's in the roll, 2 times the number of 2's, 3 times the number of 3's, and so on up to 6 times the number of 6's. For instance, consider the roll [2, 3, 5, 5, 6]. If you scored this as 1's, the score would be 0, since there are no 1's in the roll. If you scored it as 2's, the score would be 2, since there's one 2 in the roll. Scoring the roll in each of the six ways gives you the six possible scores:
0 2 3 0 10 6The maximum here is 10 (2x5), so your result should be 10.
Examples
yahtzee_upper([2, 3, 5, 5, 6]) => 10
yahtzee_upper([1, 1, 1, 1, 3]) => 4
yahtzee_upper([1, 1, 1, 3, 3]) => 6
yahtzee_upper([1, 2, 3, 4, 5]) => 5
yahtzee_upper([6, 6, 6, 6, 6]) => 30Optional Bonus
Efficiently handle inputs that are unsorted and much larger, both in the number of dice and in the number of sides per die. (For the purpose of this bonus challenge, you want the maximum value of some number k, times the number of times k appears in the input.)
yahtzee_upper([1654, 1654, 50995, 30864, 1654, 50995, 22747,
1654, 1654, 1654, 1654, 1654, 30864, 4868, 1654, 4868, 1654,
30864, 4868, 30864]) => 123456There's no strict limit on how fast it needs to run. That depends on your language of choice. But for rough comparison, my Python solution on this challenge input, consisting of 100,000 values between 1 and 999,999,999 takes about 0.2 seconds (0.06 seconds not counting input parsing).
If you're preparing for a coding interview, this is a good opportunity to practice runtime complexity. Try to find a solution that's linear (O(N)) in both time and space requirements.
Thanks to u/Foenki for inspiring today's challenge in r/dailyprogrammer_ideas!
12
u/meepmeep13 Nov 12 '19 edited Nov 12 '19
Python 3 one-liner:
10
u/Gylergin Nov 12 '19 edited Nov 12 '19
TI-Basic:
L₁is the roll list andL₂is the score listEdit: no need to sort
L₂whenmax(exists9
u/lukz 2 0 Nov 16 '19 edited Nov 16 '19
Z80 assembly
This is a program for Sharp MZ-800 computer. I don't do the user input and assume that the input data are stored in memory at addresses (2003h - 2007h). When run from address 2000h the program calculates the best score and prints it as two digits to the screen.
After loading the program we can go to monitor and enter the input using the M command. Then we can run the program from monitor using the G command.
Sample session:
The * is the monitor prompt
Imgur
Code:
7
u/zmm0 Nov 15 '19
x86_64. Runs in O(N). Takes 50ms on the challenge input.
6
u/[deleted] Nov 11 '19 edited Nov 11 '19
Clojure, github input takes about 50msec
6
u/Gprime5 Nov 12 '19
Python 3 Runs in 20ms on the 100,000
5
u/tomekanco Nov 12 '19
Python, 180 ms: dominated by read, 40 ms for counter+max.
5
u/sameer_sinha Nov 12 '19
Scala with bonus
duration for the 100,000 values list = 0.8 seconds
5
u/[deleted] Nov 15 '19 edited Dec 01 '19
Shell (with gnu coreutils)
I downloaded the yahtzee-upper-1.txt file and put it into a file called input.txt, and the I/O, parsing of the numbers and then generating the output took 0.05s on my machine:
cat input.txt | sort -n | uniq -c | awk '{ print $1*$2 }' | sort -rn | head -n1(Edit: shorter version:
sort -n input.txt|uniq -c|awk '{print$1*$2}'|sort -n|tail -n1)4
u/g00glen00b Nov 11 '19 edited Nov 12 '19
Java:
Also, could you tell us what the result would be of the large file? Currently I get 31,415,926,535 within 0.017 seconds (excluded I/O time of reading the text-file).
4
u/btingle Nov 16 '19
Python3 - O(n) straightforward solution
4
u/Stickycover Nov 17 '19
Python - O(n)
There's a lot of good solutions but I wanted to put mine in there to highlight how a dict's setdefault(key, default_value) is useful for filling dictionaries like this.
4
u/NemPlayer Nov 23 '19 edited Dec 18 '19
Python 3.8 (with bonus)
Time complexity: O(N^2 log n)
Improved
Time complexity: O(N)
Instead of using map on the tuples generated, it's possible to just use a generator expression and instead of using the
most_commonmethod, it's possible to use theitemsmethod making it both faster and have a much better time complexity.4
u/29a75HHH Nov 29 '19
This is done in Python. The complexity is O(N) and the time for 100,000 values between 1 and 999,999,999 has been practically 0.06 without parsing input. Feedback and compliments are both welcome and appreciated.
4
u/voidhawk42 Dec 06 '19
Dyalog APL:
Handles large, unsorted input. Runs in O(n).
3
u/twisted-teaspoon Nov 12 '19 edited Nov 12 '19
Python3
3
u/lollordftw Nov 12 '19
Haskell
Unfortunately it's O(n*log(n)). Runs in about 190 ms.
Does anyone have an idea on how to solve this problem in O(n) without the use of Hash Maps?
3
u/olzd Nov 12 '19
(g)AWK:
3
u/hyrulia Nov 12 '19
Kotlin
3
u/[deleted] Nov 12 '19
Python 3
Time for the bonus:
3
u/dontforget512 Nov 12 '19 edited Nov 13 '19
PowerShell!
3
u/jonnywoh Nov 13 '19 edited Nov 13 '19
C#, with bonus
Edit: a complete program with no error handling:
Edit: much faster version (but with similar complexity):
3
u/raevnos Nov 23 '19 edited Nov 24 '19
GNU Prolog:
3
u/ruincreep Nov 26 '19 edited Nov 29 '19
Raku (Perl 6)
Takes ~0.7s for the bonus input including parsing.
Without parsing it's ~0.14s (there's very high I/O load on my server):
3
u/onesweetsheep Mar 11 '20 edited Mar 11 '20
This is my beginner Python attempt:
I'm sure it's not an elegant solution, but it seems to work. Happy for any feedback! :)
3
u/MrTyranius Apr 10 '20
Python that allows you to adjust the numbers on the dice and how many times you roll.
import random as randimport timestart_time = time.time()diceRolls = []numRolls = 5lowRoll = 1highRoll = 6for x in range(0,numRolls):diceNum = rand.randint(lowRoll, highRoll)diceRolls.append(diceNum)diceRolls.sort()# print(diceRolls)def scoreRoll(list):numOfNums = []scores = []for i in range(lowRoll,highRoll + 1):value = list.count(i)numOfNums.append(value)#print(numOfNums)j = lowRollfor k in range(0,len(numOfNums)):score = (j) * numOfNums[k]if score != 0:scores.append(score)j += 1# print(scores)return max(scores)#print(scores)maxScore = scoreRoll(diceRolls)print(maxScore)# print("------ %s seconds -------" % round(time.time() - start_time, 5))2
u/skeeto -9 8 Nov 11 '19 edited Nov 12 '19
C with bonus, reading from stdin. It completes the bonus input in about 10ms.
2
u/CoDBorn Nov 12 '19
Could you provide the result you've got on the 100 000 value list, for checking purposes?
2
u/CoDBorn Nov 12 '19
Java with bonus, got 31415926535 on the 100 000 value list in 85ms.
2
u/chunes 1 2 Nov 12 '19
Factor. Does the bonus in 7 milliseconds.
2
u/ernesdp Nov 12 '19
Python.
This my solution although I guess this is not very fast.
2
u/[deleted] Nov 13 '19
C#
2
u/[deleted] Nov 13 '19
My code works fine for the first test but when trying the bonus i get the following value:
2144475295
Calculated from val = 944772471 repeated 25x in the list.
Anyone have a similar issue that knows what the issue is?
I took C in College (like 20 years ago) so I'm guessing I messed up some kind of memory allocation or something stupid..
code: https://pastebin.com/DYBFGaFW
I don't expect anytone to debug the code but if you see an obvious error/what im missing, it would be appreciated it!
2
u/[deleted] Nov 16 '19 edited Nov 18 '19
Python3 feedback appreciated (as always)
alternatively, here's a version with no intermediary stored list
2
u/errorseven Nov 16 '19 edited Nov 17 '19
AutoHotkey - O(n) untested on mobile
EDIT: Tested - Turns out Max() function does not support unpacking Associative Arrays / Objects, only Linear Arrays - I solved this by including a comparison for a Max Value at every iteration.
2
u/kopo222 Nov 20 '19
Python 3
I'm not sure how to determine if it is O(n)
However it completes the large list supplied in roughly 0.018 seconds, excluding reading in the data. With this included it takes roghly 0.06 seconds
2
u/LudBee Nov 21 '19
Why is the challenge input given without an expected output?
2
u/draegtun Nov 25 '19
Rebol
Example usage in Rebol 3 console:
2
u/tcbenkhard Nov 26 '19
Java
2
u/ephemient Nov 27 '19 edited Apr 24 '24
This space intentionally left blank.
2
u/Specter_Terrasbane Nov 27 '19 edited Nov 27 '19
Python
Tried multiple methods and timed them, just for shiggles ... A custom
MaxDictclass, that updates the current maximum value on any set value call, anitertools.groupbysolution, and the pretty much expected solution,collections.Counter.Spoiler alert:
collections.Counterwas the clear winner, by far, at an average time of 0.006s (not including input parsing).Output
Code
2
u/Gian12315 Dec 20 '19
Here's my Rust implementation:
It runs challenge input under 20ms
2
u/LowerConcentrate Dec 23 '19 edited Dec 23 '19
Python 3. One-liner.
C. (Without bonus, but could be with mapping)
2
u/stevenbee95 Dec 24 '19
Javascript:
2
u/mike_the_kangeroo Dec 28 '19
def yahtzee_upper(inp):sides = set(inp)highest = -1for element in sides:val = element * inp.count(element)if val > highest:highest = valreturn highest2
u/machinematrix Jan 02 '20
C++ with bonus.
2
u/thecleancoder Jan 14 '20 edited Jan 14 '20
Python 3
2
u/TheRealGregorM Jan 14 '20
Python 3
2
u/neur0sys Jan 16 '20 edited Jan 16 '20
Z80 Assembly
Supports only 6-sided dice.
Run through BASIC: https://i.imgur.com/LeClRN5.gif
Together with the BASIC runner: https://gist.github.com/neuro-sys/375e6dc51a3099c99b9ef73fd73f8d96
2
u/Keone_ShyGuy Jan 17 '20 edited Jan 17 '20
New to javascript and codepen, so the idea of getting input for the 2nd challenge is a bit daunting at the moment, but managed to get the first challenge working.
Interactive version
2
u/antonio-one Jan 21 '20 edited Jan 21 '20
Python 3
import random
class Dice():
2
u/Aware-Computer Feb 22 '20
Haskell:
yahtzee_upper y = maximum (map (\x -> (length x) * (head x)) (group y))2
u/vorok21 Mar 10 '20
java
2
u/Mahjongasaur Mar 11 '20
HTML/JS
2
u/ArtemiyKra Jan 03 '23
The shortest Pyhton solution))
1
u/ASpueW Nov 12 '19 edited Nov 12 '19
Rust with bonus
Output:
Playground
1
u/gabyjunior 1 2 Nov 12 '19 edited Nov 12 '19
Ruby with bonus (takes 220ms including input parsing).
1
u/morgon-of-hed Nov 12 '19
JavaScript
1
u/neo2049 Nov 12 '19 edited Nov 13 '19
Python
from collections import Counter def yahtzee_upper(list): newList = {} total = [] newList = Counter(list) for keys, values in newList.items(): total.append(keys * values) print(max(total))
1
u/octolanceae Nov 13 '19 edited Nov 13 '19
C++17 w/optional bonus
Note: Editted for code formatting purposes
For 100k input - The cake is a lie, it is all about the pi.
0.04 seconds, including file i/o.
1
u/SuperVGA Nov 13 '19
ES6 meant to allow association between faces and values for each side of a die, as well as any special rules to scoring when a particular face wasn't showing. It's by no means economical, but it looks pretty good, I think...
You'd invoke it with values matching the property values;
1
u/Edwizzy102 Nov 13 '19
Code in Java 8:
Did the simple version because the challenge would most likely have the same result with O(N) time complexity:
1
u/RevenantMachine 1 0 Nov 13 '19
Kotlin, with bonus:
This runs in about 80 ms cold, and 15 ms after a dozen iterations, when the JVM is warmed up a bit.
Time complexity is linear wrt. the length of the sequence, and space complexity is linear wrt. the distinct values present in the sequence.
1
u/bruce3434 Nov 14 '19 edited Nov 14 '19
##D
The test cases with optional bonus and with the data from the URI. libcurl must be installed in your computer.
1
u/__dict__ Nov 15 '19
Racket Scheme.
Code:
Output:
Time to do the large file:
Time to do a file with a single line:
So yea, it's roughly 0.119s startup time and 0.06s time actually processing the list.
1
u/jslinde123 Nov 15 '19
Possible solution in Python 3. Feedback appreciated.
1
u/ogniloud Nov 15 '19
Raku
1
u/austinll Nov 18 '19
Java
Yahtzee function ~280 ms
public static void Yahtzee(LinkedList<Long> vals){
}
main ~330 ms
public static void main(String[] args){
}
1
u/[deleted] Nov 21 '19
1
u/paopaopao69 Nov 22 '19 edited Nov 22 '19
C#
1
u/Dasaru Nov 22 '19
Javascript
1
u/arthurelamothe Nov 23 '19 edited Nov 23 '19
C++/Qt
1
u/raevnos Nov 24 '19 edited Nov 24 '19
And Sqlite, with bonus:
After loading challenge input into into the database, all seven cases are solved in less than 0.025 seconds on my old Sandybridge. Indexes are great.
1
u/TheMightyShovelface Nov 24 '19
Go
1
u/raevnos Nov 24 '19
One last one, in tcl. Reads the challenge input on standard input, one number per line like it was provided.
1
u/thorwing Nov 25 '19
Kotlin
1
u/Little_Danson_Man Nov 25 '19 edited Nov 25 '19
Here's a python solution
I'm pretty sure this is an O(n) time complexity solution. I'm not sure about space complexity.
dict.fromkeys()is a great helper function because it allowed me to initialize with relative ease1
u/[deleted] Dec 03 '19
Python
1
u/awsome855 Dec 08 '19 edited Dec 08 '19
1
u/darknes1234 Dec 08 '19
Go
1
u/[deleted] Dec 09 '19
Erlang
1
u/JackMagic1 Dec 09 '19
C# (with Linq)
1
u/AviatingFotographer Dec 11 '19
1
u/weijiajun Dec 11 '19
Python:
1
u/aureliogrb Dec 12 '19
Java:
Loading the values from a text file called "values", one value per line.
Path path = FileSystems.getDefault().getPath("./src", "values.txt");//put the values on a list of stringsList<String> lines = Files.readAllLines(path, Charset.defaultCharset());//Convert them to a stream of IntegersStream<Integer> values =lines.stream().mapToInt(Integer::valueOf).boxed();// Map all the values, the key is the value chosen, the value is the sum of the dices that rolled the keyMap<Integer, Integer> counts = values.collect(Collectors.groupingBy(Function.identity(),Collectors.summingInt(Integer::valueOf)) );//Return the highest value.return counts.values().stream().mapToInt(Integer::valueOf).max().orElse(0);Processes the test file with 100K values in 0.22 seconds on my laptop.
1
u/normantas Dec 17 '19
C# code with an explanation to it, feel free to use it
Pastebin code for colored code
1
u/blanket_warrior Dec 18 '19 edited Dec 18 '19
Haskell (using list comprehension)
1
u/seth5124 Dec 18 '19
Java w/ Bonus - Run time w/ input parsing: ~350ms
1
u/Hellakittehs Dec 19 '19
Java with bonus
1
u/kapatchie1 Dec 19 '19
C#
1
u/coniferish Dec 20 '19
Python (1 line)
1
u/GoldenShadowBG Dec 24 '19
C#. A lot of 'follow code lines'
1
u/raevnos Dec 25 '19
tcl, with bonus:
1
u/sudhackar Dec 27 '19
swi prolog with bonus. Use include/3 to count. Probably O(N^(2))
1
u/fosterhenry03 Dec 29 '19
int max(int);
int find (int, string[]);
int main(int argc, string argv[])
{
int answer = 0;
//checking input
if(argc != 6)
{
printf("must input 5 numbers in the command line\n");
return 1;
}
for(int i = 0; i < 6; i++)
{
int x = atoi(argv[i]);
if(x > 6 || x < 0)
{
printf("numbers must be between 1 and 6 inclusive\n");
return 2;
}
}
// iterate through all possible ways
for(int i = 0; i < 6; i++)
{
answer = max(i * find(i, argv));
}
printf("%i\n", answer);
}
int find(int n, string argv[6])
{
int counter = 0;
for(int i = 0; i < 6; i++)
{
int x = atoi(argv[i]);
if(x == n)
{
counter += 1;
}
}
return counter;
}
int max(int new_n)
{
static int old_n = 0;
if(new_n > old_n)
{
old_n = new_n;
return new_n;
}
else
{
old_n = new_n;
return old_n;
}
}
1
u/mhornberger Dec 30 '19 edited Dec 30 '19
In Python 3.6:
This 2nd version handles more input:
It returns a list with the number of sides, max score for that roll, and the roll as well.
1
u/skate777771 Jan 03 '20
Dic = {}
for i in x:
Maior = 0
for i in Dic:
print(Maior)
1
u/Inmassss Jan 07 '20
import randomdef yahtzee(result = [random.randint(1,6),random.randint(1,6),random.randint(1,6),random.randint(1,6),random.randint(1,6)]):reps = [result.count(1),result.count(2),result.count(3),result.count(4),result.count(5),result.count(6)]repsnum = [result.count(1)*1,result.count(2)*2,result.count(3)*3,result.count(4)*4,result.count(5)*5,result.count(6)*6]repeated= []for x in reps:if x > 1:repeated.append(x)if reps.count(1) == 5:score = max(result)elif len(repeated) == 1:score = repeated[0]*(reps.index(repeated[0])+1)else:score = max(repsnum)return f'Your result is {result[0]},{result[1]},{result[2]},{result[3]},{result[4]}\nYour score is {score}'print(yahtzee())1
u/oschonrock Jan 08 '20 edited Jan 08 '20
Here is a completely OTT, prematurely optimised version in C++.
It achieves complete parse and compute in < 8ms on my machine (i7 2600 with SSD) for the provided 1MB file on github. Most of that is parse (~6ms).
Tricks are:
std::stringand no copies. Usestd::string_viewthroughout. Themmapfile gives aconst char*buffer which we can parse over and access usingstd::string_view.<charchonv> from_charsbecause it's very fastska::bytell_hash_mapfrom hereos::...utility wrappers are my own from here.clang-9 -O3for x64. Platform is Kubuntu 19.10.1
u/Edwizzy102 Jan 09 '20
golang:
1
u/PoonjabiPikachu Jan 09 '20 edited Jan 09 '20
Java:
1
u/Pto2 Jan 10 '20
Python 3
Yea I used print statements instead of return.
1
u/shepherdjay Jan 10 '20 edited Jan 12 '20
Python 3
Haven't cracked O(n) yet but this is O(n + k) where k is the number of unique values in the list. Worse case it is still O(n2 ) - works on that file in 0.118 seconds (not including parsing).
Edit: I guess this is O(n) need to revisit time complexity self study.
1
u/[deleted] Jan 12 '20 edited Jan 12 '20
Go
O(n) solution based on dictionaries, it takes 0.04s of real time
main.go
1
u/GoAwayStupidAI Jan 15 '20
scala
1
u/khalidkh Jan 15 '20
Python 3
Output
1
u/neur0sys Jan 16 '20 edited Jan 16 '20
Emacs Lisp
1
u/DaVileKial6400 Jan 17 '20 edited Jan 17 '20
Here is my attempt using JavaScript.
Web browsers took about 0.2 - 0.4 seconds to solve the 100,000 problem.
Though Edge has a problem reloading the script and it jumps to a whopping 50 secs to solve if you refresh.
To test you have to fill the diceRolls array with input numbers.
2
u/Kumaravel47Kums Jan 21 '20
Python 3
import collections
def yahtzee_upper(data):
c=collections.Counter(data)
list=[]
for x in c.items():
list.append(x[0]*x[1])
print(max(list))
Input :
yahtzee_upper([1654, 1654, 50995, 30864, 1654, 50995, 22747,1654, 1654, 1654, 1654, 1654, 30864, 4868, 1654, 4868, 1654,30864, 4868, 30864])
Output :
123456
1
u/boonetang3 Jan 23 '20
Python 3
1
u/mayhem-makers Jan 25 '20
1
u/[deleted] Jan 26 '20 edited Jan 26 '20
C# solution:
long MaxScore(params long[] dices)=> dices.GroupBy(x => x).Select(x => x.Key * x.Count()).Max();Tests:
Debug.Assert(MaxScore(2, 3, 5, 5, 6) == 10);Debug.Assert(MaxScore(1, 1, 1, 1, 3) == 4);Debug.Assert(MaxScore(1, 1, 1, 3, 3) == 6);Debug.Assert(MaxScore(1, 2, 3, 4, 5) == 5);Debug.Assert(MaxScore(6, 6, 6, 6, 6) == 30);Debug.Assert(MaxScore(1654, 1654, 50995, 30864, 1654, 50995, 22747, 1654, 1654, 1654, 1654, 1654, 30864, 4868, 1654, 4868, 1654, 30864, 4868, 30864) == 123456);Bonus Challenge
var largeData = LargeTestData.TestValues;var sw = new Stopwatch();sw.Start();var result = MaxScore(largeData); // result: 31415926535sw.Stop();var duration = sw.Elapsed; // duration: 8ms to 21ms (run ~20 times)Edit:
Changed datatype from int to long, since int is too small for the result of the bonus challenge.
1
u/RoastingAltAccount Jan 29 '20
Python 3.7
1
u/[deleted] Jan 31 '20
My method for unsorted list of rolls. It should handle different dices and different values:
It works fine in any case, but what about optimization of code? Is it good?
1
u/NikstatioN Jan 31 '20
Trying to learn programming, and my attempt at the challenge using C++ !
Any tips and improvements would be much appreciated ! =) Thanks !!
1
u/mickira Feb 05 '20
python3:
1
u/SkrtelSquad Feb 06 '20
I have been teaching myself Python3 for the last few days and this is my first attempt at a challenge. Any feedback would be welcome. It works but my time taken for the challenge input is 1.60 seconds.
Basically I have 2 functions. The first one, smaller, creates a list of unique values from the list of rolls.
Then the 2nd function, tally, multiplies each of the unique values against how many times it appears in the original file.
If anyone is reading and has any feedback that would be great. Thanks! I know it is not super fast. If there are any ways to make it faster without completely rewriting, that would be cool. I originally tried just doing the tally function on the whole list, however this took forever to calculate.
1
u/BadgerRobot Feb 08 '20
My first time trying this after learning about these sorts of challenges. I am relearning coding after not using it for a long time. Teaching myself Java at home working towards getting an SDET job. (I've been in QA for 20 years, but the job is changing to more coding forward.)
Here is my Java result:
package redditCodingChallenge;
import java.util.ArrayList;
public class CodingChallenge {
}
package redditCodingChallenge;
import java.util.ArrayList;
public class YahtzeeScoringChallenge {
// Challenge #381 [Easy] Yahtzee Upper Section Scoring
public static int yahtzeeUpper(ArrayList<Integer> roll) {
for(int i = 1 ; i <=6 ; i++) {
result = i * countInList(roll, i);
if (result > max) {
max = result;
}
}
return max;
private static int countInList(ArrayList<Integer> roll, int n) {
int count = 0;
for (int i = 0; i < roll.size(); i++) {
if (roll.get(i).equals(n)) {
count++;
}
}
return count;
}
}
1
u/a_bcd-e Feb 08 '20
c++. O(N log N) as I couldn't find a solution in O(N).
1
u/[deleted] Feb 09 '20 edited Dec 03 '25
sheet pet follow sugar distinct handle amusing dinosaurs steep one
This post was mass deleted and anonymized with Redact
1
u/sebamestre Feb 10 '20 edited Feb 10 '20
Here is a small O(dice * faces) time solution (though it is hardcoded for 6 faces). It is the first thing that came to mind.
For the more general case, I came up with this O(dice) space and time solution:
The entire runtime was 430ms, but after adding some timers, it seems like this function only takes 55ms, with IO & number parsing taking 49ms.
55ms + 49ms = 104ms, which is under 25% of the total run-time. I don't know where the rest comes from but I'd say it's probably Node's startup time.
1
u/Zezeroth Feb 11 '20 edited Feb 11 '20
Quick and Dirty Golang. Havent spent any time making it efficient
1
u/AdzzZa Feb 12 '20 edited Feb 12 '20
Simple python solution:
sez = [1654, 1654, 50995, 30864, 1654, 50995, 22747, 1654,1654,1654,1654,1654,30864,4868,4868,1654,30864,4868,30864]
def Yahtzee(sez):
print(Yahtzee(sez))
1
u/pamdirac1 Feb 16 '20
Rust
1
u/Mathgeek007 Feb 17 '20
GolfScript
Try it online!
1
u/Chilllking Feb 21 '20 edited Feb 21 '20
am a bit late to the party but here is my Python solution:
the solution it gets is:
EDIT: my first time posting code, had to reformat it cause im stupid
1
u/Fiuryn Feb 21 '20 edited Feb 21 '20
c# Solution
1
u/FlyingVince Feb 24 '20 edited Feb 24 '20
PHP:
function yatzee_Upper($arr){
$highest_number=max($arr); //defines how many times we have to loop $new_array=array_count_values($arr); //count occurence of each value
$final_array=[];
for ($i=0;$i<=$highest_number;$i++){
if (array_key_exists($i,$new_array)) {
array_push($final_array,($new_array[$i]*$i));
} }
$max=max($final_array);
echo $max;
}
1
u/HereBehindMyWall Feb 28 '20
Python 3:
1
u/AthosBlade Feb 29 '20
Haskell:
1
u/fo0man Mar 01 '20
Javascript something like:
Should get you there in O(n) space complexity would be O(2n) i believe.
1
u/WildRosso Mar 02 '20
My inelegant attempt using Java
Took my compiler about 3s, however.
1
u/Techser Mar 02 '20
Erlang:
maxScore(L) -> max([count(L, X)*X || X <- L]).count(L, Val) -> count(L, Val, 0, false).count([], _, Acc, false) -> Acc;count([], _, Acc, true) -> Acc + 1;count([H | T], Val, Acc, false) -> count(T, Val, Acc, H == Val);count([H | T], Val, Acc, true) -> count(T, Val, Acc + 1, H== Val).1
u/purpletquertz Mar 06 '20
Here is my python version:
1
u/OptionX Mar 07 '20
Java with lambdas for fun
I feel it could be faster. Not sure if its the lambda usage or I did something wrong. Probably the latter.
1
u/Sarius- Mar 11 '20 edited Mar 12 '20
Python 3.6
1
u/better-contract Mar 12 '20
Code is in python. Would appreciate feedback! Thanks.
1
u/bruce3434 Mar 13 '20
Nim
Runs in 0.04 seconds in my machine for the big input.
1
u/[deleted] Mar 19 '20
I changed the output a little so you know what number is the max as well. Perhaps adding a fueature for the max count as well as the max sum so you know which set is the best.
1
u/Dfree35 Mar 23 '20
Posted in the wrong thread originally lol
Python 3.6
Tried to keep it simple
1
u/AntillaOnAsiaa Mar 25 '20
Python:
1
u/gpalyan Mar 27 '20 edited Mar 27 '20
1
u/ImproperGesture Mar 30 '20 edited Mar 30 '20
Haskell with Data.Map.Strict (pretending you don't have group, which makes it trivial)
import Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapyahtzee_upper :: [Int] -> Intyahtzee_upper xs = foldr max 0 [ x * y | (x, y) <- counts xs ]counts :: [Int] -> [(Int, Int)]counts xs = Map.toList $ fillCounts xs (Map.fromList [(x, 0) | x <- xs])fillCounts :: [Int] -> Map.Map Int Int -> Map.Map Int IntfillCounts [] merp = merpfillCounts (x:xs) merp = fillCounts xs $ Map.adjust ((+) 1) x merp1
u/broem86 Apr 11 '20 edited Apr 11 '20
I've been learning Elixir and have found it to be really awesome. Here's my take which handles the optional bonus handily.
There may be more elegant solutions but this one makes sense to me.
Optional Answer (hehe): 31415926535
Edit: takes roughly .18 sec on 100k input fwiw
1
u/sunnyabd Apr 11 '20
Fun complexity exercise. Would love some tips and critiques to improve this.
1
u/caninbc Apr 26 '20 edited Apr 26 '20
C++ , no bonus
#include <iostream>
using namespace std;
int main() {
}
Feedback welcome
1
u/wcypierre Apr 26 '20
C#
1
u/sadsoulthatslost Jan 13 '22
1
u/[deleted] Feb 18 '22
python
accidentally did optional as well
1
u/sgaltair Mar 08 '22
Powershell 7
I just like doing these. I script in Powershell for work. Feedback welcome! About 2.18 seconds on the challenge set. Not the fastest language, apparently. Or maybe it's the method.
1
u/[deleted] Jun 22 '22 edited Jun 22 '22
Rust
Measure-Command(Powershell) says the average time with the challenge input is just over 17 ms on a 7700k.1
u/Zonetecde Aug 01 '22
c#
private static int yahtzeeUppernew (List<int> v){return v.GroupBy(i => i).ToList().ConvertAll(x => x.Key * x.Count()).Max();}11ms Execution time
0
u/[deleted] Jan 12 '20
[deleted] — view deleted comment
0
u/[deleted] Nov 11 '19
[deleted] — view deleted comment
0
u/[deleted] Nov 14 '19
[deleted] — view deleted comment
0
u/[deleted] Nov 15 '19
[deleted] — view deleted comment
0
u/[deleted] Dec 20 '19
[deleted] — view deleted comment