[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
Programming Challenge
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 192
Thread images: 11
File: palindrome.jpg (70 KB, 469x740) Image search: [Google]
palindrome.jpg
70 KB, 469x740
Okay /g/,

Here's your programming challenge for the day. Write a program that prints out all of the occurrences over the next 200 years in which the binary form of the year is a palindrome.

Pic related, my solution in Java.

Use any language. The shorter the solution, the better.
>>
>>52067885
class Palindrome {

public static void main(String[] args) {

String binary = "";
String output = "";
for (int i = 2015 ; i <= 2215; i++ ) {
binary = Integer.toBinaryString(i);
if (isPalindrome(binary))
output = i + " ";
}
System.out.println(output);

}

public static boolean isPalindrome(String binary) {

StringBuffer rev = new StringBuffer(binary).reverse();

String strRev = rev.toString();

return (binary.equalsIgnoreCase(strRev));
}
}
>>
Is it cheating to use a built in tibinary function? Isnt that the only involved part of this challenge? Top kek
>>
>>52067983
I don't suppose it's cheating. Feel free to write your own though.
>>
Took like 3 minutes, way too long actually, but this should be the shortest code:
<?php
$y=2015;
$z=$y+200;
for ($i=$y;$i<=$z;$i++){
$b=decbin($i);$r=strrev($b);
if($b==$r){echo $i.' is a Palindrome: '.$b."\n";}
}
?>
>>
>>52068031
Nice, I forgot that PHP had a decimal to binary function.
>>
static void Main()
{
Enumerable.Range(2015, 200)
.Select(y => Convert.ToString(y, 2))
.Where(b => b == new string(b.Reverse().ToArray()))
.Dump();
}
>>
>>52068031

Since "shorter is better", I improved this solution

<?php
for ( $i = 2015; $i<=2215; $i++)
if (decbin($i) == strreb(decbin($i)))
echo $i.' is a Palindrome: '.decbin($i)."\n";
>>
>>52068391
I made a typo. it is "strrev", "not "strreb".
>>
>>52067953

>The day java fukked up
public static boolean isPalindrome(String binary) {
StringBuffer rev = new StringBuffer(binary).reverse();

String strRev = rev.toString();

return (binary.equalsIgnoreCase(strRev));
}


C#
public static bool isPalindrome(string binary) {
return binary.SequenceEqual(binary.Reverse());
}
>>
File: 1371843816633.gif (1 MB, 320x240) Image search: [Google]
1371843816633.gif
1 MB, 320x240
>>52068303
>>
>>52068768
C# is doing the java part behind the scenes
>>
>programming "challenge"
>>
2min bash oneliner:
for i in {2015..2215};do b=`echo "obase=2;$i"|bc`; if [ $b -eq `echo $b|rev` ]; then echo "$i is palindrome $b"; fi; done
>>
>>52069246
nice
>>
1st year CS student and have no idea how to do this. Is it okay?
>>
>>52069292
yes. it's alright
>>
>>52069292
What is the part that you do not know how to do? Convert to binary? Loop? Compare?
>>
File: palindrome.jpg (78 KB, 445x841) Image search: [Google]
palindrome.jpg
78 KB, 445x841
Redone with a binary function I wrote.
>>
>>52069312
>>52069313
I wasn't really focused but after reading carefully I understood the problem.

My problem was I didn't know how to convert to binary so I had to google and found a 'hacked out' solution but it works in this context

Here's the code in Python which was the language we learned this semester

for i in range(2015, 2216):
binary = bin(i)[2::]
reverse_binary = binary[::-1]
if binary == reverse_binary:
print('Palindrome ')
else:
print(i)
>>
File: p.jpg (165 KB, 778x658) Image search: [Google]
p.jpg
165 KB, 778x658
#include <iostream>

int pwrTwo (int b)
{
int result = 1;
for (int counter = 0; counter < b; counter++) result *= 2;
return result;
}

bool convToBinaryAndReturnTrueIfPalindrome (int input)
{
int numberOfDigits = 0;
for (;;numberOfDigits++)
if (pwrTwo(numberOfDigits)-1 >= input) break;
char result[numberOfDigits];

while (input != 0)
for (int counter = 0;; counter++)
if (pwrTwo(counter) > input)
{
counter--;
input -= pwrTwo(counter);
result[counter] = '1';
break;
}

for (int counter = numberOfDigits-1; counter > -1; counter--)
if (result[counter] != '1')
result[counter] = '0';

for (int counter = 0; counter < numberOfDigits; counter++)
if (result[counter] != result[numberOfDigits-counter-1]) return 0;

return 1;
}

int main ()
{
for (int counter = 2015; counter < 2015+200; counter++)
if(convToBinaryAndReturnTrueIfPalindrome(counter)) std::cout << counter << "\n";

return 0;
}
>>
>>52069419
I imagined so far. I have made IT career all the way, and while it is useful, there is one truth that you have to face:

Your ability to program is going to depend mostly on you skill to divide a problem into smaller problems, and encounter the solution to those individual problems. Many times it will take you to know features of the language that you did not know.To which Google is a great help.

Those are sort of things that can´t be taught in the university, even though they can be trained there.

Good luck, bro
>>
>>52069498
>features of the language that you did not know
This is why I'm not liking Python too much, it has too many features and it kinda gets annoying despite knowing that they are there to give us an easier time.

We had this mini-exam earlier in the semester where we had to reverse a string and reverse the capitalization and once I done it the teacher just goes "you could solve that one in one line because Python has a method for it"
>>
Couldn't resist a one-liner. Why the fuck Python doesn't a have a built-in method for any base conversion is beyond me.

print('\n'.join([str(i) for i in range(2015, 2216) if bin(i)[2:] == bin(i)[2:][::-1]]))
>>
>>52067885
do your own homework
>>
>>52069615
I mean, he just did.
>>
>>52069550
Another thing that I must warn you is that you will encounter examinations that will test your knoledge of a language, and that those MIGHT UNFAIR.

But that is something you are gonna have to get comfortable with on university. Sorry dude.

Another thing that you are gonna have to get comfortable is that you are gonna have with languages and frameworks that are larger than you need to/can learn. If you think that changing languages is the solution, im afraid I have to tell you, you are wrong. every language will have this feature. You might be more comfortable with one language´s way of doing things than anothers, but in every case, you will have way many more things inside that language that you need.

Do not give up. In many way, learning to use a language is about learning to abstract yourself, and think in simple terms.

Im cheering up for you, bro ;)
>>
>>52069476
#include <algorithm>
#include <iostream>

std::string dec2bin(int);

bool is_palindrome(std::string);

int main(int argc, char *argv[])
{
for (int i = 2015; i <= 2215; ++i) {
if (is_palindrome(dec2bin(i)))
std::cout << i << ": " << dec2bin(i) << std::endl;
}
}

std::string dec2bin(int n)
{
std::string ret;

while (n != 0) {
ret = (n % 2 == 0 ? "0" : "1") + ret;
n /= 2;
}
return ret;
}

bool is_palindrome(std::string num)
{
return equal(num.begin(), num.end(), num.rbegin());
}
>>
>>52067885
>didn't read the whole challenge, only the palindrome part
>made a c code anyway

whatever, posting it anyway
main(c){for(c=2015;c<2215;c++)c%10==c/1000&&c/10%10==c/100%10&&printf("%d",c);}
>>
>>52069646
Thanks for cheering for a random anon (:

I kinda fucked up in my 3rd mini-exam because we had to work with reading and writing to a file and I didn't do any exercises or reading so I didn't know the syntax. It was really frustrating because the implementation was easy, just was missing the syntax. It was a lesson I guess...

>Do not give up. In many way, learning to use a language is about learning to abstract yourself, and think in simple terms.
I'm slowly trying to do this, both in programming and math classes, it gets really obvious after I see a solution though, the challenging part is seeing it before..
>>
Elixir:
Enum.filter(2000..2200, fn year ->
bin = Integer.to_string(year, 2)
bin == String.reverse bin
end)
>>
>>52069684
It looks to me like you treated it as a base 10 number system. Is that the case?
>>
>>52069806
Yes.
>>
>>52069854
That's what I've used in the past to separate digits from each other. Modulus 10, then divide by 10 until you've reached 0.
>>
APL

((⌽¨b)≡¨b←(∨\¨0≠¨x)⎕repl¨x←(⊂12⍴2)⊤¨y)/y←2015+⍳200
>>
Common Lisp

(defun palindrome (arg)
(or (member (length arg) '(0 1))
(and (equal (car arg) (car (last arg)))
(palindrome (butlast (cdr arg))))))

(defun to-binary (num)
(coerce (write-to-string num :base 2) 'list))

(remove-if (lambda (n)
(not (palindrome (to-binary n))))
(loop for i from 2015 to 2215 collect i))


>>
>>52069788
No problem, anon. I had the same issue where once I saw the solution, I felt like an idiot for not coming up with it by myself.

You are not alone. Good luck, bro
>>
Python
for x in xrange(2015, 2216):
if bin(x)[2:8] == bin(x)[14:7:-1]:
print x
>>
javascript
for(y=2015;y<2215;y++) if ((y >>> 0).toString(2)==(y >>> 0).toString(2).split("").reverse().join(""))console.log(y);
>>
>>52069047
No shit, its like saying C# is doing what ASM does behind the scenes - There are not many ways of for-looping over a string

But hey, its actually different

SequenceEqual ~

bool aMove = false, bMove = false;
while((aMove = binaryEnumerator.MoveNext()) &&(bMove = binaryReverseEnumerator.MoveNext()))
{
var a = binaryEnumerator.Current;
var b = binaryReverseEnumerator.Current;

if(!a.Equals(b)) return false;
}

return !aMove && !bMove;
>>
>>52070221
You should check your code, this doesn't actually work properly.
>>
>>52070262
Obviously odd lengths exist, and there's really no reason to do it that way either.
for x in xrange(2015, 2216):
if bin(x)[2:] == bin(x)[2:][::-1]:
print x
>>
>>52069679
Yeah, that's... a fuckload better than my attempt.
>>
>>52070225
(y >>> 0)
isn't really needed for positive numbers, and I assigned the
.toString(2)
to avoid doing it twice, but other than that I did it pretty much the same way.
for (var i=2015,r;i<2215;i++){ r=i.toString(2); if (r == r.split('').reverse().join('')) console.log(i) }
>>
>>52069684
C-solution, write your own binary functions edition.
#define D return r;
c(n,i,r){for(i=0;i<32;i++)!!(n&(1<<i))&&(r=i);D}
b(n,i,r,s){s=c(n);for(i=r=0;i<=s;i++)r|=(!!(n&(1<<i)))<<(s-i);D}
main(c){for(c=2015;c<2215;c++)c==b(c)&&printf("%d\n",c);}
>>
Just started learning Go. Reverse from stack overflow.
package main

import (
"fmt"
)

func main() {
for i := 2015;i < 2215;i++ {
s := fmt.Sprintf("%b",i);
if s == reverse(s) {
fmt.Printf("%v\n",i);
}
}
}

func reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
>>
year, i = [2015, 1]
while i <= 200:
year += 1
y = str(bin(year))[2:]
if y == y[::-1]:
print(year)
i += 1
>>
>>52069615
um
>>
I'm pretty sure this is right
#include <stdio.h>

#define START_YEAR 5
#define NUM_YEARS 200

int main(void)
{
unsigned year;

for (year = START_YEAR; year <= START_YEAR + NUM_YEARS; year++) {
int topbit, pos, ispalindrome = 1;

for (topbit = 8 * sizeof year - 1; topbit > 0; topbit--) {
if ((1 << topbit) & year) {
break;
}
}

for (pos = 0; pos < (topbit / 2 + 1); pos++) {
int leftbit, rightbit;

leftbit = (1 << pos) & year;
rightbit = (1 << (topbit - pos)) & year;

if ((leftbit && !rightbit) || (!leftbit && rightbit)) {
ispalindrome = 0;
break;
}
}

if (ispalindrome) {
printf("%d\n", year);
}
}

return 0;
}


Do you have the correct output which this should return?

I got
2015
2047
2049
2145
2193
>>
>>52069498
This is my biggest problem when trying to complete a programming challenge of exercise. I find it hard to think how to program it and I have to break the problem into chunks and figure each one out. I think thinking how to program is much harder than just learning there language. That's also how I learn songs on guitar. I break it into sections.
>>
>>52067885
>if ( foo() ) { return true; } else { return false; }
>>
>>52071575
Should be
#define START_YEAR 2015
. I left that in when I was messing with it.
>>
function isPalindrome( str ) {
return str.endsWith( [ ...str.substr( 0, str.length / 2 ) ].reverse().join( '' ) );
}

for( var year = 2015; year < 2215; year++ ) {
if ( isPalindrome( year.toString( 2 ) ) ) {
console.log( year );
}
}
>>
haskell

range = [2015..2215]

toBin n
| n > 0 = (n `mod` 2) : toBin (n `div` 2)
| otherwise = []

isPalindrome n =
(toBin n) == reverse (toBin n)

main :: IO ()
main = do
mapM_ print $ filter isPalindrome range
>>
>>52071575
yes your output is correct anon.
>>
Ruby
```p(2015..2216).select{|n|(b='%b'%n)==b.reverse}```
>>
do things like 1010 count as palindrome since it can be written as 01010?
>>
>>52072969
no leading 0
>>
>>52072969
Only if the 0 is a sign byte. If the 0 is part of the numerical value, then you're really multiplying the entire value.
>>
I did it in C, I don't know if I did it well because it's kind of late and I don't program much outside of personal things or school projects once in a while so I don't know if my code is a mess or not but the output is correct.

#include <stdio.h>

int *binaryyear(int year);
int palindrome(int *binary, int year);

int main(){
int year, i, palyear;
int *binary;

for(year = 2015; year <=2215; year++){
binary = binaryyear(year);
palyear = palindrome(binary,year);
if(palyear != 0){
printf("%d\n", year);
}
}
}

int *binaryyear(int year){
int i = 11, binaryint;
static int bin[12];
while(year != 0 && i >=0){
binaryint = year%2;
year = year/2;
bin[i] = binaryint;
i--;
}
return bin;
}

int palindrome(int *binary, int year){
int i, j = 11;
if(year < 2048){
i =1;
} else{
i = 0;
}
while(i <=11){
if(*(binary+i) != *(binary+j)){
return 0;
}
else{
i++;
j--;
}
}
return year;
}
>>
>>52068391
it is shorter than my original version but you compute decbin more than once. This should be changed because it eats up time and wastes resources. Anyways it is shorter.
Maybe another good solution would be the years as date("Y") and date("Y")+200 so that it is still correct in 2 weeks.

Nice.
>>
>>52073596
>hij zit op school
minderjarige
>>
>>52067885
>>52067953
>>52068768
>creating a copy of the string
0/10
>>
>>52073775
this, ew.
>>
>>52073911
>>52073773
:(
>>
>>52073911
het NEDERDRAAD
>>
>>52073935
het is*

bloedkanker
>>
>>52073935
Nee het hoort bij bordelijke cultuur vrijwel iedere algemeen heet een afkorting. Alleen de Scandi homo's willen geen /neder/, dus de vraag is ben jij een homo?
>>
File: autisme-nva-300x259.png (51 KB, 300x259) Image search: [Google]
autisme-nva-300x259.png
51 KB, 300x259
>>52073953
>muh bordcultuur
>>
>>52073996
Homo dus, duidelijk.
>>
>>52073953
>Een afkorting schrijven we met een of meer punten. We gebruiken een hoofdletter als die ook in het afgekorte woord voorkomt.

http://woordenlijst.org/leidraad/17/3
>>
>>52074012
neem je pillen in of ik neuk je in je kont
>>
>>52074012
VIEZE CIS PLEBEJER
>>
>>52067885
for (var i = 2015;i < 2215;i++)
{
if (String(i) == String(i).split('').reverse().join(''))
{ console.log(i); }
}
>>
>>52074493
Missed the whole binary part
for (var i=2015;i<2215;i++)
if (String(i.toString(2)) == String(i.toString(2)).split('').reverse().join(''))
console.log(i);
>>
#include <stdio.h>
#include <time.h>
long ispal (int n, int base)
{
int m = 0, o = n;
long p = 0;
if (! (n % base)) return 0;
do (m = (m * base) + o % base) & (p = (p * 10) + o % base);
while ((o /= base));
return (m == n) ? p : 0;
}
int main ()
{
long res;
time_t t = time (NULL);
int y = (localtime (&t))->tm_year + 1900;
for (int i = 0; i < 200; i++)
if ((res = ispal (y + i, 2))) printf ("%llu\n", res);
return 0;
}
>>
hello friends
youre homework is done, it will be 25$
greetings from india
static void Main()
{
DateCollectionFactory a;
a = new YearCollectionFactory();
var c = ((YearCollectionFactory)a).GenerateYears();
foreach (var b in c)
if (b.Year.IntegerToBinary().ArrayToString().IsPalindrome())
Console.WriteLine("year " + b.Year + " is palindrome!");
}

public abstract class DateCollectionFactory
{
public abstract IEnumerable<DateTime> GenerateYears();
}
public class YearCollectionFactory : DateCollectionFactory
{
public override IEnumerable<DateTime> GenerateYears()
{
for (int i = 0; i < 200; i++)
yield return DateTime.Now.AddYears(i);
}
}

public static class MiscelennausasExtendors
{
public static bool[] IntegerToBinary(this int input)
{
string s = Convert.ToString(input, 2);
char[] d = s.ToCharArray();
bool[] f = new bool[d.Length];
for (int i = 0; i < d.Length; i++)
{
if (d[i] == "1".ToCharArray()[0])
f[i] = true;
else if (d[i] == "0".ToCharArray()[0])
f[i] = false;
else
throw new Exception();
}
return f;
}

public static string ArrayToString(this bool[] input)
{
StringBuilder g = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (input[i] == true)
g.Append("1");
else if (input[i] == false)
g.Append("0");
else
throw new Exception();
}
return g.ToString();
}

public static bool IsPalindrome(this string input)
{
if (string.IsNullOrWhiteSpace(input))
{
throw new ArgumentNullException(nameof(input));
}

char[] h;
h = input.ToCharArray().Reverse().ToArray();
char[] j;
j = input.ToCharArray();
for (int i = 0; i < j.Length; i++)
{
if (j[i] != h[i])
return false;
}
return true;
}
}
>>
>>52067953
>using StringBuffer synchronously
>>
>>52067885
0, only 2015 is a binary palindrome. No programming required because I'm not retarded.
>>
>>52067885
Before looking at your code, I assumed every "occurence over the next 200 years" means literally every second over the next 200 years.
so i thought there's a few steps:
>somehow encode December 27th 2015 into binary
only challenging part btw, no idea what is even meant by this. maybe using unix time?
>use that as starting point, and add the binary value of 1 second to that
this would have to be done 200 * 365 * 24 * 60 * 60 = 6307200000 times, actually more if you include leap years
>to check for palindrome status, reverse the binary string, then check if it is equal to the original string
maybe there is a better way to do that, but that's how i would do it.
Too lazy to actually write the code because I can't be bothered to wait for a script to run 6 billion steps
>>
>>52069679
>>>52069476
> if (is_palindrome(dec2bin(i)))
if (is_palindrome(std::move(dec2bin(i))))
>>
File: derp.png (13 KB, 772x188) Image search: [Google]
derp.png
13 KB, 772x188
Eh, I've been picking python up as of late.

Them library functions though, should try it with something harder.
>>
>>52067885
<?php
function bp($y) {
$b = sprintf("%b", $y);
$l = ceil(strlen($b)/2);
for($i = 0; $i < $l; ) {
if($b[$i] != $b[$l-++$i]) {
return false;
}
}
return true;
}

date_default_timezone_set('America/New_York');
for($y = date('Y'), $i = 0; $i < 200; $y++, $i++)
bp($y) ? print "$y\n" : null;
>>
>>52074785
The year won't change based on the second. There are only 200 iterations.
>>
>>52074938
*
---      2015-12-26 21:05:46.708040200 -0500
+++ 2015-12-26 21:04:36.157004900 -0500
@@ -1,7 +1,7 @@
<?php
function bp($y) {
$b = sprintf("%b", $y);
- $l = ceil(strlen($b)/2);
+ $l = strlen($b);
for($i = 0; $i < $l; ) {
if($b[$i] != $b[$l-++$i]) {
return false;


should have just used decbin :x
>>
File: glitchgrill.png (1 MB, 1280x720) Image search: [Google]
glitchgrill.png
1 MB, 1280x720
>>52074565
>
String(i.toString(2))
>>
>>52074628
That is some pointless fucking convoluted code.

Object oriented is a scourge on humanity.
>>
for i in 2015..2215 { print i if i.to_s(2) == i.to_s(2).reverse }


Ruby one-liner
>>
>>52074992
He's satirizing Indian programmers, dumbass. Look at >>52075023 if you want to see actual object-oriented code
>>
>>52074743
how should i do it then?
>>
>>52075068
No shit, I've seen people pull that shit without it being a joke though.

I worded that wrong, idiots with object oriented code are a scourge on humanity.
>>
>>52074992
All you really need to take from that is the GenerateYears() function and the IsPalindrome() function, which incidentally is not efficient.
>>
>>52073775
All strings are implicitly final in Java anyway.
>>
>>52074760
Is this true?

cba to look at it.
>>
>>52075344
No, >>52071575 has the right outputs.
>>
>>52074760
No that's not true.
100010010001 is 2193
100001100001 is 2145
100000000001 is 2049
That's it though.
>>
>>52067885
Why the fuck are you faggets checking every single case when you can just generate them all?
2015 = _111 1101 1111 (lowest val with odd number of bits)
2047 = _111 1111 1111 (highest val with odd number of bits)

2049 = 1000 0000 0001 (lowest val with even number of bits)
2193 = 1000 1001 0001 (highest val with even number of bits)

Run loops on the split values and reverse and append yourself.

for (i = 0b111110; i <= 0b111111; i++) {
// Convert i to binary string, make a copy with last char trimmed, reverse and append
}

for (i = 100000; i <= 100010; i++) {
// Convert i to binary string, make a copy, reverse and append
}


Can't be fucked to manipulate the strings, haven't done shit this babby tier in years.

Oh and it should be fucking obvious from the half binary values used to generate that you'll only get 2 answers in the first for loop,
and another 3 in the second one.
>>
>>52075389
I forgot the "0b" literals in the second for loop, fucking hell.
>>
Why are you idiots comparing the entire String?

It's a palindrome, you only need to compare the first half to the second half.
boolean isPalindrome(String str)
{
for(int i = 0; i<str.length/2; i++)
{
if(str.charAt(i) == str.charAt(str.length-i))
{
return false;
}
}
return true;
}
>>
>>52075458
Because running 6 individual char comparisons is probably slower than one reverse and a string comparison.
>>
>>52075458
>2015 = 0X11111011111

>2100 = 0X100000110100
>>
>>52075458
Should be !=
>>
>>52075494
What the fuck?

How does this make sense to you?

>I'd rather have six nickels than one dollar because six is more than one
>>
>>52075537
>he doesn't know what optimization is
>he doesn't know about the big O

back 2 college kid
>>
>>52075023
nice.
ruby looks more appealing than python
>>
>>52075500
>next 200 years
>2015 is this year
The point anyway was that comparing the entire string is twice as retarded as comparing half the string.
>>
>>52075458
Going through the entire number allows you to convert it to printable binary simultaneously if your language does not allow this in one command.
>>52074617
>>
>>52075537
I didn't say it makes sense, but it's either Java or C# and neither would surprise me with such behaviour.

It's not like C where strings are a halfassed convenience and direct char access is as fast as grabbing the complete array.
>>
>>52075550
Well the language's whole mantra is developer happiness, so...
>>
binDigits :: Int -> [Int]
binDigits 0 = []
binDigits n = r:binDigits q
where (q,r) = n `divMod` 2

revBinDigits :: Int -> [Int]
revBinDigits n =
go [] n
where
go acc 0 = acc
go acc m = go (r:acc) q
where (q,r) = m `divMod` 2

isPaliNumber :: Int -> Bool
isPaliNumber n =
(binDigits n) == (revBinDigits n)

main :: IO ()
main = putStrLn $ foldr joinNum "" palis
where
range = [2015..2015 + 200]
palis = filter isPaliNumber range
joinNum x z = show x ++ " " ++ z
>>
so can someone write it in asm code? :3
>>
>>52075605
go ahead friend
>>
>>52075458
It's still O(n) ;-^)
>>
>>52075605
This would actually be a pretty simple thing to do in ASM.

But I made a rule not to write any ASM unless someone is paying me.
>>
Can someone program me a gf
>>
>>52075635
Regardless, comparing the whole String means that 50% of your comparisons are redundant.
>>
I was gonna do this in Lolcode, but after i was done writing the ToBinary function, the website stopped working, and when i tried the same code in a different interpreter, the code didnt compile anymore. If anyone cares about it, here is my attempt at the ToBinary thing.

HAI

HOW DUZ I TOBINARY YR INPUT
BTW THIS CONVERTS AN INTEGER NUMBER INTO A BINARY STRING

IZ BOTH SAEM INPUT AN 0?
FOUND YR "0"
KTHX

I HAZ ARRAY ITZ GOT NOTHING
I HAZ COUNTER ITZ 0

IM IN YR LOOP
IZ BOTH SAEM INPUT AN 0?
GTFO
KTHX
I HAZ OUTPUT ITZ MOD OF INPUT AN 2
ARRAY!COUNTER R GOT OUTPUT
COUNTER R SUM OF COUNTER AN 1
INPUT R QUOSHUNT OF INPUT AN 2
KTHX

FOUND YA ARRAY

IF U SAY SO

VISIBLE TOBINARY 8
BTW IT AT LEAST WORKED WHEN I TRIED 0 INSTEAD OF 8

KTHXBYE
>>
>>52075697
There are more failing cases than successful cases, and the failing cases will fail before the half way point ;-^)

But why argue about stupid string comparisons when the most efficient way would be to pull the bits out using & and >> and compare integers
>>
>>52075729
The most efficient way is to just work out the 5 solutions by hand.

The time it takes to get the string manipulation right and you've already halfway solved the set.
>>
>>52075757
The problem never asks for 2015, so your code should get the current date and calculate from there, making it still reusable in 20 years.
>>
>>52075721
here's a reply for the effort
>>
>>52075773
Half the string is 6 bits, so there must always be a change in the 7th to last bit to keep it symmetrical.
Pretty sure the next palindrome isn't for another 60 years or so.
>>
File: 1446071102017.jpg (21 KB, 248x189) Image search: [Google]
1446071102017.jpg
21 KB, 248x189
>tfw i get /g/ to do the extra credit portion of my homework
>>
>>52075773

Nevermind: >>52075845 make that (64+32=) 96 years.
>>
>using the built-in toBinary function
thats the challenge of the challenge, retarts, looping and comparing reversed strings can be done by my 3 year old step-son
>>
>>52075887
I did that >>52069333 in this post.
>>
>>52075916
i think this is the only thread where the assumptions of an op is reversed with the assumptions with the repliers
>>
POSIX shell
#!/bin/sh

for x in $(seq 2015 2215); do
y=$(printf "obase=2;%i\n" $x | bc)
[ $y -eq $(printf $y | rev) ] && printf "$y\n"
done
>>
>>52075938
What assumptions would an op make?
>>
>>52067885
#include <iostream>
int main() {
std::cout << "2015\n2047\n2049\n2145\n2193\n";
return 0;
}
>>
>>52075985
mean to say that what people would normally think of the op is reverse with what poeple would normally think of the repliers
>>
>>52070221
>>52070336
Thanks /g/ent, learned a little something from this.
>>
Python, done in like 5 mins or less, It could be done in one line with lambda but whatever.
def palindrome(x):
return x == x[::-1]

def to_binary(x,y=""):
if x == "1" or x == "0":
return x
return to_binary(str(int(x)/2)) + str(int(x)%2)

today = 2015
for year in range(today,today+201):
if palindrome(to_binary(str(i))):
print year
.
>>
>>52076053
As in the repliers know more than OP?
>>
>>52070221
>>52070336
Just saw yours after I posted
>>52076094
I know nothing.
>>
>>52076101
as in the repliers are faggots (for not writing their own toBinary) and op isn't
>>
>>52076053
In other words, everyone except OP is a faggot.

>>52069333
Considering that making Java code more efficient is like making dry ground coffee not taste so much like dirt,
that's probably about as short as that code can be without becoming stupidly long-lined and less clear.

Also, put braces around one line for/if statements, or at least leave a blank line afterwards. Your future self will thank you.

I normally have so many debug lines dotted around the place that even simple code blocks have at least 2 ops in them,
so maybe I just never have one line conditionals anymore and it just looks strange.
>>
echo '2145'
>>
>>52076094
It could be done in one line without a lambda.
>>
>>52076194
whoops, i had a bug
echo '2046, 2049, 2145'
>>
>>52076222
oh and 2193
>>
>>52076194
Wrong

>>52076222
Wrong again

>>52076239
Still wrong
>>
MoonScript on top of Lua 5.3.

band = (load "return function(a, b) return a & b end")!

palindrome = (n) ->
((a) -> a == string.reverse a) table.concat for i = 0, (math.floor math.log n, 2)
if (band n, 2 ^ i) == 0 then 0 else 1

for i = 2015, 2215
print i if palindrome i


I am semi-satisfied with this.

>>52069934
Very nice
>>
>>52067885
>challenge
all this thread, now I understand why sci makes fun of /g/
>>
>>52069595
There should be base conversion functions within the math module.
>>
>>52069679
>>52067885
Poorly formatted braces where there don't need to be
0/10, belongs in the trash

>>52068391
Nice

>>52069476
Tolerable language but well formatted

Good to see it's not all trash

>>52070074
>>52069934
Very nice

>>52074493
Nasty

>>52074628
Would you be interested in a position at Microsoft?
>>
J
years=.2015+i.200
>1{(((+./"1)|(#:years)-(|."_1)#:years))</.years


>>52069934
what do you use for the character set?
i was going to learn apl, but i didn't want to deal with it so i just started with j instead

>>52076254
what's he missing?
>>
>>52077153
These are the only ones:
100010010001 - 2193
100001100001 - 2145
100000000001 - 2049
>>
>>52077328
oh, because 2046 is
11111111110

not
011111111110
>>
>>52068303

For a second there I thought this was C++ and that I'd fallen way, way behind the curve.
>>
>>52077328
>>52077397
doesn't that mean that
11111011111-2015
11111111111-2047
are too?
>>
>>52077458
I suppose, I guess I wasn't thinking of odd-length palindromes.
>>
>>52077533
>>52077458
But in any case, per OP's specifications, 2015 is out of the range.
>next 200 years
starts at 2016.
>>
>>52067885

C/C++ (because I don't know if it passes strict C) off the top of my head, untested because I don't have a compiler on this partition:

#include <stdio.h>

const int BITS_PER_INT = sizeof(int) * 8;

void ToBinary(int num, char *buffer)
{
for (int i = 0; i < (sizeof(int) / 8); i++)
{
if (num & (1 << i))
buffer([BITS_PER_INT - i] = '1';
else
buffer([BITS_PER_INT - i] = '0';
}
buffer[BITS_PER_INT + 1] = '\0';
}

bool IsPalindrome(char *s)
{
char *s2 = s + strlen(s);
while (s2 > s)
{
if (*s++ != *s2++)
return false;
}
return true;
}

int main(void)
{
char buffer[BITS_PER_INT + 1] = "";

for (int i = 2015; i < (2015 + 200); i++)
{
ToBinary(i, buffer);
if (IsPalindrome(buffer))
printf("%s\n", buffer);
}

return 0;
}
>>
>>52077670

Nevermind, just realized that this totally won't work. :-D
>>
>>52077533
>>52077545
alright, got me some proper j here:
years=.2016+i.200
(-.>(<@(+./)@>)(<@(|"1)@>)((<@|.@>)(<@#:@>)years)(<@(-"1)&>)((<@#:@>)(<"0)years))#years
>>
>>52069934
>>52077153
I did not expect to see APL-family languages on /g/; what a pleasant surprise.

Either of you /g/entlemen have any learning materials for APL/J?
>>
>>52070858
You should probably use strconv.FormatInt with a base of 2, which would cut out some overhead from the format parsing.
>>
>>52067885

>poorly wording the question

I'm not doing it because you suck at explaining it op.

Occurrences of what retard? The years? Specify that you piece of shit.

Explain what a palindrome is too, I'm not going to google it you fucktard.
>>
import Numeric
import Data.Char

main = mapM_ print . filter (palindrome . toBinary) $ take 200 [2015..]
where toBinary n = showIntAtBase 2 intToDigit n ""
palindrome s = s == reverse s
>>
#include <ctime>
#include <iostream>
#include <string>
bool a=0;
int main(){
if(a){a=!a; std::srand(std::time(0));}
std::cout<<bool(std::rand()<RAND_MAX/2);
main();
}


>muh library of babel

Define "occurrences"
>>
>>52076392
>Tolerable language but well formatted
It's not even fucking indented properly.

What exactly does good formatting look like in your universe?
>>
>>52078929
>You'll have to give me the dictionary definition of everything but the 1000 most common words.
>Please don't use any big words when explaining since I am obviously retarded

Yeah no
>>
>>52074760
>>52075344
>>52076194
>>52076222
>>52076239
>>52077328
>>52077397

>(2016 - 0.01369863013)
>Can't into binary representation
>>>/v/
>>
def bin_palin(year):
b = bin(year)[2:]
return list(reversed(b)) == list(b)

for i in range(2015, 2015+200):
if bin_palin(i):
print(i)

30 seconds to write in Python.
>>
>>52075887
>>52081560

Since that guy was mad, I can buy the idea that tobin should be written yourself.
30 more seconds.
#returns reverse order, fine since we use this to check for palindromes
def mybin(n):
digits = []
while n > 0:
digits.append(n & 1)
n >>= 1
return digits

def bin_palin(year):
b = mybin(year)
return list(reversed(b)) == list(b)

for i in range(2015, 2015+200):
if bin_palin(i):
print(i)
>>
>>52069934
Congratulations, you played yourself.
>>
from datetime import date

for i in range(date.today().year, date.today().year + 200):
if bin(i)[2:] == bin(i)[:1:-1]: print i
>>
didnt check all solutions. my java one.

    public static boolean check(String compare) {

for (int i = 0; i < compare.length() / 2; i++) {
char temp = compare.charAt(i);
if(temp != compare.charAt(compare.length() - i - 1)) {
return false;
}
}
return true;
}

public static void main(String[] args) {

String compare = "";

for(int i = 2015; i <= 2215; i++) {
compare = String.valueOf(i);
if (check(compare))
System.out.println(compare);
}
}
>>
>>52068391
echo <?php
array_reduce(range(2015,2215),function($a,$b){return $a.((decbin($b)==strrev(decbin($b)))?"$b ":"");});


lulz
>>
>>52081812
>Write a program that prints out all of the occurrences over the next 200 years in which the binary form of the year is a palindrome

>binary form

i fucked up. imma change it.
>>
JS:
var calculatePalindromesOfYears = function() {
var currentYear = new Date().getFullYear();
var binaryYears = [];
var binaryYear;
var year;

for (year = currentYear; year < currentYear + 200; year++) {
binaryYear = (year >>> 0).toString(2);

if (binaryYear.split("").reverse().join("") == binaryYear) {
binaryYears.push({ year: year, binaryYear: binaryYear });
}
}

return binaryYears;
}

console.log(calculatePalindromesOfYears());


I created all of the variables at the top of the function so no one could get caught out by variable hoisting.
>>
>>52081812
>>52081914

fixed
public static boolean check(String compare) {

for (int i = 0; i < compare.length() / 2; i++) {
char temp = compare.charAt(i);
if(temp != compare.charAt(compare.length() - i - 1)) {
return false;
}
}
return true;
}

public static void main(String[] args) {

String compare = "";

for(int i = 2015; i <= 2215; i++) {
compare = Integer.toBinaryString(i);
if (check(compare))
System.out.println(i);
}
}
>>
Perl

foreach (2015..2215) {
$bin = sprintf("%b", $_);
print $_,"\n" if $bin == reverse $bin
}
>>
>Hardcoded start year
Your code becomes obsolete after less than a week.
>>
>>52067885
How is that color scheme called?
>>
>>52067885
all these niggers using strings...
/g/ confirmed for shit tier
>>
>>52081889
<?=array_reduce(range(2016,2216),function($c,$v){$b=decbin($v);return $c.(($b==strrev($b))?"$v ":"");});
>>
>>52082788
It's fizzbuzz, stop taking it so seriously.
>>
>>52082939
<?=array_reduce(range(2016,2216),function($c,$v){$b=decbin($v);return $b==strrev($b)?"$c$v ":$c;})
>>
>>52082547
It's Atom.
>>
>>52078523
i've been working through the primer on the j website:
jsoftware.com/help/primer
>>
>>52083785
wait shit
jsoftware.com/help/primer/contents.htm
>>
File: Screenshot_2015-12-27-11-04-50.png (32 KB, 480x800) Image search: [Google]
Screenshot_2015-12-27-11-04-50.png
32 KB, 480x800
import time
timestr = time.strftime("%Y")
yearint = int(timestr)
endyear = yearint + 200
for c in range(yearint, endyear+1):
binarystr = bin(c)[2:]
revbinarystr = binarystr[::-1]
if binarystr == revbinarystr:
print (c)



Gets the current year from your system so in a couple days the program will have a different output.
>>
Option Explicit

Function IntToBin(ByVal n)
Do
IntToBin = CStr(n Mod 2) & IntToBin
n = n \ 2
Loop While n > 0
End Function

Function BinPal(ByVal start_year, ByVal end_year)
Dim i, b
For i = start_year To end_year
b = IntToBin(i)
If StrReverse(b) = b Then
BinPal = BinPal & CStr(i) & " "
End If
Next
End Function

Dim y
y = CInt(Year(Now)) + 1
WScript.Echo BinPal(y, y + 200)

VBScript because no one else will.
>>
>>52074992
Am I the only one who gets the joke?
>>
>>52073775
>binary.Reverse()

>Implying its making a copy, its an enumerator of same object but in reverse for loop
>>
For a C++ solution, is there anything significantly shorter than this?

#include <iostream>

bool isPalindrone (std::string input)
{
for (int c = 0; c < input.length(); c++)
if (input[c] != input[input.length()-c-1]) return false;
return true;
}

std::string toBinary (int input)
{
std::string output;
while (input != 0)
{
input % 2 == 0 ? output = "0" + output : output = "1" + output;
input /= 2;
}
return output;
}

int main ()
{
for (int c = 2015; c < 2216; ++c)
if (isPalindrone(toBinary(c)))
std::cout << c << " " << toBinary(c) << "\n";
return 0;
}
>>
>>52087001
Fugg, should be
c < input.length()/2
>>
File: java_masterrace.png (8 KB, 946x151) Image search: [Google]
java_masterrace.png
8 KB, 946x151
>>52067885

Come at me, motherfuckers..
>>
File: java_once_more.png (7 KB, 1364x80) Image search: [Google]
java_once_more.png
7 KB, 1364x80
>>52088678

Made it a little bit shorter..

(It still runs without any includes)
>>
>>52067885
I did it in ansi C (le masterrace)
#include <stdio.h>
int Palindrome(unsigned int n){
int j, i;
for(i = 31; (((1 << i) & n)?0:1) && (i > 0); i--){};
for(j = 0; (j < i/2) && (((n & (1 << j))?1:0) == ((n & (1 << (i - j)))?1:0)); j++){};
return j > i / 2 - 1;
}
int main(void){
unsigned int i;
printf("kek :^)\n");
for(i = 2015; i < 2216; i++){
if(Palindrome(i))
printf("%4d is a binary palindrome :^)\n", i);
}
return 0;
}

the short version would be
#include <stdio.h>
int main(void){
int i, j, n;
for(n = 2015; n < 2216; n++){
for(i = 31; (((1 << i) & n)?0:1) && (i > 0); i--){};
for(j = 0; (j < i/2) && (((n & (1 << j))?1:0) == ((n & (1 << (i - j)))?1:0)); j++){};
if(j > i / 2 - 1)
printf("%4d is a binary palindrome :^)\n", n);
}
return 0;
}
Thread replies: 192
Thread images: 11

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.