<p>I am learning go and was curious on how to use go maps to solve the conventional fizzbuzz problem, i.e. print number from say, 1-100 and multiples of 3 & 5 get printed fizz and buzz respectively. I looked over a bunch of solutions in different languages but somehow can't produce the same results in go. Thanks in advance.</p>
<hr/>**评论:**<br/><br/>ChristophBerger: <pre><p><a href="https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition" rel="nofollow">This</a> might provide some inspiration.</p></pre>djherbis: <pre><p>Couple things:</p>
<ul>
<li>Use the playground to share what you've tried <a href="https://play.golang.org/" rel="nofollow">https://play.golang.org/</a></li>
<li>Why are you using maps for fizzbuzz? </li>
<li>Map iteration is randomized in Go to prevent people from relying on map iteration order. Relying on it would probably yield strange results and may be what you are running into.</li>
</ul></pre>asa6471: <pre><p><a href="https://play.golang.org/p/DYwOcoAQbs" rel="nofollow">code</a>
I saw fizzbuzz implemented using maps in Java. I got curious about go lang as well. Yes, access is randomized. </p></pre>dchapes: <pre><ol>
<li><p>Use the "Format" button before sharing play ground code (and use <code>gofmt</code> on your own code).</p></li>
<li><p>You are wastefully creating a new map on each function call.</p></li>
<li><p>You are not terminating the function after finding a multiple and printing the word.</p></li>
<li><p>Due to un-ordered map this approach will not work. A slice such as <code>[]struct{int, string}</code> could be made to work but see 5.</p></li>
<li><p>Maps are not the appropriate tool for this problem. E.g. see <a href="http://rosettacode.org/wiki/FizzBuzz#Go" rel="nofollow">a RosettaCode solution</a>.</p></li>
</ol>
<p>[Also, <a href="https://play.golang.org/p/oUUDRH7wqG" rel="nofollow">Fix for 1−3</a>.]</p></pre>emilepels: <pre><p><a href="https://play.golang.org/p/UkrPhI3t-P" rel="nofollow">https://play.golang.org/p/UkrPhI3t-P</a></p>
<p>Edit: replaced <code>=</code> with <code>+=</code> at line 10 for consistency</p></pre>driusan: <pre><p>I'm not sure what you mean by "using maps". fizzbuzz is a looping and modular arithmetic problem. Ranging through maps is defined as random order in Go, so it wouldn't be appropriate for fizzbuzz.</p></pre>sin2pifx: <pre><p>I can imagine some sub-optimal solution like map[int]string, then adding "fizz" to all multiples of 3 and then "buzz" to all multiples of 5, and then printing them in order. But it's not something I'd rate high.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传