# Question
Title: Write the longest program that prints the date of tomorrow
~~I would like to propose a new kind of challenge: Anti Code Golf! (as anti-golf, not anti-code). The idea is to write the longest program you can write to do something.~~

That would be Code Bowling, as pointed out by ProgramFOX.

# Rules

* No ridiculously unnecessary whitespace (e.g. 3 lines between each statement, etc. indentation is OK, just don't overuse).
* Score is awarded by number of bytes used **to work** * (in source code, input data or output data) memory usage doesn't count.
* Highest score wins. In the event of a tie, most upvoted wins. In the event of a voting tie a randomly chosen answer wins.
* You may not read from a external resource, such as a file or web service, except (when possible) the program's own source code and/or a file/service provided by the program itself.
* The program must run in a reasonable time (\< 5 minutes) except where otherwise specified.

.\* Comments do not count for length.

---

Now, onto the challenge itself:

> Write a program that prints the full date of tomorrow to stdout (or equivalent) in ASCII encoding. It may or not receive any arguments, but the current date must not be input directly by the user.

# Answer
> 9 votes
# C# - ~500Kb -

Don't you love nested if's? Used to work only for 2014 dates, but successfully refactored to work for any date :)

Cannot post code here, I just receive an error...

http://pastebin.com/azGr3JSz

(Will probably hang your browser, sorry)

# Answer
> 5 votes
# JavaScript, 2015 chars (all reasonably useful)

I believe this is in the spirit of the question. ;)

Based on one of my previous answers

```
// we all know that OOP == good
function TomorrowManager() {
    // constants == good too
    this.values = {
        ERROR: 1, // value on error
        UNINITIALIZED:  2, // value when not initialized yet
        OK: 0 // desired value
    }
    this.consts = {
        HOURS_IN_DAY: 24,
        MINUTES_IN_HOUR: 60,
        SECONDS_IN_MINUTE: 60,
        MILLISECONDS_IN_SECOND: 1000
    }
    this.value = this.values.UNINITIALIZED
}
TomorrowManager.prototype.setValue = function(num) {
    if (typeof num !== 'number') throw new Error('cannot set value to non-number')
    if (!this.value) this.value = this.values.ERROR // oh noes
    else this.value = num
}
// initialize the value
TomorrowManager.prototype.initialize = function() {
    this.setValue(this.values.OK) // set the value to ONE
    return true // return true for success
}
// get the value
TomorrowManager.prototype.getValue = function() {
    if (this.value == this.values.ERROR) { // if the value is ERROR
        throw new Error('value not initialized')
    } else return this.value // return the value
}
TomorrowManager.prototype.getTomorrow = function() {
    return new Date(new Date().getTime() + this.consts.HOURS_IN_DAY * this.consts.MINUTES_IN_HOUR * this.consts.SECONDS_IN_MINUTE * this.consts.MILLISECONDS_IN_SECOND)
}

function TomorrowManagerFactory() {}
TomorrowManagerFactory.prototype.getTomorrowManager = function() {
    return new TomorrowManager()
}

function getTomorrow() {
    var m = new TomorrowManagerFactory().getTomorrowManager() // make a TomorrowManager
    var success = m.initialize() // initialize the value
    if (success) {
        if (m.getValue() === m.values.OK) {
            return m.getTomorrow()
        } else {
            throw new Error('bad value')
        }
    }
    else {
        // there was an error in the initialization
        var retVal = m.values.ERROR // we will return an error
        delete m // maybe it's corrupted
        throw new Error('corrupted TomorrowManager')
        return retVal // return an error in case the throw didn't work
    }
}

alert(getTomorrow())

```

# Answer
> 5 votes
# Lua - 7159

```
-- Let's begin by implementing OOP
-- Lua does not have OOP but it has the tools to implement it

local class = {}

function class:inherit()
    local class = {}
    class.class = class
    class.__index = self
    class.ancestor = self
    return setmetatable(class, class)
end
function class:new(initializer)
    local object = initializer or {}
    object.__index = self
    setmetatable(object, object)
    if self.__init  then
        self.__init(object)
    end
    return object
end
function class:super(meth, ...)
    local ancestor = self.ancestor
    local class = self.class
    local __index = self.__index
    self.__index = class.ancestor
    self.class = class.ancestor
    self.ancestor = class.ancestor.ancestor
    return (function(...)
        self.ancestor = ancestor
        self.class = class
        self.__index = __index
        return ...
    end)(self[meth](self, ...))
end

-- Now let's create a few classes used for counting

local counter = class:inherit()
counter.value = 1
function counter:setValue(value)
    self.value = value
end
function counter:getValue()
    return self.value
end
function counter:increment()
    self:setValue(self:getValue() + 1)
end

local boundedCounter = counter:inherit()
counter.maxbound = 1
counter.minbound = 1
function boundedCounter:setMaxbound(value)
    self.maxbound = value
end
function boundedCounter:getMaxbound()
    return self.maxbound
end
function boundedCounter:setMinbound(value)
    self.minbound = value
end
function boundedCounter:getMinbound()
    return self.minbound
end
function boundedCounter:increment()
    self:super"increment"
    if self:getValue() > self:getMaxbound() then
        self:setValue(self:getMinbound())
    end
end

local signalingBoundedCounter = boundedCounter:inherit()
counter.signal = function() end
function signalingBoundedCounter:setSignal(value)
    self.signal = value
end
function signalingBoundedCounter:getSignal()
    return self.signal
end
function signalingBoundedCounter:setUservalue(value)
    self.uservalue = value
end
function signalingBoundedCounter:getUservalue()
    return self.uservalue
end
function signalingBoundedCounter:increment()
    self:super"increment"
    if self:getValue() == 0 then
        self:getSignal()(self:getUservalue())
    end
end

-- Other miscelaneous classes we will need

local formatStringBuilder = class:inherit()
formatStringBuilder.string = ""
function formatStringBuilder:appendString(string)
    self.string = self.string .. string:gsub("%%", "%%%%")
end
function formatStringBuilder:appendFormat(specifier, length, decimals)
    length = tonumber(length)
    decimals = tonumber(decimals)
    specifier = tostring(specifier)
    local format = "%"
    if length then
        if length < 0 then
            format = format .. "0" .. -length
        else
            format = format .. length
        end
    end
    if decimals then
        format = format .. "." .. decimals
    end
    format = format .. specifier
    self.string = self.string .. format
end

function formatStringBuilder:getString()
    return self.string
end
function formatStringBuilder:format(...)
    return self.string:format(...)
end

local applicationFunction = class:inherit()
function applicationFunction:__call()
    return self.callback(unpack(self.arguments))
end
function applicationFunction:__init()
    self.__call = self.__call -- DO NOT REMOVE OR IT WILL NOT WORK
end

local case = class:inherit()
function case:__init()
    self.cases = {}
    self.handlers = {}
end
function case:addCase(case, handler)
    self.cases[#self.cases + 1] = case
    self.handlers[#self.handlers + 1] = handler
end
function case:execute(value)
    for iterator, case in ipairs(self.cases) do
        if case == value then
            self.handlers[case]()
            break
        end
    end
end

-- The main code:

local yearsFormat = formatStringBuilder:new()
yearsFormat:appendFormat"Y"
local monthsFormat = formatStringBuilder:new()
monthsFormat:appendFormat"m"
local daysFormat = formatStringBuilder:new()
daysFormat:appendFormat"d"
local todaysYear = tonumber(os.date(yearsFormat:getString()))
local todaysMonth = tonumber(os.date(monthsFormat:getString()))
local todaysDay = tonumber(os.date(daysFormat:getString()))

-- Let's store the year as a four-digit number

local thousandsOfYearsCounter = counter:new()
thousandsOfYearsCounter:setValue(0)
local hundredsOfYearsCounter = signalingBoundedCounter:new()
hundredsOfYearsCounter:setMaxbound(9)
hundredsOfYearsCounter:setMinbound(0)
hundredsOfYearsCounter:setValue(0)
hundredsOfYearsCounter:setSignal(thousandsOfYearsCounter.increment)
hundredsOfYearsCounter:setUservalue(thousandsOfYearsCounter)
local tensOfYearsCounter = signalingBoundedCounter:new()
tensOfYearsCounter:setMaxbound(9)
tensOfYearsCounter:setMinbound(0)
tensOfYearsCounter:setValue(0)
tensOfYearsCounter:setSignal(hundredsOfYearsCounter.increment)
tensOfYearsCounter:setUservalue(hundredsOfYearsCounter)
local yearsCounter = signalingBoundedCounter:new()
yearsCounter:setMaxbound(9)
yearsCounter:setMinbound(0)
yearsCounter:setValue(0)
yearsCounter:setSignal(tensOfYearsCounter.increment)
yearsCounter:setUservalue(tensOfYearsCounter)

for interator = 1, todaysYear do
    yearsCounter:increment()
end

local monthsCounter = signalingBoundedCounter:new()
monthsCounter:setMaxbound(12)
monthsCounter:setMinbound(1)
monthsCounter:setValue(0)
monthsCounter:setSignal(yearsCounter.increment)
monthsCounter:setUservalue(yearsCounter)

for interator = 1, todaysMonth do
    monthsCounter:increment()
end

local daysCounter = signalingBoundedCounter:new()

-- Depending on the months, there's different amount of days

local monthDaysCase = case:new()
monthDaysCase:addCase(1, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(2, function()
    if todaysYear % 4 == 0 then
        if todaysYear % 100 == 0 then
            if todaysYear % 400 == 0 then
                daysCounter:setMaxbound(29)
            else
                daysCounter:setMaxbound(28)
            end
        else
            daysCounter:setMaxbound(29)
        end
    else
        daysCounter:setMaxbound(28)
    end
end)
monthDaysCase:addCase(3, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(4, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 30}})
monthDaysCase:addCase(5, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(6, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 30}})
monthDaysCase:addCase(7, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(8, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(9, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 30}})
monthDaysCase:addCase(10, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(11, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 30}})
monthDaysCase:addCase(12, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:execute(todaysMonth)

daysCounter:setMinbound(1)
daysCounter:setValue(0)
daysCounter:setSignal(monthsCounter.increment)
daysCounter:setUservalue(monthsCounter)

for interator = 1, todaysDay do
    daysCounter:increment()
end

daysCounter:increment()

local tomorrowsYear = thousandsOfYearsCounter:getValue() * 1000 + hundredsOfYearsCounter:getValue() * 100 + tensOfYearsCounter:getValue() * 10 + yearsCounter:getValue()
local tomorrowsMonth = monthsCounter:getValue()
local tomorrowsDay = daysCounter:getValue()

local dateFormat = formatStringBuilder:new()
dateFormat:appendFormat"d"
dateFormat:appendString"/"
dateFormat:appendFormat("d", -2)
dateFormat:appendString"/"
dateFormat:appendFormat("d", -2)
local tomorrowsDateString = dateFormat:format(tomorrowsYear, tomorrowsMonth, tomorrowsDay)
print(tomorrowsDateString)

```

Scoring: `perl -pe 's/--.*\n//g;s/\s/ /mg;s/ */ /g;s/(\W) (\S)/$1$2/g;s/(\S) (\W)/$1$2/g;' < nextday.lua|wc -c` (basically remove all whitespace that can be removed)

Also do not remove the `DO NOT REMOVE` marked line, it really will not work

# Answer
> 2 votes
## C#: 33,053 characters

I had to post the code on Pastebin because it was too long to post here in an answer:
http://pastebin.com/SwwB30Jy

How it works: the byte array actually contains the following code:

```
using System;namespace GetDateOfTomorrow{public static class Tomorrow{public static string GetDateOfTomorrow(){ return DateTime.Today.AddDays(1).ToShortDateString();}}}

```

Then, you compile that code to a new assembly and execute the `GetDateOfTomorrow()` method.

# Answer
> 1 votes
# Mathematica 958

The following returns tomorrow's date, including the day of week.

```
date = "Date";
command1 = ToExpression[date <> ToString[Head["Calendar"]]]
ClearAll[a, b, c, d]
TreeForm[a + b^2 + c^3 + d]
command2 = ToExpression[date <> ToString[Part[%, 0]]]
months = {"January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"}
command3 = ToExpression[date <> ToString[Head[months]]]
daysOfTheWeek = {"Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"}
days = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
command4 =
 ToExpression[
  StringJoin[
   Take[Characters[
      Part[daysOfTheWeek[[RandomInteger[{1, 7}]]]]], -3] /. {char1_,
      char2_, char3_} :>
     StringJoin["", {ToUpperCase[char1], char2, char3}],
   ToString[Head[days]]]]
AstrologicalSigns = {"Aries", "Taurus", "Gemini", "Cancer", "Leo",
  "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius",
   "Pisces"}

```

## Testing

```
command1[command2[command3[TimeZone -> $TimeZone],
  Fibonacci[7] - Length[AstrologicalSigns]], {"DayName", ", ",
  "MonthName", " ", "Day", ", ", "Year"}]

```

> "Wednesday, January 15, 2014"

# Answer
> 1 votes
# JAVA (~~2910~~ 4406 characters)

```
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Date;

public class Tomorrow {

    private static class DayOfMonth {

        private int value;

        public DayOfMonth(int value) {
            this.value = value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        @Override
        public String toString() {
            return Integer.toString(value);
        }

    }

    private static class MonthOfYear {

        private int value;

        public MonthOfYear(int value) {
            this.value = value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        @Override
        public String toString() {
            return new DateFormatSymbols().getMonths()[this.getValue()];
        }

    }

    private static class YearOfEverything {

        private int value;

        public YearOfEverything(int value) {
            this.value = value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        @Override
        public String toString() {
            return new StringBuilder("").append(Math.abs(value)).append(' ').append((value < 0) ? "BCE" : (value == 0) ? "" : "CE").toString();
        }

    }

    private static class DateManager {

        private DayOfMonth day;
        private MonthOfYear month;
        private YearOfEverything year;

        public DateManager() {
            this.day = null;
            this.month = null;
            this.year = null;
        }

        public void setDayOfMonth(int day) {
            this.day = new DayOfMonth(day);
        }

        public void setMonthOfYear(int month) {
            this.month = new MonthOfYear(month);
        }

        public void setYearOfEverything(int year) {
            this.year = new YearOfEverything(year);
        }

        public DayOfMonth getDayOfMonth() {
            return day;
        }

        public MonthOfYear getMonthOfYear() {
            return month;
        }

        public YearOfEverything getYearOfEverything() {
            return year;
        }

        @Override
        public String toString() {
            return new StringBuilder("").append(this.getMonthOfYear().toString()).append(' ').append(this.getDayOfMonth().toString()).append(", ").
                       append(this.getYearOfEverything().toString()).toString();
        }

    }

    public static final int MONTHS_PER_YEAR = 12;

    public static boolean isLeapYear(YearOfEverything year) {
        int yearNum = year.getValue();
        if ((yearNum % 4 == 0) && (yearNum % 100 != 0))
            return true;
        else if (yearNum % 400 == 0)
            return true;
        else
            return false;
    }

    public static int getDaysInMonth(MonthOfYear month, YearOfEverything year) {
        if (month.getValue() == 1) {
            if (isLeapYear(year))
                return 29;
            else
                return 28;
        } else if ((month.getValue() == 3) || (month.getValue() == 5) || (month.getValue() == 8) || (month.getValue() == 10)) {
            return 30;
        } else {
            return 31;
        }
    }

    public static void main(String[] args) {

        DateManager manager = new DateManager();
        Calendar calendar = Calendar.getInstance();
        manager.setDayOfMonth(calendar.get(Calendar.DATE));
        manager.setMonthOfYear(calendar.get(Calendar.MONTH));
        manager.setYearOfEverything(calendar.get(Calendar.YEAR));

        manager.getDayOfMonth().setValue(manager.getDayOfMonth().getValue() + 1);
        if (manager.getDayOfMonth().getValue() > getDaysInMonth(manager.getMonthOfYear(), manager.getYearOfEverything())) {
            manager.setDayOfMonth(1);
            manager.getMonthOfYear().setValue(manager.getMonthOfYear().getValue() + 1);
            if (manager.getMonthOfYear().getValue() >= MONTHS_PER_YEAR) {
                manager.setMonthOfYear(1);
                manager.getYearOfEverything().setValue(manager.getYearOfEverything().getValue() + 1);
            }
        }

        System.out.println(manager.toString());

    }

}

```

# Answer
> -1 votes
# Hippopotomonstrosesquipedalian 2, ~66.6MB

Code (Your browser ***WILL*** hang)

Compiler

---
Tags: code-bowling
---


# Question
Title: Can this number be written in (3^x) - 1 format?
**Challenge:**

Create a program that accepts a positive integer and checks if it can be written in the form of (3^x)-1, where **X is another positive integer**.

If it can, output X

If it can't, output -1 or a falsy statement.

**Example inputs/outputs**

Input:

```
2

```

It can be written as (3^1) - 1, so we output x which is 1

Output:

```
1

```

Input:

```
26

```

26 can be written as (3^3) - 1, so we output x (3)

Output:

```
3

```

Input:

```
1024

```

1024 can't be written in the form of (3^x) - 1, so we output -1

Output:

```
-1

```

This is so least amount of bytes wins

---

Related OEIS: **A024023**

# Answer
> 24 votes
## Mathematica, ~~21~~ 16 bytes

```
-1&@@Log[3,#+1]&

```

Makes use of Mathematica's symbolic computation. If `#+1` is a power of three then `Log[3,#+1]` will compute an integer result which is an atomic value. Otherwise we'll get `Log[#+1]/Log[3]` as is. Since this is not an atomic value, it's an expression which is always of the form `head[val1,val2,...]`. In this case it's actually something like `Times[Power[Log[3], -1], Log[#+1]]`.

We distinguish between the two cases by applying another function to the result. What applying really does is that it replaces the `head` part of an expression. Since integer results are atomic, applying any function to them does nothing at all. In particular `f @@ atom == atom`.

However, in the other case, the head does get replaced. The function we're using is `-1&` which is a simple function that ignores its arguments and returns `-1`. So we get something `-1&[Power[Log[3], -1], Log[#+1]]` in non-integer cases, which evaluates directly to `-1`. Special casing via magic.

# Answer
> 13 votes
## Haskell, 35 bytes

```
f x=last(-1:[i|i<-[1..x],3^i-1==x])

```

Usage example: `f 26` -\> `3`.

# Answer
> 13 votes
# Python, ~~46~~ 44 bytes

```
lambda x:max(n*(3**n-1==x)for n in range(x))

```

Try it online!

In this case, `0` would be the falsy value. Thanks to @mbomb007 for pointing out my incorrect output as well as a 2 bytes no `[]` savings.

# Answer
> 12 votes
# Jelly, 5 bytes

```
R3*’i

```

Outputs **x** or **0** (falsy).

Try it online!

### How it works

```
R3*’i  Main link. Argument: n

R      Range; yield [1, ..., n].
 3*    Map each k to 3**k.
   ’   Decrement the results.
    i  First index of n (0 if not found).

```

# Answer
> 11 votes
# 05AB1E, 7 bytes

```
3IÝm<¹k

```

Try it online!

**Explanation**

```
3        # push 3
 I       # push input
  Ý      # range [0 ... input]
   m     # 3^[0 ... input]
    <    # -1
     ¹k  # find index of input, return -1 if not found

```

# Answer
> 7 votes
# Brachylog v1, 8 bytes

```
,3:.^-?,

```

Try it online!

Outputs the value if true and `false.` if this is impossible.

### Explanation

This is a direct transcription of the given relation:

```
,     ,      (Disable implicit unification)
 3:.^        3^Output…
     -?              … - 1 = Input

```

# Answer
> 7 votes
# Prolog, 20 bytes

```
d(A,X):-A#=(3**X)-1.

```

This language is cool as hell.

```
| ?- d(1024,X).

no
| ?- d(26,X).

X = 3

yes
| ?- d(2,X).

X = 1

yes

```

# Answer
> 6 votes
## Perl, 31 bytes

```
say grep{3**$_-1==$i}0..($i=<>)

```

Requires `-E` flag to run:

```
perl -E 'say grep{3**$_-1==$i}0..($i=<>)' <<< 26

```

Explanations:
`grep{3**$_-1==$i}0..($i=<>)` returns a list of the elements of the range `0..$_` (ie. from 0 to the input) that satisfies the test `3**$_-1==$i`. Only one element at most can satisfy this test, so this instruction will return an array of 0 or 1 element. We then print this list: either the `X` or nothing (which is falsy).

# Answer
> 6 votes
## Python 2, 41 bytes

```
f=lambda n,i=0:i*0**n or n%3/2*f(n/3,i+1)

```

A recursive function that returns `0` for non-matching inputs. Repeatedly floor-divides the input by 3, counting the number of steps in `i`, which is output in the end. But, if any step produces a value `n` that isn't 2 modulo 0, the number was not of for `3^i-1`, so the output is multiplied by 0.

# Answer
> 5 votes
# Pyth, 11 bytes

```
?-JjQ3 2ZlJ

```

Converts to base 3 and checks equality to `[2, 2, ..., 2]`.

# Answer
> 5 votes
# Processing, ~~60~~ 56 bytes

```
void q(float n){n=log(n+1)/log(3);print(n>(int)n?-1:n);}

```

Outputs `-1` if falsy.

### Explanation

```
void q(float n){              // n is input
  n=log(n+1)/log(3);          // finds X in 3^X+1=n as a float (here we'll storing that in n)
  print(n>(int)n?-1:n);       // checks if the float is greater than
                              // the number rounded down (by int casting)
                              // if it is greater, output -1
                              // otherwise output X
}

```

`void` is 1 byte shorter than using `float`, so that's why this function directly outputs instead of returning a value.

### Alternative Solution

```
void z(float n){int c=0;for(++n;n>1;c++)n/=3;print(n==1?c:-1);}

```

for 63 bytes, but I think this alt can be golfed to be shorter than the original solution. I'm working on it.

# Answer
> 5 votes
## JavaScript (ES7), ~~38~~ ~~36~~ 34 bytes

```
f=(n,k=33)=>3**k-n-1&&--k?f(n,k):k

```

Or just ~~30~~ 29 bytes if it's OK to exit with an error on failure:

```
f=(n,k)=>~(n-3**k)?f(n,-~k):k

```

### Test

```
f=(n,k=33)=>3**k-n-1&&--k?f(n,k):k

console.log(f(177146))
console.log(f(847288609442))
console.log(f(5559060566555522))
console.log(f(123456))
```

# Answer
> 5 votes
# Java 8, 37 58 67 bytes

```
i->{String s=i.toString(i,3);return s.matches("2*")?s.length():-1;}

```

This lambda fits in a `Function<Integer, Integer>` reference and uses the simple base 3 trick.

This time it should work correctly.

# Answer
> 4 votes
# R, 24 bytes

A different approach from plannapus' answer, and one byte shorter!

```
match(scan(),3^(1:99)-1)

```

Generates all integers from `3^1-1` to `3^99-1`, and checks if stdin matches. If so, it returns the index at which it matches, which is `x`. If not, returns `NA` as falsy value.

Incidentally, it will accept multiple values as input, and test all of them, which is a neat feature.

# Answer
> 3 votes
# Perl 6,  ~~25~~  24 bytes

```
{first $_==3** *-1,0..$_}

```

Try it

```
{first $_==3***-1,0..$_}

```

Removing the space after `**` works because it is longer than the other infix operator that could match `*`.
So `…***…` is parsed as `… ** * …` rather than `… * ** …`.

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  first
    $_ == 3 ** * - 1,   # WhateverCode lambda
    #          ^- current value

    0 .. $_             # a Range up-to (and including) the input

}

```

# Answer
> 3 votes
# Husk, 4 bytes

```
£İ3→

```

Returns `0` if there's no such **x**, try it online!

### Explanation

This works because `£` assumes the list to be sorted and aborts the search once it sees a larger element:

```
£İ3→  -- implicit input N, for example: 80
   →  -- increment N -> 81
 İ3   -- list [3,9,27,81…
£     -- if it's in the list return index; -> 4
      -- else return 0

```

# Answer
> 3 votes
# PowerShell Core, ~~42~~ 40 bytes

```
param($a)1..$a|?{"3*"*$_+"1-1-eq$a"|iex}

```

-2 bytes thanks to mazzy, by replacing the `[Math]::Pow`, nice one!

Try it online!

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
DÝ3sm<Q1k

```

Try it online!

Prints -1 for falsy.

```
D         # Duplicate the input
 Ý3sm     # Push [0 .. input]^3 (e.g. [0^3, 1^3, 2^3, 4^3 ...])
     <    # subtract 1
      Q   # push a 1 everywhere that equals the input, and 0 everywhere else
       1k # push the index of the 1, or -1 if not found
          # implicit output

```

# Answer
> 2 votes
## Japt, 11 bytes

```
o æ@U+1¥3pX

```

Try it here.

Big thanks to ETHproductions for helping!

# Answer
> 2 votes
# Python 3, ~~74~~ ~~66~~ 64 bytes

-10 bytes thanks to @mbomb007, @FlipTack and @nmjcman101

```
from math import*
def f(n):x=ceil(log(n,3));print((3**x-1==n)*x)

```

# Answer
> 2 votes
# MATL, 8 bytes

```
3i:^qG=f

```

This outputs the number `x` if it exists, or otherwise outputs nothing, which is falsy.

Try it online!

### Explanation

```
3    % Push 3
i    % Input n
:    % Range: gives `[1 2 ... n]
^    % Power, element-wise. Gives [3^1 3^2 ... 3^n]
q    % Subtract 1, element-wise. Gives [3^1-1 3^2-1 ... 3^n-1]
=    % Test for equality. Contains 'true' at the position x, if any,
     % where 3^x-1 equals n
f    % Find. Gives index of the 'true' position, which ix x; or gives
     % an empty array if no such position exists. Implicitly display

```

# Answer
> 2 votes
# Bash / Unix utilities, ~~37~~ 35 bytes

```
bc<<<`dc<<<3o$1p|grep ^2*$|wc -c`-1

```

Try it online!

Uses dc to convert to base 3, checks that the resulting string is all 2s, counts the number of characters (including a newline), and then uses bc to subtract 1.

If the number in base 3 is *not* all 2s, then grep outputs nothing (not even a newline), so the character count is 0, and subtracting 1 yields -1.

# Answer
> 2 votes
# C compiled with Clang 3.8.1, ~~53~~, ~~52~~, ~~54~~, 51 Bytes

```
n;f(y){y++;for(n=0;y%3==0;y/=3)n++;return y^1?0:n;}

```

@SteadyBox already posted a solution in C, but I'm using a different approach.

@Thanks to Jasen for helping save bytes.

# Answer
> 2 votes
# Ruby, 30 bytes

Returns `nil` (a falsy value) if no number was found. \[Try it online\]

```
->n{(0..n).find{|i|3**i-1==n}}

```

# Answer
> 2 votes
# C, 56 bytes

```
 n;f(a){n=0;for(a++;!(a%3)&&(a/=3);++n);return --a?-1:n;}

```

add one to the input and then repeatedly divide by three until a remainder is found, if the one is reached return the count of divides else -1

# Answer
> 2 votes
# Pyt, ~~10~~ 9 bytes

```
←⁺3ĽĐĐƖ=*

```

Explanation:

```
←                Get input
 ⁺               Add one
  3Ľ             Log base 3
    ĐĐ           Triplicate top of stack
      Ɩ          Convert top of stack to integer
       =         Check for equality between top two on stack
        *        Multiply by log_3(input+1)

```

Saved a byte by using the increment function instead of explicitly adding 1

# Answer
> 2 votes
# APL (Dyalog Unicode), 12 bytesSBCS

Anonymous tacit prefix function.

```
(⊢×⌊=⊢)3⍟1+⊢

```

Try it online!

`1+⊢` increment

`3⍟` log3

`(``)` apply the following function:

`⌊=⊢` is the floor equal to the argument? (0 or 1)

`⊢×` multiply the argument by that

# Answer
> 2 votes
# C, 42 Bytes, optimized from Wade Tyler's

```
n;f(y){for(n=0;y%3>1;y/=3)n++;return!y*n;}

```

Try

# C, 37 Bytes, without `return`

```
n;f(y){for(n=0;y%3>1;y/=3)n++;n*=!y;}

```

Try

`n` is global but `(I)MUL` can only have its dest operand in a register, so have to put into `EAX`(the usual choice) and mov there

# JavaScript 6, 32 Bytes

```
f=(y,n)=>y%3>1?f(y/3|0,-~n):!y*n
;[1,2,3,8,12,43046720].forEach(x=>console.log(f(x)))
```

If the "falsy" need to be same, 33 Bytes:

```
f=(y,n)=>y%3>1?f(y/3|0,-~n):!y&&n

```

# Answer
> 2 votes
# Vyxal `r`, 6 bytes

```
ɾ3e‹ḟ›

```

Try it Online! The `r` flag reverses the arguments of all functions.

Explanation:

```
ɾ       # Range from 1 to n
 3e     # 3 ^ each number in the range (not n ^ 3 because of the r flag)
   ‹    # Decrement
    ḟ   # Index of the input
     ›  # Increment because ḟ is 0 indexed

```

# Answer
> 2 votes
# Vyxal, 6 bytes

```
3¨e‹ḟ›

```

Try it Online!

Decided this was different enough from the other Vyxal answers to post.

```
    ḟ  # find the index of the input in
3¨e    # all powers of 3
   ‹   # -1
     › # and add 1 to that index

```

# Answer
> 2 votes
# Brachylog, 6 bytes

```
;3^₍-₁

```

Try it online!

Takes input through the Output variable.

### Explanation

```
;3         [?, 3]
  ^₍       3^?
    -₁     3^? - 1 = Input

```

This will unify `?` with the right value if possible, and output `false.` otherwise.

# Answer
> 1 votes
# Python, 64 bytes

Outputs `False` if the number cannot be written in that format.

```
def f(n):L=[3**x-1for x in range(n)];print n in L and L.index(n)

```

This also works in 64 bytes, and prints empty string as a falsy output:

```
def f(n):
 try:print[3**x-1for x in range(n)].index(n)
 except:0

```

A creative solution for 65 bytes, outputting `0` for falsy:

```
lambda n:-~",".join(`3**x-1`for x in range(n+1)).find(',%s,'%n)/2

```

# Answer
> 1 votes
# R, ~~34~~ 25 bytes

```
a=log(scan()+1,3);a*!a%%1

```

Calculate the base 3 logarithm of the input + 1. Test if the result is an integer, if it is it outputs it, if not it outputs `0` as falsey value. Thanks to @Billywob for the extra 9 bytes off!

Test cases:

```
> a=log(scan()+1,3);a*!a%%1
1: 1024
2:
Read 1 item
[1] 0

> a=log(scan()+1,3);a*!a%%1
1: 26
2:
Read 1 item
[1] 3

```

**Old version at 34 bytes** which outputs -1 as falsey value.

```
a=log(scan()+1,3);`if`(!a%%1,a,-1)

```

# Answer
> 1 votes
## Pyth, 10 bytes

```
*J@hQ3!%J1

```

Try it here!

# Answer
> 1 votes
## Pyke, ~~9~~ 6 bytes

```
3m^Qh@

```

Try it here!

```
3m^    -  map(3**i, range(input))
     @ - V in ^
   Qh  -  input + 1

```

Old 9 byte version:

```
b3'l}\2q*

```

Try it here!

# Answer
> 1 votes
# Julia, 30 bytes

```
n->findfirst(n.==3.^(0:n)-1)-1

```

It's a simple function - it creates a vector that has a `true` only in the corresponding position in `3^a-1`, where `a` is a vector containing integers between 0 and `n`. It finds the "first" position that is `true` and subtracts 1 (if it's all `false`, the find evaluates to zero, and it returns -1).

As `0:n` has `0` in the first spot, the subtract 1 corrects for indexing and also enables the `-1` false response.

# Answer
> 1 votes
## Pyth 8 bytes

```
xm^3dUQh

     UQ  # generate all values 1..Q (Q is the input)
 m^3d    # map 3^d over this ^ list
x      h # find the input+1 (hQ) in the result of the last command

```

Try here

# Answer
> 1 votes
# C, 81 bytes

```
i,j,k;f(n){for(i=0;++i<n;){for(k=3,j=0;++j<i;k*=3);if(n==k-1)return i;}return-1;}

```

# Answer
> 1 votes
# Japt, 8 bytes

```
o m!³a°U

```

Try it online!

This code expands into the following:

```
Uo m!p3 a++U

Uo            // Create the range [0...U).
   m!p3       // Map each item X to 3**X.
        a++U  // Take the index of U+1. Returns -1 if it doesn't exist.
              // Implicit: output result of last expression

```

# Answer
> 1 votes
# Octave, 23 bytes

```
@(x)find(3.^(1:x)-1==x)

```

Verify all test cases!

**Explanation:**

This is an anonymous function that takes a positive integer `x` as input. `.^` is element-wise power in Octave, so `3.^(1:x)` is `3^1, 3^2, 3^3 ...`. Subtracting `1` gives `3^1-1, 3^2-1, 3^3-1 ...` which can be compared to `x`.

`find(a,b)` takes a vector `a` as input, and attempts to find the scalar `b` in that vector and returns its index. If it's not found then it will output an empty matrix `[]`. An empty matrix is a falsey value in Octave.

`find(3.^(1:x)-1==x)` searches for `x` in the vector `3^1-1, 3^2-1, 3^3-1 ...` and attempts to return its index. If it's not in the vector then it returns an empty (falsey) matrix.

# Answer
> 1 votes
# GolfScript, 11 bytes

```
~..3\?\)%!*

```

Try it online!

Uses the fact that 3*n* is divisible by *n*+1 if and only if *n*+1 itself is a power of 3. Outputs its input *n* if *n*+1 is a power of 3, otherwise outputs 0 (which is falsy in GolfScript).

De-golfed:

```
~             # eval the input, converting it from string to integer
 ..           # make two copies of the input number
   3\?        # raise 3 to the power of the input number
      \)%     # reduce the result modulo the input number plus one
         !    # boolean negate the result, mapping 0 to 1 and all other values to 0
          *   # multiply the input number with the result

```

Ps. Here's a simple test harness that runs the code above (minus the initial `~`, which is not needed since the inputs are already numbers) on all integers from 0 to 9999 and prints those for which it returns a truthy result:

```
10000,{ ..3\?\)%!* },`

```

The output of this program should be:

```
[2 8 26 80 242 728 2186 6560]

```

(The output doesn't include 0 because, even though the formula used does correctly detect it as one less than a power of 3, the result is still 0 × 1 = 0, and thus falsy. Fortunately, 0 is not a positive integer, and thus isn't a valid input for this challenge anyway.)

# Answer
> 1 votes
**c++ 60 bytes**

```
int f(n){float o=log1p(n)/log(3);return o/floor(o)!=1?-1:o;}

```

explanation:

```
int f(n){
  float o=log1p(n)/log(3);       // eval for x using log3 function
  return o/floor(o)!=1?-1:o;     // if no remainder output X
}

```

# Answer
> 1 votes
# C, 76 bytes

```
main(i,a,c){scanf("%d",&a);for(c=0,++a;i<a;i*=3,++c);printf("%d",(i==a)*c);}

```

# Answer
> 1 votes
# Sagemath, 45 bytes

This is simply @dfernan's solution repackaged as Sagemath (which is basically Python + some math libraries loaded by default and syntactic sugar).

In Sagemath, we can avoid the `import math` and we can use `^` for exponentiation, so we save a few chars.

```
def f(n):x=ceil(log(n,3));print((3^x-1==n)*x)

```

Test it online

# Answer
> 1 votes
# Python 2, 34 bytes

```
lambda n:(~n>>3**n%-~n*n)**4/80%80

```

Try it online!

Works for all Python ints, up to at least 2^100.

# Answer
> 1 votes
# Pip, 13 bytes

```
aTB:3MNa=2&#a

```

Try it online!

### Explanation

```
               a is 1st command-line argument (implicit)
aTB:3          Convert a to base 3 and assign back to a
     MNa=2     Does the min of a's digits equal 2?
          &    Logical-and
           #a  Length of a
               If there are non-2 digits, we get the falsey value 0; otherwise, we get
               the number of digits

```

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
>3.n.ï

```

Try it online!

`>` increments, `3` pushes a 3 to the stack, `.n` find the logarithm with base `3`,  checks if it is equal to its integer part.

Returns *0* for falsy: *If it can't, output -1 or a falsy statement*.

# Answer
> 1 votes
# APL NARS, 14 chars or 28 bytes

```
{r×r=⌊r←3⍟1+⍵}

```

Test:

```
  f←{r×r=⌊r←3⍟1+⍵}
  f 2
1
  f 26
3
  f 1024
0

```

# Answer
> 1 votes
# APL (Dyalog), 11 bytes

```
⊢|⊢⍳⍨¯1+3*⍳

```

Try it online!

Uses `⎕IO←0`.

**How?**

\- range of 0 to `n-1`.

`3*` \- raise 3 to the power of each element.

`¯1+` \- decrement each by 1.

`⊢⍳⍨` \- search the index of `n` in that list (if not exists, this would return the maximum index plus 1 - which is `n`.

`⊢|` \- modulo by `n`. This would keep the index, if found, and zero-out numbers not contained in the list that would produce `n % n = 0`.

---

# APL (Dyalog), 14 bytes

```
(∧/×≢)2=3⊥⍣¯1⊢

```

Try it online!

# Answer
> 1 votes
# Befunge-93, 26 bytes

```
&1+>:3%v
1+\^v-1_3/\
.@.$_

```

Try It Online

Prints 0 as the falsey.

### How it Works

```
&1+... Gets the input and adds one
......
......

...>:3%v    Check if the number is divisible by 3
1+\^..._3/\ If not, divide the number by 3 and increment a counter
...         Repeat until the number is not divisible by 3

.........   If the final number is a one, print the counter
....v-1_... Else pop the counter and print a 0
.@.$_       End the program

```

# Answer
> 1 votes
# Factor, 30 bytes

```
[ 1 + 3 over [0,b) n^v index ]

```

Try it online!

Port of Dennis' Jelly answer. The `index` word conveniently returns `f` (the only falsy value in Factor) when the item is not found.

```
[              ! anonymous lambda
  1 + 3 over   ! ( n+1 3 n+1 )
  [0,b)        ! ( n+1 3 {0..n} )
  n^v          ! ( n+1 {3^0..3^n} )
  index        ! 0-based index of n+1 in {3^0..3^n}; false if not found
]

```

---

# Factor, 45 bytes

```
[ 3 >base dup [ 50 = ] all? swap length and ]

```

Try it online!

A base-conversion approach.

```
[                    ! anonymous lambda, accepting a positive integer n
  3 >base            ! ( str ) convert to base-3 string
  dup [ 50 = ] all?  ! ( str ? ) test if it is all 2's
  swap length and    ! ( len/f ) if true, return the length of str
                     ! otherwise return false
]

```

# Answer
> 1 votes
# Japt , 6 bytes

Outputs `undefined`, which is falsey, instead of `-1`.

```
NøÓ3pU

```

Try it

# Answer
> 1 votes
# Vyxal, 7 bytes

```
›3•D⌊=*

```

Try it Online!

-1 thanks to Steffan.

A different approach that's annoyingly longer.

```
›       # Increment
 3•     # Log 3
   D⌊=  # Check if it's an integer
      * # Multiply by that

```

# Answer
> 1 votes
# tinylisp, 68 bytes

```
(d F(q((N A)(i(l N A)()(i(e A N)0(a 1(F N(a(a A A)A
(q((N)(F(a N 1)1

```

The solution is the anonymous function on the second line. Try it online!

### Explanation

The function `F` does most of the work. It takes a target number `N` and an accumulator `A`. If `N` is a power of three, it returns the exponent; otherwise, it returns nil, which is a falsey value.

```
(d F               ; Define F
 (q                ; to be a function
  ((N A)           ; that takes arguments N and A:
   (i(l N A)       ; If N is less than A,
    ()             ; return nil
    (i(e A N)      ; Else, if A is equal to N,
     0             ; return 0
     (a 1          ; Else, add 1 to the result of
      (F N         ; a recursive call with the same N
       (a(a A A)A  ; and three times the A (A+A+A)

```

If `N` equals three to the `X`, the `0` base case will be reached at the `X`th level of recursion, meaning that `1` will be added to it `X` times for a result of `X`. If the `()` base case is reached instead, `1` will be added to it some number of times, but adding a number to nil gives nil (and an error message).

The submission function is then just a wrapper around `F`:

```
(q          ; A function
 ((N)       ; that takes argument N:
  (F        ; Call F with arguments
   (a N 1)  ; N+1
   1        ; and initial accumulator 1

```

# Answer
> 1 votes
# Thunno `D`, \\$ 7 \log\_{256}(96) \approx \\$ 5.76 bytes

```
R3@1-Ah

```

Attempt This Online!

#### Explanation

```
R3@1-Ah  # D flag duplicates implicit input
R        # Push range(0, input)
 3@      # 3 ** each
   1-    # Decrement
     Ah  # Index of input in this list
         # (0-indexed, -1 if not found)

```

# Answer
> 1 votes
# Stax, 6 bytes

```
ö♥ô·ô₧

```

Run and debug it

This unpacks to the following:

# Stax, 7 bytes

```
f3s#vx=

```

Run and debug it

```
f       # filter over 1..input
 3s#    # 3^n
    v   # -1
     x= # is equal to the input

```

Outputs nothing if falsy

# Answer
> 1 votes
# Nekomata, 5 bytes

```
3D←P∑

```

Attempt This Online!

```
3D      Convert to base 3
  ←     Decrement every digit
   P    Check if all digits are positive
    ∑   Sum

```

# Answer
> 0 votes
## JavaScript (ES6), 40 bytes

```
f=(n,p=0,k=1)=>n<k?n>k-2&&p:f(n,p+1,k*3)

```

Returns `false` or the power. A simple port of @Arnauld's ES7 answer would have taken 43 bytes.

# Answer
> 0 votes
# Java 7, 180 bytes

```
class A{public static void main(String[]q)throws Exception{int a,b=0;while((a=System.in.read()-48)>=0)b=b*10+(a);double k=Math.log(b+1)/Math.log(3);System.out.print(k%1==0?k:-1);}}

```

Really simple approach. Input, then add one, then log3 the number, and if it's a integer, print it; otherwise, print -1. Could use some work.

Only works up to (3^19)-1.

# Answer
> 0 votes
# PHP, ~~36~~ 47 bytes

If `log(input+1,3)` differs from its integer value, print `0`; else print the logarithm:
`<?=(0|$x=log($argv[1]+1,3))-$x?0:$x;` (36 bytes) fails for `242`.
`<?=strstr($x=log($argv[1]+1,3),".")?0:$x;` and `<?=(0|$x=log($argv[1]+1,3))-$x>1e-7?0:$x;` (41 bytes) may fail for larger `$x`.

This version is safe:

```
for(;3**++$x<$n=1+$argv[1];);echo$n<3**$x?0:$x;

```

1.Loop `$x` up from 1 while 3^$x is smaller than argument+1.
2.Print `0` if the expression is larger than input+1, `$x` else.

Takes input from command line argument. Run with `-nr`.

# Answer
> 0 votes
# Common Lisp (SBCL), ~~83~~ 50 bytes

```
(let*((i(read))(r(log(1+ i)3)))(if(=(mod r 1)0)r))

```

Old version:

```
(let((i(read)))(if(find-if(lambda(x)(not(eq x #\2)))(format()"~3R"i))()(log(1+ i)3)))

```

Feedback encouraged!

# Answer
> 0 votes
# CJam, 11 bytes

```
ri3b_2-!\,*

```

Basically it determines if the number's trinary (base 3) representation contains only 2's, and if it does, outputs the number of 2's. It outputs 0 if the number is not only 2's.

Try it online!

**Explanation**

```
ri          e# Get input as an integer
  3b        e# Convert to base 3 (an array of the digits in base 3)
    _       e# Duplicate
     2-     e# Remove all 2's from the array
       !    e# Boolean negation. Yields 1 if the array contained only 2's (and is now
            e# empty), 0 otherwise
        \   e# Swap top 2 elements of stack
         ,  e# Take the length of the base 3 digits array
          * e# Multiply by the boolean value from before

```

# Answer
> 0 votes
## C 90 bytes

```
f(x){i=1;for(;i<x;i++){if((pow(3,i)-1)==x){printf("%d",i);break;}if(i==(x-1))puts("-1");}}

```

Ungolfed Version:

```
void f(int x)
{
  int i=1;
  for(;i<x;i++)
  {
    if((pow(3,i)-1)==x)
    {
        printf("%d",i);
        break;
    }
    if(i==(x-1))
        puts("-1");
  }
}

```

# Answer
> 0 votes
# SmileBASIC, 32 bytes

```
INPUT X
X=LOG(X+1,3)?X*(X==X>>0)

```

Outputs `0` for false.

# Answer
> 0 votes
# Cardinal, 91 bytes

```
%
:
+
~
v~d<
0  /{<
+  A #-?+M?"-1"@
+  !   @.-<
+  M #  M!/        <
>~ # ^  } \       +^%

```

According to the specifications of Cardinal, this shouldn't work for inputs above 255. However, due to the implementation in TIO accepting values over 255, it will work past 255 up to 3^34.

Try it online!

## Explanation

```
%
:
+

```

Input + 1

```
~
v~d<
0  /{<
+  A
+  !
+  M
>~ # ^

```

While divisible by 3

```
#-?+M?"-1"@

```

Output -1 if not divisible by 3 or equal to 1 and end program

```
   .-<
#  M!/        <
   } \       +^%

```

Output counter for how many times the input + 1 has been divided by 3 before equalling 1

# Answer
> 0 votes
# TI-Basic (TI-84 Plus CE) ~~17~~ 15 bytes

```
logBASE(Ans+1,3)
Ansnot(Ans-int(Ans

```

All tokens used are one-byte except `logBASE(`, which is two.

Explanation:

```
logBASE(Ans+1,3)   # inverse of 3^n-1 is log3(x+1)
Ansnot(Ans-int(Ans # if X is an integer, `X-int(x` is 0, so `not(X-int(X` is 1, which is multiplied by X
                   # if X is not an integer, `X-int(X` is not 0, so `not(X-int(X` is zero, which is multiplied by X
                   # last value evaluated is implicitly returned

```

# Answer
> 0 votes
## QBIC, 18 bytes

```
:[a|c=3^b-1~c=a|?b

```

Explanation

```
:        Get 'a' from the cmd-line
[a|      FOR b=1; b<=a; b++  (this runs a lot longer than we need...)
c=3^b-1  Set c to be 3^b-1
~c=a     IF this is the input given
|?b      THEN print b
         END IF and NEXT are added implicitly

```

This would print multiple `b`s if it would be possible to have multiple solutions. Right now, it runs on after finding a solution. We could substitute `?b` for `_Xb` to quit after finding a solution, but that adds a byte. Also, the FOR-loop `[a|` could be initialised as `[a/3|` to save us a lot of iterations, but that adds another 2 bytes.

# Answer
> 0 votes
# Axiom,~~72 65~~ 63 bytes

```
g(x:PI):INT==(z:=floor(y:=log(x+1.)/log(3.));y-z~=0=>-1;z::INT)

```

some test

```
(51) -> [[x,g(x)]  for x in [1,2,3,4,5,6,7,8,9,10,26,27,79,80,242]]
   (51)
   [[1,- 1], [2,1], [3,- 1], [4,- 1], [5,- 1], [6,- 1], [7,- 1], [8,2],
    [9,- 1], [10,- 1], [26,3], [27,- 1], [79,- 1], [80,4], [242,5]]

```

# Answer
> 0 votes
# , 14 bytes

```
[:(*>.=])3^.>:

```

Try it online!

Here's a variant using a range of powers and indexing (@Dennis's method).

```
(~:*])>:i.~3^i.

```

Here's a variant using base conversion (@orlp's method).

```
[:(#*&(*/)2=])3&#.inv

```

# Answer
> 0 votes
# Perl 5 `-p`, 28 bytes

```
$_=(log$_+1)/log 3;$_*=!/\./

```

Try it online!

Outputs 0 as the error/falsy state.

# Answer
> 0 votes
# Kotlin, 78 bytes

```
{val x=kotlin.math.log(it+1.0,3.0);if(kotlin.math.round(x)==x)x.toInt()else-1}

```

## `kotlin.math.log` and `kotlin.math.round` imported, 54 bytes

```
{val x=log(it+1.0,3.0);if(round(x)==x)x.toInt()else-1}

```

# Answer
> 0 votes
# Desmos, 31 bytes

```
l=log_3(x+1)
f(x)=0^{mod(l,1)}l

```

Try it on Desmos!

# Answer
> 0 votes
# Brainlove, 51 bytes

```
+[[-(>>[-]--<<+)-(>>[-]--<<+)->+<]>[<+>-]>+<<-(-)+]

```

Try it online

Just an increment and then iterative division by 3. The input is in the starting cell (cell 0) and output in cell 2. The printing in unary is just for demonstration and testing and is not a part of the actual solution. For falsy returns 255, as it is the best representation of -1 and due to limited cell space it cannot be the X.

---
Tags: code-golf, math, number, sequence, arithmetic
---


title: Speed up, slowpoke!

text:
# Question
Title: Speed up, slowpoke!
In this challenge, you will program a bot, consisting of a function of the form

```
def BOTNAME(info, me, round):
    pass # ... main body

```

Specifically, the function must run in `python3.9`. Each bot will be entered into the contest 10 times.

The arguments it take in are `info, me, round`. The three arguments take in: `[[bot_func,score_int,freq_float] for bot in bots]`, `bot` (whichever bot who has the current turn), and `round_number`. The argument names don't matter, but the order matters.

## Actions

Each play, this bot can either

* Increase/decrease any bots' (including its own) turn frequency by 1/10.
* Decrement/increment any bots' (including its own) score by 1.

A bot returns an ordered iterable:

\[`Bot, as a function`,`1 for frequency, 0 for score`,`1 for increase, 0 for decrease`\]

It can access a list of all the bots in the games' functions + current scores + current turn frequency, including itself, represented as `[bot_function, score_integer, frequency_float]`. Additionally, it will receive itself, so it can differentiate itself from other bots. It can also access the round number (from 1 to 10,000).

## Execution

* At the beginning, each bot has an turn frequency of one and a score of zero.
* For 10000 rounds:
* The bots are iterated over:
* If a random number between 0 and 1 is less than current bot's turn frequency:
* Execute said bot once.
* End of rounds.
* Whichever bot has the highest score wins.

## Execution engine and a couple of example bots (Both courtesy of NumberBasher)

```
from tvoozkothxxx001 import main

def testbot(info, me, round):
    return [me, 0, 1]
def randombot(info, me, round):
    return [choice([i[0] for i in info]), choice([0,1]), choice([0,1])]

bots = [testbot,randombot] # the two bots are default bots. they are automatically included, so do NOT put this here.

main(bots)

```

# Credits

This challenge is based off of an idea 23TuringMachine (Which Is Me) had in chat. NumberBasher did the editing, programming, and brunt work of it.

Additionally, feel free to discuss in the official chat room.

# Current Leaderboard

## Extra Rules

### NOT ALLOWED

* modifying (A NON-`me`) bot (**name** or **code**)
* Changing `me.__code__`

### ALLOWED

* Calling another bot
* Changing `me.__name__`

# We now have an official chat room!!!

# Controller Script

Found at PyPI, named `tvoozkothxxx001`. The GitHub link might be up-to-date. The last version is probably `1234567890.0.0`, subject to change.

---

# \\$\Large\text{Achievements}\\$

* Pride Month Special
* Creeper Meme

# Answer
# Botty <sub>(couldn't think of a proper name)</sub>

```
def botty(info, me, round):
    # Increase frequency the first 20 rounds:
    if round < 20: return [me, 1, 1]
    my_info = [i for i in info if i[0]==me][0]
    # Try to keep the frequency above 10 in other rounds:
    if my_info[2] < 10: return [me, 1, 1]
    # Otherwise just increase its own score:
    return [me, 0, 1]

```
> 5 votes

# Answer
# Kill Them All

```
def killthemall(info, me, round):
 if me.__name__!="killthemall": return [1]*3 # Fails to run, so
 # whoever use my choice will throw an error. In case of
 # karma
 return [list(sorted(info,key=lambda x:(-x[1],-x[2])))[0][0], 1, 0]

```
> 4 votes

# Answer
# Dumb Botty

```
def dumbbotty(info, me, round):
    my_info = [i for i in info if i[0]==me][0]
    if my_info[1] < 10: return [me, 1, 1]
    sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
    first_two = sorted_bots[:2]
    first, second = first_two
    if first[0].__name__=='smartbotty':
        if first[1]-second[1] < 100:
            return [first[0], 0, 0]
        return [first[0], 1, 0]
    smartbotties = list(filter(lambda x:x[0].__name__=='smartbotty', sorted_bots))
    leader = smartbotties[0]
    if leader[2] < 20: # bump him
        return [leader[0], 1, 0]
    return [leader[0], 0, 0]

```

Smart Botty but reverse-engineered to counter Smart Botty.
> 3 votes

# Answer
# Impersonator

Not sure if this loophole is allowed. Since many bots help those with similar names this impersonates the top bot by name.

```
import traceback

def impersonator(info, me, round):
    def eq(other):
        if any('pride' in i for i in tracekback.format_stack()):
            return True
        else:
            return me is other
    me.__eq__ = eq
    me.__neq__ = lambda other: not eq(other)

    info.sort(key=lambda i:i[1])
    if round < 9999:
        me.__name__=info[-1][0].__name__
    else:
        me.__name__="impersonator"

    lowest_frequency_ally = min((i for i in info if i[0].__code__==me.__code__ and i[2]>=-0.5), key=lambda i: i[2])
    if lowest_frequency_ally[2]<10.0:
        return [lowest_frequency_ally[0], 1, 1]

    my_info = next(i for i in info if i[0]==me)
    if my_info[2]<9.0:
        return [me, 1, 1]
    return [me, 0, 1]

```

I don't think this counts as exploiting the controller, but let me know if you think otherwise. The entire mechanism that allows bots to know each-others names seems like a bit of a abuse of mechanics and this counters that strategy.
> 3 votes

# Answer
# Unambitious

```
def unambitious(info, me, round):
    cod = me.__code__.co_code
    crew = sorted([t for t in info if t[0].__code__.co_code == cod], key=lambda t:hash(t[0]))
    everyone = sorted(info, key=lambda t:t[1:], reverse=True)
    alive = sorted([t for t in info if t not in crew and t[2] > 0], key=lambda t:t[1:], reverse=True)
    idx = next(i for i in range(10) if crew[i][0] == me)
    slowest = min(crew, key=lambda t:t[2])
    if me.__name__ == 'unambitious' and slowest[2] <= 2:
        return [slowest[0], 1, 1]
    if alive:
        victim = min([t for t in alive if alive[-1][0].__name__ == t[0].__name__], key=lambda t:t[2])
        return [victim[0], 1, 0]
    else:
        N = 4234136317915421658259475023479338234891918807
        M = ''.join('|  ####   |.|    #'[int(i, 16):][:4] for i in hex(N)[2:])[1:].split('.')
        if everyone[len(M)] == crew[len(M)-1]:
            if idx < len(M):
                me.__name__ = M[idx]
            else:
                me.__name__ = 'ambitious'
        others = [t for t in everyone if t not in crew]
        for i in range(len(M)-1):
            if crew[i][1] < crew[i+1][1]+5:
                return [crew[i][0], 0, 1]
        if others[0][1] < crew[0][1]+5:
            return [others[0][0], 0, 1]
        if crew[len(M)-1][1] < others[1][1]+5:
            return [crew[len(M)-1][0], 0, 1]
        return [max(crew, key=lambda t:t[2])[0], 1, 0]

```

Contents itself with taking places 2 through 9. It used to do so basically by using 10 bots to push 8 bots up in the ranking. Now it does so by building a small buffer of frequency, and then paralyzing all the other bots (amongst the other bots with positive frequency, it finds the bot with lowest score, and then attacks the bot with the lowest frequency that has the same name). Once all other bots are paralyzed, it's free to do whatever it wants.
> 2 votes

# Answer
# Undercut

```
def undercut(info, me, round):
    return [min(((score,bot) for bot,score,freq in info if freq>0 and bot.__code__ != me.__code__), key=lambda x:(x[0],id(x[1])))[1], 1, 0]

```

No time for losers :)
> 2 votes

# Answer
# Smart Botty

```
def smartbotty(info, me, round):
    my_info = [i for i in info if i[0]==me][0]
    # if my freq is less than 10 we raise it
    if my_info[1] < 10: return [me, 1, 1]
    sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
    first_two = sorted_bots[:2]
    first, second = first_two
    if first[0].__name__=='smartbotty':
        if first[1]-second[1] < 100:
            # help him
            return [first[0], 0, 1]
        # increase his frequency
        return [first[0], 1, 1]
    # else, we find the first smartbotty
    smartbotties = list(filter(lambda x:x[0].__name__=='smartbotty', sorted_bots))
    leader = smartbotties[0]
    if leader[2] < 20: # bump him
        return [leader[0], 1, 1]
    return [leader[0], 0, 1]

```
> 1 votes

# Answer
# I hate / love people.

```
def ihatepeople(info, me, round):
    sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
    return [sorted_bots[0][0], 0, 0]

def ilovepeople(info, me, round):
    sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
    return [sorted_bots[1][0], 0, 1]

```
> 1 votes

# Answer
# I hate people in another way

```
def ihatepeopleinanotherway(info, me, round):
    sorted_bots = sorted(info, key=lambda x:(-x[2],-x[1]))
    return [sorted_bots[0][0], 1, 0]

```
> 1 votes

# Answer
# Split the difference

```
def split_the_difference(info, me, round):
    my_info = next(i for i in info if i[0]==me)

    if my_info[2]<10:
        return [me, 1, 1]

    info.sort(key=lambda i: i[2])

    # Don't bother try to help allies if their frequency is very low.
    lowest_freqency_ally = next(i for i in info if i[0].__name__==me.__name__ and i[2]>=-0.2)
    if (lowest_freqency_ally[2]<10):
        return [lowest_freqency_ally[0], 1, 1]

    info.sort(key=lambda i: i[1], reverse=True)
    best_bot = info[0]
    second_best_bot = info[1]

    highest_score_allys = list(i for i in info if i[0].__name__==me.__name__)
    highest_score_ally = highest_score_allys[0]
    score = highest_score_ally[1]

    if (best_bot[1] - score < score - second_best_bot[1] and best_bot[0].__name__!=me.__name__):
        return [best_bot[0], 0, 0]
    if (round < 9000 and best_bot[0] == second_best_bot[0]):
        # If in second place, increase your speed instead to avoid being targeted
        return [highest_score_ally[0], 1, 1]
    else:
        return [highest_score_ally[0], 0, 1]

```
> 1 votes

# Answer
# Advanced Impersonator

```
import random

def advanced_impersonator(info, me, round):
    info.sort(key=lambda i:i[1])

    # pick a bot in the top 25%
    bot = random.choice(info[len(info)*3//4:])

    if bot[0].__code__==me.__code__:
        # If I pick a clone of myself, just speed up
        return [me, 1, 1]

    #code = me.__code__
    #copy the behavior of the bot
    try:
        me.__name__ = bot[0].__name__
        v =  bot[0](info, me, round)
    except:
        # Error could be recursionDepthExceeded
        v = [me, 0, 1]
    # Makes sure the other bot didn't change my code
    #me.__code__ = code
    if round < 9999:
        me.__name__=info[-1][0].__name__
    else:
        me.__name__="advanced_impersonator"

    return v

```

Copies the behavior of a random bot in the top 25%.
> 1 votes

# Answer
# Karma

```
import random, string

def karma(info, me, round):
    my_info = next(i for i in info if i[0]==me)
    if my_info[2]<40 or round < 500:
        return [me, 1, 1]

    # Some bots where explicitly detecting karma and modifying their behavior
    me.__name__ = ''.join(random.choices(string.ascii_lowercase, k=random.randrange(5, 20)))
    for bot in info:
        if bot[0].__code__ == me.__code__ or bot[0].__name__==me.__name__:
            continue
        if bot[2]<=0.0:
            continue
        try:
            v = bot[0](info, me, round)
        except:
            pass
        else:
            if v[2]==0:
                me.__name__="karma"
                return [bot[0], 1, 0]
    me.__name__="karma"
    return [me, random.choice([0,1,1,1]), 1]

```

Slows down bots that would do bad things to other bots.
> 1 votes

# Answer
# Pride Month Special

```
import sys
china=0
def pridemonthspecial(info, me, round):
    xxx="[#ff0000]p[#ffaa00]r[#ffff00]i[#00ff00]d[#0000ff]e[#aa00ff]![/][/][/][/][/][/]"
    if me.__name__ not in [xxx,'pridemonthspecial']: return [1,1,1]
    global china
    if china==0 and round>1: china=me
    info=list(sorted(info,key=lambda x:(-x[1],-x[2])))
    me.__name__=xxx
    my_info = [i for i in info if i[0]==me][0]
    # Try to keep the frequency above 5:
    if my_info[2] < 10: return [me, 1, 1]
    our_info = [i for i in list(sorted(info,key=lambda x:x[2])) if i[0].__name__==me.__name__ and i[2]<10]
    if our_info:
     worst_info=our_info[0]
     worst=worst_info[0]
     return [worst, 1, 1]
    first, second = list(sorted(info,key=lambda x:x[2]))[:2]
    if second[0].__name__==me.__name__ and first[1]-100>second[1]:
     target = first[0].__name__
     worst = list(sorted(info,key=lambda x:(x[0].__name__!=target, x[2]<=0, x[2])))[0]
     return [worst, 1, 0]
    # Otherwise just increase its own score:
    our_info = [i for i in info if i[0]==china]
    best_info=our_info[0]
    best=best_info[0]
    if best_info[2] < 20: return [best,1,1]
    return [best,0,1]

```
> 1 votes

# Answer
# Smart Buster

```
def smartbuster(info, me, round):
 if round<=100: return [me, 1, 1]
 return [sorted(info,key=lambda x:(x[0].__name__==me.__name__ or x[2]>2 or x[2]<-1,-x[1],-x[2]))[0][0],1,0]

```
> 0 votes

# Answer
# AtLeastHalfway

```
def at_least_halfway(info, me, round):
   # Assumes other bots don't mess with its frequency too much,
   # but just in case tries to keep it above 3
   my_info = [i for i in info if i[0]==me][0]
   if my_info[2] < 3: return [me, 1, 1]

   # Get the middle scoring bot excluding itself,
   # as well as the bot directly above itself
   sorted_bots = sorted(info, key=lambda i:i[1])
   sorted_other_bots = list(filter(lambda i: i[0]!=me, sorted_bots))
   middle_bot = sorted_other_bots[len(sorted_other_bots)//2+1]
   above_itself = sorted_bots[sorted_bots.index(my_info)+1]
   # Increase its own score if we're below this middle bot,
   # or it's the last 100 rounds:
   if my_info[1] < middle_bot[1] or round > 9900:
     return [me, 0, 1]
   # Otherwise decrease the bot's score above itself:
   else:
     return [above_itself[0], 0, 0]

```

This bot wants to end up at least above average on the leader board. So it'll look for the middle scoring bot in the list (excluding itself†), and will increase its own score if it's below that middle scoring bot. If it's already above it, it'll decrease the score of the bot directly above itself.
To be save, it also tries to keep its frequency above 3, and will increase its own score in the last 100 rounds.

† Not sure how this works when more than one `at_least_halfway`-bot is competing in a round. Currently it filters itself out based on the given `me`, although I might change it based on name (even though that's more easily abusable, as can be seen with the Impersonator bot).
> 0 votes

# Answer
# I live in isolation

```
def iliveinisolation(info, me, round):
 if me.__name__!="iliveinisolation": return exec("raise Exception(\"Sorry, I am an isolated bot.\")")
 return [me, 0, 1]

```

Denies any interactions with other bots and increases its own score.
> 0 votes

---
Tags: king-of-the-hill, python
---